blob: f709aa782afcca420335401d3c29f24529df4401 [file] [log] [blame]
Simon Hunt195cb382014-11-03 17:50:51 -08001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
Simon Hunt142d0032014-11-04 20:13:09 -080018 ONOS network topology viewer - version 1.1
Simon Hunt195cb382014-11-03 17:50:51 -080019
20 @author Simon Hunt
21 */
22
23(function (onos) {
24 'use strict';
25
Simon Hunt1a9eff92014-11-07 11:06:34 -080026 // shorter names for library APIs
Simon Huntbb282f52014-11-10 11:08:19 -080027 var d3u = onos.lib.d3util,
Simon Hunt12ce12e2014-11-15 21:13:19 -080028 gly = onos.lib.glyphs,
Simon Huntbb282f52014-11-10 11:08:19 -080029 trace;
Simon Hunt1a9eff92014-11-07 11:06:34 -080030
Simon Hunt195cb382014-11-03 17:50:51 -080031 // configuration data
32 var config = {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -080033 useLiveData: true,
Simon Huntfc274c92014-11-11 11:05:46 -080034 fnTrace: true,
Simon Hunt195cb382014-11-03 17:50:51 -080035 debugOn: false,
36 debug: {
Simon Hunt99c13842014-11-06 18:23:12 -080037 showNodeXY: true,
38 showKeyHandler: false
Simon Hunt195cb382014-11-03 17:50:51 -080039 },
Simon Hunt12ce12e2014-11-15 21:13:19 -080040 birdDim: 400,
Simon Hunt195cb382014-11-03 17:50:51 -080041 options: {
42 layering: true,
43 collisionPrevention: true,
Simon Hunt142d0032014-11-04 20:13:09 -080044 showBackground: true
Simon Hunt195cb382014-11-03 17:50:51 -080045 },
46 backgroundUrl: 'img/us-map.png',
Thomas Vachuska7d638d32014-11-07 10:24:43 -080047 webSockUrl: 'ws/topology',
Simon Hunt195cb382014-11-03 17:50:51 -080048 data: {
49 live: {
50 jsonUrl: 'rs/topology/graph',
51 detailPrefix: 'rs/topology/graph/',
52 detailSuffix: ''
53 },
54 fake: {
55 jsonUrl: 'json/network2.json',
56 detailPrefix: 'json/',
57 detailSuffix: '.json'
58 }
59 },
Simon Hunt99c13842014-11-06 18:23:12 -080060 labels: {
61 imgPad: 16,
62 padLR: 4,
63 padTB: 3,
64 marginLR: 3,
65 marginTB: 2,
66 port: {
67 gap: 3,
68 width: 18,
69 height: 14
70 }
71 },
Simon Hunt1a9eff92014-11-07 11:06:34 -080072 topo: {
73 linkInColor: '#66f',
74 linkInWidth: 14
75 },
Simon Hunt99c13842014-11-06 18:23:12 -080076 icons: {
77 w: 28,
78 h: 28,
79 xoff: -12,
80 yoff: -8
81 },
Simon Hunt195cb382014-11-03 17:50:51 -080082 iconUrl: {
83 device: 'img/device.png',
84 host: 'img/host.png',
85 pkt: 'img/pkt.png',
86 opt: 'img/opt.png'
87 },
Simon Hunt195cb382014-11-03 17:50:51 -080088 force: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080089 note_for_links: 'link.type is used to differentiate',
Simon Huntc7ee0662014-11-05 16:44:37 -080090 linkDistance: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080091 direct: 100,
92 optical: 120,
Thomas Vachuska3266abf2014-11-13 09:28:46 -080093 hostLink: 3
Simon Huntc7ee0662014-11-05 16:44:37 -080094 },
95 linkStrength: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080096 direct: 1.0,
97 optical: 1.0,
98 hostLink: 1.0
Simon Huntc7ee0662014-11-05 16:44:37 -080099 },
Simon Hunt7cd48f32014-11-09 23:42:50 -0800100 note_for_nodes: 'node.class is used to differentiate',
Simon Huntc7ee0662014-11-05 16:44:37 -0800101 charge: {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800102 device: -8000,
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800103 host: -5000
Simon Huntc7ee0662014-11-05 16:44:37 -0800104 },
105 pad: 20,
Simon Hunt195cb382014-11-03 17:50:51 -0800106 translate: function() {
107 return 'translate(' +
Simon Huntc7ee0662014-11-05 16:44:37 -0800108 config.force.pad + ',' +
109 config.force.pad + ')';
Simon Hunt195cb382014-11-03 17:50:51 -0800110 }
Paul Greyson6cb8ca02014-11-12 18:09:02 -0800111 },
112 // see below in creation of viewBox on main svg
113 logicalSize: 1000
Simon Hunt195cb382014-11-03 17:50:51 -0800114 };
115
Simon Hunt142d0032014-11-04 20:13:09 -0800116 // radio buttons
Simon Hunt9462e8c2014-11-14 17:28:09 -0800117 var layerButtons = [
118 { text: 'All Layers', id: 'all', cb: showAllLayers },
119 { text: 'Packet Only', id: 'pkt', cb: showPacketLayer },
120 { text: 'Optical Only', id: 'opt', cb: showOpticalLayer }
121 ],
122 layerBtnSet,
123 layerBtnDispatch = {
124 all: showAllLayers,
125 pkt: showPacketLayer,
126 opt: showOpticalLayer
127 };
Simon Hunt934c3ce2014-11-05 11:45:07 -0800128
129 // key bindings
130 var keyDispatch = {
Simon Hunta255a2c2014-11-13 22:29:35 -0800131 M: testMe, // TODO: remove (testing only)
132 S: injectStartupEvents, // TODO: remove (testing only)
133 space: injectTestEvent, // TODO: remove (testing only)
Simon Hunt99c13842014-11-06 18:23:12 -0800134
Simon Hunt01095ff2014-11-13 16:37:29 -0800135 B: toggleBg,
Simon Hunt934c3ce2014-11-05 11:45:07 -0800136 L: cycleLabels,
137 P: togglePorts,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800138 U: unpin,
Paul Greysonfcba0e82014-11-13 10:21:16 -0800139 R: resetZoomPan,
Simon Hunt9462e8c2014-11-14 17:28:09 -0800140 esc: handleEscape
Simon Hunt934c3ce2014-11-05 11:45:07 -0800141 };
Simon Hunt142d0032014-11-04 20:13:09 -0800142
Simon Hunt195cb382014-11-03 17:50:51 -0800143 // state variables
Simon Hunt99c13842014-11-06 18:23:12 -0800144 var network = {
Simon Hunt50128c02014-11-08 13:36:15 -0800145 view: null, // view token reference
Simon Hunt99c13842014-11-06 18:23:12 -0800146 nodes: [],
147 links: [],
148 lookup: {}
149 },
Simon Hunt56d51852014-11-09 13:03:35 -0800150 scenario = {
151 evDir: 'json/ev/',
152 evScenario: '/scenario.json',
153 evPrefix: '/ev_',
154 evOnos: '_onos.json',
155 evUi: '_ui.json',
156 ctx: null,
157 params: {},
158 evNumber: 0,
159 view: null,
160 debug: false
161 },
Thomas Vachuska7d638d32014-11-07 10:24:43 -0800162 webSock,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800163 sid = 0,
Simon Hunt56d51852014-11-09 13:03:35 -0800164 deviceLabelIndex = 0,
165 hostLabelIndex = 0,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800166 selections = {},
Simon Hunta5e89142014-11-14 07:00:33 -0800167 selectOrder = [],
Simon Hunt6ac93f32014-11-13 12:17:27 -0800168 hovered = null,
Simon Hunta5e89142014-11-14 07:00:33 -0800169 detailPane,
Simon Hunta255a2c2014-11-13 22:29:35 -0800170 antTimer = null,
Simon Hunta5e89142014-11-14 07:00:33 -0800171 onosInstances = {},
172 onosOrder = [],
173 oiBox,
Simon Hunt9462e8c2014-11-14 17:28:09 -0800174 oiShowMaster = false,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800175
Simon Hunt195cb382014-11-03 17:50:51 -0800176 portLabelsOn = false;
177
Simon Hunt934c3ce2014-11-05 11:45:07 -0800178 // D3 selections
179 var svg,
Paul Greysonfcba0e82014-11-13 10:21:16 -0800180 zoomPanContainer,
Simon Hunt934c3ce2014-11-05 11:45:07 -0800181 bgImg,
Simon Huntc7ee0662014-11-05 16:44:37 -0800182 topoG,
183 nodeG,
184 linkG,
185 node,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800186 link,
187 mask;
Simon Hunt195cb382014-11-03 17:50:51 -0800188
Paul Greyson6cb8ca02014-11-12 18:09:02 -0800189 // the projection for the map background
190 var geoMapProjection;
191
Paul Greysonfcba0e82014-11-13 10:21:16 -0800192 // the zoom function
193 var zoom;
194
Simon Hunt142d0032014-11-04 20:13:09 -0800195 // ==============================
Simon Hunt934c3ce2014-11-05 11:45:07 -0800196 // For Debugging / Development
Simon Hunt195cb382014-11-03 17:50:51 -0800197
Simon Hunt99c13842014-11-06 18:23:12 -0800198 function note(label, msg) {
199 console.log('NOTE: ' + label + ': ' + msg);
Simon Hunt195cb382014-11-03 17:50:51 -0800200 }
201
Simon Hunt99c13842014-11-06 18:23:12 -0800202 function debug(what) {
203 return config.debugOn && config.debug[what];
Simon Hunt934c3ce2014-11-05 11:45:07 -0800204 }
205
Simon Huntfc274c92014-11-11 11:05:46 -0800206 function fnTrace(msg, id) {
207 if (config.fnTrace) {
208 console.log('FN: ' + msg + ' [' + id + ']');
209 }
210 }
Simon Hunt99c13842014-11-06 18:23:12 -0800211
Simon Hunta5e89142014-11-14 07:00:33 -0800212 function evTrace(data) {
213 fnTrace(data.event, data.payload.id);
214 }
215
Simon Hunt934c3ce2014-11-05 11:45:07 -0800216 // ==============================
217 // Key Callbacks
218
Simon Hunt99c13842014-11-06 18:23:12 -0800219 function testMe(view) {
Simon Hunta5e89142014-11-14 07:00:33 -0800220 //view.alert('test');
Simon Hunt12ce12e2014-11-15 21:13:19 -0800221 noWebSock(true);
Simon Hunt99c13842014-11-06 18:23:12 -0800222 }
223
Simon Hunt56d51852014-11-09 13:03:35 -0800224 function abortIfLive() {
Simon Hunt50128c02014-11-08 13:36:15 -0800225 if (config.useLiveData) {
Simon Huntb53e0682014-11-12 13:32:01 -0800226 network.view.alert("Sorry, currently using live data..");
Simon Hunt56d51852014-11-09 13:03:35 -0800227 return true;
Simon Hunt50128c02014-11-08 13:36:15 -0800228 }
Simon Hunt56d51852014-11-09 13:03:35 -0800229 return false;
230 }
Simon Hunt50128c02014-11-08 13:36:15 -0800231
Simon Hunt56d51852014-11-09 13:03:35 -0800232 function testDebug(msg) {
233 if (scenario.debug) {
234 scenario.view.alert(msg);
235 }
236 }
Simon Hunt99c13842014-11-06 18:23:12 -0800237
Simon Hunt56d51852014-11-09 13:03:35 -0800238 function injectTestEvent(view) {
239 if (abortIfLive()) { return; }
240 var sc = scenario,
241 evn = ++sc.evNumber,
242 pfx = sc.evDir + sc.ctx + sc.evPrefix + evn,
243 onosUrl = pfx + sc.evOnos,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800244 uiUrl = pfx + sc.evUi,
245 stack = [
246 { url: onosUrl, cb: handleServerEvent },
247 { url: uiUrl, cb: handleUiEvent }
248 ];
249 recurseFetchEvent(stack, evn);
Simon Hunt56d51852014-11-09 13:03:35 -0800250 }
251
Simon Hunt7cd48f32014-11-09 23:42:50 -0800252 function recurseFetchEvent(stack, evn) {
253 var v = scenario.view,
254 frame;
255 if (stack.length === 0) {
Simon Huntfc274c92014-11-11 11:05:46 -0800256 v.alert('Oops!\n\nNo event #' + evn + ' found.');
Simon Hunt7cd48f32014-11-09 23:42:50 -0800257 return;
258 }
259 frame = stack.shift();
260
261 d3.json(frame.url, function (err, data) {
Simon Hunt99c13842014-11-06 18:23:12 -0800262 if (err) {
Simon Hunt56d51852014-11-09 13:03:35 -0800263 if (err.status === 404) {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800264 // if we didn't find the data, try the next stack frame
265 recurseFetchEvent(stack, evn);
Simon Hunt56d51852014-11-09 13:03:35 -0800266 } else {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800267 v.alert('non-404 error:\n\n' + frame.url + '\n\n' + err);
Simon Hunt56d51852014-11-09 13:03:35 -0800268 }
Simon Hunt99c13842014-11-06 18:23:12 -0800269 } else {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800270 testDebug('loaded: ' + frame.url);
271 frame.cb(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800272 }
273 });
Simon Hunt934c3ce2014-11-05 11:45:07 -0800274
Simon Hunt56d51852014-11-09 13:03:35 -0800275 }
Simon Hunt50128c02014-11-08 13:36:15 -0800276
Simon Hunt56d51852014-11-09 13:03:35 -0800277 function handleUiEvent(data) {
Simon Huntbb282f52014-11-10 11:08:19 -0800278 scenario.view.alert('UI Tx: ' + data.event + '\n\n' +
279 JSON.stringify(data));
Simon Hunt56d51852014-11-09 13:03:35 -0800280 }
281
282 function injectStartupEvents(view) {
283 var last = scenario.params.lastAuto || 0;
284 if (abortIfLive()) { return; }
285
286 while (scenario.evNumber < last) {
Simon Hunt1a9eff92014-11-07 11:06:34 -0800287 injectTestEvent(view);
288 }
289 }
290
Simon Hunt934c3ce2014-11-05 11:45:07 -0800291 function toggleBg() {
292 var vis = bgImg.style('visibility');
293 bgImg.style('visibility', (vis === 'hidden') ? 'visible' : 'hidden');
294 }
295
Simon Hunt99c13842014-11-06 18:23:12 -0800296 function cycleLabels() {
Simon Huntbb282f52014-11-10 11:08:19 -0800297 deviceLabelIndex = (deviceLabelIndex === network.deviceLabelCount - 1)
298 ? 0 : deviceLabelIndex + 1;
Simon Hunt5f36d342014-11-08 21:33:14 -0800299
Simon Hunt99c13842014-11-06 18:23:12 -0800300 network.nodes.forEach(function (d) {
Simon Huntbb282f52014-11-10 11:08:19 -0800301 if (d.class === 'device') {
302 updateDeviceLabel(d);
303 }
Simon Hunt99c13842014-11-06 18:23:12 -0800304 });
Simon Hunt934c3ce2014-11-05 11:45:07 -0800305 }
306
307 function togglePorts(view) {
Simon Hunt50128c02014-11-08 13:36:15 -0800308 view.alert('togglePorts() callback')
Simon Hunt934c3ce2014-11-05 11:45:07 -0800309 }
310
Simon Hunt6ac93f32014-11-13 12:17:27 -0800311 function unpin() {
312 if (hovered) {
313 hovered.fixed = false;
314 hovered.el.classed('fixed', false);
315 network.force.resume();
316 }
Simon Hunt934c3ce2014-11-05 11:45:07 -0800317 }
318
Simon Hunt9462e8c2014-11-14 17:28:09 -0800319 function handleEscape(view) {
320 if (oiShowMaster) {
321 cancelAffinity();
322 } else {
323 deselectAll();
324 }
325 }
326
Simon Hunt934c3ce2014-11-05 11:45:07 -0800327 // ==============================
328 // Radio Button Callbacks
329
Simon Hunta5e89142014-11-14 07:00:33 -0800330 var layerLookup = {
331 host: {
332 endstation: 'pkt', // default, if host event does not define type
333 bgpSpeaker: 'pkt'
334 },
335 device: {
336 switch: 'pkt',
337 roadm: 'opt'
338 },
339 link: {
340 hostLink: 'pkt',
341 direct: 'pkt',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800342 indirect: '',
343 tunnel: '',
Simon Hunta5e89142014-11-14 07:00:33 -0800344 optical: 'opt'
345 }
346 };
347
348 function inLayer(d, layer) {
Simon Hunt8257f4c2014-11-16 19:34:54 -0800349 var type = d.class === 'link' ? d.type() : d.type,
350 look = layerLookup[d.class],
351 lyr = look && look[type];
Simon Hunta5e89142014-11-14 07:00:33 -0800352 return lyr === layer;
353 }
354
355 function unsuppressLayer(which) {
356 node.each(function (d) {
357 var node = d.el;
358 if (inLayer(d, which)) {
359 node.classed('suppressed', false);
360 }
361 });
362
363 link.each(function (d) {
364 var link = d.el;
365 if (inLayer(d, which)) {
366 link.classed('suppressed', false);
367 }
368 });
369 }
370
Simon Hunt9462e8c2014-11-14 17:28:09 -0800371 function suppressLayers(b) {
372 node.classed('suppressed', b);
373 link.classed('suppressed', b);
Simon Hunt142d0032014-11-04 20:13:09 -0800374// d3.selectAll('svg .port').classed('inactive', false);
375// d3.selectAll('svg .portText').classed('inactive', false);
Simon Hunt195cb382014-11-03 17:50:51 -0800376 }
377
Simon Hunt9462e8c2014-11-14 17:28:09 -0800378 function showAllLayers() {
379 suppressLayers(false);
380 }
381
Simon Hunt195cb382014-11-03 17:50:51 -0800382 function showPacketLayer() {
Simon Hunta5e89142014-11-14 07:00:33 -0800383 node.classed('suppressed', true);
384 link.classed('suppressed', true);
385 unsuppressLayer('pkt');
Simon Hunt195cb382014-11-03 17:50:51 -0800386 }
387
388 function showOpticalLayer() {
Simon Hunta5e89142014-11-14 07:00:33 -0800389 node.classed('suppressed', true);
390 link.classed('suppressed', true);
391 unsuppressLayer('opt');
Simon Hunt195cb382014-11-03 17:50:51 -0800392 }
393
Simon Hunt9462e8c2014-11-14 17:28:09 -0800394 function restoreLayerState() {
395 layerBtnDispatch[layerBtnSet.selected()]();
396 }
397
Simon Hunt142d0032014-11-04 20:13:09 -0800398 // ==============================
Simon Hunt934c3ce2014-11-05 11:45:07 -0800399 // Private functions
400
Simon Hunt99c13842014-11-06 18:23:12 -0800401 function safeId(s) {
402 return s.replace(/[^a-z0-9]/gi, '-');
403 }
404
Simon Huntc7ee0662014-11-05 16:44:37 -0800405 // set the size of the given element to that of the view (reduced if padded)
406 function setSize(el, view, pad) {
407 var padding = pad ? pad * 2 : 0;
Simon Hunt934c3ce2014-11-05 11:45:07 -0800408 el.attr({
Simon Huntc7ee0662014-11-05 16:44:37 -0800409 width: view.width() - padding,
410 height: view.height() - padding
Simon Hunt934c3ce2014-11-05 11:45:07 -0800411 });
412 }
413
Simon Hunt8257f4c2014-11-16 19:34:54 -0800414 function makeNodeKey(d, what) {
415 var port = what + 'Port';
416 return d[what] + '/' + d[port];
417 }
418
419 function makeLinkKey(d, flipped) {
420 var one = flipped ? makeNodeKey(d, 'dst') : makeNodeKey(d, 'src'),
421 two = flipped ? makeNodeKey(d, 'src') : makeNodeKey(d, 'dst');
422 return one + '-' + two;
423 }
424
425 function findLink(linkData, op) {
426 var key = makeLinkKey(linkData),
427 keyrev = makeLinkKey(linkData, 1),
428 link = network.lookup[key],
429 linkRev = network.lookup[keyrev],
430 result = {},
431 ldata = link || linkRev,
432 rawLink;
433
434 if (op === 'add') {
435 if (link) {
436 // trying to add a link that we already know about
437 result.ldata = link;
438 result.badLogic = 'addLink: link already added';
439
440 } else if (linkRev) {
441 // we found the reverse of the link to be added
442 result.ldata = linkRev;
443 if (linkRev.fromTarget) {
444 result.badLogic = 'addLink: link already added';
445 }
446 }
447 } else if (op === 'update') {
448 if (!ldata) {
449 result.badLogic = 'updateLink: link not found';
450 } else {
451 rawLink = link ? ldata.fromSource : ldata.fromTarget;
452 result.updateWith = function (data) {
453 $.extend(rawLink, data);
454 restyleLinkElement(ldata);
455 }
456 }
457 } else if (op === 'remove') {
458 if (!ldata) {
459 result.badLogic = 'removeLink: link not found';
460 } else {
461 rawLink = link ? ldata.fromSource : ldata.fromTarget;
462
463 if (!rawLink) {
464 result.badLogic = 'removeLink: link not found';
465
466 } else {
467 result.removeRawLink = function () {
468 if (link) {
469 // remove fromSource
470 ldata.fromSource = null;
471 if (ldata.fromTarget) {
472 // promote target into source position
473 ldata.fromSource = ldata.fromTarget;
474 ldata.fromTarget = null;
475 ldata.key = keyrev;
476 delete network.lookup[key];
477 network.lookup[keyrev] = ldata;
478 }
479 } else {
480 // remove fromTarget
481 ldata.fromTarget = null;
482 }
483 if (ldata.fromSource) {
484 restyleLinkElement(ldata);
485 } else {
486 removeLinkElement(ldata);
487 }
488 }
489 }
490 }
491 }
492 return result;
493 }
494
495 function addLinkUpdate(ldata, link) {
496 // add link event, but we already have the reverse link installed
497 ldata.fromTarget = link;
498 restyleLinkElement(ldata);
499 }
500
501 var allLinkTypes = 'direct indirect optical tunnel',
502 defaultLinkType = 'direct';
503
504 function restyleLinkElement(ldata) {
505 // this fn's job is to look at raw links and decide what svg classes
506 // need to be applied to the line element in the DOM
507 var el = ldata.el,
508 type = ldata.type(),
509 lw = ldata.linkWidth(),
510 online = ldata.online();
511
512 el.classed('link', true);
513 el.classed('inactive', !online);
514 el.classed(allLinkTypes, false);
515 if (type) {
516 el.classed(type, true);
517 }
518 el.transition()
519 .duration(1000)
520 .attr('stroke-width', linkScale(lw))
521 .attr('stroke', '#666'); // TODO: remove explicit stroke (use CSS)
522 }
Simon Hunt934c3ce2014-11-05 11:45:07 -0800523
Simon Hunt99c13842014-11-06 18:23:12 -0800524 // ==============================
525 // Event handlers for server-pushed events
526
Simon Huntbb282f52014-11-10 11:08:19 -0800527 function logicError(msg) {
528 // TODO, report logic error to server, via websock, so it can be logged
Simon Huntcb56cff2014-11-17 11:42:26 -0800529 //network.view.alert('Logic Error:\n\n' + msg);
Simon Huntfc274c92014-11-11 11:05:46 -0800530 console.warn(msg);
Simon Huntbb282f52014-11-10 11:08:19 -0800531 }
532
Simon Hunt99c13842014-11-06 18:23:12 -0800533 var eventDispatch = {
Simon Hunta5e89142014-11-14 07:00:33 -0800534 addInstance: addInstance,
Simon Hunt99c13842014-11-06 18:23:12 -0800535 addDevice: addDevice,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800536 addLink: addLink,
Simon Hunt56d51852014-11-09 13:03:35 -0800537 addHost: addHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800538
Simon Huntd72bc702014-11-13 18:38:04 -0800539 updateInstance: stillToImplement,
Simon Huntbb282f52014-11-10 11:08:19 -0800540 updateDevice: updateDevice,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800541 updateLink: updateLink,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800542 updateHost: updateHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800543
Simon Huntd72bc702014-11-13 18:38:04 -0800544 removeInstance: stillToImplement,
Simon Huntbb282f52014-11-10 11:08:19 -0800545 removeDevice: stillToImplement,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800546 removeLink: removeLink,
Simon Hunt44031102014-11-11 13:20:36 -0800547 removeHost: removeHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800548
Simon Hunt61d04042014-11-11 17:27:16 -0800549 showDetails: showDetails,
Simon Huntb53e0682014-11-12 13:32:01 -0800550 showPath: showPath,
551 showTraffic: showTraffic
Simon Hunt99c13842014-11-06 18:23:12 -0800552 };
553
Simon Hunta5e89142014-11-14 07:00:33 -0800554 function addInstance(data) {
555 evTrace(data);
556 var inst = data.payload,
557 id = inst.id;
558 if (onosInstances[id]) {
559 logicError('ONOS instance already added: ' + id);
560 return;
561 }
562 onosInstances[id] = inst;
563 onosOrder.push(inst);
564 updateInstances();
565 }
566
Simon Hunt99c13842014-11-06 18:23:12 -0800567 function addDevice(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800568 evTrace(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800569 var device = data.payload,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800570 nodeData = createDeviceNode(device);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800571 network.nodes.push(nodeData);
572 network.lookup[nodeData.id] = nodeData;
Simon Hunt99c13842014-11-06 18:23:12 -0800573 updateNodes();
574 network.force.start();
575 }
576
Simon Hunt99c13842014-11-06 18:23:12 -0800577 function addLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800578 evTrace(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800579 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800580 result = findLink(link, 'add'),
581 bad = result.badLogic,
582 ldata = result.ldata;
583
584 if (bad) {
585 logicError(bad + ': ' + link.id);
586 return;
587 }
588
589 if (ldata) {
590 // we already have a backing store link for src/dst nodes
591 addLinkUpdate(ldata, link);
592 return;
593 }
594
595 // no backing store link yet
596 ldata = createLink(link);
597 if (ldata) {
598 network.links.push(ldata);
599 network.lookup[ldata.key] = ldata;
Simon Hunt99c13842014-11-06 18:23:12 -0800600 updateLinks();
601 network.force.start();
602 }
603 }
604
Simon Hunt56d51852014-11-09 13:03:35 -0800605 function addHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800606 evTrace(data);
Simon Hunt56d51852014-11-09 13:03:35 -0800607 var host = data.payload,
608 node = createHostNode(host),
609 lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800610 network.nodes.push(node);
611 network.lookup[host.id] = node;
612 updateNodes();
613
614 lnk = createHostLink(host);
615 if (lnk) {
Simon Hunt44031102014-11-11 13:20:36 -0800616 node.linkData = lnk; // cache ref on its host
Simon Hunt56d51852014-11-09 13:03:35 -0800617 network.links.push(lnk);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800618 network.lookup[host.ingress] = lnk;
619 network.lookup[host.egress] = lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800620 updateLinks();
621 }
622 network.force.start();
623 }
624
Simon Hunt44031102014-11-11 13:20:36 -0800625 // TODO: fold updateX(...) methods into one base method; remove duplication
Simon Huntbb282f52014-11-10 11:08:19 -0800626 function updateDevice(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800627 evTrace(data);
Simon Huntbb282f52014-11-10 11:08:19 -0800628 var device = data.payload,
629 id = device.id,
630 nodeData = network.lookup[id];
631 if (nodeData) {
632 $.extend(nodeData, device);
633 updateDeviceState(nodeData);
634 } else {
635 logicError('updateDevice lookup fail. ID = "' + id + '"');
636 }
637 }
638
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800639 function updateLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800640 evTrace(data);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800641 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800642 result = findLink(link, 'update'),
643 bad = result.badLogic;
644 if (bad) {
645 logicError(bad + ': ' + link.id);
646 return;
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800647 }
Simon Hunt8257f4c2014-11-16 19:34:54 -0800648 result.updateWith(link);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800649 }
650
Simon Hunt7cd48f32014-11-09 23:42:50 -0800651 function updateHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800652 evTrace(data);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800653 var host = data.payload,
Simon Huntbb282f52014-11-10 11:08:19 -0800654 id = host.id,
655 hostData = network.lookup[id];
656 if (hostData) {
657 $.extend(hostData, host);
658 updateHostState(hostData);
659 } else {
660 logicError('updateHost lookup fail. ID = "' + id + '"');
661 }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800662 }
663
Simon Hunt44031102014-11-11 13:20:36 -0800664 // TODO: fold removeX(...) methods into base method - remove dup code
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800665 function removeLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800666 evTrace(data);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800667 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800668 result = findLink(link, 'remove'),
669 bad = result.badLogic;
670 if (bad) {
671 logicError(bad + ': ' + link.id);
672 return;
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800673 }
Simon Hunt8257f4c2014-11-16 19:34:54 -0800674 result.removeRawLink();
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800675 }
676
Simon Hunt44031102014-11-11 13:20:36 -0800677 function removeHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800678 evTrace(data);
Simon Hunt44031102014-11-11 13:20:36 -0800679 var host = data.payload,
680 id = host.id,
681 hostData = network.lookup[id];
682 if (hostData) {
683 removeHostElement(hostData);
684 } else {
685 logicError('removeHost lookup fail. ID = "' + id + '"');
686 }
687 }
688
Simon Hunt61d04042014-11-11 17:27:16 -0800689 function showDetails(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800690 evTrace(data);
Simon Hunt61d04042014-11-11 17:27:16 -0800691 populateDetails(data.payload);
692 detailPane.show();
693 }
694
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800695 function showPath(data) {
Simon Huntd72bc702014-11-13 18:38:04 -0800696 // TODO: review - making sure we are handling the payload correctly.
Simon Hunta5e89142014-11-14 07:00:33 -0800697 evTrace(data);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800698 var links = data.payload.links,
699 s = [ data.event + "\n" + links.length ];
700 links.forEach(function (d, i) {
701 s.push(d);
702 });
703 network.view.alert(s.join('\n'));
704
705 links.forEach(function (d, i) {
706 var link = network.lookup[d];
707 if (link) {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800708 link.el.classed('showPath', true);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800709 }
710 });
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800711 }
712
Simon Huntb53e0682014-11-12 13:32:01 -0800713 function showTraffic(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800714 evTrace(data);
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800715 var paths = data.payload.paths;
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800716
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800717 // Revert any links hilighted previously.
Simon Hunta255a2c2014-11-13 22:29:35 -0800718 link.classed('primary secondary animated optical', false);
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800719
720 // Now hilight all links in the paths payload.
Simon Hunta255a2c2014-11-13 22:29:35 -0800721 paths.forEach(function (p) {
722 var cls = p.class;
723 p.links.forEach(function (id) {
724 var lnk = network.lookup[id];
725 if (lnk) {
726 lnk.el.classed(cls, true);
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800727 }
728 });
729 });
Simon Huntb53e0682014-11-12 13:32:01 -0800730 }
731
Simon Hunt56d51852014-11-09 13:03:35 -0800732 // ...............................
733
734 function stillToImplement(data) {
735 var p = data.payload;
736 note(data.event, p.id);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800737 network.view.alert('Not yet implemented: "' + data.event + '"');
Simon Hunt56d51852014-11-09 13:03:35 -0800738 }
Simon Hunt99c13842014-11-06 18:23:12 -0800739
740 function unknownEvent(data) {
Simon Hunt50128c02014-11-08 13:36:15 -0800741 network.view.alert('Unknown event type: "' + data.event + '"');
Simon Hunt99c13842014-11-06 18:23:12 -0800742 }
743
744 function handleServerEvent(data) {
745 var fn = eventDispatch[data.event] || unknownEvent;
746 fn(data);
747 }
748
749 // ==============================
Simon Hunt61d04042014-11-11 17:27:16 -0800750 // Out-going messages...
751
Simon Huntb53e0682014-11-12 13:32:01 -0800752 function userFeedback(msg) {
753 // for now, use the alert pane as is. Maybe different alert style in
754 // the future (centered on view; dismiss button?)
755 network.view.alert(msg);
756 }
757
758 function nSel() {
759 return selectOrder.length;
760 }
Simon Hunt61d04042014-11-11 17:27:16 -0800761 function getSel(idx) {
762 return selections[selectOrder[idx]];
763 }
Simon Huntb53e0682014-11-12 13:32:01 -0800764 function getSelId(idx) {
765 return getSel(idx).obj.id;
766 }
767 function allSelectionsClass(cls) {
768 for (var i=0, n=nSel(); i<n; i++) {
769 if (getSel(i).obj.class !== cls) {
770 return false;
771 }
772 }
773 return true;
774 }
Simon Hunt61d04042014-11-11 17:27:16 -0800775
Simon Hunt61d04042014-11-11 17:27:16 -0800776 // request details for the selected element
Simon Huntd72bc702014-11-13 18:38:04 -0800777 // invoked from selection of a single node.
Simon Hunt61d04042014-11-11 17:27:16 -0800778 function requestDetails() {
779 var data = getSel(0).obj,
780 payload = {
781 id: data.id,
782 class: data.class
783 };
784 sendMessage('requestDetails', payload);
785 }
786
Simon Huntd72bc702014-11-13 18:38:04 -0800787 function addIntentAction() {
788 sendMessage('addHostIntent', {
789 one: getSelId(0),
Thomas Vachuska82f2c622014-11-17 12:23:18 -0800790 two: getSelId(1),
791 ids: [ getSelId(0), getSelId(1) ]
Simon Huntd72bc702014-11-13 18:38:04 -0800792 });
793 }
794
795 function showTrafficAction() {
796 // if nothing is hovered over, and nothing selected, send cancel request
797 if (!hovered && nSel() === 0) {
798 sendMessage('cancelTraffic', {});
799 return;
800 }
801
802 // NOTE: hover is only populated if "show traffic on hover" is
803 // toggled on, and the item hovered is a host...
804 var hoverId = (trafficHover() && hovered && hovered.class === 'host')
805 ? hovered.id : '';
806 sendMessage('requestTraffic', {
807 ids: selectOrder,
808 hover: hoverId
809 });
810 }
811
812
Simon Hunt61d04042014-11-11 17:27:16 -0800813 // ==============================
Simon Hunta5e89142014-11-14 07:00:33 -0800814 // onos instance panel functions
815
816 function updateInstances() {
817 var onoses = oiBox.el.selectAll('.onosInst')
818 .data(onosOrder, function (d) { return d.id; });
819
820 // operate on existing onoses if necessary
821
822 var entering = onoses.enter()
823 .append('div')
824 .attr('class', 'onosInst')
825 .classed('online', function (d) { return d.online; })
Simon Hunt9c15eca2014-11-15 18:37:59 -0800826 .on('click', clickInst);
827
828 entering.each(function (d, i) {
829 var el = d3.select(this),
830 img;
831
832 $('<img src="img/host.png">').appendTo(el);
833 img = el.select('img')
834 .attr({
835 width: 40,
836 top: -10,
837 left: -10
838 })
839 .style({
840 });
841
842 $('<div>').attr('class', 'onosTitle').text(d.id).appendTo(el);
843
844 // is the UI attached to this instance?
845 // TODO: need uiAttached boolean in instance data
846 //if (d.uiAttached) {
847 if (i === 0) {
848 $('<img src="img/ui.png">').attr('class','ui').appendTo(el);
849 }
850 });
Simon Hunta5e89142014-11-14 07:00:33 -0800851
852 // operate on existing + new onoses here
853
854 // the departed...
855 var exiting = onoses.exit()
856 .transition()
857 .style('opacity', 0)
858 .remove();
859 }
860
Simon Hunt9462e8c2014-11-14 17:28:09 -0800861 function clickInst(d) {
862 var el = d3.select(this),
863 aff = el.classed('affinity');
864 if (!aff) {
865 setAffinity(el, d);
866 } else {
867 cancelAffinity();
868 }
869 }
870
871 function setAffinity(el, d) {
872 d3.selectAll('.onosInst')
873 .classed('mastership', true)
874 .classed('affinity', false);
875 el.classed('affinity', true);
876
877 suppressLayers(true);
878 node.each(function (n) {
879 if (n.master === d.id) {
880 n.el.classed('suppressed', false);
881 }
882 });
883 oiShowMaster = true;
884 }
885
886 function cancelAffinity() {
887 d3.selectAll('.onosInst')
888 .classed('mastership affinity', false);
889 restoreLayerState();
890 oiShowMaster = false;
891 }
892
Simon Hunta5e89142014-11-14 07:00:33 -0800893 // ==============================
Simon Hunt99c13842014-11-06 18:23:12 -0800894 // force layout modification functions
895
896 function translate(x, y) {
897 return 'translate(' + x + ',' + y + ')';
898 }
899
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800900 function missMsg(what, id) {
901 return '\n[' + what + '] "' + id + '" missing ';
902 }
903
904 function linkEndPoints(srcId, dstId) {
905 var srcNode = network.lookup[srcId],
906 dstNode = network.lookup[dstId],
907 sMiss = !srcNode ? missMsg('src', srcId) : '',
908 dMiss = !dstNode ? missMsg('dst', dstId) : '';
909
910 if (sMiss || dMiss) {
911 logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
912 return null;
913 }
914 return {
915 source: srcNode,
916 target: dstNode,
917 x1: srcNode.x,
918 y1: srcNode.y,
919 x2: dstNode.x,
920 y2: dstNode.y
921 };
922 }
923
Simon Hunt56d51852014-11-09 13:03:35 -0800924 function createHostLink(host) {
925 var src = host.id,
926 dst = host.cp.device,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800927 id = host.ingress,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800928 lnk = linkEndPoints(src, dst);
Simon Hunt56d51852014-11-09 13:03:35 -0800929
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800930 if (!lnk) {
Simon Hunt56d51852014-11-09 13:03:35 -0800931 return null;
932 }
933
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800934 // Synthesize link ...
935 $.extend(lnk, {
Simon Hunt8257f4c2014-11-16 19:34:54 -0800936 key: id,
Simon Hunt56d51852014-11-09 13:03:35 -0800937 class: 'link',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800938
939 type: function () { return 'hostLink'; },
940 // TODO: ideally, we should see if our edge switch is online...
941 online: function () { return true; },
942 linkWidth: function () { return 1; }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800943 });
Simon Hunt99c13842014-11-06 18:23:12 -0800944 return lnk;
945 }
946
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800947 function createLink(link) {
948 var lnk = linkEndPoints(link.src, link.dst),
949 type = link.type;
950
951 if (!lnk) {
952 return null;
953 }
954
Simon Hunt8257f4c2014-11-16 19:34:54 -0800955 $.extend(lnk, {
956 key: link.id,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800957 class: 'link',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800958 fromSource: link,
959
960 // functions to aggregate dual link state
961 type: function () {
962 var s = lnk.fromSource,
963 t = lnk.fromTarget;
964 return (s && s.type) || (t && t.type) || defaultLinkType;
965 },
966 online: function () {
967 var s = lnk.fromSource,
968 t = lnk.fromTarget;
969 return (s && s.online) || (t && t.online);
970 },
971 linkWidth: function () {
972 var s = lnk.fromSource,
973 t = lnk.fromTarget,
974 ws = (s && s.linkWidth) || 0,
975 wt = (t && t.linkWidth) || 0;
976 return Math.max(ws, wt);
977 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800978 });
979 return lnk;
Simon Hunt1a9eff92014-11-07 11:06:34 -0800980 }
981
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800982 var widthRatio = 1.4,
983 linkScale = d3.scale.linear()
984 .domain([1, 12])
985 .range([widthRatio, 12 * widthRatio])
986 .clamp(true);
987
Simon Hunt99c13842014-11-06 18:23:12 -0800988 function updateLinks() {
989 link = linkG.selectAll('.link')
Simon Hunt8257f4c2014-11-16 19:34:54 -0800990 .data(network.links, function (d) { return d.key; });
Simon Hunt99c13842014-11-06 18:23:12 -0800991
992 // operate on existing links, if necessary
993 // link .foo() .bar() ...
994
995 // operate on entering links:
996 var entering = link.enter()
997 .append('line')
998 .attr({
Simon Hunt99c13842014-11-06 18:23:12 -0800999 x1: function (d) { return d.x1; },
1000 y1: function (d) { return d.y1; },
1001 x2: function (d) { return d.x2; },
1002 y2: function (d) { return d.y2; },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001003 stroke: config.topo.linkInColor,
1004 'stroke-width': config.topo.linkInWidth
Simon Hunt99c13842014-11-06 18:23:12 -08001005 });
1006
1007 // augment links
Simon Hunt7cd48f32014-11-09 23:42:50 -08001008 entering.each(function (d) {
1009 var link = d3.select(this);
1010 // provide ref to element selection from backing data....
1011 d.el = link;
Simon Hunt8257f4c2014-11-16 19:34:54 -08001012 restyleLinkElement(d);
Simon Hunt99c13842014-11-06 18:23:12 -08001013
Simon Hunt7cd48f32014-11-09 23:42:50 -08001014 // TODO: add src/dst port labels etc.
1015 });
Thomas Vachuska4830d392014-11-09 17:09:56 -08001016
1017 // operate on both existing and new links, if necessary
1018 //link .foo() .bar() ...
1019
1020 // operate on exiting links:
Thomas Vachuska4830d392014-11-09 17:09:56 -08001021 link.exit()
Thomas Vachuska4830d392014-11-09 17:09:56 -08001022 .attr({
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001023 'stroke-dasharray': '3, 3'
Thomas Vachuska4830d392014-11-09 17:09:56 -08001024 })
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001025 .style('opacity', 0.4)
1026 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001027 .duration(1500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001028 .attr({
1029 'stroke-dasharray': '3, 12'
1030 })
1031 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001032 .duration(500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001033 .style('opacity', 0.0)
Thomas Vachuska4830d392014-11-09 17:09:56 -08001034 .remove();
Simon Hunt99c13842014-11-06 18:23:12 -08001035 }
1036
1037 function createDeviceNode(device) {
1038 // start with the object as is
1039 var node = device,
Simon Huntbb282f52014-11-10 11:08:19 -08001040 type = device.type,
1041 svgCls = type ? 'node device ' + type : 'node device';
Simon Hunt99c13842014-11-06 18:23:12 -08001042
1043 // Augment as needed...
1044 node.class = 'device';
Simon Huntbb282f52014-11-10 11:08:19 -08001045 node.svgClass = device.online ? svgCls + ' online' : svgCls;
Simon Hunt99c13842014-11-06 18:23:12 -08001046 positionNode(node);
1047
1048 // cache label array length
1049 network.deviceLabelCount = device.labels.length;
Simon Hunt99c13842014-11-06 18:23:12 -08001050 return node;
1051 }
1052
Simon Hunt56d51852014-11-09 13:03:35 -08001053 function createHostNode(host) {
1054 // start with the object as is
1055 var node = host;
1056
1057 // Augment as needed...
1058 node.class = 'host';
Simon Hunt7cd48f32014-11-09 23:42:50 -08001059 if (!node.type) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001060 node.type = 'endstation';
1061 }
Simon Hunt56d51852014-11-09 13:03:35 -08001062 node.svgClass = 'node host';
Simon Hunt56d51852014-11-09 13:03:35 -08001063 positionNode(node);
1064
1065 // cache label array length
1066 network.hostLabelCount = host.labels.length;
Simon Hunt56d51852014-11-09 13:03:35 -08001067 return node;
1068 }
1069
Simon Hunt99c13842014-11-06 18:23:12 -08001070 function positionNode(node) {
1071 var meta = node.metaUi,
Simon Huntac9e24f2014-11-12 10:12:21 -08001072 x = meta && meta.x,
1073 y = meta && meta.y,
1074 xy;
Simon Hunt99c13842014-11-06 18:23:12 -08001075
Simon Huntac9e24f2014-11-12 10:12:21 -08001076 // If we have [x,y] already, use that...
Simon Hunt99c13842014-11-06 18:23:12 -08001077 if (x && y) {
1078 node.fixed = true;
Simon Huntac9e24f2014-11-12 10:12:21 -08001079 node.x = x;
1080 node.y = y;
1081 return;
Simon Hunt99c13842014-11-06 18:23:12 -08001082 }
Simon Huntac9e24f2014-11-12 10:12:21 -08001083
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001084 var location = node.location;
1085 if (location && location.type === 'latlng') {
1086 var coord = geoMapProjection([location.lng, location.lat]);
1087 node.fixed = true;
1088 node.x = coord[0];
1089 node.y = coord[1];
1090 return;
1091 }
1092
Simon Huntac9e24f2014-11-12 10:12:21 -08001093 // Note: Placing incoming unpinned nodes at exactly the same point
1094 // (center of the view) causes them to explode outwards when
1095 // the force layout kicks in. So, we spread them out a bit
1096 // initially, to provide a more serene layout convergence.
1097 // Additionally, if the node is a host, we place it near
1098 // the device it is connected to.
1099
1100 function spread(s) {
1101 return Math.floor((Math.random() * s) - s/2);
1102 }
1103
1104 function randDim(dim) {
1105 return dim / 2 + spread(dim * 0.7071);
1106 }
1107
1108 function rand() {
1109 return {
1110 x: randDim(network.view.width()),
1111 y: randDim(network.view.height())
1112 };
1113 }
1114
1115 function near(node) {
1116 var min = 12,
1117 dx = spread(12),
1118 dy = spread(12);
1119 return {
1120 x: node.x + min + dx,
1121 y: node.y + min + dy
1122 };
1123 }
1124
1125 function getDevice(cp) {
1126 var d = network.lookup[cp.device];
1127 return d || rand();
1128 }
1129
1130 xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
1131 $.extend(node, xy);
Simon Hunt99c13842014-11-06 18:23:12 -08001132 }
1133
Simon Hunt99c13842014-11-06 18:23:12 -08001134 function iconUrl(d) {
1135 return 'img/' + d.type + '.png';
1136 }
1137
1138 // returns the newly computed bounding box of the rectangle
1139 function adjustRectToFitText(n) {
1140 var text = n.select('text'),
1141 box = text.node().getBBox(),
1142 lab = config.labels;
1143
1144 text.attr('text-anchor', 'middle')
1145 .attr('y', '-0.8em')
1146 .attr('x', lab.imgPad/2);
1147
1148 // translate the bbox so that it is centered on [x,y]
1149 box.x = -box.width / 2;
1150 box.y = -box.height / 2;
1151
1152 // add padding
1153 box.x -= (lab.padLR + lab.imgPad/2);
1154 box.width += lab.padLR * 2 + lab.imgPad;
1155 box.y -= lab.padTB;
1156 box.height += lab.padTB * 2;
1157
1158 return box;
1159 }
1160
Simon Hunt1a9eff92014-11-07 11:06:34 -08001161 function mkSvgClass(d) {
1162 return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
1163 }
1164
Simon Hunt7cd48f32014-11-09 23:42:50 -08001165 function hostLabel(d) {
1166 var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
1167 return d.labels[idx];
1168 }
1169 function deviceLabel(d) {
1170 var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
1171 return d.labels[idx];
1172 }
1173 function niceLabel(label) {
1174 return (label && label.trim()) ? label : '.';
1175 }
1176
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001177 function updateDeviceLabel(d) {
1178 var label = niceLabel(deviceLabel(d)),
1179 node = d.el,
1180 box;
1181
1182 node.select('text')
1183 .text(label)
1184 .style('opacity', 0)
1185 .transition()
1186 .style('opacity', 1);
1187
1188 box = adjustRectToFitText(node);
1189
1190 node.select('rect')
1191 .transition()
1192 .attr(box);
1193
1194 node.select('image')
1195 .transition()
1196 .attr('x', box.x + config.icons.xoff)
1197 .attr('y', box.y + config.icons.yoff);
1198 }
1199
1200 function updateHostLabel(d) {
1201 var label = hostLabel(d),
1202 host = d.el;
1203
1204 host.select('text').text(label);
1205 }
1206
Simon Huntbb282f52014-11-10 11:08:19 -08001207 function updateDeviceState(nodeData) {
1208 nodeData.el.classed('online', nodeData.online);
1209 updateDeviceLabel(nodeData);
1210 // TODO: review what else might need to be updated
1211 }
1212
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001213 function updateLinkState(linkData) {
1214 updateLinkWidth(linkData);
Thomas Vachuskabadb93f2014-11-15 23:51:17 -08001215 linkData.el.classed('inactive', !linkData.online);
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001216 // TODO: review what else might need to be updated
1217 // update label, if showing
1218 }
1219
Simon Huntbb282f52014-11-10 11:08:19 -08001220 function updateHostState(hostData) {
1221 updateHostLabel(hostData);
1222 // TODO: review what else might need to be updated
1223 }
1224
Simon Hunt6ac93f32014-11-13 12:17:27 -08001225 function nodeMouseOver(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001226 hovered = d;
Simon Huntd72bc702014-11-13 18:38:04 -08001227 if (trafficHover() && d.class === 'host') {
1228 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001229 }
1230 }
1231
1232 function nodeMouseOut(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001233 hovered = null;
Simon Huntd72bc702014-11-13 18:38:04 -08001234 if (trafficHover() && d.class === 'host') {
1235 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001236 }
1237 }
Simon Huntbb282f52014-11-10 11:08:19 -08001238
Simon Hunt99c13842014-11-06 18:23:12 -08001239 function updateNodes() {
1240 node = nodeG.selectAll('.node')
1241 .data(network.nodes, function (d) { return d.id; });
1242
1243 // operate on existing nodes, if necessary
Simon Hunt7cd48f32014-11-09 23:42:50 -08001244 // update host labels
Simon Hunt99c13842014-11-06 18:23:12 -08001245 //node .foo() .bar() ...
1246
1247 // operate on entering nodes:
1248 var entering = node.enter()
1249 .append('g')
1250 .attr({
1251 id: function (d) { return safeId(d.id); },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001252 class: mkSvgClass,
Simon Hunt99c13842014-11-06 18:23:12 -08001253 transform: function (d) { return translate(d.x, d.y); },
1254 opacity: 0
1255 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001256 .call(network.drag)
Simon Hunt6ac93f32014-11-13 12:17:27 -08001257 .on('mouseover', nodeMouseOver)
1258 .on('mouseout', nodeMouseOut)
Simon Hunt99c13842014-11-06 18:23:12 -08001259 .transition()
1260 .attr('opacity', 1);
1261
1262 // augment device nodes...
1263 entering.filter('.device').each(function (d) {
1264 var node = d3.select(this),
1265 icon = iconUrl(d),
Simon Hunt7cd48f32014-11-09 23:42:50 -08001266 label = niceLabel(deviceLabel(d)),
Simon Hunt99c13842014-11-06 18:23:12 -08001267 box;
1268
Simon Hunt7cd48f32014-11-09 23:42:50 -08001269 // provide ref to element from backing data....
1270 d.el = node;
1271
Simon Hunt99c13842014-11-06 18:23:12 -08001272 node.append('rect')
1273 .attr({
1274 'rx': 5,
1275 'ry': 5
1276 });
1277
1278 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001279 .text(label)
Simon Hunt99c13842014-11-06 18:23:12 -08001280 .attr('dy', '1.1em');
1281
1282 box = adjustRectToFitText(node);
1283
1284 node.select('rect')
1285 .attr(box);
1286
1287 if (icon) {
1288 var cfg = config.icons;
1289 node.append('svg:image')
1290 .attr({
1291 x: box.x + config.icons.xoff,
1292 y: box.y + config.icons.yoff,
1293 width: cfg.w,
1294 height: cfg.h,
1295 'xlink:href': icon
1296 });
1297 }
1298
1299 // debug function to show the modelled x,y coordinates of nodes...
1300 if (debug('showNodeXY')) {
1301 node.select('rect').attr('fill-opacity', 0.5);
1302 node.append('circle')
1303 .attr({
1304 class: 'debug',
1305 cx: 0,
1306 cy: 0,
1307 r: '3px'
1308 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001309 }
1310 });
Simon Hunt934c3ce2014-11-05 11:45:07 -08001311
Simon Hunt56d51852014-11-09 13:03:35 -08001312 // augment host nodes...
1313 entering.filter('.host').each(function (d) {
1314 var node = d3.select(this),
Simon Hunt56d51852014-11-09 13:03:35 -08001315 box;
1316
Simon Hunt7cd48f32014-11-09 23:42:50 -08001317 // provide ref to element from backing data....
1318 d.el = node;
1319
Simon Hunt56d51852014-11-09 13:03:35 -08001320 node.append('circle')
1321 .attr('r', 8); // TODO: define host circle radius
1322
Simon Hunt56d51852014-11-09 13:03:35 -08001323 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001324 .text(hostLabel)
1325 .attr('dy', '1.3em')
1326 .attr('text-anchor', 'middle');
Simon Hunt56d51852014-11-09 13:03:35 -08001327
1328 // debug function to show the modelled x,y coordinates of nodes...
1329 if (debug('showNodeXY')) {
1330 node.select('circle').attr('fill-opacity', 0.5);
1331 node.append('circle')
1332 .attr({
1333 class: 'debug',
1334 cx: 0,
1335 cy: 0,
1336 r: '3px'
1337 });
1338 }
1339 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001340
Simon Hunt99c13842014-11-06 18:23:12 -08001341 // operate on both existing and new nodes, if necessary
1342 //node .foo() .bar() ...
Simon Huntc7ee0662014-11-05 16:44:37 -08001343
Simon Hunt99c13842014-11-06 18:23:12 -08001344 // operate on exiting nodes:
Simon Huntea80eb42014-11-11 13:46:57 -08001345 // Note that the node is removed after 2 seconds.
1346 // Sub element animations should be shorter than 2 seconds.
1347 var exiting = node.exit()
Simon Hunt44031102014-11-11 13:20:36 -08001348 .transition()
1349 .duration(2000)
Simon Huntea80eb42014-11-11 13:46:57 -08001350 .style('opacity', 0)
Simon Hunt99c13842014-11-06 18:23:12 -08001351 .remove();
Simon Huntea80eb42014-11-11 13:46:57 -08001352
1353 // host node exits....
1354 exiting.filter('.host').each(function (d) {
1355 var node = d3.select(this);
1356
1357 node.select('text')
1358 .style('opacity', 0.5)
1359 .transition()
1360 .duration(1000)
1361 .style('opacity', 0);
1362 // note, leave <g>.remove to remove this element
1363
1364 node.select('circle')
1365 .style('stroke-fill', '#555')
1366 .style('fill', '#888')
1367 .style('opacity', 0.5)
1368 .transition()
1369 .duration(1500)
1370 .attr('r', 0);
1371 // note, leave <g>.remove to remove this element
1372
1373 });
1374
1375 // TODO: device node exits
Simon Huntc7ee0662014-11-05 16:44:37 -08001376 }
1377
Simon Hunt8257f4c2014-11-16 19:34:54 -08001378 function find(key, array) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001379 for (var idx = 0, n = array.length; idx < n; idx++) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001380 if (array[idx].key === key) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001381 return idx;
1382 }
1383 }
1384 return -1;
1385 }
1386
1387 function removeLinkElement(linkData) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001388 var idx = find(linkData.key, network.links),
1389 removed;
1390 if (idx >=0) {
1391 // remove from links array
1392 removed = network.links.splice(idx, 1);
1393 // remove from lookup cache
1394 delete network.lookup[removed[0].key];
1395 updateLinks();
1396 network.force.resume();
1397 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001398 }
Simon Huntc7ee0662014-11-05 16:44:37 -08001399
Simon Hunt44031102014-11-11 13:20:36 -08001400 function removeHostElement(hostData) {
1401 // first, remove associated hostLink...
1402 removeLinkElement(hostData.linkData);
1403
1404 // remove from lookup cache
1405 delete network.lookup[hostData.id];
1406 // remove from nodes array
1407 var idx = find(hostData.id, network.nodes);
1408 network.nodes.splice(idx, 1);
1409 // remove from SVG
1410 updateNodes();
1411 network.force.resume();
1412 }
1413
1414
Simon Huntc7ee0662014-11-05 16:44:37 -08001415 function tick() {
1416 node.attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001417 transform: function (d) { return translate(d.x, d.y); }
Simon Huntc7ee0662014-11-05 16:44:37 -08001418 });
1419
1420 link.attr({
1421 x1: function (d) { return d.source.x; },
1422 y1: function (d) { return d.source.y; },
1423 x2: function (d) { return d.target.x; },
1424 y2: function (d) { return d.target.y; }
1425 });
1426 }
Simon Hunt934c3ce2014-11-05 11:45:07 -08001427
1428 // ==============================
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001429 // Web-Socket for live data
1430
1431 function webSockUrl() {
1432 return document.location.toString()
1433 .replace(/\#.*/, '')
1434 .replace('http://', 'ws://')
1435 .replace('https://', 'wss://')
1436 .replace('index2.html', config.webSockUrl);
1437 }
1438
1439 webSock = {
1440 ws : null,
1441
1442 connect : function() {
1443 webSock.ws = new WebSocket(webSockUrl());
1444
1445 webSock.ws.onopen = function() {
Simon Hunt0c6d4192014-11-12 12:07:10 -08001446 noWebSock(false);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001447 };
1448
1449 webSock.ws.onmessage = function(m) {
1450 if (m.data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001451 wsTraceRx(m.data);
Thomas Vachuskad472c6e2014-11-07 19:11:05 -08001452 handleServerEvent(JSON.parse(m.data));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001453 }
1454 };
1455
1456 webSock.ws.onclose = function(m) {
1457 webSock.ws = null;
Simon Hunt0c6d4192014-11-12 12:07:10 -08001458 noWebSock(true);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001459 };
1460 },
1461
1462 send : function(text) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001463 if (text != null) {
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001464 webSock._send(text);
1465 }
1466 },
1467
1468 _send : function(message) {
1469 if (webSock.ws) {
1470 webSock.ws.send(message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001471 } else if (config.useLiveData) {
Simon Hunt56d51852014-11-09 13:03:35 -08001472 network.view.alert('no web socket open\n\n' + message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001473 } else {
1474 console.log('WS Send: ' + JSON.stringify(message));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001475 }
1476 }
1477
1478 };
1479
Simon Hunt0c6d4192014-11-12 12:07:10 -08001480 function noWebSock(b) {
1481 mask.style('display',b ? 'block' : 'none');
1482 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001483
Simon Hunt61d04042014-11-11 17:27:16 -08001484 // TODO: use cache of pending messages (key = sid) to reconcile responses
1485
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001486 function sendMessage(evType, payload) {
1487 var toSend = {
Simon Huntbb282f52014-11-10 11:08:19 -08001488 event: evType,
1489 sid: ++sid,
1490 payload: payload
1491 },
1492 asText = JSON.stringify(toSend);
1493 wsTraceTx(asText);
1494 webSock.send(asText);
1495 }
1496
1497 function wsTraceTx(msg) {
1498 wsTrace('tx', msg);
1499 }
1500 function wsTraceRx(msg) {
1501 wsTrace('rx', msg);
1502 }
1503 function wsTrace(rxtx, msg) {
Simon Huntbb282f52014-11-10 11:08:19 -08001504 console.log('[' + rxtx + '] ' + msg);
1505 // TODO: integrate with trace view
1506 //if (trace) {
1507 // trace.output(rxtx, msg);
1508 //}
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001509 }
1510
1511
1512 // ==============================
1513 // Selection stuff
1514
1515 function selectObject(obj, el) {
1516 var n,
Simon Hunt01095ff2014-11-13 16:37:29 -08001517 srcEv = d3.event.sourceEvent,
1518 meta = srcEv.metaKey,
1519 shift = srcEv.shiftKey;
1520
Simon Huntdeab4322014-11-13 18:49:07 -08001521 if ((panZoom() && !meta) || (!panZoom() && meta)) {
Simon Hunt01095ff2014-11-13 16:37:29 -08001522 return;
1523 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001524
1525 if (el) {
1526 n = d3.select(el);
1527 } else {
1528 node.each(function(d) {
1529 if (d == obj) {
1530 n = d3.select(el = this);
1531 }
1532 });
1533 }
1534 if (!n) return;
1535
Simon Hunt01095ff2014-11-13 16:37:29 -08001536 if (shift && n.classed('selected')) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001537 deselectObject(obj.id);
Simon Hunt61d04042014-11-11 17:27:16 -08001538 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001539 return;
1540 }
1541
Simon Hunt01095ff2014-11-13 16:37:29 -08001542 if (!shift) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001543 deselectAll();
1544 }
1545
Simon Huntc31d5692014-11-12 13:27:18 -08001546 selections[obj.id] = { obj: obj, el: el };
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001547 selectOrder.push(obj.id);
1548
1549 n.classed('selected', true);
Simon Hunt61d04042014-11-11 17:27:16 -08001550 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001551 }
1552
1553 function deselectObject(id) {
Simon Huntc31d5692014-11-12 13:27:18 -08001554 var obj = selections[id],
1555 idx;
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001556 if (obj) {
1557 d3.select(obj.el).classed('selected', false);
Simon Hunt61d04042014-11-11 17:27:16 -08001558 delete selections[id];
Simon Huntc31d5692014-11-12 13:27:18 -08001559 idx = $.inArray(id, selectOrder);
1560 if (idx >= 0) {
1561 selectOrder.splice(idx, 1);
1562 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001563 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001564 }
1565
1566 function deselectAll() {
1567 // deselect all nodes in the network...
1568 node.classed('selected', false);
1569 selections = {};
1570 selectOrder = [];
Simon Hunt61d04042014-11-11 17:27:16 -08001571 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001572 }
1573
Simon Hunt61d04042014-11-11 17:27:16 -08001574 // update the state of the detail pane, based on current selections
1575 function updateDetailPane() {
1576 var nSel = selectOrder.length;
1577 if (!nSel) {
1578 detailPane.hide();
Simon Huntd72bc702014-11-13 18:38:04 -08001579 showTrafficAction(); // sends cancelTraffic event
Simon Hunt61d04042014-11-11 17:27:16 -08001580 } else if (nSel === 1) {
1581 singleSelect();
1582 } else {
1583 multiSelect();
1584 }
1585 }
1586
1587 function singleSelect() {
1588 requestDetails();
Simon Huntb53e0682014-11-12 13:32:01 -08001589 // NOTE: detail pane will be shown from showDetails event callback
Simon Hunt61d04042014-11-11 17:27:16 -08001590 }
1591
1592 function multiSelect() {
Simon Huntb53e0682014-11-12 13:32:01 -08001593 populateMultiSelect();
Simon Huntb53e0682014-11-12 13:32:01 -08001594 }
1595
1596 function addSep(tbody) {
1597 var tr = tbody.append('tr');
1598 $('<hr>').appendTo(tr.append('td').attr('colspan', 2));
1599 }
1600
1601 function addProp(tbody, label, value) {
1602 var tr = tbody.append('tr');
1603
1604 tr.append('td')
1605 .attr('class', 'label')
1606 .text(label + ' :');
1607
1608 tr.append('td')
1609 .attr('class', 'value')
1610 .text(value);
1611 }
1612
1613 function populateMultiSelect() {
1614 detailPane.empty();
1615
1616 var title = detailPane.append("h2"),
1617 table = detailPane.append("table"),
1618 tbody = table.append("tbody");
1619
1620 title.text('Multi-Select...');
1621
1622 selectOrder.forEach(function (d, i) {
1623 addProp(tbody, i+1, d);
1624 });
Simon Huntd72bc702014-11-13 18:38:04 -08001625
1626 addMultiSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001627 }
1628
1629 function populateDetails(data) {
1630 detailPane.empty();
1631
1632 var title = detailPane.append("h2"),
1633 table = detailPane.append("table"),
1634 tbody = table.append("tbody");
1635
1636 $('<img src="img/' + data.type + '.png">').appendTo(title);
1637 $('<span>').attr('class', 'icon').text(data.id).appendTo(title);
1638
1639 data.propOrder.forEach(function(p) {
1640 if (p === '-') {
1641 addSep(tbody);
1642 } else {
1643 addProp(tbody, p, data.props[p]);
1644 }
1645 });
Simon Huntd72bc702014-11-13 18:38:04 -08001646
1647 addSingleSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001648 }
1649
Simon Huntd72bc702014-11-13 18:38:04 -08001650 function addSingleSelectActions() {
1651 detailPane.append('hr');
1652 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001653 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001654 }
1655
1656 function addMultiSelectActions() {
1657 detailPane.append('hr');
1658 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001659 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001660 // if exactly two hosts are selected, also want 'add host intent'
1661 if (nSel() === 2 && allSelectionsClass('host')) {
Simon Hunta5e89142014-11-14 07:00:33 -08001662 addAction(detailPane, 'Add Host Intent', addIntentAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001663 }
1664 }
1665
Simon Hunta5e89142014-11-14 07:00:33 -08001666 function addAction(panel, text, cb) {
1667 panel.append('div')
Simon Huntd72bc702014-11-13 18:38:04 -08001668 .classed('actionBtn', true)
1669 .text(text)
1670 .on('click', cb);
1671 }
1672
1673
Paul Greysonfcba0e82014-11-13 10:21:16 -08001674 function zoomPan(scale, translate) {
1675 zoomPanContainer.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
1676 // keep the map lines constant width while zooming
1677 bgImg.style("stroke-width", 2.0 / scale + "px");
1678 }
1679
1680 function resetZoomPan() {
1681 zoomPan(1, [0,0]);
1682 zoom.scale(1).translate([0,0]);
1683 }
1684
1685 function setupZoomPan() {
1686 function zoomed() {
Simon Huntdeab4322014-11-13 18:49:07 -08001687 if (!panZoom() ^ !d3.event.sourceEvent.metaKey) {
Paul Greysonfcba0e82014-11-13 10:21:16 -08001688 zoomPan(d3.event.scale, d3.event.translate);
1689 }
1690 }
1691
1692 zoom = d3.behavior.zoom()
1693 .translate([0, 0])
1694 .scale(1)
1695 .scaleExtent([1, 8])
1696 .on("zoom", zoomed);
1697
1698 svg.call(zoom);
1699 }
1700
Simon Hunt61d04042014-11-11 17:27:16 -08001701 // ==============================
1702 // Test harness code
Simon Hunt56d51852014-11-09 13:03:35 -08001703
1704 function prepareScenario(view, ctx, dbg) {
1705 var sc = scenario,
1706 urlSc = sc.evDir + ctx + sc.evScenario;
1707
1708 if (!ctx) {
1709 view.alert("No scenario specified (null ctx)");
1710 return;
1711 }
1712
1713 sc.view = view;
1714 sc.ctx = ctx;
1715 sc.debug = dbg;
1716 sc.evNumber = 0;
1717
1718 d3.json(urlSc, function(err, data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001719 var p = data && data.params || {},
1720 desc = data && data.description || null,
Simon Huntfc274c92014-11-11 11:05:46 -08001721 intro = data && data.title;
Simon Huntbb282f52014-11-10 11:08:19 -08001722
Simon Hunt56d51852014-11-09 13:03:35 -08001723 if (err) {
1724 view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
1725 } else {
1726 sc.params = p;
Simon Huntbb282f52014-11-10 11:08:19 -08001727 if (desc) {
1728 intro += '\n\n ' + desc.join('\n ');
1729 }
1730 view.alert(intro);
Simon Hunt56d51852014-11-09 13:03:35 -08001731 }
1732 });
1733
1734 }
1735
Simon Hunt01095ff2014-11-13 16:37:29 -08001736 // ==============================
1737 // Toggle Buttons in masthead
Simon Hunt0c6d4192014-11-12 12:07:10 -08001738
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001739 // TODO: toggle button (and other widgets in the masthead) should be provided
1740 // by the framework; not generated by the view.
1741
Simon Hunta5e89142014-11-14 07:00:33 -08001742 var showInstances,
1743 doPanZoom,
1744 showTrafficOnHover;
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001745
1746 function addButtonBar(view) {
1747 var bb = d3.select('#mast')
1748 .append('span').classed('right', true).attr('id', 'bb');
1749
Simon Hunta5e89142014-11-14 07:00:33 -08001750 function mkTogBtn(text, cb) {
1751 return bb.append('span')
1752 .classed('btn', true)
1753 .text(text)
1754 .on('click', cb);
1755 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001756
Simon Hunta5e89142014-11-14 07:00:33 -08001757 showInstances = mkTogBtn('Show Instances', toggleInst);
1758 doPanZoom = mkTogBtn('Pan/Zoom', togglePanZoom);
1759 showTrafficOnHover = mkTogBtn('Show traffic on hover', toggleTrafficHover);
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001760 }
1761
Simon Hunta5e89142014-11-14 07:00:33 -08001762 function instShown() {
1763 return showInstances.classed('active');
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001764 }
Simon Hunta5e89142014-11-14 07:00:33 -08001765 function toggleInst() {
1766 showInstances.classed('active', !instShown());
1767 if (instShown()) {
1768 oiBox.show();
1769 } else {
1770 oiBox.hide();
1771 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001772 }
1773
Simon Huntdeab4322014-11-13 18:49:07 -08001774 function panZoom() {
1775 return doPanZoom.classed('active');
Simon Hunt01095ff2014-11-13 16:37:29 -08001776 }
Simon Hunta5e89142014-11-14 07:00:33 -08001777 function togglePanZoom() {
1778 doPanZoom.classed('active', !panZoom());
1779 }
1780
1781 function trafficHover() {
1782 return showTrafficOnHover.classed('active');
1783 }
1784 function toggleTrafficHover() {
1785 showTrafficOnHover.classed('active', !trafficHover());
1786 }
1787
Simon Hunt01095ff2014-11-13 16:37:29 -08001788
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001789 // ==============================
Simon Hunt142d0032014-11-04 20:13:09 -08001790 // View life-cycle callbacks
Simon Hunt195cb382014-11-03 17:50:51 -08001791
Simon Huntf67722a2014-11-10 09:32:06 -08001792 function preload(view, ctx, flags) {
Simon Hunt142d0032014-11-04 20:13:09 -08001793 var w = view.width(),
1794 h = view.height(),
Simon Huntc7ee0662014-11-05 16:44:37 -08001795 fcfg = config.force,
1796 fpad = fcfg.pad,
1797 forceDim = [w - 2*fpad, h - 2*fpad];
Simon Hunt195cb382014-11-03 17:50:51 -08001798
Simon Hunt142d0032014-11-04 20:13:09 -08001799 // NOTE: view.$div is a D3 selection of the view's div
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001800 var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
1801 svg = view.$div.append('svg').attr('viewBox', viewBox);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001802 setSize(svg, view);
1803
Simon Hunt12ce12e2014-11-15 21:13:19 -08001804 var defs = svg.append('defs');
1805 gly.defBird(defs);
1806
Paul Greysonfcba0e82014-11-13 10:21:16 -08001807 zoomPanContainer = svg.append('g').attr('id', 'zoomPanContainer');
Paul Greysonfcba0e82014-11-13 10:21:16 -08001808 setupZoomPan();
1809
Simon Hunt1a9eff92014-11-07 11:06:34 -08001810 // add blue glow filter to svg layer
Paul Greysonfcba0e82014-11-13 10:21:16 -08001811 d3u.appendGlow(zoomPanContainer);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001812
Simon Huntc7ee0662014-11-05 16:44:37 -08001813 // group for the topology
Paul Greysonfcba0e82014-11-13 10:21:16 -08001814 topoG = zoomPanContainer.append('g')
Simon Huntd3b7d512014-11-12 15:48:41 -08001815 .attr('id', 'topo-G')
Simon Huntc7ee0662014-11-05 16:44:37 -08001816 .attr('transform', fcfg.translate());
1817
1818 // subgroups for links and nodes
1819 linkG = topoG.append('g').attr('id', 'links');
1820 nodeG = topoG.append('g').attr('id', 'nodes');
1821
1822 // selection of nodes and links
1823 link = linkG.selectAll('.link');
1824 node = nodeG.selectAll('.node');
1825
Simon Hunt7cd48f32014-11-09 23:42:50 -08001826 function chrg(d) {
1827 return fcfg.charge[d.class] || -12000;
1828 }
Simon Hunt99c13842014-11-06 18:23:12 -08001829 function ldist(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001830 return fcfg.linkDistance[d.type] || 50;
Simon Hunt99c13842014-11-06 18:23:12 -08001831 }
1832 function lstrg(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001833 // 0.0 - 1.0
1834 return fcfg.linkStrength[d.type] || 1.0;
Simon Hunt99c13842014-11-06 18:23:12 -08001835 }
1836
Simon Hunt1a9eff92014-11-07 11:06:34 -08001837 function selectCb(d, self) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001838 selectObject(d, self);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001839 }
1840
1841 function atDragEnd(d, self) {
Simon Hunt56d51852014-11-09 13:03:35 -08001842 // once we've finished moving, pin the node in position
1843 d.fixed = true;
1844 d3.select(self).classed('fixed', true);
1845 if (config.useLiveData) {
Simon Hunt902c9922014-11-11 11:59:31 -08001846 sendUpdateMeta(d);
Simon Hunta255a2c2014-11-13 22:29:35 -08001847 } else {
1848 console.log('Moving node ' + d.id + ' to [' + d.x + ',' + d.y + ']');
Simon Hunt1a9eff92014-11-07 11:06:34 -08001849 }
1850 }
1851
Simon Hunt902c9922014-11-11 11:59:31 -08001852 function sendUpdateMeta(d) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001853 sendMessage('updateMeta', {
1854 id: d.id,
1855 'class': d.class,
Simon Hunt902c9922014-11-11 11:59:31 -08001856 'memento': {
Simon Hunt01095ff2014-11-13 16:37:29 -08001857 x: d.x,
1858 y: d.y
Simon Hunt902c9922014-11-11 11:59:31 -08001859 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001860 });
1861 }
1862
Simon Huntc7ee0662014-11-05 16:44:37 -08001863 // set up the force layout
1864 network.force = d3.layout.force()
1865 .size(forceDim)
1866 .nodes(network.nodes)
1867 .links(network.links)
Simon Hunt7cd48f32014-11-09 23:42:50 -08001868 .gravity(0.4)
1869 .friction(0.7)
1870 .charge(chrg)
Simon Hunt99c13842014-11-06 18:23:12 -08001871 .linkDistance(ldist)
1872 .linkStrength(lstrg)
Simon Huntc7ee0662014-11-05 16:44:37 -08001873 .on('tick', tick);
Simon Hunt195cb382014-11-03 17:50:51 -08001874
Simon Hunt01095ff2014-11-13 16:37:29 -08001875 network.drag = d3u.createDragBehavior(network.force,
Simon Huntdeab4322014-11-13 18:49:07 -08001876 selectCb, atDragEnd, panZoom);
Simon Hunt0c6d4192014-11-12 12:07:10 -08001877
1878 // create mask layer for when we lose connection to server.
Simon Hunta5e89142014-11-14 07:00:33 -08001879 // TODO: this should be part of the framework
Simon Hunt0c6d4192014-11-12 12:07:10 -08001880 mask = view.$div.append('div').attr('id','topo-mask');
1881 para(mask, 'Oops!');
1882 para(mask, 'Web-socket connection to server closed...');
1883 para(mask, 'Try refreshing the page.');
Simon Hunt12ce12e2014-11-15 21:13:19 -08001884
1885 mask.append('svg')
1886 .attr({
1887 id: 'mask-bird',
1888 width: w,
1889 height: h
1890 })
1891 .append('g')
1892 .attr('transform', birdTranslate(w, h))
1893 .style('opacity', 0.3)
1894 .append('use')
1895 .attr({
1896 'xlink:href': '#bird',
1897 width: config.birdDim,
1898 height: config.birdDim,
1899 fill: '#111'
1900 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001901 }
Simon Hunt195cb382014-11-03 17:50:51 -08001902
Simon Hunt01095ff2014-11-13 16:37:29 -08001903 function para(sel, text) {
1904 sel.append('p').text(text);
1905 }
1906
1907
Simon Hunt56d51852014-11-09 13:03:35 -08001908 function load(view, ctx, flags) {
Simon Huntf67722a2014-11-10 09:32:06 -08001909 // resize, in case the window was resized while we were not loaded
1910 resize(view, ctx, flags);
1911
Simon Hunt99c13842014-11-06 18:23:12 -08001912 // cache the view token, so network topo functions can access it
1913 network.view = view;
Simon Hunt56d51852014-11-09 13:03:35 -08001914 config.useLiveData = !flags.local;
1915
1916 if (!config.useLiveData) {
1917 prepareScenario(view, ctx, flags.debug);
1918 }
Simon Hunt99c13842014-11-06 18:23:12 -08001919
1920 // set our radio buttons and key bindings
Simon Hunt9462e8c2014-11-14 17:28:09 -08001921 layerBtnSet = view.setRadio(layerButtons);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001922 view.setKeys(keyDispatch);
Simon Hunt195cb382014-11-03 17:50:51 -08001923
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001924 // patch in our "button bar" for now
1925 // TODO: implement a more official frameworky way of doing this..
1926 addButtonBar(view);
1927
Simon Huntd3b7d512014-11-12 15:48:41 -08001928 // Load map data asynchronously; complete startup after that..
1929 loadGeoJsonData();
Simon Hunta255a2c2014-11-13 22:29:35 -08001930
1931 // start the and timer
1932 var dashIdx = 0;
1933 antTimer = setInterval(function () {
1934 // TODO: figure out how to choose Src-->Dst and Dst-->Src, per link
1935 dashIdx = dashIdx === 0 ? 14 : dashIdx - 2;
1936 d3.selectAll('.animated').style('stroke-dashoffset', dashIdx);
1937 }, 35);
1938 }
1939
1940 function unload(view, ctx, flags) {
1941 if (antTimer) {
1942 clearInterval(antTimer);
1943 antTimer = null;
1944 }
Simon Huntd3b7d512014-11-12 15:48:41 -08001945 }
1946
1947 // TODO: move these to config/state portion of script
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001948 var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
Simon Huntd3b7d512014-11-12 15:48:41 -08001949 geoJson;
1950
1951 function loadGeoJsonData() {
1952 d3.json(geoJsonUrl, function (err, data) {
1953 if (err) {
1954 // fall back to USA map background
1955 loadStaticMap();
1956 } else {
1957 geoJson = data;
1958 loadGeoMap();
1959 }
1960
1961 // finally, connect to the server...
1962 if (config.useLiveData) {
1963 webSock.connect();
1964 }
1965 });
1966 }
1967
1968 function showBg() {
1969 return config.options.showBackground ? 'visible' : 'hidden';
1970 }
1971
1972 function loadStaticMap() {
1973 fnTrace('loadStaticMap', config.backgroundUrl);
1974 var w = network.view.width(),
1975 h = network.view.height();
1976
1977 // load the background image
1978 bgImg = svg.insert('svg:image', '#topo-G')
1979 .attr({
1980 id: 'topo-bg',
1981 width: w,
1982 height: h,
1983 'xlink:href': config.backgroundUrl
1984 })
1985 .style({
1986 visibility: showBg()
1987 });
1988 }
1989
1990 function loadGeoMap() {
1991 fnTrace('loadGeoMap', geoJsonUrl);
Simon Huntd3b7d512014-11-12 15:48:41 -08001992
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001993 // extracts the topojson data into geocoordinate-based geometry
1994 var topoData = topojson.feature(geoJson, geoJson.objects.states);
Simon Huntd3b7d512014-11-12 15:48:41 -08001995
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001996 // see: http://bl.ocks.org/mbostock/4707858
1997 geoMapProjection = d3.geo.mercator();
1998 var path = d3.geo.path().projection(geoMapProjection);
Simon Huntd3b7d512014-11-12 15:48:41 -08001999
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002000 geoMapProjection
2001 .scale(1)
2002 .translate([0, 0]);
Simon Huntd3b7d512014-11-12 15:48:41 -08002003
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002004 // [[x1,y1],[x2,y2]]
2005 var b = path.bounds(topoData);
Paul Greysonfcba0e82014-11-13 10:21:16 -08002006 // size map to 95% of minimum dimension to fill space
2007 var s = .95 / Math.min((b[1][0] - b[0][0]) / config.logicalSize, (b[1][1] - b[0][1]) / config.logicalSize);
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002008 var t = [(config.logicalSize - s * (b[1][0] + b[0][0])) / 2, (config.logicalSize - s * (b[1][1] + b[0][1])) / 2];
Simon Huntd3b7d512014-11-12 15:48:41 -08002009
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002010 geoMapProjection
2011 .scale(s)
2012 .translate(t);
2013
Paul Greysonfcba0e82014-11-13 10:21:16 -08002014 bgImg = zoomPanContainer.insert("g", '#topo-G');
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002015 bgImg.attr('id', 'map').selectAll('path')
2016 .data(topoData.features)
2017 .enter()
2018 .append('path')
2019 .attr('d', path);
Simon Hunt195cb382014-11-03 17:50:51 -08002020 }
2021
Simon Huntf67722a2014-11-10 09:32:06 -08002022 function resize(view, ctx, flags) {
Simon Hunt12ce12e2014-11-15 21:13:19 -08002023 var w = view.width(),
2024 h = view.height();
2025
Simon Hunt934c3ce2014-11-05 11:45:07 -08002026 setSize(svg, view);
Simon Hunt12ce12e2014-11-15 21:13:19 -08002027
2028 d3.select('#mask-bird').attr({ width: w, height: h})
2029 .select('g').attr('transform', birdTranslate(w, h));
Simon Hunt142d0032014-11-04 20:13:09 -08002030 }
2031
Simon Hunt12ce12e2014-11-15 21:13:19 -08002032 function birdTranslate(w, h) {
2033 var bdim = config.birdDim;
2034 return 'translate('+((w-bdim)*.4)+','+((h-bdim)*.1)+')';
2035 }
Simon Hunt142d0032014-11-04 20:13:09 -08002036
2037 // ==============================
2038 // View registration
Simon Hunt195cb382014-11-03 17:50:51 -08002039
Simon Hunt25248912014-11-04 11:25:48 -08002040 onos.ui.addView('topo', {
Simon Hunt142d0032014-11-04 20:13:09 -08002041 preload: preload,
2042 load: load,
Simon Hunta255a2c2014-11-13 22:29:35 -08002043 unload: unload,
Simon Hunt142d0032014-11-04 20:13:09 -08002044 resize: resize
Simon Hunt195cb382014-11-03 17:50:51 -08002045 });
2046
Simon Hunt61d04042014-11-11 17:27:16 -08002047 detailPane = onos.ui.addFloatingPanel('topo-detail');
Simon Hunta5e89142014-11-14 07:00:33 -08002048 oiBox = onos.ui.addFloatingPanel('topo-oibox', 'TL');
Simon Hunt61d04042014-11-11 17:27:16 -08002049
Simon Hunt195cb382014-11-03 17:50:51 -08002050}(ONOS));