blob: a2dfbeab1afd8aa29a882338674f84ba68da1861 [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),
790 two: getSelId(1)
791 });
792 }
793
794 function showTrafficAction() {
795 // if nothing is hovered over, and nothing selected, send cancel request
796 if (!hovered && nSel() === 0) {
797 sendMessage('cancelTraffic', {});
798 return;
799 }
800
801 // NOTE: hover is only populated if "show traffic on hover" is
802 // toggled on, and the item hovered is a host...
803 var hoverId = (trafficHover() && hovered && hovered.class === 'host')
804 ? hovered.id : '';
805 sendMessage('requestTraffic', {
806 ids: selectOrder,
807 hover: hoverId
808 });
809 }
810
811
Simon Hunt61d04042014-11-11 17:27:16 -0800812 // ==============================
Simon Hunta5e89142014-11-14 07:00:33 -0800813 // onos instance panel functions
814
815 function updateInstances() {
816 var onoses = oiBox.el.selectAll('.onosInst')
817 .data(onosOrder, function (d) { return d.id; });
818
819 // operate on existing onoses if necessary
820
821 var entering = onoses.enter()
822 .append('div')
823 .attr('class', 'onosInst')
824 .classed('online', function (d) { return d.online; })
Simon Hunt9c15eca2014-11-15 18:37:59 -0800825 .on('click', clickInst);
826
827 entering.each(function (d, i) {
828 var el = d3.select(this),
829 img;
830
831 $('<img src="img/host.png">').appendTo(el);
832 img = el.select('img')
833 .attr({
834 width: 40,
835 top: -10,
836 left: -10
837 })
838 .style({
839 });
840
841 $('<div>').attr('class', 'onosTitle').text(d.id).appendTo(el);
842
843 // is the UI attached to this instance?
844 // TODO: need uiAttached boolean in instance data
845 //if (d.uiAttached) {
846 if (i === 0) {
847 $('<img src="img/ui.png">').attr('class','ui').appendTo(el);
848 }
849 });
Simon Hunta5e89142014-11-14 07:00:33 -0800850
851 // operate on existing + new onoses here
852
853 // the departed...
854 var exiting = onoses.exit()
855 .transition()
856 .style('opacity', 0)
857 .remove();
858 }
859
Simon Hunt9462e8c2014-11-14 17:28:09 -0800860 function clickInst(d) {
861 var el = d3.select(this),
862 aff = el.classed('affinity');
863 if (!aff) {
864 setAffinity(el, d);
865 } else {
866 cancelAffinity();
867 }
868 }
869
870 function setAffinity(el, d) {
871 d3.selectAll('.onosInst')
872 .classed('mastership', true)
873 .classed('affinity', false);
874 el.classed('affinity', true);
875
876 suppressLayers(true);
877 node.each(function (n) {
878 if (n.master === d.id) {
879 n.el.classed('suppressed', false);
880 }
881 });
882 oiShowMaster = true;
883 }
884
885 function cancelAffinity() {
886 d3.selectAll('.onosInst')
887 .classed('mastership affinity', false);
888 restoreLayerState();
889 oiShowMaster = false;
890 }
891
Simon Hunta5e89142014-11-14 07:00:33 -0800892 // ==============================
Simon Hunt99c13842014-11-06 18:23:12 -0800893 // force layout modification functions
894
895 function translate(x, y) {
896 return 'translate(' + x + ',' + y + ')';
897 }
898
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800899 function missMsg(what, id) {
900 return '\n[' + what + '] "' + id + '" missing ';
901 }
902
903 function linkEndPoints(srcId, dstId) {
904 var srcNode = network.lookup[srcId],
905 dstNode = network.lookup[dstId],
906 sMiss = !srcNode ? missMsg('src', srcId) : '',
907 dMiss = !dstNode ? missMsg('dst', dstId) : '';
908
909 if (sMiss || dMiss) {
910 logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
911 return null;
912 }
913 return {
914 source: srcNode,
915 target: dstNode,
916 x1: srcNode.x,
917 y1: srcNode.y,
918 x2: dstNode.x,
919 y2: dstNode.y
920 };
921 }
922
Simon Hunt56d51852014-11-09 13:03:35 -0800923 function createHostLink(host) {
924 var src = host.id,
925 dst = host.cp.device,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800926 id = host.ingress,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800927 lnk = linkEndPoints(src, dst);
Simon Hunt56d51852014-11-09 13:03:35 -0800928
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800929 if (!lnk) {
Simon Hunt56d51852014-11-09 13:03:35 -0800930 return null;
931 }
932
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800933 // Synthesize link ...
934 $.extend(lnk, {
Simon Hunt8257f4c2014-11-16 19:34:54 -0800935 key: id,
Simon Hunt56d51852014-11-09 13:03:35 -0800936 class: 'link',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800937
938 type: function () { return 'hostLink'; },
939 // TODO: ideally, we should see if our edge switch is online...
940 online: function () { return true; },
941 linkWidth: function () { return 1; }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800942 });
Simon Hunt99c13842014-11-06 18:23:12 -0800943 return lnk;
944 }
945
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800946 function createLink(link) {
947 var lnk = linkEndPoints(link.src, link.dst),
948 type = link.type;
949
950 if (!lnk) {
951 return null;
952 }
953
Simon Hunt8257f4c2014-11-16 19:34:54 -0800954 $.extend(lnk, {
955 key: link.id,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800956 class: 'link',
Simon Hunt8257f4c2014-11-16 19:34:54 -0800957 fromSource: link,
958
959 // functions to aggregate dual link state
960 type: function () {
961 var s = lnk.fromSource,
962 t = lnk.fromTarget;
963 return (s && s.type) || (t && t.type) || defaultLinkType;
964 },
965 online: function () {
966 var s = lnk.fromSource,
967 t = lnk.fromTarget;
968 return (s && s.online) || (t && t.online);
969 },
970 linkWidth: function () {
971 var s = lnk.fromSource,
972 t = lnk.fromTarget,
973 ws = (s && s.linkWidth) || 0,
974 wt = (t && t.linkWidth) || 0;
975 return Math.max(ws, wt);
976 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800977 });
978 return lnk;
Simon Hunt1a9eff92014-11-07 11:06:34 -0800979 }
980
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800981 var widthRatio = 1.4,
982 linkScale = d3.scale.linear()
983 .domain([1, 12])
984 .range([widthRatio, 12 * widthRatio])
985 .clamp(true);
986
Simon Hunt99c13842014-11-06 18:23:12 -0800987 function updateLinks() {
988 link = linkG.selectAll('.link')
Simon Hunt8257f4c2014-11-16 19:34:54 -0800989 .data(network.links, function (d) { return d.key; });
Simon Hunt99c13842014-11-06 18:23:12 -0800990
991 // operate on existing links, if necessary
992 // link .foo() .bar() ...
993
994 // operate on entering links:
995 var entering = link.enter()
996 .append('line')
997 .attr({
Simon Hunt99c13842014-11-06 18:23:12 -0800998 x1: function (d) { return d.x1; },
999 y1: function (d) { return d.y1; },
1000 x2: function (d) { return d.x2; },
1001 y2: function (d) { return d.y2; },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001002 stroke: config.topo.linkInColor,
1003 'stroke-width': config.topo.linkInWidth
Simon Hunt99c13842014-11-06 18:23:12 -08001004 });
1005
1006 // augment links
Simon Hunt7cd48f32014-11-09 23:42:50 -08001007 entering.each(function (d) {
1008 var link = d3.select(this);
1009 // provide ref to element selection from backing data....
1010 d.el = link;
Simon Hunt8257f4c2014-11-16 19:34:54 -08001011 restyleLinkElement(d);
Simon Hunt99c13842014-11-06 18:23:12 -08001012
Simon Hunt7cd48f32014-11-09 23:42:50 -08001013 // TODO: add src/dst port labels etc.
1014 });
Thomas Vachuska4830d392014-11-09 17:09:56 -08001015
1016 // operate on both existing and new links, if necessary
1017 //link .foo() .bar() ...
1018
1019 // operate on exiting links:
Thomas Vachuska4830d392014-11-09 17:09:56 -08001020 link.exit()
Thomas Vachuska4830d392014-11-09 17:09:56 -08001021 .attr({
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001022 'stroke-dasharray': '3, 3'
Thomas Vachuska4830d392014-11-09 17:09:56 -08001023 })
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001024 .style('opacity', 0.4)
1025 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001026 .duration(1500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001027 .attr({
1028 'stroke-dasharray': '3, 12'
1029 })
1030 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001031 .duration(500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001032 .style('opacity', 0.0)
Thomas Vachuska4830d392014-11-09 17:09:56 -08001033 .remove();
Simon Hunt99c13842014-11-06 18:23:12 -08001034 }
1035
1036 function createDeviceNode(device) {
1037 // start with the object as is
1038 var node = device,
Simon Huntbb282f52014-11-10 11:08:19 -08001039 type = device.type,
1040 svgCls = type ? 'node device ' + type : 'node device';
Simon Hunt99c13842014-11-06 18:23:12 -08001041
1042 // Augment as needed...
1043 node.class = 'device';
Simon Huntbb282f52014-11-10 11:08:19 -08001044 node.svgClass = device.online ? svgCls + ' online' : svgCls;
Simon Hunt99c13842014-11-06 18:23:12 -08001045 positionNode(node);
1046
1047 // cache label array length
1048 network.deviceLabelCount = device.labels.length;
Simon Hunt99c13842014-11-06 18:23:12 -08001049 return node;
1050 }
1051
Simon Hunt56d51852014-11-09 13:03:35 -08001052 function createHostNode(host) {
1053 // start with the object as is
1054 var node = host;
1055
1056 // Augment as needed...
1057 node.class = 'host';
Simon Hunt7cd48f32014-11-09 23:42:50 -08001058 if (!node.type) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001059 node.type = 'endstation';
1060 }
Simon Hunt56d51852014-11-09 13:03:35 -08001061 node.svgClass = 'node host';
Simon Hunt56d51852014-11-09 13:03:35 -08001062 positionNode(node);
1063
1064 // cache label array length
1065 network.hostLabelCount = host.labels.length;
Simon Hunt56d51852014-11-09 13:03:35 -08001066 return node;
1067 }
1068
Simon Hunt99c13842014-11-06 18:23:12 -08001069 function positionNode(node) {
1070 var meta = node.metaUi,
Simon Huntac9e24f2014-11-12 10:12:21 -08001071 x = meta && meta.x,
1072 y = meta && meta.y,
1073 xy;
Simon Hunt99c13842014-11-06 18:23:12 -08001074
Simon Huntac9e24f2014-11-12 10:12:21 -08001075 // If we have [x,y] already, use that...
Simon Hunt99c13842014-11-06 18:23:12 -08001076 if (x && y) {
1077 node.fixed = true;
Simon Huntac9e24f2014-11-12 10:12:21 -08001078 node.x = x;
1079 node.y = y;
1080 return;
Simon Hunt99c13842014-11-06 18:23:12 -08001081 }
Simon Huntac9e24f2014-11-12 10:12:21 -08001082
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001083 var location = node.location;
1084 if (location && location.type === 'latlng') {
1085 var coord = geoMapProjection([location.lng, location.lat]);
1086 node.fixed = true;
1087 node.x = coord[0];
1088 node.y = coord[1];
1089 return;
1090 }
1091
Simon Huntac9e24f2014-11-12 10:12:21 -08001092 // Note: Placing incoming unpinned nodes at exactly the same point
1093 // (center of the view) causes them to explode outwards when
1094 // the force layout kicks in. So, we spread them out a bit
1095 // initially, to provide a more serene layout convergence.
1096 // Additionally, if the node is a host, we place it near
1097 // the device it is connected to.
1098
1099 function spread(s) {
1100 return Math.floor((Math.random() * s) - s/2);
1101 }
1102
1103 function randDim(dim) {
1104 return dim / 2 + spread(dim * 0.7071);
1105 }
1106
1107 function rand() {
1108 return {
1109 x: randDim(network.view.width()),
1110 y: randDim(network.view.height())
1111 };
1112 }
1113
1114 function near(node) {
1115 var min = 12,
1116 dx = spread(12),
1117 dy = spread(12);
1118 return {
1119 x: node.x + min + dx,
1120 y: node.y + min + dy
1121 };
1122 }
1123
1124 function getDevice(cp) {
1125 var d = network.lookup[cp.device];
1126 return d || rand();
1127 }
1128
1129 xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
1130 $.extend(node, xy);
Simon Hunt99c13842014-11-06 18:23:12 -08001131 }
1132
Simon Hunt99c13842014-11-06 18:23:12 -08001133 function iconUrl(d) {
1134 return 'img/' + d.type + '.png';
1135 }
1136
1137 // returns the newly computed bounding box of the rectangle
1138 function adjustRectToFitText(n) {
1139 var text = n.select('text'),
1140 box = text.node().getBBox(),
1141 lab = config.labels;
1142
1143 text.attr('text-anchor', 'middle')
1144 .attr('y', '-0.8em')
1145 .attr('x', lab.imgPad/2);
1146
1147 // translate the bbox so that it is centered on [x,y]
1148 box.x = -box.width / 2;
1149 box.y = -box.height / 2;
1150
1151 // add padding
1152 box.x -= (lab.padLR + lab.imgPad/2);
1153 box.width += lab.padLR * 2 + lab.imgPad;
1154 box.y -= lab.padTB;
1155 box.height += lab.padTB * 2;
1156
1157 return box;
1158 }
1159
Simon Hunt1a9eff92014-11-07 11:06:34 -08001160 function mkSvgClass(d) {
1161 return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
1162 }
1163
Simon Hunt7cd48f32014-11-09 23:42:50 -08001164 function hostLabel(d) {
1165 var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
1166 return d.labels[idx];
1167 }
1168 function deviceLabel(d) {
1169 var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
1170 return d.labels[idx];
1171 }
1172 function niceLabel(label) {
1173 return (label && label.trim()) ? label : '.';
1174 }
1175
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001176 function updateDeviceLabel(d) {
1177 var label = niceLabel(deviceLabel(d)),
1178 node = d.el,
1179 box;
1180
1181 node.select('text')
1182 .text(label)
1183 .style('opacity', 0)
1184 .transition()
1185 .style('opacity', 1);
1186
1187 box = adjustRectToFitText(node);
1188
1189 node.select('rect')
1190 .transition()
1191 .attr(box);
1192
1193 node.select('image')
1194 .transition()
1195 .attr('x', box.x + config.icons.xoff)
1196 .attr('y', box.y + config.icons.yoff);
1197 }
1198
1199 function updateHostLabel(d) {
1200 var label = hostLabel(d),
1201 host = d.el;
1202
1203 host.select('text').text(label);
1204 }
1205
Simon Huntbb282f52014-11-10 11:08:19 -08001206 function updateDeviceState(nodeData) {
1207 nodeData.el.classed('online', nodeData.online);
1208 updateDeviceLabel(nodeData);
1209 // TODO: review what else might need to be updated
1210 }
1211
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001212 function updateLinkState(linkData) {
1213 updateLinkWidth(linkData);
Thomas Vachuskabadb93f2014-11-15 23:51:17 -08001214 linkData.el.classed('inactive', !linkData.online);
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001215 // TODO: review what else might need to be updated
1216 // update label, if showing
1217 }
1218
Simon Huntbb282f52014-11-10 11:08:19 -08001219 function updateHostState(hostData) {
1220 updateHostLabel(hostData);
1221 // TODO: review what else might need to be updated
1222 }
1223
Simon Hunt6ac93f32014-11-13 12:17:27 -08001224 function nodeMouseOver(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001225 hovered = d;
Simon Huntd72bc702014-11-13 18:38:04 -08001226 if (trafficHover() && d.class === 'host') {
1227 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001228 }
1229 }
1230
1231 function nodeMouseOut(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001232 hovered = null;
Simon Huntd72bc702014-11-13 18:38:04 -08001233 if (trafficHover() && d.class === 'host') {
1234 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001235 }
1236 }
Simon Huntbb282f52014-11-10 11:08:19 -08001237
Simon Hunt99c13842014-11-06 18:23:12 -08001238 function updateNodes() {
1239 node = nodeG.selectAll('.node')
1240 .data(network.nodes, function (d) { return d.id; });
1241
1242 // operate on existing nodes, if necessary
Simon Hunt7cd48f32014-11-09 23:42:50 -08001243 // update host labels
Simon Hunt99c13842014-11-06 18:23:12 -08001244 //node .foo() .bar() ...
1245
1246 // operate on entering nodes:
1247 var entering = node.enter()
1248 .append('g')
1249 .attr({
1250 id: function (d) { return safeId(d.id); },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001251 class: mkSvgClass,
Simon Hunt99c13842014-11-06 18:23:12 -08001252 transform: function (d) { return translate(d.x, d.y); },
1253 opacity: 0
1254 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001255 .call(network.drag)
Simon Hunt6ac93f32014-11-13 12:17:27 -08001256 .on('mouseover', nodeMouseOver)
1257 .on('mouseout', nodeMouseOut)
Simon Hunt99c13842014-11-06 18:23:12 -08001258 .transition()
1259 .attr('opacity', 1);
1260
1261 // augment device nodes...
1262 entering.filter('.device').each(function (d) {
1263 var node = d3.select(this),
1264 icon = iconUrl(d),
Simon Hunt7cd48f32014-11-09 23:42:50 -08001265 label = niceLabel(deviceLabel(d)),
Simon Hunt99c13842014-11-06 18:23:12 -08001266 box;
1267
Simon Hunt7cd48f32014-11-09 23:42:50 -08001268 // provide ref to element from backing data....
1269 d.el = node;
1270
Simon Hunt99c13842014-11-06 18:23:12 -08001271 node.append('rect')
1272 .attr({
1273 'rx': 5,
1274 'ry': 5
1275 });
1276
1277 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001278 .text(label)
Simon Hunt99c13842014-11-06 18:23:12 -08001279 .attr('dy', '1.1em');
1280
1281 box = adjustRectToFitText(node);
1282
1283 node.select('rect')
1284 .attr(box);
1285
1286 if (icon) {
1287 var cfg = config.icons;
1288 node.append('svg:image')
1289 .attr({
1290 x: box.x + config.icons.xoff,
1291 y: box.y + config.icons.yoff,
1292 width: cfg.w,
1293 height: cfg.h,
1294 'xlink:href': icon
1295 });
1296 }
1297
1298 // debug function to show the modelled x,y coordinates of nodes...
1299 if (debug('showNodeXY')) {
1300 node.select('rect').attr('fill-opacity', 0.5);
1301 node.append('circle')
1302 .attr({
1303 class: 'debug',
1304 cx: 0,
1305 cy: 0,
1306 r: '3px'
1307 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001308 }
1309 });
Simon Hunt934c3ce2014-11-05 11:45:07 -08001310
Simon Hunt56d51852014-11-09 13:03:35 -08001311 // augment host nodes...
1312 entering.filter('.host').each(function (d) {
1313 var node = d3.select(this),
Simon Hunt56d51852014-11-09 13:03:35 -08001314 box;
1315
Simon Hunt7cd48f32014-11-09 23:42:50 -08001316 // provide ref to element from backing data....
1317 d.el = node;
1318
Simon Hunt56d51852014-11-09 13:03:35 -08001319 node.append('circle')
1320 .attr('r', 8); // TODO: define host circle radius
1321
Simon Hunt56d51852014-11-09 13:03:35 -08001322 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001323 .text(hostLabel)
1324 .attr('dy', '1.3em')
1325 .attr('text-anchor', 'middle');
Simon Hunt56d51852014-11-09 13:03:35 -08001326
1327 // debug function to show the modelled x,y coordinates of nodes...
1328 if (debug('showNodeXY')) {
1329 node.select('circle').attr('fill-opacity', 0.5);
1330 node.append('circle')
1331 .attr({
1332 class: 'debug',
1333 cx: 0,
1334 cy: 0,
1335 r: '3px'
1336 });
1337 }
1338 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001339
Simon Hunt99c13842014-11-06 18:23:12 -08001340 // operate on both existing and new nodes, if necessary
1341 //node .foo() .bar() ...
Simon Huntc7ee0662014-11-05 16:44:37 -08001342
Simon Hunt99c13842014-11-06 18:23:12 -08001343 // operate on exiting nodes:
Simon Huntea80eb42014-11-11 13:46:57 -08001344 // Note that the node is removed after 2 seconds.
1345 // Sub element animations should be shorter than 2 seconds.
1346 var exiting = node.exit()
Simon Hunt44031102014-11-11 13:20:36 -08001347 .transition()
1348 .duration(2000)
Simon Huntea80eb42014-11-11 13:46:57 -08001349 .style('opacity', 0)
Simon Hunt99c13842014-11-06 18:23:12 -08001350 .remove();
Simon Huntea80eb42014-11-11 13:46:57 -08001351
1352 // host node exits....
1353 exiting.filter('.host').each(function (d) {
1354 var node = d3.select(this);
1355
1356 node.select('text')
1357 .style('opacity', 0.5)
1358 .transition()
1359 .duration(1000)
1360 .style('opacity', 0);
1361 // note, leave <g>.remove to remove this element
1362
1363 node.select('circle')
1364 .style('stroke-fill', '#555')
1365 .style('fill', '#888')
1366 .style('opacity', 0.5)
1367 .transition()
1368 .duration(1500)
1369 .attr('r', 0);
1370 // note, leave <g>.remove to remove this element
1371
1372 });
1373
1374 // TODO: device node exits
Simon Huntc7ee0662014-11-05 16:44:37 -08001375 }
1376
Simon Hunt8257f4c2014-11-16 19:34:54 -08001377 function find(key, array) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001378 for (var idx = 0, n = array.length; idx < n; idx++) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001379 if (array[idx].key === key) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001380 return idx;
1381 }
1382 }
1383 return -1;
1384 }
1385
1386 function removeLinkElement(linkData) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001387 var idx = find(linkData.key, network.links),
1388 removed;
1389 if (idx >=0) {
1390 // remove from links array
1391 removed = network.links.splice(idx, 1);
1392 // remove from lookup cache
1393 delete network.lookup[removed[0].key];
1394 updateLinks();
1395 network.force.resume();
1396 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001397 }
Simon Huntc7ee0662014-11-05 16:44:37 -08001398
Simon Hunt44031102014-11-11 13:20:36 -08001399 function removeHostElement(hostData) {
1400 // first, remove associated hostLink...
1401 removeLinkElement(hostData.linkData);
1402
1403 // remove from lookup cache
1404 delete network.lookup[hostData.id];
1405 // remove from nodes array
1406 var idx = find(hostData.id, network.nodes);
1407 network.nodes.splice(idx, 1);
1408 // remove from SVG
1409 updateNodes();
1410 network.force.resume();
1411 }
1412
1413
Simon Huntc7ee0662014-11-05 16:44:37 -08001414 function tick() {
1415 node.attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001416 transform: function (d) { return translate(d.x, d.y); }
Simon Huntc7ee0662014-11-05 16:44:37 -08001417 });
1418
1419 link.attr({
1420 x1: function (d) { return d.source.x; },
1421 y1: function (d) { return d.source.y; },
1422 x2: function (d) { return d.target.x; },
1423 y2: function (d) { return d.target.y; }
1424 });
1425 }
Simon Hunt934c3ce2014-11-05 11:45:07 -08001426
1427 // ==============================
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001428 // Web-Socket for live data
1429
1430 function webSockUrl() {
1431 return document.location.toString()
1432 .replace(/\#.*/, '')
1433 .replace('http://', 'ws://')
1434 .replace('https://', 'wss://')
1435 .replace('index2.html', config.webSockUrl);
1436 }
1437
1438 webSock = {
1439 ws : null,
1440
1441 connect : function() {
1442 webSock.ws = new WebSocket(webSockUrl());
1443
1444 webSock.ws.onopen = function() {
Simon Hunt0c6d4192014-11-12 12:07:10 -08001445 noWebSock(false);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001446 };
1447
1448 webSock.ws.onmessage = function(m) {
1449 if (m.data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001450 wsTraceRx(m.data);
Thomas Vachuskad472c6e2014-11-07 19:11:05 -08001451 handleServerEvent(JSON.parse(m.data));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001452 }
1453 };
1454
1455 webSock.ws.onclose = function(m) {
1456 webSock.ws = null;
Simon Hunt0c6d4192014-11-12 12:07:10 -08001457 noWebSock(true);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001458 };
1459 },
1460
1461 send : function(text) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001462 if (text != null) {
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001463 webSock._send(text);
1464 }
1465 },
1466
1467 _send : function(message) {
1468 if (webSock.ws) {
1469 webSock.ws.send(message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001470 } else if (config.useLiveData) {
Simon Hunt56d51852014-11-09 13:03:35 -08001471 network.view.alert('no web socket open\n\n' + message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001472 } else {
1473 console.log('WS Send: ' + JSON.stringify(message));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001474 }
1475 }
1476
1477 };
1478
Simon Hunt0c6d4192014-11-12 12:07:10 -08001479 function noWebSock(b) {
1480 mask.style('display',b ? 'block' : 'none');
1481 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001482
Simon Hunt61d04042014-11-11 17:27:16 -08001483 // TODO: use cache of pending messages (key = sid) to reconcile responses
1484
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001485 function sendMessage(evType, payload) {
1486 var toSend = {
Simon Huntbb282f52014-11-10 11:08:19 -08001487 event: evType,
1488 sid: ++sid,
1489 payload: payload
1490 },
1491 asText = JSON.stringify(toSend);
1492 wsTraceTx(asText);
1493 webSock.send(asText);
1494 }
1495
1496 function wsTraceTx(msg) {
1497 wsTrace('tx', msg);
1498 }
1499 function wsTraceRx(msg) {
1500 wsTrace('rx', msg);
1501 }
1502 function wsTrace(rxtx, msg) {
Simon Huntbb282f52014-11-10 11:08:19 -08001503 console.log('[' + rxtx + '] ' + msg);
1504 // TODO: integrate with trace view
1505 //if (trace) {
1506 // trace.output(rxtx, msg);
1507 //}
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001508 }
1509
1510
1511 // ==============================
1512 // Selection stuff
1513
1514 function selectObject(obj, el) {
1515 var n,
Simon Hunt01095ff2014-11-13 16:37:29 -08001516 srcEv = d3.event.sourceEvent,
1517 meta = srcEv.metaKey,
1518 shift = srcEv.shiftKey;
1519
Simon Huntdeab4322014-11-13 18:49:07 -08001520 if ((panZoom() && !meta) || (!panZoom() && meta)) {
Simon Hunt01095ff2014-11-13 16:37:29 -08001521 return;
1522 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001523
1524 if (el) {
1525 n = d3.select(el);
1526 } else {
1527 node.each(function(d) {
1528 if (d == obj) {
1529 n = d3.select(el = this);
1530 }
1531 });
1532 }
1533 if (!n) return;
1534
Simon Hunt01095ff2014-11-13 16:37:29 -08001535 if (shift && n.classed('selected')) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001536 deselectObject(obj.id);
Simon Hunt61d04042014-11-11 17:27:16 -08001537 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001538 return;
1539 }
1540
Simon Hunt01095ff2014-11-13 16:37:29 -08001541 if (!shift) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001542 deselectAll();
1543 }
1544
Simon Huntc31d5692014-11-12 13:27:18 -08001545 selections[obj.id] = { obj: obj, el: el };
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001546 selectOrder.push(obj.id);
1547
1548 n.classed('selected', true);
Simon Hunt61d04042014-11-11 17:27:16 -08001549 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001550 }
1551
1552 function deselectObject(id) {
Simon Huntc31d5692014-11-12 13:27:18 -08001553 var obj = selections[id],
1554 idx;
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001555 if (obj) {
1556 d3.select(obj.el).classed('selected', false);
Simon Hunt61d04042014-11-11 17:27:16 -08001557 delete selections[id];
Simon Huntc31d5692014-11-12 13:27:18 -08001558 idx = $.inArray(id, selectOrder);
1559 if (idx >= 0) {
1560 selectOrder.splice(idx, 1);
1561 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001562 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001563 }
1564
1565 function deselectAll() {
1566 // deselect all nodes in the network...
1567 node.classed('selected', false);
1568 selections = {};
1569 selectOrder = [];
Simon Hunt61d04042014-11-11 17:27:16 -08001570 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001571 }
1572
Simon Hunt61d04042014-11-11 17:27:16 -08001573 // update the state of the detail pane, based on current selections
1574 function updateDetailPane() {
1575 var nSel = selectOrder.length;
1576 if (!nSel) {
1577 detailPane.hide();
Simon Huntd72bc702014-11-13 18:38:04 -08001578 showTrafficAction(); // sends cancelTraffic event
Simon Hunt61d04042014-11-11 17:27:16 -08001579 } else if (nSel === 1) {
1580 singleSelect();
1581 } else {
1582 multiSelect();
1583 }
1584 }
1585
1586 function singleSelect() {
1587 requestDetails();
Simon Huntb53e0682014-11-12 13:32:01 -08001588 // NOTE: detail pane will be shown from showDetails event callback
Simon Hunt61d04042014-11-11 17:27:16 -08001589 }
1590
1591 function multiSelect() {
Simon Huntb53e0682014-11-12 13:32:01 -08001592 populateMultiSelect();
Simon Huntb53e0682014-11-12 13:32:01 -08001593 }
1594
1595 function addSep(tbody) {
1596 var tr = tbody.append('tr');
1597 $('<hr>').appendTo(tr.append('td').attr('colspan', 2));
1598 }
1599
1600 function addProp(tbody, label, value) {
1601 var tr = tbody.append('tr');
1602
1603 tr.append('td')
1604 .attr('class', 'label')
1605 .text(label + ' :');
1606
1607 tr.append('td')
1608 .attr('class', 'value')
1609 .text(value);
1610 }
1611
1612 function populateMultiSelect() {
1613 detailPane.empty();
1614
1615 var title = detailPane.append("h2"),
1616 table = detailPane.append("table"),
1617 tbody = table.append("tbody");
1618
1619 title.text('Multi-Select...');
1620
1621 selectOrder.forEach(function (d, i) {
1622 addProp(tbody, i+1, d);
1623 });
Simon Huntd72bc702014-11-13 18:38:04 -08001624
1625 addMultiSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001626 }
1627
1628 function populateDetails(data) {
1629 detailPane.empty();
1630
1631 var title = detailPane.append("h2"),
1632 table = detailPane.append("table"),
1633 tbody = table.append("tbody");
1634
1635 $('<img src="img/' + data.type + '.png">').appendTo(title);
1636 $('<span>').attr('class', 'icon').text(data.id).appendTo(title);
1637
1638 data.propOrder.forEach(function(p) {
1639 if (p === '-') {
1640 addSep(tbody);
1641 } else {
1642 addProp(tbody, p, data.props[p]);
1643 }
1644 });
Simon Huntd72bc702014-11-13 18:38:04 -08001645
1646 addSingleSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001647 }
1648
Simon Huntd72bc702014-11-13 18:38:04 -08001649 function addSingleSelectActions() {
1650 detailPane.append('hr');
1651 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001652 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001653 }
1654
1655 function addMultiSelectActions() {
1656 detailPane.append('hr');
1657 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001658 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001659 // if exactly two hosts are selected, also want 'add host intent'
1660 if (nSel() === 2 && allSelectionsClass('host')) {
Simon Hunta5e89142014-11-14 07:00:33 -08001661 addAction(detailPane, 'Add Host Intent', addIntentAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001662 }
1663 }
1664
Simon Hunta5e89142014-11-14 07:00:33 -08001665 function addAction(panel, text, cb) {
1666 panel.append('div')
Simon Huntd72bc702014-11-13 18:38:04 -08001667 .classed('actionBtn', true)
1668 .text(text)
1669 .on('click', cb);
1670 }
1671
1672
Paul Greysonfcba0e82014-11-13 10:21:16 -08001673 function zoomPan(scale, translate) {
1674 zoomPanContainer.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
1675 // keep the map lines constant width while zooming
1676 bgImg.style("stroke-width", 2.0 / scale + "px");
1677 }
1678
1679 function resetZoomPan() {
1680 zoomPan(1, [0,0]);
1681 zoom.scale(1).translate([0,0]);
1682 }
1683
1684 function setupZoomPan() {
1685 function zoomed() {
Simon Huntdeab4322014-11-13 18:49:07 -08001686 if (!panZoom() ^ !d3.event.sourceEvent.metaKey) {
Paul Greysonfcba0e82014-11-13 10:21:16 -08001687 zoomPan(d3.event.scale, d3.event.translate);
1688 }
1689 }
1690
1691 zoom = d3.behavior.zoom()
1692 .translate([0, 0])
1693 .scale(1)
1694 .scaleExtent([1, 8])
1695 .on("zoom", zoomed);
1696
1697 svg.call(zoom);
1698 }
1699
Simon Hunt61d04042014-11-11 17:27:16 -08001700 // ==============================
1701 // Test harness code
Simon Hunt56d51852014-11-09 13:03:35 -08001702
1703 function prepareScenario(view, ctx, dbg) {
1704 var sc = scenario,
1705 urlSc = sc.evDir + ctx + sc.evScenario;
1706
1707 if (!ctx) {
1708 view.alert("No scenario specified (null ctx)");
1709 return;
1710 }
1711
1712 sc.view = view;
1713 sc.ctx = ctx;
1714 sc.debug = dbg;
1715 sc.evNumber = 0;
1716
1717 d3.json(urlSc, function(err, data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001718 var p = data && data.params || {},
1719 desc = data && data.description || null,
Simon Huntfc274c92014-11-11 11:05:46 -08001720 intro = data && data.title;
Simon Huntbb282f52014-11-10 11:08:19 -08001721
Simon Hunt56d51852014-11-09 13:03:35 -08001722 if (err) {
1723 view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
1724 } else {
1725 sc.params = p;
Simon Huntbb282f52014-11-10 11:08:19 -08001726 if (desc) {
1727 intro += '\n\n ' + desc.join('\n ');
1728 }
1729 view.alert(intro);
Simon Hunt56d51852014-11-09 13:03:35 -08001730 }
1731 });
1732
1733 }
1734
Simon Hunt01095ff2014-11-13 16:37:29 -08001735 // ==============================
1736 // Toggle Buttons in masthead
Simon Hunt0c6d4192014-11-12 12:07:10 -08001737
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001738 // TODO: toggle button (and other widgets in the masthead) should be provided
1739 // by the framework; not generated by the view.
1740
Simon Hunta5e89142014-11-14 07:00:33 -08001741 var showInstances,
1742 doPanZoom,
1743 showTrafficOnHover;
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001744
1745 function addButtonBar(view) {
1746 var bb = d3.select('#mast')
1747 .append('span').classed('right', true).attr('id', 'bb');
1748
Simon Hunta5e89142014-11-14 07:00:33 -08001749 function mkTogBtn(text, cb) {
1750 return bb.append('span')
1751 .classed('btn', true)
1752 .text(text)
1753 .on('click', cb);
1754 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001755
Simon Hunta5e89142014-11-14 07:00:33 -08001756 showInstances = mkTogBtn('Show Instances', toggleInst);
1757 doPanZoom = mkTogBtn('Pan/Zoom', togglePanZoom);
1758 showTrafficOnHover = mkTogBtn('Show traffic on hover', toggleTrafficHover);
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001759 }
1760
Simon Hunta5e89142014-11-14 07:00:33 -08001761 function instShown() {
1762 return showInstances.classed('active');
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001763 }
Simon Hunta5e89142014-11-14 07:00:33 -08001764 function toggleInst() {
1765 showInstances.classed('active', !instShown());
1766 if (instShown()) {
1767 oiBox.show();
1768 } else {
1769 oiBox.hide();
1770 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001771 }
1772
Simon Huntdeab4322014-11-13 18:49:07 -08001773 function panZoom() {
1774 return doPanZoom.classed('active');
Simon Hunt01095ff2014-11-13 16:37:29 -08001775 }
Simon Hunta5e89142014-11-14 07:00:33 -08001776 function togglePanZoom() {
1777 doPanZoom.classed('active', !panZoom());
1778 }
1779
1780 function trafficHover() {
1781 return showTrafficOnHover.classed('active');
1782 }
1783 function toggleTrafficHover() {
1784 showTrafficOnHover.classed('active', !trafficHover());
1785 }
1786
Simon Hunt01095ff2014-11-13 16:37:29 -08001787
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001788 // ==============================
Simon Hunt142d0032014-11-04 20:13:09 -08001789 // View life-cycle callbacks
Simon Hunt195cb382014-11-03 17:50:51 -08001790
Simon Huntf67722a2014-11-10 09:32:06 -08001791 function preload(view, ctx, flags) {
Simon Hunt142d0032014-11-04 20:13:09 -08001792 var w = view.width(),
1793 h = view.height(),
Simon Huntc7ee0662014-11-05 16:44:37 -08001794 fcfg = config.force,
1795 fpad = fcfg.pad,
1796 forceDim = [w - 2*fpad, h - 2*fpad];
Simon Hunt195cb382014-11-03 17:50:51 -08001797
Simon Hunt142d0032014-11-04 20:13:09 -08001798 // NOTE: view.$div is a D3 selection of the view's div
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001799 var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
1800 svg = view.$div.append('svg').attr('viewBox', viewBox);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001801 setSize(svg, view);
1802
Simon Hunt12ce12e2014-11-15 21:13:19 -08001803 var defs = svg.append('defs');
1804 gly.defBird(defs);
1805
Paul Greysonfcba0e82014-11-13 10:21:16 -08001806 zoomPanContainer = svg.append('g').attr('id', 'zoomPanContainer');
Paul Greysonfcba0e82014-11-13 10:21:16 -08001807 setupZoomPan();
1808
Simon Hunt1a9eff92014-11-07 11:06:34 -08001809 // add blue glow filter to svg layer
Paul Greysonfcba0e82014-11-13 10:21:16 -08001810 d3u.appendGlow(zoomPanContainer);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001811
Simon Huntc7ee0662014-11-05 16:44:37 -08001812 // group for the topology
Paul Greysonfcba0e82014-11-13 10:21:16 -08001813 topoG = zoomPanContainer.append('g')
Simon Huntd3b7d512014-11-12 15:48:41 -08001814 .attr('id', 'topo-G')
Simon Huntc7ee0662014-11-05 16:44:37 -08001815 .attr('transform', fcfg.translate());
1816
1817 // subgroups for links and nodes
1818 linkG = topoG.append('g').attr('id', 'links');
1819 nodeG = topoG.append('g').attr('id', 'nodes');
1820
1821 // selection of nodes and links
1822 link = linkG.selectAll('.link');
1823 node = nodeG.selectAll('.node');
1824
Simon Hunt7cd48f32014-11-09 23:42:50 -08001825 function chrg(d) {
1826 return fcfg.charge[d.class] || -12000;
1827 }
Simon Hunt99c13842014-11-06 18:23:12 -08001828 function ldist(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001829 return fcfg.linkDistance[d.type] || 50;
Simon Hunt99c13842014-11-06 18:23:12 -08001830 }
1831 function lstrg(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001832 // 0.0 - 1.0
1833 return fcfg.linkStrength[d.type] || 1.0;
Simon Hunt99c13842014-11-06 18:23:12 -08001834 }
1835
Simon Hunt1a9eff92014-11-07 11:06:34 -08001836 function selectCb(d, self) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001837 selectObject(d, self);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001838 }
1839
1840 function atDragEnd(d, self) {
Simon Hunt56d51852014-11-09 13:03:35 -08001841 // once we've finished moving, pin the node in position
1842 d.fixed = true;
1843 d3.select(self).classed('fixed', true);
1844 if (config.useLiveData) {
Simon Hunt902c9922014-11-11 11:59:31 -08001845 sendUpdateMeta(d);
Simon Hunta255a2c2014-11-13 22:29:35 -08001846 } else {
1847 console.log('Moving node ' + d.id + ' to [' + d.x + ',' + d.y + ']');
Simon Hunt1a9eff92014-11-07 11:06:34 -08001848 }
1849 }
1850
Simon Hunt902c9922014-11-11 11:59:31 -08001851 function sendUpdateMeta(d) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001852 sendMessage('updateMeta', {
1853 id: d.id,
1854 'class': d.class,
Simon Hunt902c9922014-11-11 11:59:31 -08001855 'memento': {
Simon Hunt01095ff2014-11-13 16:37:29 -08001856 x: d.x,
1857 y: d.y
Simon Hunt902c9922014-11-11 11:59:31 -08001858 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001859 });
1860 }
1861
Simon Huntc7ee0662014-11-05 16:44:37 -08001862 // set up the force layout
1863 network.force = d3.layout.force()
1864 .size(forceDim)
1865 .nodes(network.nodes)
1866 .links(network.links)
Simon Hunt7cd48f32014-11-09 23:42:50 -08001867 .gravity(0.4)
1868 .friction(0.7)
1869 .charge(chrg)
Simon Hunt99c13842014-11-06 18:23:12 -08001870 .linkDistance(ldist)
1871 .linkStrength(lstrg)
Simon Huntc7ee0662014-11-05 16:44:37 -08001872 .on('tick', tick);
Simon Hunt195cb382014-11-03 17:50:51 -08001873
Simon Hunt01095ff2014-11-13 16:37:29 -08001874 network.drag = d3u.createDragBehavior(network.force,
Simon Huntdeab4322014-11-13 18:49:07 -08001875 selectCb, atDragEnd, panZoom);
Simon Hunt0c6d4192014-11-12 12:07:10 -08001876
1877 // create mask layer for when we lose connection to server.
Simon Hunta5e89142014-11-14 07:00:33 -08001878 // TODO: this should be part of the framework
Simon Hunt0c6d4192014-11-12 12:07:10 -08001879 mask = view.$div.append('div').attr('id','topo-mask');
1880 para(mask, 'Oops!');
1881 para(mask, 'Web-socket connection to server closed...');
1882 para(mask, 'Try refreshing the page.');
Simon Hunt12ce12e2014-11-15 21:13:19 -08001883
1884 mask.append('svg')
1885 .attr({
1886 id: 'mask-bird',
1887 width: w,
1888 height: h
1889 })
1890 .append('g')
1891 .attr('transform', birdTranslate(w, h))
1892 .style('opacity', 0.3)
1893 .append('use')
1894 .attr({
1895 'xlink:href': '#bird',
1896 width: config.birdDim,
1897 height: config.birdDim,
1898 fill: '#111'
1899 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001900 }
Simon Hunt195cb382014-11-03 17:50:51 -08001901
Simon Hunt01095ff2014-11-13 16:37:29 -08001902 function para(sel, text) {
1903 sel.append('p').text(text);
1904 }
1905
1906
Simon Hunt56d51852014-11-09 13:03:35 -08001907 function load(view, ctx, flags) {
Simon Huntf67722a2014-11-10 09:32:06 -08001908 // resize, in case the window was resized while we were not loaded
1909 resize(view, ctx, flags);
1910
Simon Hunt99c13842014-11-06 18:23:12 -08001911 // cache the view token, so network topo functions can access it
1912 network.view = view;
Simon Hunt56d51852014-11-09 13:03:35 -08001913 config.useLiveData = !flags.local;
1914
1915 if (!config.useLiveData) {
1916 prepareScenario(view, ctx, flags.debug);
1917 }
Simon Hunt99c13842014-11-06 18:23:12 -08001918
1919 // set our radio buttons and key bindings
Simon Hunt9462e8c2014-11-14 17:28:09 -08001920 layerBtnSet = view.setRadio(layerButtons);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001921 view.setKeys(keyDispatch);
Simon Hunt195cb382014-11-03 17:50:51 -08001922
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001923 // patch in our "button bar" for now
1924 // TODO: implement a more official frameworky way of doing this..
1925 addButtonBar(view);
1926
Simon Huntd3b7d512014-11-12 15:48:41 -08001927 // Load map data asynchronously; complete startup after that..
1928 loadGeoJsonData();
Simon Hunta255a2c2014-11-13 22:29:35 -08001929
1930 // start the and timer
1931 var dashIdx = 0;
1932 antTimer = setInterval(function () {
1933 // TODO: figure out how to choose Src-->Dst and Dst-->Src, per link
1934 dashIdx = dashIdx === 0 ? 14 : dashIdx - 2;
1935 d3.selectAll('.animated').style('stroke-dashoffset', dashIdx);
1936 }, 35);
1937 }
1938
1939 function unload(view, ctx, flags) {
1940 if (antTimer) {
1941 clearInterval(antTimer);
1942 antTimer = null;
1943 }
Simon Huntd3b7d512014-11-12 15:48:41 -08001944 }
1945
1946 // TODO: move these to config/state portion of script
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001947 var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
Simon Huntd3b7d512014-11-12 15:48:41 -08001948 geoJson;
1949
1950 function loadGeoJsonData() {
1951 d3.json(geoJsonUrl, function (err, data) {
1952 if (err) {
1953 // fall back to USA map background
1954 loadStaticMap();
1955 } else {
1956 geoJson = data;
1957 loadGeoMap();
1958 }
1959
1960 // finally, connect to the server...
1961 if (config.useLiveData) {
1962 webSock.connect();
1963 }
1964 });
1965 }
1966
1967 function showBg() {
1968 return config.options.showBackground ? 'visible' : 'hidden';
1969 }
1970
1971 function loadStaticMap() {
1972 fnTrace('loadStaticMap', config.backgroundUrl);
1973 var w = network.view.width(),
1974 h = network.view.height();
1975
1976 // load the background image
1977 bgImg = svg.insert('svg:image', '#topo-G')
1978 .attr({
1979 id: 'topo-bg',
1980 width: w,
1981 height: h,
1982 'xlink:href': config.backgroundUrl
1983 })
1984 .style({
1985 visibility: showBg()
1986 });
1987 }
1988
1989 function loadGeoMap() {
1990 fnTrace('loadGeoMap', geoJsonUrl);
Simon Huntd3b7d512014-11-12 15:48:41 -08001991
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001992 // extracts the topojson data into geocoordinate-based geometry
1993 var topoData = topojson.feature(geoJson, geoJson.objects.states);
Simon Huntd3b7d512014-11-12 15:48:41 -08001994
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001995 // see: http://bl.ocks.org/mbostock/4707858
1996 geoMapProjection = d3.geo.mercator();
1997 var path = d3.geo.path().projection(geoMapProjection);
Simon Huntd3b7d512014-11-12 15:48:41 -08001998
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001999 geoMapProjection
2000 .scale(1)
2001 .translate([0, 0]);
Simon Huntd3b7d512014-11-12 15:48:41 -08002002
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002003 // [[x1,y1],[x2,y2]]
2004 var b = path.bounds(topoData);
Paul Greysonfcba0e82014-11-13 10:21:16 -08002005 // size map to 95% of minimum dimension to fill space
2006 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 -08002007 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 -08002008
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002009 geoMapProjection
2010 .scale(s)
2011 .translate(t);
2012
Paul Greysonfcba0e82014-11-13 10:21:16 -08002013 bgImg = zoomPanContainer.insert("g", '#topo-G');
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002014 bgImg.attr('id', 'map').selectAll('path')
2015 .data(topoData.features)
2016 .enter()
2017 .append('path')
2018 .attr('d', path);
Simon Hunt195cb382014-11-03 17:50:51 -08002019 }
2020
Simon Huntf67722a2014-11-10 09:32:06 -08002021 function resize(view, ctx, flags) {
Simon Hunt12ce12e2014-11-15 21:13:19 -08002022 var w = view.width(),
2023 h = view.height();
2024
Simon Hunt934c3ce2014-11-05 11:45:07 -08002025 setSize(svg, view);
Simon Hunt12ce12e2014-11-15 21:13:19 -08002026
2027 d3.select('#mask-bird').attr({ width: w, height: h})
2028 .select('g').attr('transform', birdTranslate(w, h));
Simon Hunt142d0032014-11-04 20:13:09 -08002029 }
2030
Simon Hunt12ce12e2014-11-15 21:13:19 -08002031 function birdTranslate(w, h) {
2032 var bdim = config.birdDim;
2033 return 'translate('+((w-bdim)*.4)+','+((h-bdim)*.1)+')';
2034 }
Simon Hunt142d0032014-11-04 20:13:09 -08002035
2036 // ==============================
2037 // View registration
Simon Hunt195cb382014-11-03 17:50:51 -08002038
Simon Hunt25248912014-11-04 11:25:48 -08002039 onos.ui.addView('topo', {
Simon Hunt142d0032014-11-04 20:13:09 -08002040 preload: preload,
2041 load: load,
Simon Hunta255a2c2014-11-13 22:29:35 -08002042 unload: unload,
Simon Hunt142d0032014-11-04 20:13:09 -08002043 resize: resize
Simon Hunt195cb382014-11-03 17:50:51 -08002044 });
2045
Simon Hunt61d04042014-11-11 17:27:16 -08002046 detailPane = onos.ui.addFloatingPanel('topo-detail');
Simon Hunta5e89142014-11-14 07:00:33 -08002047 oiBox = onos.ui.addFloatingPanel('topo-oibox', 'TL');
Simon Hunt61d04042014-11-11 17:27:16 -08002048
Simon Hunt195cb382014-11-03 17:50:51 -08002049}(ONOS));