blob: e89d4bca4cc2d19ae32c6907a03eaa81f845aa54 [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);
Simon Hunt1712ed82014-11-17 12:56:00 -0800271 wsTrace('test', JSON.stringify(data));
Simon Hunt7cd48f32014-11-09 23:42:50 -0800272 frame.cb(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800273 }
274 });
Simon Hunt934c3ce2014-11-05 11:45:07 -0800275
Simon Hunt56d51852014-11-09 13:03:35 -0800276 }
Simon Hunt50128c02014-11-08 13:36:15 -0800277
Simon Hunt56d51852014-11-09 13:03:35 -0800278 function handleUiEvent(data) {
Simon Huntbb282f52014-11-10 11:08:19 -0800279 scenario.view.alert('UI Tx: ' + data.event + '\n\n' +
280 JSON.stringify(data));
Simon Hunt56d51852014-11-09 13:03:35 -0800281 }
282
283 function injectStartupEvents(view) {
284 var last = scenario.params.lastAuto || 0;
285 if (abortIfLive()) { return; }
286
287 while (scenario.evNumber < last) {
Simon Hunt1a9eff92014-11-07 11:06:34 -0800288 injectTestEvent(view);
289 }
290 }
291
Simon Hunt934c3ce2014-11-05 11:45:07 -0800292 function toggleBg() {
293 var vis = bgImg.style('visibility');
294 bgImg.style('visibility', (vis === 'hidden') ? 'visible' : 'hidden');
295 }
296
Simon Hunt99c13842014-11-06 18:23:12 -0800297 function cycleLabels() {
Simon Huntbb282f52014-11-10 11:08:19 -0800298 deviceLabelIndex = (deviceLabelIndex === network.deviceLabelCount - 1)
299 ? 0 : deviceLabelIndex + 1;
Simon Hunt5f36d342014-11-08 21:33:14 -0800300
Simon Hunt99c13842014-11-06 18:23:12 -0800301 network.nodes.forEach(function (d) {
Simon Huntbb282f52014-11-10 11:08:19 -0800302 if (d.class === 'device') {
303 updateDeviceLabel(d);
304 }
Simon Hunt99c13842014-11-06 18:23:12 -0800305 });
Simon Hunt934c3ce2014-11-05 11:45:07 -0800306 }
307
308 function togglePorts(view) {
Simon Hunt50128c02014-11-08 13:36:15 -0800309 view.alert('togglePorts() callback')
Simon Hunt934c3ce2014-11-05 11:45:07 -0800310 }
311
Simon Hunt6ac93f32014-11-13 12:17:27 -0800312 function unpin() {
313 if (hovered) {
314 hovered.fixed = false;
315 hovered.el.classed('fixed', false);
316 network.force.resume();
317 }
Simon Hunt934c3ce2014-11-05 11:45:07 -0800318 }
319
Simon Hunt9462e8c2014-11-14 17:28:09 -0800320 function handleEscape(view) {
321 if (oiShowMaster) {
322 cancelAffinity();
323 } else {
324 deselectAll();
325 }
326 }
327
Simon Hunt934c3ce2014-11-05 11:45:07 -0800328 // ==============================
329 // Radio Button Callbacks
330
Simon Hunta5e89142014-11-14 07:00:33 -0800331 var layerLookup = {
332 host: {
333 endstation: 'pkt', // default, if host event does not define type
334 bgpSpeaker: 'pkt'
335 },
336 device: {
337 switch: 'pkt',
338 roadm: 'opt'
339 },
340 link: {
341 hostLink: 'pkt',
342 direct: 'pkt',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800343 indirect: '',
344 tunnel: '',
Simon Hunta5e89142014-11-14 07:00:33 -0800345 optical: 'opt'
346 }
347 };
348
349 function inLayer(d, layer) {
Simon Hunt8257f4c2014-11-16 19:34:54 -0800350 var type = d.class === 'link' ? d.type() : d.type,
351 look = layerLookup[d.class],
352 lyr = look && look[type];
Simon Hunta5e89142014-11-14 07:00:33 -0800353 return lyr === layer;
354 }
355
356 function unsuppressLayer(which) {
357 node.each(function (d) {
358 var node = d.el;
359 if (inLayer(d, which)) {
360 node.classed('suppressed', false);
361 }
362 });
363
364 link.each(function (d) {
365 var link = d.el;
366 if (inLayer(d, which)) {
367 link.classed('suppressed', false);
368 }
369 });
370 }
371
Simon Hunt9462e8c2014-11-14 17:28:09 -0800372 function suppressLayers(b) {
373 node.classed('suppressed', b);
374 link.classed('suppressed', b);
Simon Hunt142d0032014-11-04 20:13:09 -0800375// d3.selectAll('svg .port').classed('inactive', false);
376// d3.selectAll('svg .portText').classed('inactive', false);
Simon Hunt195cb382014-11-03 17:50:51 -0800377 }
378
Simon Hunt9462e8c2014-11-14 17:28:09 -0800379 function showAllLayers() {
380 suppressLayers(false);
381 }
382
Simon Hunt195cb382014-11-03 17:50:51 -0800383 function showPacketLayer() {
Simon Hunta5e89142014-11-14 07:00:33 -0800384 node.classed('suppressed', true);
385 link.classed('suppressed', true);
386 unsuppressLayer('pkt');
Simon Hunt195cb382014-11-03 17:50:51 -0800387 }
388
389 function showOpticalLayer() {
Simon Hunta5e89142014-11-14 07:00:33 -0800390 node.classed('suppressed', true);
391 link.classed('suppressed', true);
392 unsuppressLayer('opt');
Simon Hunt195cb382014-11-03 17:50:51 -0800393 }
394
Simon Hunt9462e8c2014-11-14 17:28:09 -0800395 function restoreLayerState() {
396 layerBtnDispatch[layerBtnSet.selected()]();
397 }
398
Simon Hunt142d0032014-11-04 20:13:09 -0800399 // ==============================
Simon Hunt934c3ce2014-11-05 11:45:07 -0800400 // Private functions
401
Simon Hunt99c13842014-11-06 18:23:12 -0800402 function safeId(s) {
403 return s.replace(/[^a-z0-9]/gi, '-');
404 }
405
Simon Huntc7ee0662014-11-05 16:44:37 -0800406 // set the size of the given element to that of the view (reduced if padded)
407 function setSize(el, view, pad) {
408 var padding = pad ? pad * 2 : 0;
Simon Hunt934c3ce2014-11-05 11:45:07 -0800409 el.attr({
Simon Huntc7ee0662014-11-05 16:44:37 -0800410 width: view.width() - padding,
411 height: view.height() - padding
Simon Hunt934c3ce2014-11-05 11:45:07 -0800412 });
413 }
414
Simon Hunt8257f4c2014-11-16 19:34:54 -0800415 function makeNodeKey(d, what) {
416 var port = what + 'Port';
417 return d[what] + '/' + d[port];
418 }
419
420 function makeLinkKey(d, flipped) {
421 var one = flipped ? makeNodeKey(d, 'dst') : makeNodeKey(d, 'src'),
422 two = flipped ? makeNodeKey(d, 'src') : makeNodeKey(d, 'dst');
423 return one + '-' + two;
424 }
425
426 function findLink(linkData, op) {
427 var key = makeLinkKey(linkData),
428 keyrev = makeLinkKey(linkData, 1),
429 link = network.lookup[key],
430 linkRev = network.lookup[keyrev],
431 result = {},
432 ldata = link || linkRev,
433 rawLink;
434
435 if (op === 'add') {
436 if (link) {
437 // trying to add a link that we already know about
438 result.ldata = link;
439 result.badLogic = 'addLink: link already added';
440
441 } else if (linkRev) {
442 // we found the reverse of the link to be added
443 result.ldata = linkRev;
444 if (linkRev.fromTarget) {
445 result.badLogic = 'addLink: link already added';
446 }
447 }
448 } else if (op === 'update') {
449 if (!ldata) {
450 result.badLogic = 'updateLink: link not found';
451 } else {
452 rawLink = link ? ldata.fromSource : ldata.fromTarget;
453 result.updateWith = function (data) {
454 $.extend(rawLink, data);
455 restyleLinkElement(ldata);
456 }
457 }
458 } else if (op === 'remove') {
459 if (!ldata) {
460 result.badLogic = 'removeLink: link not found';
461 } else {
462 rawLink = link ? ldata.fromSource : ldata.fromTarget;
463
464 if (!rawLink) {
465 result.badLogic = 'removeLink: link not found';
466
467 } else {
468 result.removeRawLink = function () {
469 if (link) {
470 // remove fromSource
471 ldata.fromSource = null;
472 if (ldata.fromTarget) {
473 // promote target into source position
474 ldata.fromSource = ldata.fromTarget;
475 ldata.fromTarget = null;
476 ldata.key = keyrev;
477 delete network.lookup[key];
478 network.lookup[keyrev] = ldata;
479 }
480 } else {
481 // remove fromTarget
482 ldata.fromTarget = null;
483 }
484 if (ldata.fromSource) {
485 restyleLinkElement(ldata);
486 } else {
487 removeLinkElement(ldata);
488 }
489 }
490 }
491 }
492 }
493 return result;
494 }
495
496 function addLinkUpdate(ldata, link) {
497 // add link event, but we already have the reverse link installed
498 ldata.fromTarget = link;
499 restyleLinkElement(ldata);
500 }
501
502 var allLinkTypes = 'direct indirect optical tunnel',
503 defaultLinkType = 'direct';
504
505 function restyleLinkElement(ldata) {
506 // this fn's job is to look at raw links and decide what svg classes
507 // need to be applied to the line element in the DOM
508 var el = ldata.el,
509 type = ldata.type(),
510 lw = ldata.linkWidth(),
511 online = ldata.online();
512
513 el.classed('link', true);
514 el.classed('inactive', !online);
515 el.classed(allLinkTypes, false);
516 if (type) {
517 el.classed(type, true);
518 }
519 el.transition()
520 .duration(1000)
521 .attr('stroke-width', linkScale(lw))
522 .attr('stroke', '#666'); // TODO: remove explicit stroke (use CSS)
523 }
Simon Hunt934c3ce2014-11-05 11:45:07 -0800524
Simon Hunt99c13842014-11-06 18:23:12 -0800525 // ==============================
526 // Event handlers for server-pushed events
527
Simon Huntbb282f52014-11-10 11:08:19 -0800528 function logicError(msg) {
529 // TODO, report logic error to server, via websock, so it can be logged
Simon Huntcb56cff2014-11-17 11:42:26 -0800530 //network.view.alert('Logic Error:\n\n' + msg);
Simon Huntfc274c92014-11-11 11:05:46 -0800531 console.warn(msg);
Simon Huntbb282f52014-11-10 11:08:19 -0800532 }
533
Simon Hunt99c13842014-11-06 18:23:12 -0800534 var eventDispatch = {
Simon Hunta5e89142014-11-14 07:00:33 -0800535 addInstance: addInstance,
Simon Hunt99c13842014-11-06 18:23:12 -0800536 addDevice: addDevice,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800537 addLink: addLink,
Simon Hunt56d51852014-11-09 13:03:35 -0800538 addHost: addHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800539
Simon Huntd72bc702014-11-13 18:38:04 -0800540 updateInstance: stillToImplement,
Simon Huntbb282f52014-11-10 11:08:19 -0800541 updateDevice: updateDevice,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800542 updateLink: updateLink,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800543 updateHost: updateHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800544
Simon Huntd72bc702014-11-13 18:38:04 -0800545 removeInstance: stillToImplement,
Simon Huntbb282f52014-11-10 11:08:19 -0800546 removeDevice: stillToImplement,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800547 removeLink: removeLink,
Simon Hunt44031102014-11-11 13:20:36 -0800548 removeHost: removeHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800549
Simon Hunt61d04042014-11-11 17:27:16 -0800550 showDetails: showDetails,
Simon Huntb53e0682014-11-12 13:32:01 -0800551 showPath: showPath,
552 showTraffic: showTraffic
Simon Hunt99c13842014-11-06 18:23:12 -0800553 };
554
Simon Hunta5e89142014-11-14 07:00:33 -0800555 function addInstance(data) {
556 evTrace(data);
557 var inst = data.payload,
558 id = inst.id;
559 if (onosInstances[id]) {
560 logicError('ONOS instance already added: ' + id);
561 return;
562 }
563 onosInstances[id] = inst;
564 onosOrder.push(inst);
565 updateInstances();
566 }
567
Simon Hunt99c13842014-11-06 18:23:12 -0800568 function addDevice(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800569 evTrace(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800570 var device = data.payload,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800571 nodeData = createDeviceNode(device);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800572 network.nodes.push(nodeData);
573 network.lookup[nodeData.id] = nodeData;
Simon Hunt99c13842014-11-06 18:23:12 -0800574 updateNodes();
575 network.force.start();
576 }
577
Simon Hunt99c13842014-11-06 18:23:12 -0800578 function addLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800579 evTrace(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800580 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800581 result = findLink(link, 'add'),
582 bad = result.badLogic,
583 ldata = result.ldata;
584
585 if (bad) {
586 logicError(bad + ': ' + link.id);
587 return;
588 }
589
590 if (ldata) {
591 // we already have a backing store link for src/dst nodes
592 addLinkUpdate(ldata, link);
593 return;
594 }
595
596 // no backing store link yet
597 ldata = createLink(link);
598 if (ldata) {
599 network.links.push(ldata);
600 network.lookup[ldata.key] = ldata;
Simon Hunt99c13842014-11-06 18:23:12 -0800601 updateLinks();
602 network.force.start();
603 }
604 }
605
Simon Hunt56d51852014-11-09 13:03:35 -0800606 function addHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800607 evTrace(data);
Simon Hunt56d51852014-11-09 13:03:35 -0800608 var host = data.payload,
609 node = createHostNode(host),
610 lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800611 network.nodes.push(node);
612 network.lookup[host.id] = node;
613 updateNodes();
614
615 lnk = createHostLink(host);
616 if (lnk) {
Simon Hunt44031102014-11-11 13:20:36 -0800617 node.linkData = lnk; // cache ref on its host
Simon Hunt56d51852014-11-09 13:03:35 -0800618 network.links.push(lnk);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800619 network.lookup[host.ingress] = lnk;
620 network.lookup[host.egress] = lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800621 updateLinks();
622 }
623 network.force.start();
624 }
625
Simon Hunt44031102014-11-11 13:20:36 -0800626 // TODO: fold updateX(...) methods into one base method; remove duplication
Simon Huntbb282f52014-11-10 11:08:19 -0800627 function updateDevice(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800628 evTrace(data);
Simon Huntbb282f52014-11-10 11:08:19 -0800629 var device = data.payload,
630 id = device.id,
631 nodeData = network.lookup[id];
632 if (nodeData) {
633 $.extend(nodeData, device);
634 updateDeviceState(nodeData);
635 } else {
636 logicError('updateDevice lookup fail. ID = "' + id + '"');
637 }
638 }
639
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800640 function updateLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800641 evTrace(data);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800642 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800643 result = findLink(link, 'update'),
644 bad = result.badLogic;
645 if (bad) {
646 logicError(bad + ': ' + link.id);
647 return;
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800648 }
Simon Hunt8257f4c2014-11-16 19:34:54 -0800649 result.updateWith(link);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800650 }
651
Simon Hunt7cd48f32014-11-09 23:42:50 -0800652 function updateHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800653 evTrace(data);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800654 var host = data.payload,
Simon Huntbb282f52014-11-10 11:08:19 -0800655 id = host.id,
656 hostData = network.lookup[id];
657 if (hostData) {
658 $.extend(hostData, host);
659 updateHostState(hostData);
660 } else {
661 logicError('updateHost lookup fail. ID = "' + id + '"');
662 }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800663 }
664
Simon Hunt44031102014-11-11 13:20:36 -0800665 // TODO: fold removeX(...) methods into base method - remove dup code
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800666 function removeLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800667 evTrace(data);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800668 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800669 result = findLink(link, 'remove'),
670 bad = result.badLogic;
671 if (bad) {
672 logicError(bad + ': ' + link.id);
673 return;
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800674 }
Simon Hunt8257f4c2014-11-16 19:34:54 -0800675 result.removeRawLink();
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800676 }
677
Simon Hunt44031102014-11-11 13:20:36 -0800678 function removeHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800679 evTrace(data);
Simon Hunt44031102014-11-11 13:20:36 -0800680 var host = data.payload,
681 id = host.id,
682 hostData = network.lookup[id];
683 if (hostData) {
684 removeHostElement(hostData);
685 } else {
686 logicError('removeHost lookup fail. ID = "' + id + '"');
687 }
688 }
689
Simon Hunt61d04042014-11-11 17:27:16 -0800690 function showDetails(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800691 evTrace(data);
Simon Hunt61d04042014-11-11 17:27:16 -0800692 populateDetails(data.payload);
693 detailPane.show();
694 }
695
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800696 function showPath(data) {
Simon Huntd72bc702014-11-13 18:38:04 -0800697 // TODO: review - making sure we are handling the payload correctly.
Simon Hunta5e89142014-11-14 07:00:33 -0800698 evTrace(data);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800699 var links = data.payload.links,
700 s = [ data.event + "\n" + links.length ];
701 links.forEach(function (d, i) {
702 s.push(d);
703 });
704 network.view.alert(s.join('\n'));
705
706 links.forEach(function (d, i) {
707 var link = network.lookup[d];
708 if (link) {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800709 link.el.classed('showPath', true);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800710 }
711 });
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800712 }
713
Simon Huntb53e0682014-11-12 13:32:01 -0800714 function showTraffic(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800715 evTrace(data);
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800716 var paths = data.payload.paths;
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800717
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800718 // Revert any links hilighted previously.
Simon Hunta255a2c2014-11-13 22:29:35 -0800719 link.classed('primary secondary animated optical', false);
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800720
721 // Now hilight all links in the paths payload.
Simon Hunta255a2c2014-11-13 22:29:35 -0800722 paths.forEach(function (p) {
723 var cls = p.class;
724 p.links.forEach(function (id) {
725 var lnk = network.lookup[id];
726 if (lnk) {
727 lnk.el.classed(cls, true);
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800728 }
729 });
730 });
Simon Huntb53e0682014-11-12 13:32:01 -0800731 }
732
Simon Hunt56d51852014-11-09 13:03:35 -0800733 // ...............................
734
735 function stillToImplement(data) {
736 var p = data.payload;
737 note(data.event, p.id);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800738 network.view.alert('Not yet implemented: "' + data.event + '"');
Simon Hunt56d51852014-11-09 13:03:35 -0800739 }
Simon Hunt99c13842014-11-06 18:23:12 -0800740
741 function unknownEvent(data) {
Simon Hunt50128c02014-11-08 13:36:15 -0800742 network.view.alert('Unknown event type: "' + data.event + '"');
Simon Hunt99c13842014-11-06 18:23:12 -0800743 }
744
745 function handleServerEvent(data) {
746 var fn = eventDispatch[data.event] || unknownEvent;
747 fn(data);
748 }
749
750 // ==============================
Simon Hunt61d04042014-11-11 17:27:16 -0800751 // Out-going messages...
752
Simon Huntb53e0682014-11-12 13:32:01 -0800753 function userFeedback(msg) {
754 // for now, use the alert pane as is. Maybe different alert style in
755 // the future (centered on view; dismiss button?)
756 network.view.alert(msg);
757 }
758
759 function nSel() {
760 return selectOrder.length;
761 }
Simon Hunt61d04042014-11-11 17:27:16 -0800762 function getSel(idx) {
763 return selections[selectOrder[idx]];
764 }
Simon Huntb53e0682014-11-12 13:32:01 -0800765 function getSelId(idx) {
766 return getSel(idx).obj.id;
767 }
768 function allSelectionsClass(cls) {
769 for (var i=0, n=nSel(); i<n; i++) {
770 if (getSel(i).obj.class !== cls) {
771 return false;
772 }
773 }
774 return true;
775 }
Simon Hunt61d04042014-11-11 17:27:16 -0800776
Simon Hunt61d04042014-11-11 17:27:16 -0800777 // request details for the selected element
Simon Huntd72bc702014-11-13 18:38:04 -0800778 // invoked from selection of a single node.
Simon Hunt61d04042014-11-11 17:27:16 -0800779 function requestDetails() {
780 var data = getSel(0).obj,
781 payload = {
782 id: data.id,
783 class: data.class
784 };
785 sendMessage('requestDetails', payload);
786 }
787
Simon Huntd72bc702014-11-13 18:38:04 -0800788 function addIntentAction() {
789 sendMessage('addHostIntent', {
790 one: getSelId(0),
Thomas Vachuska82f2c622014-11-17 12:23:18 -0800791 two: getSelId(1),
792 ids: [ getSelId(0), getSelId(1) ]
Simon Huntd72bc702014-11-13 18:38:04 -0800793 });
794 }
795
796 function showTrafficAction() {
797 // if nothing is hovered over, and nothing selected, send cancel request
798 if (!hovered && nSel() === 0) {
799 sendMessage('cancelTraffic', {});
800 return;
801 }
802
803 // NOTE: hover is only populated if "show traffic on hover" is
804 // toggled on, and the item hovered is a host...
805 var hoverId = (trafficHover() && hovered && hovered.class === 'host')
806 ? hovered.id : '';
807 sendMessage('requestTraffic', {
808 ids: selectOrder,
809 hover: hoverId
810 });
811 }
812
813
Simon Hunt61d04042014-11-11 17:27:16 -0800814 // ==============================
Simon Hunta5e89142014-11-14 07:00:33 -0800815 // onos instance panel functions
816
817 function updateInstances() {
818 var onoses = oiBox.el.selectAll('.onosInst')
819 .data(onosOrder, function (d) { return d.id; });
820
821 // operate on existing onoses if necessary
822
823 var entering = onoses.enter()
824 .append('div')
825 .attr('class', 'onosInst')
826 .classed('online', function (d) { return d.online; })
Simon Hunt9c15eca2014-11-15 18:37:59 -0800827 .on('click', clickInst);
828
829 entering.each(function (d, i) {
830 var el = d3.select(this),
831 img;
832
833 $('<img src="img/host.png">').appendTo(el);
834 img = el.select('img')
835 .attr({
836 width: 40,
837 top: -10,
838 left: -10
839 })
840 .style({
841 });
842
843 $('<div>').attr('class', 'onosTitle').text(d.id).appendTo(el);
844
845 // is the UI attached to this instance?
846 // TODO: need uiAttached boolean in instance data
847 //if (d.uiAttached) {
848 if (i === 0) {
849 $('<img src="img/ui.png">').attr('class','ui').appendTo(el);
850 }
851 });
Simon Hunta5e89142014-11-14 07:00:33 -0800852
853 // operate on existing + new onoses here
854
855 // the departed...
856 var exiting = onoses.exit()
857 .transition()
858 .style('opacity', 0)
859 .remove();
860 }
861
Simon Hunt9462e8c2014-11-14 17:28:09 -0800862 function clickInst(d) {
863 var el = d3.select(this),
864 aff = el.classed('affinity');
865 if (!aff) {
866 setAffinity(el, d);
867 } else {
868 cancelAffinity();
869 }
870 }
871
872 function setAffinity(el, d) {
873 d3.selectAll('.onosInst')
874 .classed('mastership', true)
875 .classed('affinity', false);
876 el.classed('affinity', true);
877
878 suppressLayers(true);
879 node.each(function (n) {
880 if (n.master === d.id) {
881 n.el.classed('suppressed', false);
882 }
883 });
884 oiShowMaster = true;
885 }
886
887 function cancelAffinity() {
888 d3.selectAll('.onosInst')
889 .classed('mastership affinity', false);
890 restoreLayerState();
891 oiShowMaster = false;
892 }
893
Simon Hunta5e89142014-11-14 07:00:33 -0800894 // ==============================
Simon Hunt99c13842014-11-06 18:23:12 -0800895 // force layout modification functions
896
897 function translate(x, y) {
898 return 'translate(' + x + ',' + y + ')';
899 }
900
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800901 function missMsg(what, id) {
902 return '\n[' + what + '] "' + id + '" missing ';
903 }
904
905 function linkEndPoints(srcId, dstId) {
906 var srcNode = network.lookup[srcId],
907 dstNode = network.lookup[dstId],
908 sMiss = !srcNode ? missMsg('src', srcId) : '',
909 dMiss = !dstNode ? missMsg('dst', dstId) : '';
910
911 if (sMiss || dMiss) {
912 logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
913 return null;
914 }
915 return {
916 source: srcNode,
917 target: dstNode,
918 x1: srcNode.x,
919 y1: srcNode.y,
920 x2: dstNode.x,
921 y2: dstNode.y
922 };
923 }
924
Simon Hunt56d51852014-11-09 13:03:35 -0800925 function createHostLink(host) {
926 var src = host.id,
927 dst = host.cp.device,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800928 id = host.ingress,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800929 lnk = linkEndPoints(src, dst);
Simon Hunt56d51852014-11-09 13:03:35 -0800930
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800931 if (!lnk) {
Simon Hunt56d51852014-11-09 13:03:35 -0800932 return null;
933 }
934
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800935 // Synthesize link ...
936 $.extend(lnk, {
Simon Hunt8257f4c2014-11-16 19:34:54 -0800937 key: id,
Simon Hunt56d51852014-11-09 13:03:35 -0800938 class: 'link',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800939
940 type: function () { return 'hostLink'; },
941 // TODO: ideally, we should see if our edge switch is online...
942 online: function () { return true; },
943 linkWidth: function () { return 1; }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800944 });
Simon Hunt99c13842014-11-06 18:23:12 -0800945 return lnk;
946 }
947
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800948 function createLink(link) {
949 var lnk = linkEndPoints(link.src, link.dst),
950 type = link.type;
951
952 if (!lnk) {
953 return null;
954 }
955
Simon Hunt8257f4c2014-11-16 19:34:54 -0800956 $.extend(lnk, {
957 key: link.id,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800958 class: 'link',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800959 fromSource: link,
960
961 // functions to aggregate dual link state
962 type: function () {
963 var s = lnk.fromSource,
964 t = lnk.fromTarget;
965 return (s && s.type) || (t && t.type) || defaultLinkType;
966 },
967 online: function () {
968 var s = lnk.fromSource,
969 t = lnk.fromTarget;
970 return (s && s.online) || (t && t.online);
971 },
972 linkWidth: function () {
973 var s = lnk.fromSource,
974 t = lnk.fromTarget,
975 ws = (s && s.linkWidth) || 0,
976 wt = (t && t.linkWidth) || 0;
977 return Math.max(ws, wt);
978 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800979 });
980 return lnk;
Simon Hunt1a9eff92014-11-07 11:06:34 -0800981 }
982
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800983 var widthRatio = 1.4,
984 linkScale = d3.scale.linear()
985 .domain([1, 12])
986 .range([widthRatio, 12 * widthRatio])
987 .clamp(true);
988
Simon Hunt99c13842014-11-06 18:23:12 -0800989 function updateLinks() {
990 link = linkG.selectAll('.link')
Simon Hunt8257f4c2014-11-16 19:34:54 -0800991 .data(network.links, function (d) { return d.key; });
Simon Hunt99c13842014-11-06 18:23:12 -0800992
993 // operate on existing links, if necessary
994 // link .foo() .bar() ...
995
996 // operate on entering links:
997 var entering = link.enter()
998 .append('line')
999 .attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001000 x1: function (d) { return d.x1; },
1001 y1: function (d) { return d.y1; },
1002 x2: function (d) { return d.x2; },
1003 y2: function (d) { return d.y2; },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001004 stroke: config.topo.linkInColor,
1005 'stroke-width': config.topo.linkInWidth
Simon Hunt99c13842014-11-06 18:23:12 -08001006 });
1007
1008 // augment links
Simon Hunt7cd48f32014-11-09 23:42:50 -08001009 entering.each(function (d) {
1010 var link = d3.select(this);
1011 // provide ref to element selection from backing data....
1012 d.el = link;
Simon Hunt8257f4c2014-11-16 19:34:54 -08001013 restyleLinkElement(d);
Simon Hunt99c13842014-11-06 18:23:12 -08001014
Simon Hunt7cd48f32014-11-09 23:42:50 -08001015 // TODO: add src/dst port labels etc.
1016 });
Thomas Vachuska4830d392014-11-09 17:09:56 -08001017
1018 // operate on both existing and new links, if necessary
1019 //link .foo() .bar() ...
1020
1021 // operate on exiting links:
Thomas Vachuska4830d392014-11-09 17:09:56 -08001022 link.exit()
Thomas Vachuska4830d392014-11-09 17:09:56 -08001023 .attr({
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001024 'stroke-dasharray': '3, 3'
Thomas Vachuska4830d392014-11-09 17:09:56 -08001025 })
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001026 .style('opacity', 0.4)
1027 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001028 .duration(1500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001029 .attr({
1030 'stroke-dasharray': '3, 12'
1031 })
1032 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001033 .duration(500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001034 .style('opacity', 0.0)
Thomas Vachuska4830d392014-11-09 17:09:56 -08001035 .remove();
Simon Hunt99c13842014-11-06 18:23:12 -08001036 }
1037
1038 function createDeviceNode(device) {
1039 // start with the object as is
1040 var node = device,
Simon Huntbb282f52014-11-10 11:08:19 -08001041 type = device.type,
1042 svgCls = type ? 'node device ' + type : 'node device';
Simon Hunt99c13842014-11-06 18:23:12 -08001043
1044 // Augment as needed...
1045 node.class = 'device';
Simon Huntbb282f52014-11-10 11:08:19 -08001046 node.svgClass = device.online ? svgCls + ' online' : svgCls;
Simon Hunt99c13842014-11-06 18:23:12 -08001047 positionNode(node);
1048
1049 // cache label array length
1050 network.deviceLabelCount = device.labels.length;
Simon Hunt99c13842014-11-06 18:23:12 -08001051 return node;
1052 }
1053
Simon Hunt56d51852014-11-09 13:03:35 -08001054 function createHostNode(host) {
1055 // start with the object as is
1056 var node = host;
1057
1058 // Augment as needed...
1059 node.class = 'host';
Simon Hunt7cd48f32014-11-09 23:42:50 -08001060 if (!node.type) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001061 node.type = 'endstation';
1062 }
Simon Hunt56d51852014-11-09 13:03:35 -08001063 node.svgClass = 'node host';
Simon Hunt56d51852014-11-09 13:03:35 -08001064 positionNode(node);
1065
1066 // cache label array length
1067 network.hostLabelCount = host.labels.length;
Simon Hunt56d51852014-11-09 13:03:35 -08001068 return node;
1069 }
1070
Simon Hunt99c13842014-11-06 18:23:12 -08001071 function positionNode(node) {
1072 var meta = node.metaUi,
Simon Huntac9e24f2014-11-12 10:12:21 -08001073 x = meta && meta.x,
1074 y = meta && meta.y,
1075 xy;
Simon Hunt99c13842014-11-06 18:23:12 -08001076
Simon Huntac9e24f2014-11-12 10:12:21 -08001077 // If we have [x,y] already, use that...
Simon Hunt99c13842014-11-06 18:23:12 -08001078 if (x && y) {
1079 node.fixed = true;
Simon Huntac9e24f2014-11-12 10:12:21 -08001080 node.x = x;
1081 node.y = y;
1082 return;
Simon Hunt99c13842014-11-06 18:23:12 -08001083 }
Simon Huntac9e24f2014-11-12 10:12:21 -08001084
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001085 var location = node.location;
1086 if (location && location.type === 'latlng') {
1087 var coord = geoMapProjection([location.lng, location.lat]);
1088 node.fixed = true;
1089 node.x = coord[0];
1090 node.y = coord[1];
1091 return;
1092 }
1093
Simon Huntac9e24f2014-11-12 10:12:21 -08001094 // Note: Placing incoming unpinned nodes at exactly the same point
1095 // (center of the view) causes them to explode outwards when
1096 // the force layout kicks in. So, we spread them out a bit
1097 // initially, to provide a more serene layout convergence.
1098 // Additionally, if the node is a host, we place it near
1099 // the device it is connected to.
1100
1101 function spread(s) {
1102 return Math.floor((Math.random() * s) - s/2);
1103 }
1104
1105 function randDim(dim) {
1106 return dim / 2 + spread(dim * 0.7071);
1107 }
1108
1109 function rand() {
1110 return {
1111 x: randDim(network.view.width()),
1112 y: randDim(network.view.height())
1113 };
1114 }
1115
1116 function near(node) {
1117 var min = 12,
1118 dx = spread(12),
1119 dy = spread(12);
1120 return {
1121 x: node.x + min + dx,
1122 y: node.y + min + dy
1123 };
1124 }
1125
1126 function getDevice(cp) {
1127 var d = network.lookup[cp.device];
1128 return d || rand();
1129 }
1130
1131 xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
1132 $.extend(node, xy);
Simon Hunt99c13842014-11-06 18:23:12 -08001133 }
1134
Simon Hunt99c13842014-11-06 18:23:12 -08001135 function iconUrl(d) {
1136 return 'img/' + d.type + '.png';
1137 }
1138
1139 // returns the newly computed bounding box of the rectangle
1140 function adjustRectToFitText(n) {
1141 var text = n.select('text'),
1142 box = text.node().getBBox(),
1143 lab = config.labels;
1144
1145 text.attr('text-anchor', 'middle')
1146 .attr('y', '-0.8em')
1147 .attr('x', lab.imgPad/2);
1148
1149 // translate the bbox so that it is centered on [x,y]
1150 box.x = -box.width / 2;
1151 box.y = -box.height / 2;
1152
1153 // add padding
1154 box.x -= (lab.padLR + lab.imgPad/2);
1155 box.width += lab.padLR * 2 + lab.imgPad;
1156 box.y -= lab.padTB;
1157 box.height += lab.padTB * 2;
1158
1159 return box;
1160 }
1161
Simon Hunt1a9eff92014-11-07 11:06:34 -08001162 function mkSvgClass(d) {
1163 return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
1164 }
1165
Simon Hunt7cd48f32014-11-09 23:42:50 -08001166 function hostLabel(d) {
1167 var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
1168 return d.labels[idx];
1169 }
1170 function deviceLabel(d) {
1171 var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
1172 return d.labels[idx];
1173 }
1174 function niceLabel(label) {
1175 return (label && label.trim()) ? label : '.';
1176 }
1177
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001178 function updateDeviceLabel(d) {
1179 var label = niceLabel(deviceLabel(d)),
1180 node = d.el,
1181 box;
1182
1183 node.select('text')
1184 .text(label)
1185 .style('opacity', 0)
1186 .transition()
1187 .style('opacity', 1);
1188
1189 box = adjustRectToFitText(node);
1190
1191 node.select('rect')
1192 .transition()
1193 .attr(box);
1194
1195 node.select('image')
1196 .transition()
1197 .attr('x', box.x + config.icons.xoff)
1198 .attr('y', box.y + config.icons.yoff);
1199 }
1200
1201 function updateHostLabel(d) {
1202 var label = hostLabel(d),
1203 host = d.el;
1204
1205 host.select('text').text(label);
1206 }
1207
Simon Huntbb282f52014-11-10 11:08:19 -08001208 function updateDeviceState(nodeData) {
1209 nodeData.el.classed('online', nodeData.online);
1210 updateDeviceLabel(nodeData);
1211 // TODO: review what else might need to be updated
1212 }
1213
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001214 function updateLinkState(linkData) {
1215 updateLinkWidth(linkData);
Thomas Vachuskabadb93f2014-11-15 23:51:17 -08001216 linkData.el.classed('inactive', !linkData.online);
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001217 // TODO: review what else might need to be updated
1218 // update label, if showing
1219 }
1220
Simon Huntbb282f52014-11-10 11:08:19 -08001221 function updateHostState(hostData) {
1222 updateHostLabel(hostData);
1223 // TODO: review what else might need to be updated
1224 }
1225
Simon Hunt6ac93f32014-11-13 12:17:27 -08001226 function nodeMouseOver(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001227 hovered = d;
Simon Huntd72bc702014-11-13 18:38:04 -08001228 if (trafficHover() && d.class === 'host') {
1229 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001230 }
1231 }
1232
1233 function nodeMouseOut(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001234 hovered = null;
Simon Huntd72bc702014-11-13 18:38:04 -08001235 if (trafficHover() && d.class === 'host') {
1236 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001237 }
1238 }
Simon Huntbb282f52014-11-10 11:08:19 -08001239
Simon Hunt99c13842014-11-06 18:23:12 -08001240 function updateNodes() {
1241 node = nodeG.selectAll('.node')
1242 .data(network.nodes, function (d) { return d.id; });
1243
1244 // operate on existing nodes, if necessary
Simon Hunt7cd48f32014-11-09 23:42:50 -08001245 // update host labels
Simon Hunt99c13842014-11-06 18:23:12 -08001246 //node .foo() .bar() ...
1247
1248 // operate on entering nodes:
1249 var entering = node.enter()
1250 .append('g')
1251 .attr({
1252 id: function (d) { return safeId(d.id); },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001253 class: mkSvgClass,
Simon Hunt99c13842014-11-06 18:23:12 -08001254 transform: function (d) { return translate(d.x, d.y); },
1255 opacity: 0
1256 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001257 .call(network.drag)
Simon Hunt6ac93f32014-11-13 12:17:27 -08001258 .on('mouseover', nodeMouseOver)
1259 .on('mouseout', nodeMouseOut)
Simon Hunt99c13842014-11-06 18:23:12 -08001260 .transition()
1261 .attr('opacity', 1);
1262
1263 // augment device nodes...
1264 entering.filter('.device').each(function (d) {
1265 var node = d3.select(this),
1266 icon = iconUrl(d),
Simon Hunt7cd48f32014-11-09 23:42:50 -08001267 label = niceLabel(deviceLabel(d)),
Simon Hunt99c13842014-11-06 18:23:12 -08001268 box;
1269
Simon Hunt7cd48f32014-11-09 23:42:50 -08001270 // provide ref to element from backing data....
1271 d.el = node;
1272
Simon Hunt99c13842014-11-06 18:23:12 -08001273 node.append('rect')
1274 .attr({
1275 'rx': 5,
1276 'ry': 5
1277 });
1278
1279 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001280 .text(label)
Simon Hunt99c13842014-11-06 18:23:12 -08001281 .attr('dy', '1.1em');
1282
1283 box = adjustRectToFitText(node);
1284
1285 node.select('rect')
1286 .attr(box);
1287
1288 if (icon) {
1289 var cfg = config.icons;
1290 node.append('svg:image')
1291 .attr({
1292 x: box.x + config.icons.xoff,
1293 y: box.y + config.icons.yoff,
1294 width: cfg.w,
1295 height: cfg.h,
1296 'xlink:href': icon
1297 });
1298 }
1299
1300 // debug function to show the modelled x,y coordinates of nodes...
1301 if (debug('showNodeXY')) {
1302 node.select('rect').attr('fill-opacity', 0.5);
1303 node.append('circle')
1304 .attr({
1305 class: 'debug',
1306 cx: 0,
1307 cy: 0,
1308 r: '3px'
1309 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001310 }
1311 });
Simon Hunt934c3ce2014-11-05 11:45:07 -08001312
Simon Hunt56d51852014-11-09 13:03:35 -08001313 // augment host nodes...
1314 entering.filter('.host').each(function (d) {
1315 var node = d3.select(this),
Simon Hunt56d51852014-11-09 13:03:35 -08001316 box;
1317
Simon Hunt7cd48f32014-11-09 23:42:50 -08001318 // provide ref to element from backing data....
1319 d.el = node;
1320
Simon Hunt56d51852014-11-09 13:03:35 -08001321 node.append('circle')
1322 .attr('r', 8); // TODO: define host circle radius
1323
Simon Hunt56d51852014-11-09 13:03:35 -08001324 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001325 .text(hostLabel)
1326 .attr('dy', '1.3em')
1327 .attr('text-anchor', 'middle');
Simon Hunt56d51852014-11-09 13:03:35 -08001328
1329 // debug function to show the modelled x,y coordinates of nodes...
1330 if (debug('showNodeXY')) {
1331 node.select('circle').attr('fill-opacity', 0.5);
1332 node.append('circle')
1333 .attr({
1334 class: 'debug',
1335 cx: 0,
1336 cy: 0,
1337 r: '3px'
1338 });
1339 }
1340 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001341
Simon Hunt99c13842014-11-06 18:23:12 -08001342 // operate on both existing and new nodes, if necessary
1343 //node .foo() .bar() ...
Simon Huntc7ee0662014-11-05 16:44:37 -08001344
Simon Hunt99c13842014-11-06 18:23:12 -08001345 // operate on exiting nodes:
Simon Huntea80eb42014-11-11 13:46:57 -08001346 // Note that the node is removed after 2 seconds.
1347 // Sub element animations should be shorter than 2 seconds.
1348 var exiting = node.exit()
Simon Hunt44031102014-11-11 13:20:36 -08001349 .transition()
1350 .duration(2000)
Simon Huntea80eb42014-11-11 13:46:57 -08001351 .style('opacity', 0)
Simon Hunt99c13842014-11-06 18:23:12 -08001352 .remove();
Simon Huntea80eb42014-11-11 13:46:57 -08001353
1354 // host node exits....
1355 exiting.filter('.host').each(function (d) {
1356 var node = d3.select(this);
1357
1358 node.select('text')
1359 .style('opacity', 0.5)
1360 .transition()
1361 .duration(1000)
1362 .style('opacity', 0);
1363 // note, leave <g>.remove to remove this element
1364
1365 node.select('circle')
1366 .style('stroke-fill', '#555')
1367 .style('fill', '#888')
1368 .style('opacity', 0.5)
1369 .transition()
1370 .duration(1500)
1371 .attr('r', 0);
1372 // note, leave <g>.remove to remove this element
1373
1374 });
1375
1376 // TODO: device node exits
Simon Huntc7ee0662014-11-05 16:44:37 -08001377 }
1378
Simon Hunt8257f4c2014-11-16 19:34:54 -08001379 function find(key, array) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001380 for (var idx = 0, n = array.length; idx < n; idx++) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001381 if (array[idx].key === key) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001382 return idx;
1383 }
1384 }
1385 return -1;
1386 }
1387
1388 function removeLinkElement(linkData) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001389 var idx = find(linkData.key, network.links),
1390 removed;
1391 if (idx >=0) {
1392 // remove from links array
1393 removed = network.links.splice(idx, 1);
1394 // remove from lookup cache
1395 delete network.lookup[removed[0].key];
1396 updateLinks();
1397 network.force.resume();
1398 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001399 }
Simon Huntc7ee0662014-11-05 16:44:37 -08001400
Simon Hunt44031102014-11-11 13:20:36 -08001401 function removeHostElement(hostData) {
1402 // first, remove associated hostLink...
1403 removeLinkElement(hostData.linkData);
1404
1405 // remove from lookup cache
1406 delete network.lookup[hostData.id];
1407 // remove from nodes array
1408 var idx = find(hostData.id, network.nodes);
1409 network.nodes.splice(idx, 1);
1410 // remove from SVG
1411 updateNodes();
1412 network.force.resume();
1413 }
1414
1415
Simon Huntc7ee0662014-11-05 16:44:37 -08001416 function tick() {
1417 node.attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001418 transform: function (d) { return translate(d.x, d.y); }
Simon Huntc7ee0662014-11-05 16:44:37 -08001419 });
1420
1421 link.attr({
1422 x1: function (d) { return d.source.x; },
1423 y1: function (d) { return d.source.y; },
1424 x2: function (d) { return d.target.x; },
1425 y2: function (d) { return d.target.y; }
1426 });
1427 }
Simon Hunt934c3ce2014-11-05 11:45:07 -08001428
1429 // ==============================
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001430 // Web-Socket for live data
1431
1432 function webSockUrl() {
1433 return document.location.toString()
1434 .replace(/\#.*/, '')
1435 .replace('http://', 'ws://')
1436 .replace('https://', 'wss://')
1437 .replace('index2.html', config.webSockUrl);
1438 }
1439
1440 webSock = {
1441 ws : null,
1442
1443 connect : function() {
1444 webSock.ws = new WebSocket(webSockUrl());
1445
1446 webSock.ws.onopen = function() {
Simon Hunt0c6d4192014-11-12 12:07:10 -08001447 noWebSock(false);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001448 };
1449
1450 webSock.ws.onmessage = function(m) {
1451 if (m.data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001452 wsTraceRx(m.data);
Thomas Vachuskad472c6e2014-11-07 19:11:05 -08001453 handleServerEvent(JSON.parse(m.data));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001454 }
1455 };
1456
1457 webSock.ws.onclose = function(m) {
1458 webSock.ws = null;
Simon Hunt0c6d4192014-11-12 12:07:10 -08001459 noWebSock(true);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001460 };
1461 },
1462
1463 send : function(text) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001464 if (text != null) {
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001465 webSock._send(text);
1466 }
1467 },
1468
1469 _send : function(message) {
1470 if (webSock.ws) {
1471 webSock.ws.send(message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001472 } else if (config.useLiveData) {
Simon Hunt56d51852014-11-09 13:03:35 -08001473 network.view.alert('no web socket open\n\n' + message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001474 } else {
1475 console.log('WS Send: ' + JSON.stringify(message));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001476 }
1477 }
1478
1479 };
1480
Simon Hunt0c6d4192014-11-12 12:07:10 -08001481 function noWebSock(b) {
1482 mask.style('display',b ? 'block' : 'none');
1483 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001484
Simon Hunt61d04042014-11-11 17:27:16 -08001485 // TODO: use cache of pending messages (key = sid) to reconcile responses
1486
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001487 function sendMessage(evType, payload) {
1488 var toSend = {
Simon Huntbb282f52014-11-10 11:08:19 -08001489 event: evType,
1490 sid: ++sid,
1491 payload: payload
1492 },
1493 asText = JSON.stringify(toSend);
1494 wsTraceTx(asText);
1495 webSock.send(asText);
1496 }
1497
1498 function wsTraceTx(msg) {
1499 wsTrace('tx', msg);
1500 }
1501 function wsTraceRx(msg) {
1502 wsTrace('rx', msg);
1503 }
1504 function wsTrace(rxtx, msg) {
Simon Huntbb282f52014-11-10 11:08:19 -08001505 console.log('[' + rxtx + '] ' + msg);
1506 // TODO: integrate with trace view
1507 //if (trace) {
1508 // trace.output(rxtx, msg);
1509 //}
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001510 }
1511
1512
1513 // ==============================
1514 // Selection stuff
1515
1516 function selectObject(obj, el) {
1517 var n,
Simon Hunt01095ff2014-11-13 16:37:29 -08001518 srcEv = d3.event.sourceEvent,
1519 meta = srcEv.metaKey,
1520 shift = srcEv.shiftKey;
1521
Simon Huntdeab4322014-11-13 18:49:07 -08001522 if ((panZoom() && !meta) || (!panZoom() && meta)) {
Simon Hunt01095ff2014-11-13 16:37:29 -08001523 return;
1524 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001525
1526 if (el) {
1527 n = d3.select(el);
1528 } else {
1529 node.each(function(d) {
1530 if (d == obj) {
1531 n = d3.select(el = this);
1532 }
1533 });
1534 }
1535 if (!n) return;
1536
Simon Hunt01095ff2014-11-13 16:37:29 -08001537 if (shift && n.classed('selected')) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001538 deselectObject(obj.id);
Simon Hunt61d04042014-11-11 17:27:16 -08001539 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001540 return;
1541 }
1542
Simon Hunt01095ff2014-11-13 16:37:29 -08001543 if (!shift) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001544 deselectAll();
1545 }
1546
Simon Huntc31d5692014-11-12 13:27:18 -08001547 selections[obj.id] = { obj: obj, el: el };
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001548 selectOrder.push(obj.id);
1549
1550 n.classed('selected', true);
Simon Hunt61d04042014-11-11 17:27:16 -08001551 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001552 }
1553
1554 function deselectObject(id) {
Simon Huntc31d5692014-11-12 13:27:18 -08001555 var obj = selections[id],
1556 idx;
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001557 if (obj) {
1558 d3.select(obj.el).classed('selected', false);
Simon Hunt61d04042014-11-11 17:27:16 -08001559 delete selections[id];
Simon Huntc31d5692014-11-12 13:27:18 -08001560 idx = $.inArray(id, selectOrder);
1561 if (idx >= 0) {
1562 selectOrder.splice(idx, 1);
1563 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001564 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001565 }
1566
1567 function deselectAll() {
1568 // deselect all nodes in the network...
1569 node.classed('selected', false);
1570 selections = {};
1571 selectOrder = [];
Simon Hunt61d04042014-11-11 17:27:16 -08001572 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001573 }
1574
Simon Hunt61d04042014-11-11 17:27:16 -08001575 // update the state of the detail pane, based on current selections
1576 function updateDetailPane() {
1577 var nSel = selectOrder.length;
1578 if (!nSel) {
1579 detailPane.hide();
Simon Huntd72bc702014-11-13 18:38:04 -08001580 showTrafficAction(); // sends cancelTraffic event
Simon Hunt61d04042014-11-11 17:27:16 -08001581 } else if (nSel === 1) {
1582 singleSelect();
1583 } else {
1584 multiSelect();
1585 }
1586 }
1587
1588 function singleSelect() {
1589 requestDetails();
Simon Huntb53e0682014-11-12 13:32:01 -08001590 // NOTE: detail pane will be shown from showDetails event callback
Simon Hunt61d04042014-11-11 17:27:16 -08001591 }
1592
1593 function multiSelect() {
Simon Huntb53e0682014-11-12 13:32:01 -08001594 populateMultiSelect();
Simon Huntb53e0682014-11-12 13:32:01 -08001595 }
1596
1597 function addSep(tbody) {
1598 var tr = tbody.append('tr');
1599 $('<hr>').appendTo(tr.append('td').attr('colspan', 2));
1600 }
1601
1602 function addProp(tbody, label, value) {
1603 var tr = tbody.append('tr');
1604
1605 tr.append('td')
1606 .attr('class', 'label')
1607 .text(label + ' :');
1608
1609 tr.append('td')
1610 .attr('class', 'value')
1611 .text(value);
1612 }
1613
1614 function populateMultiSelect() {
1615 detailPane.empty();
1616
1617 var title = detailPane.append("h2"),
1618 table = detailPane.append("table"),
1619 tbody = table.append("tbody");
1620
1621 title.text('Multi-Select...');
1622
1623 selectOrder.forEach(function (d, i) {
1624 addProp(tbody, i+1, d);
1625 });
Simon Huntd72bc702014-11-13 18:38:04 -08001626
1627 addMultiSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001628 }
1629
1630 function populateDetails(data) {
1631 detailPane.empty();
1632
1633 var title = detailPane.append("h2"),
1634 table = detailPane.append("table"),
1635 tbody = table.append("tbody");
1636
1637 $('<img src="img/' + data.type + '.png">').appendTo(title);
1638 $('<span>').attr('class', 'icon').text(data.id).appendTo(title);
1639
1640 data.propOrder.forEach(function(p) {
1641 if (p === '-') {
1642 addSep(tbody);
1643 } else {
1644 addProp(tbody, p, data.props[p]);
1645 }
1646 });
Simon Huntd72bc702014-11-13 18:38:04 -08001647
1648 addSingleSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001649 }
1650
Simon Huntd72bc702014-11-13 18:38:04 -08001651 function addSingleSelectActions() {
1652 detailPane.append('hr');
1653 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001654 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001655 }
1656
1657 function addMultiSelectActions() {
1658 detailPane.append('hr');
1659 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001660 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001661 // if exactly two hosts are selected, also want 'add host intent'
1662 if (nSel() === 2 && allSelectionsClass('host')) {
Simon Hunta5e89142014-11-14 07:00:33 -08001663 addAction(detailPane, 'Add Host Intent', addIntentAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001664 }
1665 }
1666
Simon Hunta5e89142014-11-14 07:00:33 -08001667 function addAction(panel, text, cb) {
1668 panel.append('div')
Simon Huntd72bc702014-11-13 18:38:04 -08001669 .classed('actionBtn', true)
1670 .text(text)
1671 .on('click', cb);
1672 }
1673
1674
Paul Greysonfcba0e82014-11-13 10:21:16 -08001675 function zoomPan(scale, translate) {
1676 zoomPanContainer.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
1677 // keep the map lines constant width while zooming
1678 bgImg.style("stroke-width", 2.0 / scale + "px");
1679 }
1680
1681 function resetZoomPan() {
1682 zoomPan(1, [0,0]);
1683 zoom.scale(1).translate([0,0]);
1684 }
1685
1686 function setupZoomPan() {
1687 function zoomed() {
Simon Huntdeab4322014-11-13 18:49:07 -08001688 if (!panZoom() ^ !d3.event.sourceEvent.metaKey) {
Paul Greysonfcba0e82014-11-13 10:21:16 -08001689 zoomPan(d3.event.scale, d3.event.translate);
1690 }
1691 }
1692
1693 zoom = d3.behavior.zoom()
1694 .translate([0, 0])
1695 .scale(1)
1696 .scaleExtent([1, 8])
1697 .on("zoom", zoomed);
1698
1699 svg.call(zoom);
1700 }
1701
Simon Hunt61d04042014-11-11 17:27:16 -08001702 // ==============================
1703 // Test harness code
Simon Hunt56d51852014-11-09 13:03:35 -08001704
1705 function prepareScenario(view, ctx, dbg) {
1706 var sc = scenario,
1707 urlSc = sc.evDir + ctx + sc.evScenario;
1708
1709 if (!ctx) {
1710 view.alert("No scenario specified (null ctx)");
1711 return;
1712 }
1713
1714 sc.view = view;
1715 sc.ctx = ctx;
1716 sc.debug = dbg;
1717 sc.evNumber = 0;
1718
1719 d3.json(urlSc, function(err, data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001720 var p = data && data.params || {},
1721 desc = data && data.description || null,
Simon Huntfc274c92014-11-11 11:05:46 -08001722 intro = data && data.title;
Simon Huntbb282f52014-11-10 11:08:19 -08001723
Simon Hunt56d51852014-11-09 13:03:35 -08001724 if (err) {
1725 view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
1726 } else {
1727 sc.params = p;
Simon Huntbb282f52014-11-10 11:08:19 -08001728 if (desc) {
1729 intro += '\n\n ' + desc.join('\n ');
1730 }
1731 view.alert(intro);
Simon Hunt56d51852014-11-09 13:03:35 -08001732 }
1733 });
1734
1735 }
1736
Simon Hunt01095ff2014-11-13 16:37:29 -08001737 // ==============================
1738 // Toggle Buttons in masthead
Simon Hunt0c6d4192014-11-12 12:07:10 -08001739
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001740 // TODO: toggle button (and other widgets in the masthead) should be provided
1741 // by the framework; not generated by the view.
1742
Simon Hunta5e89142014-11-14 07:00:33 -08001743 var showInstances,
1744 doPanZoom,
1745 showTrafficOnHover;
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001746
1747 function addButtonBar(view) {
1748 var bb = d3.select('#mast')
1749 .append('span').classed('right', true).attr('id', 'bb');
1750
Simon Hunta5e89142014-11-14 07:00:33 -08001751 function mkTogBtn(text, cb) {
1752 return bb.append('span')
1753 .classed('btn', true)
1754 .text(text)
1755 .on('click', cb);
1756 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001757
Simon Hunta5e89142014-11-14 07:00:33 -08001758 showInstances = mkTogBtn('Show Instances', toggleInst);
1759 doPanZoom = mkTogBtn('Pan/Zoom', togglePanZoom);
1760 showTrafficOnHover = mkTogBtn('Show traffic on hover', toggleTrafficHover);
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001761 }
1762
Simon Hunta5e89142014-11-14 07:00:33 -08001763 function instShown() {
1764 return showInstances.classed('active');
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001765 }
Simon Hunta5e89142014-11-14 07:00:33 -08001766 function toggleInst() {
1767 showInstances.classed('active', !instShown());
1768 if (instShown()) {
1769 oiBox.show();
1770 } else {
1771 oiBox.hide();
1772 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001773 }
1774
Simon Huntdeab4322014-11-13 18:49:07 -08001775 function panZoom() {
1776 return doPanZoom.classed('active');
Simon Hunt01095ff2014-11-13 16:37:29 -08001777 }
Simon Hunta5e89142014-11-14 07:00:33 -08001778 function togglePanZoom() {
1779 doPanZoom.classed('active', !panZoom());
1780 }
1781
1782 function trafficHover() {
1783 return showTrafficOnHover.classed('active');
1784 }
1785 function toggleTrafficHover() {
1786 showTrafficOnHover.classed('active', !trafficHover());
1787 }
1788
Simon Hunt01095ff2014-11-13 16:37:29 -08001789
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001790 // ==============================
Simon Hunt142d0032014-11-04 20:13:09 -08001791 // View life-cycle callbacks
Simon Hunt195cb382014-11-03 17:50:51 -08001792
Simon Huntf67722a2014-11-10 09:32:06 -08001793 function preload(view, ctx, flags) {
Simon Hunt142d0032014-11-04 20:13:09 -08001794 var w = view.width(),
1795 h = view.height(),
Simon Huntc7ee0662014-11-05 16:44:37 -08001796 fcfg = config.force,
1797 fpad = fcfg.pad,
1798 forceDim = [w - 2*fpad, h - 2*fpad];
Simon Hunt195cb382014-11-03 17:50:51 -08001799
Simon Hunt142d0032014-11-04 20:13:09 -08001800 // NOTE: view.$div is a D3 selection of the view's div
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001801 var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
1802 svg = view.$div.append('svg').attr('viewBox', viewBox);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001803 setSize(svg, view);
1804
Simon Hunt12ce12e2014-11-15 21:13:19 -08001805 var defs = svg.append('defs');
1806 gly.defBird(defs);
1807
Paul Greysonfcba0e82014-11-13 10:21:16 -08001808 zoomPanContainer = svg.append('g').attr('id', 'zoomPanContainer');
Paul Greysonfcba0e82014-11-13 10:21:16 -08001809 setupZoomPan();
1810
Simon Hunt1a9eff92014-11-07 11:06:34 -08001811 // add blue glow filter to svg layer
Paul Greysonfcba0e82014-11-13 10:21:16 -08001812 d3u.appendGlow(zoomPanContainer);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001813
Simon Huntc7ee0662014-11-05 16:44:37 -08001814 // group for the topology
Paul Greysonfcba0e82014-11-13 10:21:16 -08001815 topoG = zoomPanContainer.append('g')
Simon Huntd3b7d512014-11-12 15:48:41 -08001816 .attr('id', 'topo-G')
Simon Huntc7ee0662014-11-05 16:44:37 -08001817 .attr('transform', fcfg.translate());
1818
1819 // subgroups for links and nodes
1820 linkG = topoG.append('g').attr('id', 'links');
1821 nodeG = topoG.append('g').attr('id', 'nodes');
1822
1823 // selection of nodes and links
1824 link = linkG.selectAll('.link');
1825 node = nodeG.selectAll('.node');
1826
Simon Hunt7cd48f32014-11-09 23:42:50 -08001827 function chrg(d) {
1828 return fcfg.charge[d.class] || -12000;
1829 }
Simon Hunt99c13842014-11-06 18:23:12 -08001830 function ldist(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001831 return fcfg.linkDistance[d.type] || 50;
Simon Hunt99c13842014-11-06 18:23:12 -08001832 }
1833 function lstrg(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001834 // 0.0 - 1.0
1835 return fcfg.linkStrength[d.type] || 1.0;
Simon Hunt99c13842014-11-06 18:23:12 -08001836 }
1837
Simon Hunt1a9eff92014-11-07 11:06:34 -08001838 function selectCb(d, self) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001839 selectObject(d, self);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001840 }
1841
1842 function atDragEnd(d, self) {
Simon Hunt56d51852014-11-09 13:03:35 -08001843 // once we've finished moving, pin the node in position
1844 d.fixed = true;
1845 d3.select(self).classed('fixed', true);
1846 if (config.useLiveData) {
Simon Hunt902c9922014-11-11 11:59:31 -08001847 sendUpdateMeta(d);
Simon Hunta255a2c2014-11-13 22:29:35 -08001848 } else {
1849 console.log('Moving node ' + d.id + ' to [' + d.x + ',' + d.y + ']');
Simon Hunt1a9eff92014-11-07 11:06:34 -08001850 }
1851 }
1852
Simon Hunt902c9922014-11-11 11:59:31 -08001853 function sendUpdateMeta(d) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001854 sendMessage('updateMeta', {
1855 id: d.id,
1856 'class': d.class,
Simon Hunt902c9922014-11-11 11:59:31 -08001857 'memento': {
Simon Hunt01095ff2014-11-13 16:37:29 -08001858 x: d.x,
1859 y: d.y
Simon Hunt902c9922014-11-11 11:59:31 -08001860 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001861 });
1862 }
1863
Simon Huntc7ee0662014-11-05 16:44:37 -08001864 // set up the force layout
1865 network.force = d3.layout.force()
1866 .size(forceDim)
1867 .nodes(network.nodes)
1868 .links(network.links)
Simon Hunt7cd48f32014-11-09 23:42:50 -08001869 .gravity(0.4)
1870 .friction(0.7)
1871 .charge(chrg)
Simon Hunt99c13842014-11-06 18:23:12 -08001872 .linkDistance(ldist)
1873 .linkStrength(lstrg)
Simon Huntc7ee0662014-11-05 16:44:37 -08001874 .on('tick', tick);
Simon Hunt195cb382014-11-03 17:50:51 -08001875
Simon Hunt01095ff2014-11-13 16:37:29 -08001876 network.drag = d3u.createDragBehavior(network.force,
Simon Huntdeab4322014-11-13 18:49:07 -08001877 selectCb, atDragEnd, panZoom);
Simon Hunt0c6d4192014-11-12 12:07:10 -08001878
1879 // create mask layer for when we lose connection to server.
Simon Hunta5e89142014-11-14 07:00:33 -08001880 // TODO: this should be part of the framework
Simon Hunt0c6d4192014-11-12 12:07:10 -08001881 mask = view.$div.append('div').attr('id','topo-mask');
1882 para(mask, 'Oops!');
1883 para(mask, 'Web-socket connection to server closed...');
1884 para(mask, 'Try refreshing the page.');
Simon Hunt12ce12e2014-11-15 21:13:19 -08001885
1886 mask.append('svg')
1887 .attr({
1888 id: 'mask-bird',
1889 width: w,
1890 height: h
1891 })
1892 .append('g')
1893 .attr('transform', birdTranslate(w, h))
1894 .style('opacity', 0.3)
1895 .append('use')
1896 .attr({
1897 'xlink:href': '#bird',
1898 width: config.birdDim,
1899 height: config.birdDim,
1900 fill: '#111'
1901 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001902 }
Simon Hunt195cb382014-11-03 17:50:51 -08001903
Simon Hunt01095ff2014-11-13 16:37:29 -08001904 function para(sel, text) {
1905 sel.append('p').text(text);
1906 }
1907
1908
Simon Hunt56d51852014-11-09 13:03:35 -08001909 function load(view, ctx, flags) {
Simon Huntf67722a2014-11-10 09:32:06 -08001910 // resize, in case the window was resized while we were not loaded
1911 resize(view, ctx, flags);
1912
Simon Hunt99c13842014-11-06 18:23:12 -08001913 // cache the view token, so network topo functions can access it
1914 network.view = view;
Simon Hunt56d51852014-11-09 13:03:35 -08001915 config.useLiveData = !flags.local;
1916
1917 if (!config.useLiveData) {
1918 prepareScenario(view, ctx, flags.debug);
1919 }
Simon Hunt99c13842014-11-06 18:23:12 -08001920
1921 // set our radio buttons and key bindings
Simon Hunt9462e8c2014-11-14 17:28:09 -08001922 layerBtnSet = view.setRadio(layerButtons);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001923 view.setKeys(keyDispatch);
Simon Hunt195cb382014-11-03 17:50:51 -08001924
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001925 // patch in our "button bar" for now
1926 // TODO: implement a more official frameworky way of doing this..
1927 addButtonBar(view);
1928
Simon Huntd3b7d512014-11-12 15:48:41 -08001929 // Load map data asynchronously; complete startup after that..
1930 loadGeoJsonData();
Simon Hunta255a2c2014-11-13 22:29:35 -08001931
1932 // start the and timer
1933 var dashIdx = 0;
1934 antTimer = setInterval(function () {
1935 // TODO: figure out how to choose Src-->Dst and Dst-->Src, per link
1936 dashIdx = dashIdx === 0 ? 14 : dashIdx - 2;
1937 d3.selectAll('.animated').style('stroke-dashoffset', dashIdx);
1938 }, 35);
1939 }
1940
1941 function unload(view, ctx, flags) {
1942 if (antTimer) {
1943 clearInterval(antTimer);
1944 antTimer = null;
1945 }
Simon Huntd3b7d512014-11-12 15:48:41 -08001946 }
1947
1948 // TODO: move these to config/state portion of script
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001949 var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
Simon Huntd3b7d512014-11-12 15:48:41 -08001950 geoJson;
1951
1952 function loadGeoJsonData() {
1953 d3.json(geoJsonUrl, function (err, data) {
1954 if (err) {
1955 // fall back to USA map background
1956 loadStaticMap();
1957 } else {
1958 geoJson = data;
1959 loadGeoMap();
1960 }
1961
1962 // finally, connect to the server...
1963 if (config.useLiveData) {
1964 webSock.connect();
1965 }
1966 });
1967 }
1968
1969 function showBg() {
1970 return config.options.showBackground ? 'visible' : 'hidden';
1971 }
1972
1973 function loadStaticMap() {
1974 fnTrace('loadStaticMap', config.backgroundUrl);
1975 var w = network.view.width(),
1976 h = network.view.height();
1977
1978 // load the background image
1979 bgImg = svg.insert('svg:image', '#topo-G')
1980 .attr({
1981 id: 'topo-bg',
1982 width: w,
1983 height: h,
1984 'xlink:href': config.backgroundUrl
1985 })
1986 .style({
1987 visibility: showBg()
1988 });
1989 }
1990
1991 function loadGeoMap() {
1992 fnTrace('loadGeoMap', geoJsonUrl);
Simon Huntd3b7d512014-11-12 15:48:41 -08001993
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001994 // extracts the topojson data into geocoordinate-based geometry
1995 var topoData = topojson.feature(geoJson, geoJson.objects.states);
Simon Huntd3b7d512014-11-12 15:48:41 -08001996
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001997 // see: http://bl.ocks.org/mbostock/4707858
1998 geoMapProjection = d3.geo.mercator();
1999 var path = d3.geo.path().projection(geoMapProjection);
Simon Huntd3b7d512014-11-12 15:48:41 -08002000
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002001 geoMapProjection
2002 .scale(1)
2003 .translate([0, 0]);
Simon Huntd3b7d512014-11-12 15:48:41 -08002004
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002005 // [[x1,y1],[x2,y2]]
2006 var b = path.bounds(topoData);
Paul Greysonfcba0e82014-11-13 10:21:16 -08002007 // size map to 95% of minimum dimension to fill space
2008 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 -08002009 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 -08002010
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002011 geoMapProjection
2012 .scale(s)
2013 .translate(t);
2014
Paul Greysonfcba0e82014-11-13 10:21:16 -08002015 bgImg = zoomPanContainer.insert("g", '#topo-G');
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002016 bgImg.attr('id', 'map').selectAll('path')
2017 .data(topoData.features)
2018 .enter()
2019 .append('path')
2020 .attr('d', path);
Simon Hunt195cb382014-11-03 17:50:51 -08002021 }
2022
Simon Huntf67722a2014-11-10 09:32:06 -08002023 function resize(view, ctx, flags) {
Simon Hunt12ce12e2014-11-15 21:13:19 -08002024 var w = view.width(),
2025 h = view.height();
2026
Simon Hunt934c3ce2014-11-05 11:45:07 -08002027 setSize(svg, view);
Simon Hunt12ce12e2014-11-15 21:13:19 -08002028
2029 d3.select('#mask-bird').attr({ width: w, height: h})
2030 .select('g').attr('transform', birdTranslate(w, h));
Simon Hunt142d0032014-11-04 20:13:09 -08002031 }
2032
Simon Hunt12ce12e2014-11-15 21:13:19 -08002033 function birdTranslate(w, h) {
2034 var bdim = config.birdDim;
2035 return 'translate('+((w-bdim)*.4)+','+((h-bdim)*.1)+')';
2036 }
Simon Hunt142d0032014-11-04 20:13:09 -08002037
2038 // ==============================
2039 // View registration
Simon Hunt195cb382014-11-03 17:50:51 -08002040
Simon Hunt25248912014-11-04 11:25:48 -08002041 onos.ui.addView('topo', {
Simon Hunt142d0032014-11-04 20:13:09 -08002042 preload: preload,
2043 load: load,
Simon Hunta255a2c2014-11-13 22:29:35 -08002044 unload: unload,
Simon Hunt142d0032014-11-04 20:13:09 -08002045 resize: resize
Simon Hunt195cb382014-11-03 17:50:51 -08002046 });
2047
Simon Hunt61d04042014-11-11 17:27:16 -08002048 detailPane = onos.ui.addFloatingPanel('topo-detail');
Simon Hunta5e89142014-11-14 07:00:33 -08002049 oiBox = onos.ui.addFloatingPanel('topo-oibox', 'TL');
Simon Hunt61d04042014-11-11 17:27:16 -08002050
Simon Hunt195cb382014-11-03 17:50:51 -08002051}(ONOS));