blob: 1dedc6d6184a76dbda3794d0f6469fb6164746f5 [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',
Simon Hunt13bf9c82014-11-18 07:26:44 -080074 linkOutColor: '#f00',
Paul Greyson29cd58f2014-11-18 13:14:57 -080075 linkInWidth: 14,
Simon Hunt13bf9c82014-11-18 07:26:44 -080076 linkOutWidth: 30
Simon Hunt1a9eff92014-11-07 11:06:34 -080077 },
Paul Greyson29cd58f2014-11-18 13:14:57 -080078 map: {
79 strokeWidth: 1
Simon Hunt99c13842014-11-06 18:23:12 -080080 },
Paul Greyson29cd58f2014-11-18 13:14:57 -080081 icons: {
82 w: 100,
83 h: 100
Simon Hunt195cb382014-11-03 17:50:51 -080084 },
Simon Hunt195cb382014-11-03 17:50:51 -080085 force: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080086 note_for_links: 'link.type is used to differentiate',
Simon Huntc7ee0662014-11-05 16:44:37 -080087 linkDistance: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080088 direct: 100,
89 optical: 120,
Thomas Vachuska3266abf2014-11-13 09:28:46 -080090 hostLink: 3
Simon Huntc7ee0662014-11-05 16:44:37 -080091 },
92 linkStrength: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080093 direct: 1.0,
94 optical: 1.0,
95 hostLink: 1.0
Simon Huntc7ee0662014-11-05 16:44:37 -080096 },
Simon Hunt7cd48f32014-11-09 23:42:50 -080097 note_for_nodes: 'node.class is used to differentiate',
Simon Huntc7ee0662014-11-05 16:44:37 -080098 charge: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080099 device: -8000,
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800100 host: -5000
Simon Huntc7ee0662014-11-05 16:44:37 -0800101 },
102 pad: 20,
Simon Hunt195cb382014-11-03 17:50:51 -0800103 translate: function() {
104 return 'translate(' +
Simon Huntc7ee0662014-11-05 16:44:37 -0800105 config.force.pad + ',' +
106 config.force.pad + ')';
Simon Hunt195cb382014-11-03 17:50:51 -0800107 }
Paul Greyson6cb8ca02014-11-12 18:09:02 -0800108 },
109 // see below in creation of viewBox on main svg
110 logicalSize: 1000
Simon Hunt195cb382014-11-03 17:50:51 -0800111 };
112
Simon Hunt142d0032014-11-04 20:13:09 -0800113 // radio buttons
Simon Hunt9462e8c2014-11-14 17:28:09 -0800114 var layerButtons = [
115 { text: 'All Layers', id: 'all', cb: showAllLayers },
116 { text: 'Packet Only', id: 'pkt', cb: showPacketLayer },
117 { text: 'Optical Only', id: 'opt', cb: showOpticalLayer }
118 ],
119 layerBtnSet,
120 layerBtnDispatch = {
121 all: showAllLayers,
122 pkt: showPacketLayer,
123 opt: showOpticalLayer
124 };
Simon Hunt934c3ce2014-11-05 11:45:07 -0800125
126 // key bindings
127 var keyDispatch = {
Simon Hunta255a2c2014-11-13 22:29:35 -0800128 M: testMe, // TODO: remove (testing only)
129 S: injectStartupEvents, // TODO: remove (testing only)
130 space: injectTestEvent, // TODO: remove (testing only)
Simon Hunt99c13842014-11-06 18:23:12 -0800131
Simon Hunt01095ff2014-11-13 16:37:29 -0800132 B: toggleBg,
Simon Hunt934c3ce2014-11-05 11:45:07 -0800133 L: cycleLabels,
134 P: togglePorts,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800135 U: unpin,
Paul Greysonfcba0e82014-11-13 10:21:16 -0800136 R: resetZoomPan,
Simon Hunt9462e8c2014-11-14 17:28:09 -0800137 esc: handleEscape
Simon Hunt934c3ce2014-11-05 11:45:07 -0800138 };
Simon Hunt142d0032014-11-04 20:13:09 -0800139
Simon Hunt195cb382014-11-03 17:50:51 -0800140 // state variables
Simon Hunt99c13842014-11-06 18:23:12 -0800141 var network = {
Simon Hunt50128c02014-11-08 13:36:15 -0800142 view: null, // view token reference
Simon Hunt99c13842014-11-06 18:23:12 -0800143 nodes: [],
144 links: [],
Simon Hunt269670f2014-11-17 16:17:43 -0800145 lookup: {},
146 revLinkToKey: {}
Simon Hunt99c13842014-11-06 18:23:12 -0800147 },
Simon Hunt56d51852014-11-09 13:03:35 -0800148 scenario = {
149 evDir: 'json/ev/',
150 evScenario: '/scenario.json',
151 evPrefix: '/ev_',
152 evOnos: '_onos.json',
153 evUi: '_ui.json',
154 ctx: null,
155 params: {},
156 evNumber: 0,
157 view: null,
158 debug: false
159 },
Thomas Vachuska7d638d32014-11-07 10:24:43 -0800160 webSock,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800161 sid = 0,
Simon Hunt56d51852014-11-09 13:03:35 -0800162 deviceLabelIndex = 0,
163 hostLabelIndex = 0,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800164 selections = {},
Simon Hunta5e89142014-11-14 07:00:33 -0800165 selectOrder = [],
Simon Hunt6ac93f32014-11-13 12:17:27 -0800166 hovered = null,
Simon Hunta5e89142014-11-14 07:00:33 -0800167 detailPane,
Simon Hunta255a2c2014-11-13 22:29:35 -0800168 antTimer = null,
Simon Hunta5e89142014-11-14 07:00:33 -0800169 onosInstances = {},
170 onosOrder = [],
171 oiBox,
Simon Hunt9462e8c2014-11-14 17:28:09 -0800172 oiShowMaster = false,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800173
Simon Hunt195cb382014-11-03 17:50:51 -0800174 portLabelsOn = false;
175
Simon Hunt934c3ce2014-11-05 11:45:07 -0800176 // D3 selections
177 var svg,
Paul Greysonfcba0e82014-11-13 10:21:16 -0800178 zoomPanContainer,
Simon Hunt934c3ce2014-11-05 11:45:07 -0800179 bgImg,
Simon Huntc7ee0662014-11-05 16:44:37 -0800180 topoG,
181 nodeG,
182 linkG,
Simon Hunte2575b62014-11-18 15:25:53 -0800183 linkLabelG,
Simon Huntc7ee0662014-11-05 16:44:37 -0800184 node,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800185 link,
Simon Hunte2575b62014-11-18 15:25:53 -0800186 linkLabel,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800187 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 Hunt625dc402014-11-18 10:57:18 -0800220 view.alert('Theme is ' + view.theme());
Simon Hunt99c13842014-11-06 18:23:12 -0800221 }
222
Simon Hunt56d51852014-11-09 13:03:35 -0800223 function abortIfLive() {
Simon Hunt50128c02014-11-08 13:36:15 -0800224 if (config.useLiveData) {
Simon Huntb53e0682014-11-12 13:32:01 -0800225 network.view.alert("Sorry, currently using live data..");
Simon Hunt56d51852014-11-09 13:03:35 -0800226 return true;
Simon Hunt50128c02014-11-08 13:36:15 -0800227 }
Simon Hunt56d51852014-11-09 13:03:35 -0800228 return false;
229 }
Simon Hunt50128c02014-11-08 13:36:15 -0800230
Simon Hunt56d51852014-11-09 13:03:35 -0800231 function testDebug(msg) {
232 if (scenario.debug) {
233 scenario.view.alert(msg);
234 }
235 }
Simon Hunt99c13842014-11-06 18:23:12 -0800236
Simon Hunt56d51852014-11-09 13:03:35 -0800237 function injectTestEvent(view) {
238 if (abortIfLive()) { return; }
239 var sc = scenario,
240 evn = ++sc.evNumber,
241 pfx = sc.evDir + sc.ctx + sc.evPrefix + evn,
242 onosUrl = pfx + sc.evOnos,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800243 uiUrl = pfx + sc.evUi,
244 stack = [
245 { url: onosUrl, cb: handleServerEvent },
246 { url: uiUrl, cb: handleUiEvent }
247 ];
248 recurseFetchEvent(stack, evn);
Simon Hunt56d51852014-11-09 13:03:35 -0800249 }
250
Simon Hunt7cd48f32014-11-09 23:42:50 -0800251 function recurseFetchEvent(stack, evn) {
252 var v = scenario.view,
253 frame;
254 if (stack.length === 0) {
Simon Huntfc274c92014-11-11 11:05:46 -0800255 v.alert('Oops!\n\nNo event #' + evn + ' found.');
Simon Hunt7cd48f32014-11-09 23:42:50 -0800256 return;
257 }
258 frame = stack.shift();
259
260 d3.json(frame.url, function (err, data) {
Simon Hunt99c13842014-11-06 18:23:12 -0800261 if (err) {
Simon Hunt56d51852014-11-09 13:03:35 -0800262 if (err.status === 404) {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800263 // if we didn't find the data, try the next stack frame
264 recurseFetchEvent(stack, evn);
Simon Hunt56d51852014-11-09 13:03:35 -0800265 } else {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800266 v.alert('non-404 error:\n\n' + frame.url + '\n\n' + err);
Simon Hunt56d51852014-11-09 13:03:35 -0800267 }
Simon Hunt99c13842014-11-06 18:23:12 -0800268 } else {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800269 testDebug('loaded: ' + frame.url);
Simon Hunt1712ed82014-11-17 12:56:00 -0800270 wsTrace('test', JSON.stringify(data));
Simon Hunt7cd48f32014-11-09 23:42:50 -0800271 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
Simon Hunt269670f2014-11-17 16:17:43 -0800425 function findLinkById(id) {
426 // check to see if this is a reverse lookup, else default to given id
427 var key = network.revLinkToKey[id] || id;
428 return key && network.lookup[key];
429 }
430
Simon Hunt8257f4c2014-11-16 19:34:54 -0800431 function findLink(linkData, op) {
432 var key = makeLinkKey(linkData),
433 keyrev = makeLinkKey(linkData, 1),
434 link = network.lookup[key],
435 linkRev = network.lookup[keyrev],
436 result = {},
437 ldata = link || linkRev,
438 rawLink;
439
440 if (op === 'add') {
441 if (link) {
442 // trying to add a link that we already know about
443 result.ldata = link;
444 result.badLogic = 'addLink: link already added';
445
446 } else if (linkRev) {
447 // we found the reverse of the link to be added
448 result.ldata = linkRev;
449 if (linkRev.fromTarget) {
450 result.badLogic = 'addLink: link already added';
451 }
452 }
453 } else if (op === 'update') {
454 if (!ldata) {
455 result.badLogic = 'updateLink: link not found';
456 } else {
457 rawLink = link ? ldata.fromSource : ldata.fromTarget;
458 result.updateWith = function (data) {
459 $.extend(rawLink, data);
460 restyleLinkElement(ldata);
461 }
462 }
463 } else if (op === 'remove') {
464 if (!ldata) {
465 result.badLogic = 'removeLink: link not found';
466 } else {
467 rawLink = link ? ldata.fromSource : ldata.fromTarget;
468
469 if (!rawLink) {
470 result.badLogic = 'removeLink: link not found';
471
472 } else {
473 result.removeRawLink = function () {
474 if (link) {
475 // remove fromSource
476 ldata.fromSource = null;
477 if (ldata.fromTarget) {
478 // promote target into source position
479 ldata.fromSource = ldata.fromTarget;
480 ldata.fromTarget = null;
481 ldata.key = keyrev;
482 delete network.lookup[key];
483 network.lookup[keyrev] = ldata;
Simon Hunt269670f2014-11-17 16:17:43 -0800484 delete network.revLinkToKey[keyrev];
Simon Hunt8257f4c2014-11-16 19:34:54 -0800485 }
486 } else {
487 // remove fromTarget
488 ldata.fromTarget = null;
Simon Hunt269670f2014-11-17 16:17:43 -0800489 delete network.revLinkToKey[keyrev];
Simon Hunt8257f4c2014-11-16 19:34:54 -0800490 }
491 if (ldata.fromSource) {
492 restyleLinkElement(ldata);
493 } else {
494 removeLinkElement(ldata);
495 }
496 }
497 }
498 }
499 }
500 return result;
501 }
502
503 function addLinkUpdate(ldata, link) {
504 // add link event, but we already have the reverse link installed
505 ldata.fromTarget = link;
Simon Hunt269670f2014-11-17 16:17:43 -0800506 network.revLinkToKey[link.id] = ldata.key;
Simon Hunt8257f4c2014-11-16 19:34:54 -0800507 restyleLinkElement(ldata);
508 }
509
510 var allLinkTypes = 'direct indirect optical tunnel',
511 defaultLinkType = 'direct';
512
513 function restyleLinkElement(ldata) {
514 // this fn's job is to look at raw links and decide what svg classes
515 // need to be applied to the line element in the DOM
516 var el = ldata.el,
517 type = ldata.type(),
518 lw = ldata.linkWidth(),
519 online = ldata.online();
520
521 el.classed('link', true);
522 el.classed('inactive', !online);
523 el.classed(allLinkTypes, false);
524 if (type) {
525 el.classed(type, true);
526 }
527 el.transition()
528 .duration(1000)
Paul Greyson29cd58f2014-11-18 13:14:57 -0800529 .attr('stroke-width', linkScale(lw));
Simon Hunt8257f4c2014-11-16 19:34:54 -0800530 }
Simon Hunt934c3ce2014-11-05 11:45:07 -0800531
Simon Hunt99c13842014-11-06 18:23:12 -0800532 // ==============================
533 // Event handlers for server-pushed events
534
Simon Huntbb282f52014-11-10 11:08:19 -0800535 function logicError(msg) {
536 // TODO, report logic error to server, via websock, so it can be logged
Simon Huntcb56cff2014-11-17 11:42:26 -0800537 //network.view.alert('Logic Error:\n\n' + msg);
Simon Huntfc274c92014-11-11 11:05:46 -0800538 console.warn(msg);
Simon Huntbb282f52014-11-10 11:08:19 -0800539 }
540
Simon Hunt99c13842014-11-06 18:23:12 -0800541 var eventDispatch = {
Simon Hunta5e89142014-11-14 07:00:33 -0800542 addInstance: addInstance,
Simon Hunt99c13842014-11-06 18:23:12 -0800543 addDevice: addDevice,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800544 addLink: addLink,
Simon Hunt56d51852014-11-09 13:03:35 -0800545 addHost: addHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800546
Simon Huntd72bc702014-11-13 18:38:04 -0800547 updateInstance: stillToImplement,
Simon Huntbb282f52014-11-10 11:08:19 -0800548 updateDevice: updateDevice,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800549 updateLink: updateLink,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800550 updateHost: updateHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800551
Simon Huntd72bc702014-11-13 18:38:04 -0800552 removeInstance: stillToImplement,
Simon Huntbb282f52014-11-10 11:08:19 -0800553 removeDevice: stillToImplement,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800554 removeLink: removeLink,
Simon Hunt44031102014-11-11 13:20:36 -0800555 removeHost: removeHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800556
Simon Hunt61d04042014-11-11 17:27:16 -0800557 showDetails: showDetails,
Simon Huntb53e0682014-11-12 13:32:01 -0800558 showTraffic: showTraffic
Simon Hunt99c13842014-11-06 18:23:12 -0800559 };
560
Simon Hunta5e89142014-11-14 07:00:33 -0800561 function addInstance(data) {
562 evTrace(data);
563 var inst = data.payload,
564 id = inst.id;
565 if (onosInstances[id]) {
566 logicError('ONOS instance already added: ' + id);
567 return;
568 }
569 onosInstances[id] = inst;
570 onosOrder.push(inst);
571 updateInstances();
572 }
573
Simon Hunt99c13842014-11-06 18:23:12 -0800574 function addDevice(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800575 evTrace(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800576 var device = data.payload,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800577 nodeData = createDeviceNode(device);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800578 network.nodes.push(nodeData);
579 network.lookup[nodeData.id] = nodeData;
Simon Hunt99c13842014-11-06 18:23:12 -0800580 updateNodes();
581 network.force.start();
582 }
583
Simon Hunt99c13842014-11-06 18:23:12 -0800584 function addLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800585 evTrace(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800586 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800587 result = findLink(link, 'add'),
588 bad = result.badLogic,
589 ldata = result.ldata;
590
591 if (bad) {
592 logicError(bad + ': ' + link.id);
593 return;
594 }
595
596 if (ldata) {
597 // we already have a backing store link for src/dst nodes
598 addLinkUpdate(ldata, link);
599 return;
600 }
601
602 // no backing store link yet
603 ldata = createLink(link);
604 if (ldata) {
605 network.links.push(ldata);
606 network.lookup[ldata.key] = ldata;
Simon Hunt99c13842014-11-06 18:23:12 -0800607 updateLinks();
608 network.force.start();
609 }
610 }
611
Simon Hunt56d51852014-11-09 13:03:35 -0800612 function addHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800613 evTrace(data);
Simon Hunt56d51852014-11-09 13:03:35 -0800614 var host = data.payload,
615 node = createHostNode(host),
616 lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800617 network.nodes.push(node);
618 network.lookup[host.id] = node;
619 updateNodes();
620
621 lnk = createHostLink(host);
622 if (lnk) {
Simon Hunt44031102014-11-11 13:20:36 -0800623 node.linkData = lnk; // cache ref on its host
Simon Hunt56d51852014-11-09 13:03:35 -0800624 network.links.push(lnk);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800625 network.lookup[host.ingress] = lnk;
626 network.lookup[host.egress] = lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800627 updateLinks();
628 }
629 network.force.start();
630 }
631
Simon Hunt44031102014-11-11 13:20:36 -0800632 // TODO: fold updateX(...) methods into one base method; remove duplication
Simon Huntbb282f52014-11-10 11:08:19 -0800633 function updateDevice(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800634 evTrace(data);
Simon Huntbb282f52014-11-10 11:08:19 -0800635 var device = data.payload,
636 id = device.id,
637 nodeData = network.lookup[id];
638 if (nodeData) {
639 $.extend(nodeData, device);
640 updateDeviceState(nodeData);
641 } else {
642 logicError('updateDevice lookup fail. ID = "' + id + '"');
643 }
644 }
645
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800646 function updateLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800647 evTrace(data);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800648 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800649 result = findLink(link, 'update'),
650 bad = result.badLogic;
651 if (bad) {
652 logicError(bad + ': ' + link.id);
653 return;
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800654 }
Simon Hunt8257f4c2014-11-16 19:34:54 -0800655 result.updateWith(link);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800656 }
657
Simon Hunt7cd48f32014-11-09 23:42:50 -0800658 function updateHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800659 evTrace(data);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800660 var host = data.payload,
Simon Huntbb282f52014-11-10 11:08:19 -0800661 id = host.id,
662 hostData = network.lookup[id];
663 if (hostData) {
664 $.extend(hostData, host);
665 updateHostState(hostData);
666 } else {
667 logicError('updateHost lookup fail. ID = "' + id + '"');
668 }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800669 }
670
Simon Hunt44031102014-11-11 13:20:36 -0800671 // TODO: fold removeX(...) methods into base method - remove dup code
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800672 function removeLink(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800673 evTrace(data);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800674 var link = data.payload,
Simon Hunt8257f4c2014-11-16 19:34:54 -0800675 result = findLink(link, 'remove'),
676 bad = result.badLogic;
677 if (bad) {
678 logicError(bad + ': ' + link.id);
679 return;
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800680 }
Simon Hunt8257f4c2014-11-16 19:34:54 -0800681 result.removeRawLink();
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800682 }
683
Simon Hunt44031102014-11-11 13:20:36 -0800684 function removeHost(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800685 evTrace(data);
Simon Hunt44031102014-11-11 13:20:36 -0800686 var host = data.payload,
687 id = host.id,
688 hostData = network.lookup[id];
689 if (hostData) {
690 removeHostElement(hostData);
691 } else {
692 logicError('removeHost lookup fail. ID = "' + id + '"');
693 }
694 }
695
Simon Hunt61d04042014-11-11 17:27:16 -0800696 function showDetails(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800697 evTrace(data);
Simon Hunt61d04042014-11-11 17:27:16 -0800698 populateDetails(data.payload);
699 detailPane.show();
700 }
701
Simon Huntb53e0682014-11-12 13:32:01 -0800702 function showTraffic(data) {
Simon Hunta5e89142014-11-14 07:00:33 -0800703 evTrace(data);
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800704 var paths = data.payload.paths;
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800705
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800706 // Revert any links hilighted previously.
Simon Hunta255a2c2014-11-13 22:29:35 -0800707 link.classed('primary secondary animated optical', false);
Simon Hunte2575b62014-11-18 15:25:53 -0800708 // Remove all previous labels.
709 removeLinkLabels();
Thomas Vachuska3266abf2014-11-13 09:28:46 -0800710
Simon Hunte2575b62014-11-18 15:25:53 -0800711 // Now hilight all links in the paths payload, and attach
712 // labels to them, if they are defined.
Simon Hunta255a2c2014-11-13 22:29:35 -0800713 paths.forEach(function (p) {
Simon Hunte2575b62014-11-18 15:25:53 -0800714 var n = p.links.length,
715 i,
716 ldata;
717
718 for (i=0; i<n; i++) {
719 ldata = findLinkById(p.links[i]);
720 if (ldata) {
721 ldata.el.classed(p.class, true);
722 ldata.label = p.labels[i];
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800723 }
Simon Hunte2575b62014-11-18 15:25:53 -0800724 }
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800725 });
Simon Hunte2575b62014-11-18 15:25:53 -0800726 updateLinks();
Simon Huntb53e0682014-11-12 13:32:01 -0800727 }
728
Simon Hunt56d51852014-11-09 13:03:35 -0800729 // ...............................
730
731 function stillToImplement(data) {
732 var p = data.payload;
733 note(data.event, p.id);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800734 network.view.alert('Not yet implemented: "' + data.event + '"');
Simon Hunt56d51852014-11-09 13:03:35 -0800735 }
Simon Hunt99c13842014-11-06 18:23:12 -0800736
737 function unknownEvent(data) {
Simon Hunt50128c02014-11-08 13:36:15 -0800738 network.view.alert('Unknown event type: "' + data.event + '"');
Simon Hunt99c13842014-11-06 18:23:12 -0800739 }
740
741 function handleServerEvent(data) {
742 var fn = eventDispatch[data.event] || unknownEvent;
743 fn(data);
744 }
745
746 // ==============================
Simon Hunt61d04042014-11-11 17:27:16 -0800747 // Out-going messages...
748
Simon Huntb53e0682014-11-12 13:32:01 -0800749 function userFeedback(msg) {
750 // for now, use the alert pane as is. Maybe different alert style in
751 // the future (centered on view; dismiss button?)
752 network.view.alert(msg);
753 }
754
755 function nSel() {
756 return selectOrder.length;
757 }
Simon Hunt61d04042014-11-11 17:27:16 -0800758 function getSel(idx) {
759 return selections[selectOrder[idx]];
760 }
Simon Huntb53e0682014-11-12 13:32:01 -0800761 function getSelId(idx) {
762 return getSel(idx).obj.id;
763 }
764 function allSelectionsClass(cls) {
765 for (var i=0, n=nSel(); i<n; i++) {
766 if (getSel(i).obj.class !== cls) {
767 return false;
768 }
769 }
770 return true;
771 }
Simon Hunt61d04042014-11-11 17:27:16 -0800772
Simon Hunt61d04042014-11-11 17:27:16 -0800773 // request details for the selected element
Simon Huntd72bc702014-11-13 18:38:04 -0800774 // invoked from selection of a single node.
Simon Hunt61d04042014-11-11 17:27:16 -0800775 function requestDetails() {
776 var data = getSel(0).obj,
777 payload = {
778 id: data.id,
779 class: data.class
780 };
781 sendMessage('requestDetails', payload);
782 }
783
Simon Huntd72bc702014-11-13 18:38:04 -0800784 function addIntentAction() {
785 sendMessage('addHostIntent', {
786 one: getSelId(0),
Thomas Vachuska82f2c622014-11-17 12:23:18 -0800787 two: getSelId(1),
788 ids: [ getSelId(0), getSelId(1) ]
Simon Huntd72bc702014-11-13 18:38:04 -0800789 });
790 }
791
792 function showTrafficAction() {
793 // if nothing is hovered over, and nothing selected, send cancel request
794 if (!hovered && nSel() === 0) {
795 sendMessage('cancelTraffic', {});
796 return;
797 }
798
799 // NOTE: hover is only populated if "show traffic on hover" is
800 // toggled on, and the item hovered is a host...
801 var hoverId = (trafficHover() && hovered && hovered.class === 'host')
802 ? hovered.id : '';
803 sendMessage('requestTraffic', {
804 ids: selectOrder,
805 hover: hoverId
806 });
807 }
808
809
Simon Hunt61d04042014-11-11 17:27:16 -0800810 // ==============================
Simon Hunta5e89142014-11-14 07:00:33 -0800811 // onos instance panel functions
812
813 function updateInstances() {
814 var onoses = oiBox.el.selectAll('.onosInst')
815 .data(onosOrder, function (d) { return d.id; });
816
817 // operate on existing onoses if necessary
818
819 var entering = onoses.enter()
820 .append('div')
821 .attr('class', 'onosInst')
822 .classed('online', function (d) { return d.online; })
Simon Hunt9c15eca2014-11-15 18:37:59 -0800823 .on('click', clickInst);
824
825 entering.each(function (d, i) {
826 var el = d3.select(this),
827 img;
828
829 $('<img src="img/host.png">').appendTo(el);
830 img = el.select('img')
831 .attr({
832 width: 40,
833 top: -10,
834 left: -10
835 })
836 .style({
837 });
838
839 $('<div>').attr('class', 'onosTitle').text(d.id).appendTo(el);
840
841 // is the UI attached to this instance?
842 // TODO: need uiAttached boolean in instance data
843 //if (d.uiAttached) {
844 if (i === 0) {
845 $('<img src="img/ui.png">').attr('class','ui').appendTo(el);
846 }
847 });
Simon Hunta5e89142014-11-14 07:00:33 -0800848
849 // operate on existing + new onoses here
850
851 // the departed...
852 var exiting = onoses.exit()
853 .transition()
854 .style('opacity', 0)
855 .remove();
856 }
857
Simon Hunt9462e8c2014-11-14 17:28:09 -0800858 function clickInst(d) {
859 var el = d3.select(this),
860 aff = el.classed('affinity');
861 if (!aff) {
862 setAffinity(el, d);
863 } else {
864 cancelAffinity();
865 }
866 }
867
868 function setAffinity(el, d) {
869 d3.selectAll('.onosInst')
870 .classed('mastership', true)
871 .classed('affinity', false);
872 el.classed('affinity', true);
873
874 suppressLayers(true);
875 node.each(function (n) {
876 if (n.master === d.id) {
877 n.el.classed('suppressed', false);
878 }
879 });
880 oiShowMaster = true;
881 }
882
883 function cancelAffinity() {
884 d3.selectAll('.onosInst')
885 .classed('mastership affinity', false);
886 restoreLayerState();
887 oiShowMaster = false;
888 }
889
Simon Hunta5e89142014-11-14 07:00:33 -0800890 // ==============================
Simon Hunt99c13842014-11-06 18:23:12 -0800891 // force layout modification functions
892
893 function translate(x, y) {
894 return 'translate(' + x + ',' + y + ')';
895 }
896
Simon Hunte2575b62014-11-18 15:25:53 -0800897 function rotate(deg) {
898 return 'rotate(' + deg + ')';
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 Hunte2575b62014-11-18 15:25:53 -0800983 function removeLinkLabels() {
984 network.links.forEach(function (d) {
985 d.label = '';
986 });
987 }
988
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800989 var widthRatio = 1.4,
990 linkScale = d3.scale.linear()
991 .domain([1, 12])
992 .range([widthRatio, 12 * widthRatio])
993 .clamp(true);
994
Simon Hunt99c13842014-11-06 18:23:12 -0800995 function updateLinks() {
996 link = linkG.selectAll('.link')
Simon Hunt8257f4c2014-11-16 19:34:54 -0800997 .data(network.links, function (d) { return d.key; });
Simon Hunt99c13842014-11-06 18:23:12 -0800998
999 // operate on existing links, if necessary
1000 // link .foo() .bar() ...
1001
1002 // operate on entering links:
1003 var entering = link.enter()
1004 .append('line')
1005 .attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001006 x1: function (d) { return d.x1; },
1007 y1: function (d) { return d.y1; },
1008 x2: function (d) { return d.x2; },
1009 y2: function (d) { return d.y2; },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001010 stroke: config.topo.linkInColor,
1011 'stroke-width': config.topo.linkInWidth
Simon Hunt99c13842014-11-06 18:23:12 -08001012 });
1013
1014 // augment links
Simon Hunt7cd48f32014-11-09 23:42:50 -08001015 entering.each(function (d) {
1016 var link = d3.select(this);
1017 // provide ref to element selection from backing data....
1018 d.el = link;
Simon Hunt8257f4c2014-11-16 19:34:54 -08001019 restyleLinkElement(d);
Simon Hunt7cd48f32014-11-09 23:42:50 -08001020 });
Thomas Vachuska4830d392014-11-09 17:09:56 -08001021
1022 // operate on both existing and new links, if necessary
1023 //link .foo() .bar() ...
1024
Simon Hunte2575b62014-11-18 15:25:53 -08001025 // apply or remove labels
1026 var labelData = getLabelData();
1027 applyLinkLabels(labelData);
1028
Thomas Vachuska4830d392014-11-09 17:09:56 -08001029 // operate on exiting links:
Thomas Vachuska4830d392014-11-09 17:09:56 -08001030 link.exit()
Simon Hunt13bf9c82014-11-18 07:26:44 -08001031 .attr('stroke-dasharray', '3, 3')
1032 .style('opacity', 0.5)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001033 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -08001034 .duration(1500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001035 .attr({
Simon Hunt13bf9c82014-11-18 07:26:44 -08001036 'stroke-dasharray': '3, 12',
1037 stroke: config.topo.linkOutColor,
1038 'stroke-width': config.topo.linkOutWidth
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001039 })
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001040 .style('opacity', 0.0)
Thomas Vachuska4830d392014-11-09 17:09:56 -08001041 .remove();
Simon Hunte2575b62014-11-18 15:25:53 -08001042
1043 // NOTE: invoke a single tick to force the labels to position
1044 // onto their links.
1045 tick();
1046 }
1047
1048 function getLabelData() {
1049 // create the backing data for showing labels..
1050 var data = [];
1051 link.each(function (d) {
1052 if (d.label) {
1053 data.push({
1054 id: 'lab-' + d.key,
1055 key: d.key,
1056 label: d.label,
1057 ldata: d
1058 });
1059 }
1060 });
1061 return data;
1062 }
1063
1064 var linkLabelOffset = '0.3em';
1065
1066 function applyLinkLabels(data) {
1067 var entering;
1068
1069 linkLabel = linkLabelG.selectAll('.linkLabel')
1070 .data(data, function (d) { return d.id; });
1071
1072 entering = linkLabel.enter().append('g')
1073 .classed('linkLabel', true)
1074 .attr('id', function (d) { return d.id; });
1075
1076 entering.each(function (d) {
1077 var el = d3.select(this),
1078 rect,
1079 text,
1080 parms = {
1081 x1: d.ldata.x1,
1082 y1: d.ldata.y1,
1083 x2: d.ldata.x2,
1084 y2: d.ldata.y2
1085 };
1086
1087 d.el = el;
1088 rect = el.append('rect');
1089 text = el.append('text').text(d.label);
1090 rect.attr(rectAroundText(el));
1091 text.attr('dy', linkLabelOffset);
1092
1093 el.attr('transform', transformLabel(parms));
1094 });
1095
1096 // Remove any links that are no longer required.
1097 linkLabel.exit().remove();
1098 }
1099
1100 function rectAroundText(el) {
1101 var text = el.select('text'),
1102 box = text.node().getBBox();
1103
1104 // translate the bbox so that it is centered on [x,y]
1105 box.x = -box.width / 2;
1106 box.y = -box.height / 2;
1107
1108 // add padding
1109 box.x -= 1;
1110 box.width += 2;
1111 return box;
1112 }
1113
1114 function transformLabel(p) {
1115 var dx = p.x2 - p.x1,
1116 dy = p.y2 - p.y1,
1117 xMid = dx/2 + p.x1,
1118 yMid = dy/2 + p.y1;
1119 //length = Math.sqrt(dx*dx + dy*dy),
1120 //rads = Math.asin(dy/length),
1121 //degs = rads / (Math.PI*2) * 360;
1122
1123 return translate(xMid, yMid);
1124
1125 // TODO: consider making label parallel to line
1126 //return [
1127 // translate(xMid, yMid),
1128 // rotate(degs),
1129 // translate(0, 8)
1130 //].join('');
Simon Hunt99c13842014-11-06 18:23:12 -08001131 }
1132
1133 function createDeviceNode(device) {
1134 // start with the object as is
1135 var node = device,
Simon Huntbb282f52014-11-10 11:08:19 -08001136 type = device.type,
1137 svgCls = type ? 'node device ' + type : 'node device';
Simon Hunt99c13842014-11-06 18:23:12 -08001138
1139 // Augment as needed...
1140 node.class = 'device';
Simon Huntbb282f52014-11-10 11:08:19 -08001141 node.svgClass = device.online ? svgCls + ' online' : svgCls;
Simon Hunt99c13842014-11-06 18:23:12 -08001142 positionNode(node);
1143
1144 // cache label array length
1145 network.deviceLabelCount = device.labels.length;
Simon Hunt99c13842014-11-06 18:23:12 -08001146 return node;
1147 }
1148
Simon Hunt56d51852014-11-09 13:03:35 -08001149 function createHostNode(host) {
1150 // start with the object as is
1151 var node = host;
1152
1153 // Augment as needed...
1154 node.class = 'host';
Simon Hunt7cd48f32014-11-09 23:42:50 -08001155 if (!node.type) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001156 node.type = 'endstation';
1157 }
Simon Hunt7fa116d2014-11-17 14:16:55 -08001158 node.svgClass = 'node host ' + node.type;
Simon Hunt56d51852014-11-09 13:03:35 -08001159 positionNode(node);
1160
1161 // cache label array length
1162 network.hostLabelCount = host.labels.length;
Simon Hunt56d51852014-11-09 13:03:35 -08001163 return node;
1164 }
1165
Simon Hunt99c13842014-11-06 18:23:12 -08001166 function positionNode(node) {
1167 var meta = node.metaUi,
Simon Huntac9e24f2014-11-12 10:12:21 -08001168 x = meta && meta.x,
1169 y = meta && meta.y,
1170 xy;
Simon Hunt99c13842014-11-06 18:23:12 -08001171
Simon Huntac9e24f2014-11-12 10:12:21 -08001172 // If we have [x,y] already, use that...
Simon Hunt99c13842014-11-06 18:23:12 -08001173 if (x && y) {
1174 node.fixed = true;
Simon Huntac9e24f2014-11-12 10:12:21 -08001175 node.x = x;
1176 node.y = y;
1177 return;
Simon Hunt99c13842014-11-06 18:23:12 -08001178 }
Simon Huntac9e24f2014-11-12 10:12:21 -08001179
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001180 var location = node.location;
1181 if (location && location.type === 'latlng') {
1182 var coord = geoMapProjection([location.lng, location.lat]);
1183 node.fixed = true;
1184 node.x = coord[0];
1185 node.y = coord[1];
1186 return;
1187 }
1188
Simon Huntac9e24f2014-11-12 10:12:21 -08001189 // Note: Placing incoming unpinned nodes at exactly the same point
1190 // (center of the view) causes them to explode outwards when
1191 // the force layout kicks in. So, we spread them out a bit
1192 // initially, to provide a more serene layout convergence.
1193 // Additionally, if the node is a host, we place it near
1194 // the device it is connected to.
1195
1196 function spread(s) {
1197 return Math.floor((Math.random() * s) - s/2);
1198 }
1199
1200 function randDim(dim) {
1201 return dim / 2 + spread(dim * 0.7071);
1202 }
1203
1204 function rand() {
1205 return {
1206 x: randDim(network.view.width()),
1207 y: randDim(network.view.height())
1208 };
1209 }
1210
1211 function near(node) {
1212 var min = 12,
1213 dx = spread(12),
1214 dy = spread(12);
1215 return {
1216 x: node.x + min + dx,
1217 y: node.y + min + dy
1218 };
1219 }
1220
1221 function getDevice(cp) {
1222 var d = network.lookup[cp.device];
1223 return d || rand();
1224 }
1225
1226 xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
1227 $.extend(node, xy);
Simon Hunt99c13842014-11-06 18:23:12 -08001228 }
1229
Paul Greyson29cd58f2014-11-18 13:14:57 -08001230 function getIconUrl(d) {
1231 return 'icons.svg#' + d.type;
Simon Hunt99c13842014-11-06 18:23:12 -08001232 }
1233
1234 // returns the newly computed bounding box of the rectangle
1235 function adjustRectToFitText(n) {
1236 var text = n.select('text'),
1237 box = text.node().getBBox(),
1238 lab = config.labels;
1239
1240 text.attr('text-anchor', 'middle')
1241 .attr('y', '-0.8em')
1242 .attr('x', lab.imgPad/2);
1243
1244 // translate the bbox so that it is centered on [x,y]
1245 box.x = -box.width / 2;
1246 box.y = -box.height / 2;
1247
1248 // add padding
1249 box.x -= (lab.padLR + lab.imgPad/2);
1250 box.width += lab.padLR * 2 + lab.imgPad;
1251 box.y -= lab.padTB;
1252 box.height += lab.padTB * 2;
1253
1254 return box;
1255 }
1256
Simon Hunt1a9eff92014-11-07 11:06:34 -08001257 function mkSvgClass(d) {
1258 return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
1259 }
1260
Simon Hunt7cd48f32014-11-09 23:42:50 -08001261 function hostLabel(d) {
1262 var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
1263 return d.labels[idx];
1264 }
1265 function deviceLabel(d) {
1266 var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
1267 return d.labels[idx];
1268 }
1269 function niceLabel(label) {
1270 return (label && label.trim()) ? label : '.';
1271 }
1272
Paul Greyson29cd58f2014-11-18 13:14:57 -08001273 function updateDeviceIconAppearance(node, box, animate) {
1274 var u = node.select('use');
1275 var ubbox = u.node().getBBox();
1276
1277 var xoff = -ubbox.width/2 - box.width/2 - 4;
1278 var yoff = -ubbox.height;
1279 var iconTransform = 'translate(' + xoff + ',' + yoff + ')';
1280 if (animate) {
1281 node.select('use')
1282 .transition()
1283 .attr('transform', iconTransform);
1284 } else {
1285 node.select('use')
1286 .attr('transform', iconTransform);
1287 }
1288
1289 var computedStyle = window.getComputedStyle(node.node());
1290 u.attr({
1291 fill: computedStyle.fill,
1292 color: computedStyle.color
1293 });
1294 }
1295
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001296 function updateDeviceLabel(d) {
1297 var label = niceLabel(deviceLabel(d)),
1298 node = d.el,
1299 box;
1300
1301 node.select('text')
1302 .text(label)
1303 .style('opacity', 0)
1304 .transition()
1305 .style('opacity', 1);
1306
1307 box = adjustRectToFitText(node);
1308
1309 node.select('rect')
1310 .transition()
1311 .attr(box);
1312
Paul Greyson29cd58f2014-11-18 13:14:57 -08001313 updateDeviceIconAppearance(node, box, true);
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001314 }
1315
1316 function updateHostLabel(d) {
1317 var label = hostLabel(d),
1318 host = d.el;
1319
1320 host.select('text').text(label);
1321 }
1322
Simon Huntbb282f52014-11-10 11:08:19 -08001323 function updateDeviceState(nodeData) {
1324 nodeData.el.classed('online', nodeData.online);
1325 updateDeviceLabel(nodeData);
1326 // TODO: review what else might need to be updated
1327 }
1328
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001329 function updateLinkState(linkData) {
1330 updateLinkWidth(linkData);
Thomas Vachuskabadb93f2014-11-15 23:51:17 -08001331 linkData.el.classed('inactive', !linkData.online);
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001332 // TODO: review what else might need to be updated
1333 // update label, if showing
1334 }
1335
Simon Huntbb282f52014-11-10 11:08:19 -08001336 function updateHostState(hostData) {
1337 updateHostLabel(hostData);
1338 // TODO: review what else might need to be updated
1339 }
1340
Simon Hunt6ac93f32014-11-13 12:17:27 -08001341 function nodeMouseOver(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001342 hovered = d;
Simon Huntd72bc702014-11-13 18:38:04 -08001343 if (trafficHover() && d.class === 'host') {
1344 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001345 }
1346 }
1347
1348 function nodeMouseOut(d) {
Simon Hunt6ac93f32014-11-13 12:17:27 -08001349 hovered = null;
Simon Huntd72bc702014-11-13 18:38:04 -08001350 if (trafficHover() && d.class === 'host') {
1351 showTrafficAction();
Simon Hunt6ac93f32014-11-13 12:17:27 -08001352 }
1353 }
Simon Huntbb282f52014-11-10 11:08:19 -08001354
Simon Hunt99c13842014-11-06 18:23:12 -08001355 function updateNodes() {
1356 node = nodeG.selectAll('.node')
1357 .data(network.nodes, function (d) { return d.id; });
1358
1359 // operate on existing nodes, if necessary
Simon Hunt7cd48f32014-11-09 23:42:50 -08001360 // update host labels
Simon Hunt99c13842014-11-06 18:23:12 -08001361 //node .foo() .bar() ...
1362
1363 // operate on entering nodes:
1364 var entering = node.enter()
1365 .append('g')
1366 .attr({
1367 id: function (d) { return safeId(d.id); },
Simon Hunt1a9eff92014-11-07 11:06:34 -08001368 class: mkSvgClass,
Simon Hunt99c13842014-11-06 18:23:12 -08001369 transform: function (d) { return translate(d.x, d.y); },
1370 opacity: 0
1371 })
Simon Hunt1a9eff92014-11-07 11:06:34 -08001372 .call(network.drag)
Simon Hunt6ac93f32014-11-13 12:17:27 -08001373 .on('mouseover', nodeMouseOver)
1374 .on('mouseout', nodeMouseOut)
Simon Hunt99c13842014-11-06 18:23:12 -08001375 .transition()
1376 .attr('opacity', 1);
1377
1378 // augment device nodes...
1379 entering.filter('.device').each(function (d) {
1380 var node = d3.select(this),
Paul Greyson29cd58f2014-11-18 13:14:57 -08001381 iconUrl = getIconUrl(d),
Simon Hunt7cd48f32014-11-09 23:42:50 -08001382 label = niceLabel(deviceLabel(d)),
Simon Hunt99c13842014-11-06 18:23:12 -08001383 box;
1384
Simon Hunt7cd48f32014-11-09 23:42:50 -08001385 // provide ref to element from backing data....
1386 d.el = node;
1387
Simon Hunt99c13842014-11-06 18:23:12 -08001388 node.append('rect')
1389 .attr({
1390 'rx': 5,
1391 'ry': 5
1392 });
1393
1394 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001395 .text(label)
Simon Hunt99c13842014-11-06 18:23:12 -08001396 .attr('dy', '1.1em');
1397
1398 box = adjustRectToFitText(node);
1399
1400 node.select('rect')
1401 .attr(box);
1402
Paul Greyson29cd58f2014-11-18 13:14:57 -08001403 if (iconUrl) {
1404 node.append('svg:use')
Simon Hunt99c13842014-11-06 18:23:12 -08001405 .attr({
Paul Greyson29cd58f2014-11-18 13:14:57 -08001406 'xlink:href': iconUrl,
1407 width: config.icons.w,
1408 height: config.icons.h
Simon Hunt99c13842014-11-06 18:23:12 -08001409 });
1410 }
1411
Paul Greyson29cd58f2014-11-18 13:14:57 -08001412 updateDeviceIconAppearance(node, box, false);
1413
Simon Hunt99c13842014-11-06 18:23:12 -08001414 // debug function to show the modelled x,y coordinates of nodes...
1415 if (debug('showNodeXY')) {
1416 node.select('rect').attr('fill-opacity', 0.5);
1417 node.append('circle')
1418 .attr({
1419 class: 'debug',
1420 cx: 0,
1421 cy: 0,
1422 r: '3px'
1423 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001424 }
1425 });
Simon Hunt934c3ce2014-11-05 11:45:07 -08001426
Simon Hunt56d51852014-11-09 13:03:35 -08001427 // augment host nodes...
1428 entering.filter('.host').each(function (d) {
1429 var node = d3.select(this),
Paul Greyson29cd58f2014-11-18 13:14:57 -08001430 iconUrl = getIconUrl(d);
Simon Hunt56d51852014-11-09 13:03:35 -08001431
Simon Hunt7cd48f32014-11-09 23:42:50 -08001432 // provide ref to element from backing data....
1433 d.el = node;
1434
Paul Greyson29cd58f2014-11-18 13:14:57 -08001435 // var box = node.append('circle')
1436 // .attr('r', r).node().getBBox();
Simon Hunt7fa116d2014-11-17 14:16:55 -08001437
Paul Greyson29cd58f2014-11-18 13:14:57 -08001438 var textYOff = 0;
1439 var textXOff = 0;
1440 if (iconUrl) {
1441 var computedStyle = window.getComputedStyle(node.node());
1442 var u = node.append('svg:use')
1443 .attr({
1444 'xlink:href': iconUrl,
1445 width: config.icons.w,
1446 height: config.icons.h,
1447 fill: computedStyle.fill,
1448 color: computedStyle.color
1449 });
1450
1451 var ubbox = node.select('use').node().getBBox();
1452 u.attr('y', -ubbox.height/2);
1453 textYOff = ubbox.height/2 + 4; // pad by 4 pixels
1454 textXOff = ubbox.width/2;
Simon Hunt7fa116d2014-11-17 14:16:55 -08001455 }
Simon Hunt56d51852014-11-09 13:03:35 -08001456
Paul Greyson29cd58f2014-11-18 13:14:57 -08001457
1458
Simon Hunt56d51852014-11-09 13:03:35 -08001459 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001460 .text(hostLabel)
Paul Greyson29cd58f2014-11-18 13:14:57 -08001461 .attr('alignment-baseline', 'text-before-edge')
1462 .attr('x', textXOff)
1463 .attr('y', textYOff)
Simon Hunt7cd48f32014-11-09 23:42:50 -08001464 .attr('text-anchor', 'middle');
Simon Hunt56d51852014-11-09 13:03:35 -08001465
1466 // debug function to show the modelled x,y coordinates of nodes...
1467 if (debug('showNodeXY')) {
1468 node.select('circle').attr('fill-opacity', 0.5);
1469 node.append('circle')
1470 .attr({
1471 class: 'debug',
1472 cx: 0,
1473 cy: 0,
1474 r: '3px'
1475 });
1476 }
1477 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001478
Simon Hunt99c13842014-11-06 18:23:12 -08001479 // operate on both existing and new nodes, if necessary
1480 //node .foo() .bar() ...
Simon Huntc7ee0662014-11-05 16:44:37 -08001481
Simon Hunt99c13842014-11-06 18:23:12 -08001482 // operate on exiting nodes:
Simon Huntea80eb42014-11-11 13:46:57 -08001483 // Note that the node is removed after 2 seconds.
1484 // Sub element animations should be shorter than 2 seconds.
1485 var exiting = node.exit()
Simon Hunt44031102014-11-11 13:20:36 -08001486 .transition()
1487 .duration(2000)
Simon Huntea80eb42014-11-11 13:46:57 -08001488 .style('opacity', 0)
Simon Hunt99c13842014-11-06 18:23:12 -08001489 .remove();
Simon Huntea80eb42014-11-11 13:46:57 -08001490
1491 // host node exits....
1492 exiting.filter('.host').each(function (d) {
1493 var node = d3.select(this);
1494
1495 node.select('text')
1496 .style('opacity', 0.5)
1497 .transition()
1498 .duration(1000)
1499 .style('opacity', 0);
1500 // note, leave <g>.remove to remove this element
1501
Paul Greyson29cd58f2014-11-18 13:14:57 -08001502 node.select('use')
1503 .style('color', '#aaa')
1504 .style('fill', '#000')
Simon Huntea80eb42014-11-11 13:46:57 -08001505 .style('opacity', 0.5)
1506 .transition()
1507 .duration(1500)
1508 .attr('r', 0);
1509 // note, leave <g>.remove to remove this element
1510
1511 });
1512
1513 // TODO: device node exits
Simon Huntc7ee0662014-11-05 16:44:37 -08001514 }
1515
Simon Hunt8257f4c2014-11-16 19:34:54 -08001516 function find(key, array) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001517 for (var idx = 0, n = array.length; idx < n; idx++) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001518 if (array[idx].key === key) {
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001519 return idx;
1520 }
1521 }
1522 return -1;
1523 }
1524
1525 function removeLinkElement(linkData) {
Simon Hunt8257f4c2014-11-16 19:34:54 -08001526 var idx = find(linkData.key, network.links),
1527 removed;
1528 if (idx >=0) {
1529 // remove from links array
1530 removed = network.links.splice(idx, 1);
1531 // remove from lookup cache
1532 delete network.lookup[removed[0].key];
1533 updateLinks();
1534 network.force.resume();
1535 }
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001536 }
Simon Huntc7ee0662014-11-05 16:44:37 -08001537
Simon Hunt44031102014-11-11 13:20:36 -08001538 function removeHostElement(hostData) {
1539 // first, remove associated hostLink...
1540 removeLinkElement(hostData.linkData);
1541
1542 // remove from lookup cache
1543 delete network.lookup[hostData.id];
1544 // remove from nodes array
1545 var idx = find(hostData.id, network.nodes);
1546 network.nodes.splice(idx, 1);
1547 // remove from SVG
1548 updateNodes();
1549 network.force.resume();
1550 }
1551
1552
Simon Huntc7ee0662014-11-05 16:44:37 -08001553 function tick() {
1554 node.attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001555 transform: function (d) { return translate(d.x, d.y); }
Simon Huntc7ee0662014-11-05 16:44:37 -08001556 });
1557
1558 link.attr({
1559 x1: function (d) { return d.source.x; },
1560 y1: function (d) { return d.source.y; },
1561 x2: function (d) { return d.target.x; },
1562 y2: function (d) { return d.target.y; }
1563 });
Simon Hunte2575b62014-11-18 15:25:53 -08001564
1565 linkLabel.each(function (d) {
1566 var el = d3.select(this);
1567 var lnk = findLinkById(d.key),
1568 parms = {
1569 x1: lnk.source.x,
1570 y1: lnk.source.y,
1571 x2: lnk.target.x,
1572 y2: lnk.target.y
1573 };
1574 el.attr('transform', transformLabel(parms));
1575 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001576 }
Simon Hunt934c3ce2014-11-05 11:45:07 -08001577
1578 // ==============================
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001579 // Web-Socket for live data
1580
1581 function webSockUrl() {
1582 return document.location.toString()
1583 .replace(/\#.*/, '')
1584 .replace('http://', 'ws://')
1585 .replace('https://', 'wss://')
1586 .replace('index2.html', config.webSockUrl);
1587 }
1588
1589 webSock = {
1590 ws : null,
1591
1592 connect : function() {
1593 webSock.ws = new WebSocket(webSockUrl());
1594
1595 webSock.ws.onopen = function() {
Simon Hunt0c6d4192014-11-12 12:07:10 -08001596 noWebSock(false);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001597 };
1598
1599 webSock.ws.onmessage = function(m) {
1600 if (m.data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001601 wsTraceRx(m.data);
Thomas Vachuskad472c6e2014-11-07 19:11:05 -08001602 handleServerEvent(JSON.parse(m.data));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001603 }
1604 };
1605
1606 webSock.ws.onclose = function(m) {
1607 webSock.ws = null;
Simon Hunt0c6d4192014-11-12 12:07:10 -08001608 noWebSock(true);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001609 };
1610 },
1611
1612 send : function(text) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001613 if (text != null) {
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001614 webSock._send(text);
1615 }
1616 },
1617
1618 _send : function(message) {
1619 if (webSock.ws) {
1620 webSock.ws.send(message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001621 } else if (config.useLiveData) {
Simon Hunt56d51852014-11-09 13:03:35 -08001622 network.view.alert('no web socket open\n\n' + message);
Simon Hunta255a2c2014-11-13 22:29:35 -08001623 } else {
1624 console.log('WS Send: ' + JSON.stringify(message));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001625 }
1626 }
1627
1628 };
1629
Simon Hunt0c6d4192014-11-12 12:07:10 -08001630 function noWebSock(b) {
1631 mask.style('display',b ? 'block' : 'none');
1632 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001633
1634 function sendMessage(evType, payload) {
1635 var toSend = {
Simon Huntbb282f52014-11-10 11:08:19 -08001636 event: evType,
1637 sid: ++sid,
1638 payload: payload
1639 },
1640 asText = JSON.stringify(toSend);
1641 wsTraceTx(asText);
1642 webSock.send(asText);
Simon Huntc76ae892014-11-18 17:31:51 -08001643
1644 // Temporary measure for debugging UI behavior ...
1645 if (!config.useLiveData) {
1646 handleTestSend(toSend);
1647 }
Simon Huntbb282f52014-11-10 11:08:19 -08001648 }
1649
1650 function wsTraceTx(msg) {
1651 wsTrace('tx', msg);
1652 }
1653 function wsTraceRx(msg) {
1654 wsTrace('rx', msg);
1655 }
1656 function wsTrace(rxtx, msg) {
Simon Huntbb282f52014-11-10 11:08:19 -08001657 console.log('[' + rxtx + '] ' + msg);
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001658 }
1659
Simon Huntc76ae892014-11-18 17:31:51 -08001660 // NOTE: Temporary hardcoded example for showing detail pane
1661 // while we fine-
1662 // Probably should not merge this change...
1663 function handleTestSend(msg) {
1664 if (msg.event === 'requestDetails') {
1665 showDetails({
1666 event: 'showDetails',
1667 sid: 1001,
1668 payload: {
1669 "id": "of:0000ffffffffff09",
1670 "type": "roadm",
1671 "propOrder": [
1672 "Name",
1673 "Vendor",
1674 "H/W Version",
1675 "S/W Version",
1676 "-",
1677 "Latitude",
1678 "Longitude",
1679 "Ports"
1680 ],
1681 "props": {
1682 "Name": null,
1683 "Vendor": "Linc",
1684 "H/W Version": "OE",
1685 "S/W Version": "?",
1686 "-": "",
1687 "Latitude": "40.8",
1688 "Longitude": "73.1",
1689 "Ports": "2"
1690 }
1691 }
1692 });
1693 }
1694 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001695
1696 // ==============================
1697 // Selection stuff
1698
1699 function selectObject(obj, el) {
1700 var n,
Simon Hunt01095ff2014-11-13 16:37:29 -08001701 srcEv = d3.event.sourceEvent,
1702 meta = srcEv.metaKey,
1703 shift = srcEv.shiftKey;
1704
Simon Huntdeab4322014-11-13 18:49:07 -08001705 if ((panZoom() && !meta) || (!panZoom() && meta)) {
Simon Hunt01095ff2014-11-13 16:37:29 -08001706 return;
1707 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001708
1709 if (el) {
1710 n = d3.select(el);
1711 } else {
1712 node.each(function(d) {
1713 if (d == obj) {
1714 n = d3.select(el = this);
1715 }
1716 });
1717 }
1718 if (!n) return;
1719
Simon Hunt01095ff2014-11-13 16:37:29 -08001720 if (shift && n.classed('selected')) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001721 deselectObject(obj.id);
Simon Hunt61d04042014-11-11 17:27:16 -08001722 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001723 return;
1724 }
1725
Simon Hunt01095ff2014-11-13 16:37:29 -08001726 if (!shift) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001727 deselectAll();
1728 }
1729
Simon Huntc31d5692014-11-12 13:27:18 -08001730 selections[obj.id] = { obj: obj, el: el };
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001731 selectOrder.push(obj.id);
1732
1733 n.classed('selected', true);
Simon Hunt61d04042014-11-11 17:27:16 -08001734 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001735 }
1736
1737 function deselectObject(id) {
Simon Huntc31d5692014-11-12 13:27:18 -08001738 var obj = selections[id],
1739 idx;
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001740 if (obj) {
1741 d3.select(obj.el).classed('selected', false);
Simon Hunt61d04042014-11-11 17:27:16 -08001742 delete selections[id];
Simon Huntc31d5692014-11-12 13:27:18 -08001743 idx = $.inArray(id, selectOrder);
1744 if (idx >= 0) {
1745 selectOrder.splice(idx, 1);
1746 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001747 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001748 }
1749
1750 function deselectAll() {
1751 // deselect all nodes in the network...
1752 node.classed('selected', false);
1753 selections = {};
1754 selectOrder = [];
Simon Hunt61d04042014-11-11 17:27:16 -08001755 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001756 }
1757
Simon Hunt61d04042014-11-11 17:27:16 -08001758 // update the state of the detail pane, based on current selections
1759 function updateDetailPane() {
1760 var nSel = selectOrder.length;
1761 if (!nSel) {
1762 detailPane.hide();
Simon Huntd72bc702014-11-13 18:38:04 -08001763 showTrafficAction(); // sends cancelTraffic event
Simon Hunt61d04042014-11-11 17:27:16 -08001764 } else if (nSel === 1) {
1765 singleSelect();
1766 } else {
1767 multiSelect();
1768 }
1769 }
1770
1771 function singleSelect() {
1772 requestDetails();
Simon Huntb53e0682014-11-12 13:32:01 -08001773 // NOTE: detail pane will be shown from showDetails event callback
Simon Hunt61d04042014-11-11 17:27:16 -08001774 }
1775
1776 function multiSelect() {
Simon Huntb53e0682014-11-12 13:32:01 -08001777 populateMultiSelect();
Simon Huntb53e0682014-11-12 13:32:01 -08001778 }
1779
1780 function addSep(tbody) {
1781 var tr = tbody.append('tr');
1782 $('<hr>').appendTo(tr.append('td').attr('colspan', 2));
1783 }
1784
1785 function addProp(tbody, label, value) {
1786 var tr = tbody.append('tr');
1787
1788 tr.append('td')
1789 .attr('class', 'label')
1790 .text(label + ' :');
1791
1792 tr.append('td')
1793 .attr('class', 'value')
1794 .text(value);
1795 }
1796
1797 function populateMultiSelect() {
1798 detailPane.empty();
1799
1800 var title = detailPane.append("h2"),
1801 table = detailPane.append("table"),
1802 tbody = table.append("tbody");
1803
1804 title.text('Multi-Select...');
1805
1806 selectOrder.forEach(function (d, i) {
1807 addProp(tbody, i+1, d);
1808 });
Simon Huntd72bc702014-11-13 18:38:04 -08001809
1810 addMultiSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001811 }
1812
1813 function populateDetails(data) {
1814 detailPane.empty();
1815
1816 var title = detailPane.append("h2"),
1817 table = detailPane.append("table"),
1818 tbody = table.append("tbody");
1819
1820 $('<img src="img/' + data.type + '.png">').appendTo(title);
1821 $('<span>').attr('class', 'icon').text(data.id).appendTo(title);
1822
1823 data.propOrder.forEach(function(p) {
1824 if (p === '-') {
1825 addSep(tbody);
1826 } else {
1827 addProp(tbody, p, data.props[p]);
1828 }
1829 });
Simon Huntd72bc702014-11-13 18:38:04 -08001830
1831 addSingleSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001832 }
1833
Simon Huntd72bc702014-11-13 18:38:04 -08001834 function addSingleSelectActions() {
1835 detailPane.append('hr');
1836 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001837 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001838 }
1839
1840 function addMultiSelectActions() {
1841 detailPane.append('hr');
1842 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001843 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001844 // if exactly two hosts are selected, also want 'add host intent'
1845 if (nSel() === 2 && allSelectionsClass('host')) {
Simon Hunta5e89142014-11-14 07:00:33 -08001846 addAction(detailPane, 'Add Host Intent', addIntentAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001847 }
1848 }
1849
Simon Hunta5e89142014-11-14 07:00:33 -08001850 function addAction(panel, text, cb) {
1851 panel.append('div')
Simon Huntd72bc702014-11-13 18:38:04 -08001852 .classed('actionBtn', true)
1853 .text(text)
1854 .on('click', cb);
1855 }
1856
1857
Paul Greysonfcba0e82014-11-13 10:21:16 -08001858 function zoomPan(scale, translate) {
1859 zoomPanContainer.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
1860 // keep the map lines constant width while zooming
Paul Greyson29cd58f2014-11-18 13:14:57 -08001861 bgImg.attr("stroke-width", config.map.strokeWidth / scale + "px");
Paul Greysonfcba0e82014-11-13 10:21:16 -08001862 }
1863
1864 function resetZoomPan() {
1865 zoomPan(1, [0,0]);
1866 zoom.scale(1).translate([0,0]);
1867 }
1868
1869 function setupZoomPan() {
1870 function zoomed() {
Simon Huntdeab4322014-11-13 18:49:07 -08001871 if (!panZoom() ^ !d3.event.sourceEvent.metaKey) {
Paul Greysonfcba0e82014-11-13 10:21:16 -08001872 zoomPan(d3.event.scale, d3.event.translate);
1873 }
1874 }
1875
1876 zoom = d3.behavior.zoom()
1877 .translate([0, 0])
1878 .scale(1)
1879 .scaleExtent([1, 8])
1880 .on("zoom", zoomed);
1881
1882 svg.call(zoom);
1883 }
1884
Simon Hunt61d04042014-11-11 17:27:16 -08001885 // ==============================
1886 // Test harness code
Simon Hunt56d51852014-11-09 13:03:35 -08001887
1888 function prepareScenario(view, ctx, dbg) {
1889 var sc = scenario,
1890 urlSc = sc.evDir + ctx + sc.evScenario;
1891
1892 if (!ctx) {
1893 view.alert("No scenario specified (null ctx)");
1894 return;
1895 }
1896
1897 sc.view = view;
1898 sc.ctx = ctx;
1899 sc.debug = dbg;
1900 sc.evNumber = 0;
1901
1902 d3.json(urlSc, function(err, data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001903 var p = data && data.params || {},
1904 desc = data && data.description || null,
Simon Huntfc274c92014-11-11 11:05:46 -08001905 intro = data && data.title;
Simon Huntbb282f52014-11-10 11:08:19 -08001906
Simon Hunt56d51852014-11-09 13:03:35 -08001907 if (err) {
1908 view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
1909 } else {
1910 sc.params = p;
Simon Huntbb282f52014-11-10 11:08:19 -08001911 if (desc) {
1912 intro += '\n\n ' + desc.join('\n ');
1913 }
1914 view.alert(intro);
Simon Hunt56d51852014-11-09 13:03:35 -08001915 }
1916 });
1917
1918 }
1919
Simon Hunt01095ff2014-11-13 16:37:29 -08001920 // ==============================
1921 // Toggle Buttons in masthead
Simon Hunt0c6d4192014-11-12 12:07:10 -08001922
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001923 // TODO: toggle button (and other widgets in the masthead) should be provided
1924 // by the framework; not generated by the view.
1925
Simon Hunta5e89142014-11-14 07:00:33 -08001926 var showInstances,
1927 doPanZoom,
1928 showTrafficOnHover;
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001929
1930 function addButtonBar(view) {
1931 var bb = d3.select('#mast')
1932 .append('span').classed('right', true).attr('id', 'bb');
1933
Simon Hunta5e89142014-11-14 07:00:33 -08001934 function mkTogBtn(text, cb) {
1935 return bb.append('span')
1936 .classed('btn', true)
1937 .text(text)
1938 .on('click', cb);
1939 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001940
Simon Hunta5e89142014-11-14 07:00:33 -08001941 showInstances = mkTogBtn('Show Instances', toggleInst);
1942 doPanZoom = mkTogBtn('Pan/Zoom', togglePanZoom);
1943 showTrafficOnHover = mkTogBtn('Show traffic on hover', toggleTrafficHover);
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001944 }
1945
Simon Hunta5e89142014-11-14 07:00:33 -08001946 function instShown() {
1947 return showInstances.classed('active');
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001948 }
Simon Hunta5e89142014-11-14 07:00:33 -08001949 function toggleInst() {
1950 showInstances.classed('active', !instShown());
1951 if (instShown()) {
1952 oiBox.show();
1953 } else {
1954 oiBox.hide();
1955 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001956 }
1957
Simon Huntdeab4322014-11-13 18:49:07 -08001958 function panZoom() {
1959 return doPanZoom.classed('active');
Simon Hunt01095ff2014-11-13 16:37:29 -08001960 }
Simon Hunta5e89142014-11-14 07:00:33 -08001961 function togglePanZoom() {
1962 doPanZoom.classed('active', !panZoom());
1963 }
1964
1965 function trafficHover() {
1966 return showTrafficOnHover.classed('active');
1967 }
1968 function toggleTrafficHover() {
1969 showTrafficOnHover.classed('active', !trafficHover());
1970 }
1971
Simon Hunt7fa116d2014-11-17 14:16:55 -08001972 function loadGlyphs(svg) {
1973 var defs = svg.append('defs');
1974 gly.defBird(defs);
1975 gly.defBullhorn(defs);
1976 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001977
Paul Greyson29cd58f2014-11-18 13:14:57 -08001978 // create references to bring these into cache so that getBBox() works when they
1979 // are inserted later
1980 function preloadIcons(svg) {
1981 var icons = [
1982 "router",
1983 "switch",
1984 "roadm",
1985 "endstation",
1986 "bgpSpeaker"
1987 ];
1988
1989 var g = svg.append('g');
1990 for (var icon in icons) {
1991 g.append('use')
1992 .attr({
1993 'xlink:href': 'icons.svg#' + icon
1994 });
1995 }
1996 g.style('visibility', 'hidden');
1997 }
1998
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001999 // ==============================
Simon Hunt142d0032014-11-04 20:13:09 -08002000 // View life-cycle callbacks
Simon Hunt195cb382014-11-03 17:50:51 -08002001
Simon Huntf67722a2014-11-10 09:32:06 -08002002 function preload(view, ctx, flags) {
Simon Hunt142d0032014-11-04 20:13:09 -08002003 var w = view.width(),
2004 h = view.height(),
Simon Huntc7ee0662014-11-05 16:44:37 -08002005 fcfg = config.force,
2006 fpad = fcfg.pad,
2007 forceDim = [w - 2*fpad, h - 2*fpad];
Simon Hunt195cb382014-11-03 17:50:51 -08002008
Simon Hunt142d0032014-11-04 20:13:09 -08002009 // NOTE: view.$div is a D3 selection of the view's div
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002010 var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
2011 svg = view.$div.append('svg').attr('viewBox', viewBox);
Simon Hunt934c3ce2014-11-05 11:45:07 -08002012 setSize(svg, view);
2013
Simon Hunt7fa116d2014-11-17 14:16:55 -08002014 loadGlyphs(svg);
Paul Greyson29cd58f2014-11-18 13:14:57 -08002015 preloadIcons(svg);
Simon Hunt12ce12e2014-11-15 21:13:19 -08002016
Paul Greysonfcba0e82014-11-13 10:21:16 -08002017 zoomPanContainer = svg.append('g').attr('id', 'zoomPanContainer');
Paul Greysonfcba0e82014-11-13 10:21:16 -08002018 setupZoomPan();
2019
Simon Hunt1a9eff92014-11-07 11:06:34 -08002020 // add blue glow filter to svg layer
Paul Greysonfcba0e82014-11-13 10:21:16 -08002021 d3u.appendGlow(zoomPanContainer);
Simon Hunt1a9eff92014-11-07 11:06:34 -08002022
Simon Huntc7ee0662014-11-05 16:44:37 -08002023 // group for the topology
Paul Greysonfcba0e82014-11-13 10:21:16 -08002024 topoG = zoomPanContainer.append('g')
Simon Huntd3b7d512014-11-12 15:48:41 -08002025 .attr('id', 'topo-G')
Simon Huntc7ee0662014-11-05 16:44:37 -08002026 .attr('transform', fcfg.translate());
2027
Simon Hunte2575b62014-11-18 15:25:53 -08002028 // subgroups for links, link labels, and nodes
Simon Huntc7ee0662014-11-05 16:44:37 -08002029 linkG = topoG.append('g').attr('id', 'links');
Simon Hunte2575b62014-11-18 15:25:53 -08002030 linkLabelG = topoG.append('g').attr('id', 'linkLabels');
Simon Huntc7ee0662014-11-05 16:44:37 -08002031 nodeG = topoG.append('g').attr('id', 'nodes');
2032
Simon Hunte2575b62014-11-18 15:25:53 -08002033 // selection of links, linkLabels, and nodes
Simon Huntc7ee0662014-11-05 16:44:37 -08002034 link = linkG.selectAll('.link');
Simon Hunte2575b62014-11-18 15:25:53 -08002035 linkLabel = linkLabelG.selectAll('.linkLabel');
Simon Huntc7ee0662014-11-05 16:44:37 -08002036 node = nodeG.selectAll('.node');
2037
Simon Hunt7cd48f32014-11-09 23:42:50 -08002038 function chrg(d) {
2039 return fcfg.charge[d.class] || -12000;
2040 }
Simon Hunt99c13842014-11-06 18:23:12 -08002041 function ldist(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08002042 return fcfg.linkDistance[d.type] || 50;
Simon Hunt99c13842014-11-06 18:23:12 -08002043 }
2044 function lstrg(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08002045 // 0.0 - 1.0
2046 return fcfg.linkStrength[d.type] || 1.0;
Simon Hunt99c13842014-11-06 18:23:12 -08002047 }
2048
Simon Hunt1a9eff92014-11-07 11:06:34 -08002049 function selectCb(d, self) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08002050 selectObject(d, self);
Simon Hunt1a9eff92014-11-07 11:06:34 -08002051 }
2052
2053 function atDragEnd(d, self) {
Simon Hunt56d51852014-11-09 13:03:35 -08002054 // once we've finished moving, pin the node in position
2055 d.fixed = true;
2056 d3.select(self).classed('fixed', true);
2057 if (config.useLiveData) {
Simon Hunt902c9922014-11-11 11:59:31 -08002058 sendUpdateMeta(d);
Simon Hunta255a2c2014-11-13 22:29:35 -08002059 } else {
2060 console.log('Moving node ' + d.id + ' to [' + d.x + ',' + d.y + ']');
Simon Hunt1a9eff92014-11-07 11:06:34 -08002061 }
2062 }
2063
Simon Hunt902c9922014-11-11 11:59:31 -08002064 function sendUpdateMeta(d) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08002065 sendMessage('updateMeta', {
2066 id: d.id,
2067 'class': d.class,
Simon Hunt902c9922014-11-11 11:59:31 -08002068 'memento': {
Simon Hunt01095ff2014-11-13 16:37:29 -08002069 x: d.x,
2070 y: d.y
Simon Hunt902c9922014-11-11 11:59:31 -08002071 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08002072 });
2073 }
2074
Simon Huntc7ee0662014-11-05 16:44:37 -08002075 // set up the force layout
2076 network.force = d3.layout.force()
2077 .size(forceDim)
2078 .nodes(network.nodes)
2079 .links(network.links)
Simon Hunt7cd48f32014-11-09 23:42:50 -08002080 .gravity(0.4)
2081 .friction(0.7)
2082 .charge(chrg)
Simon Hunt99c13842014-11-06 18:23:12 -08002083 .linkDistance(ldist)
2084 .linkStrength(lstrg)
Simon Huntc7ee0662014-11-05 16:44:37 -08002085 .on('tick', tick);
Simon Hunt195cb382014-11-03 17:50:51 -08002086
Simon Hunt01095ff2014-11-13 16:37:29 -08002087 network.drag = d3u.createDragBehavior(network.force,
Simon Huntdeab4322014-11-13 18:49:07 -08002088 selectCb, atDragEnd, panZoom);
Simon Hunt0c6d4192014-11-12 12:07:10 -08002089
2090 // create mask layer for when we lose connection to server.
Simon Hunta5e89142014-11-14 07:00:33 -08002091 // TODO: this should be part of the framework
Simon Hunt0c6d4192014-11-12 12:07:10 -08002092 mask = view.$div.append('div').attr('id','topo-mask');
2093 para(mask, 'Oops!');
2094 para(mask, 'Web-socket connection to server closed...');
2095 para(mask, 'Try refreshing the page.');
Simon Hunt12ce12e2014-11-15 21:13:19 -08002096
2097 mask.append('svg')
2098 .attr({
2099 id: 'mask-bird',
2100 width: w,
2101 height: h
2102 })
2103 .append('g')
2104 .attr('transform', birdTranslate(w, h))
2105 .style('opacity', 0.3)
2106 .append('use')
2107 .attr({
2108 'xlink:href': '#bird',
2109 width: config.birdDim,
2110 height: config.birdDim,
2111 fill: '#111'
Paul Greyson29cd58f2014-11-18 13:14:57 -08002112 });
Simon Hunt1a9eff92014-11-07 11:06:34 -08002113 }
Simon Hunt195cb382014-11-03 17:50:51 -08002114
Simon Hunt01095ff2014-11-13 16:37:29 -08002115 function para(sel, text) {
2116 sel.append('p').text(text);
2117 }
2118
2119
Simon Hunt56d51852014-11-09 13:03:35 -08002120 function load(view, ctx, flags) {
Simon Huntf67722a2014-11-10 09:32:06 -08002121 // resize, in case the window was resized while we were not loaded
2122 resize(view, ctx, flags);
2123
Simon Hunt99c13842014-11-06 18:23:12 -08002124 // cache the view token, so network topo functions can access it
2125 network.view = view;
Simon Hunt56d51852014-11-09 13:03:35 -08002126 config.useLiveData = !flags.local;
2127
2128 if (!config.useLiveData) {
2129 prepareScenario(view, ctx, flags.debug);
2130 }
Simon Hunt99c13842014-11-06 18:23:12 -08002131
2132 // set our radio buttons and key bindings
Simon Hunt9462e8c2014-11-14 17:28:09 -08002133 layerBtnSet = view.setRadio(layerButtons);
Simon Hunt934c3ce2014-11-05 11:45:07 -08002134 view.setKeys(keyDispatch);
Simon Hunt195cb382014-11-03 17:50:51 -08002135
Simon Huntf8e5b4e02014-11-13 11:17:57 -08002136 // patch in our "button bar" for now
2137 // TODO: implement a more official frameworky way of doing this..
2138 addButtonBar(view);
2139
Simon Huntd3b7d512014-11-12 15:48:41 -08002140 // Load map data asynchronously; complete startup after that..
2141 loadGeoJsonData();
Simon Hunta255a2c2014-11-13 22:29:35 -08002142
2143 // start the and timer
2144 var dashIdx = 0;
2145 antTimer = setInterval(function () {
2146 // TODO: figure out how to choose Src-->Dst and Dst-->Src, per link
2147 dashIdx = dashIdx === 0 ? 14 : dashIdx - 2;
2148 d3.selectAll('.animated').style('stroke-dashoffset', dashIdx);
2149 }, 35);
2150 }
2151
2152 function unload(view, ctx, flags) {
2153 if (antTimer) {
2154 clearInterval(antTimer);
2155 antTimer = null;
2156 }
Simon Huntd3b7d512014-11-12 15:48:41 -08002157 }
2158
2159 // TODO: move these to config/state portion of script
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002160 var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
Simon Huntd3b7d512014-11-12 15:48:41 -08002161 geoJson;
2162
2163 function loadGeoJsonData() {
2164 d3.json(geoJsonUrl, function (err, data) {
2165 if (err) {
2166 // fall back to USA map background
2167 loadStaticMap();
2168 } else {
2169 geoJson = data;
2170 loadGeoMap();
2171 }
2172
2173 // finally, connect to the server...
2174 if (config.useLiveData) {
2175 webSock.connect();
2176 }
2177 });
2178 }
2179
2180 function showBg() {
2181 return config.options.showBackground ? 'visible' : 'hidden';
2182 }
2183
2184 function loadStaticMap() {
2185 fnTrace('loadStaticMap', config.backgroundUrl);
2186 var w = network.view.width(),
2187 h = network.view.height();
2188
2189 // load the background image
2190 bgImg = svg.insert('svg:image', '#topo-G')
2191 .attr({
2192 id: 'topo-bg',
2193 width: w,
2194 height: h,
2195 'xlink:href': config.backgroundUrl
2196 })
2197 .style({
2198 visibility: showBg()
2199 });
2200 }
2201
2202 function loadGeoMap() {
2203 fnTrace('loadGeoMap', geoJsonUrl);
Simon Huntd3b7d512014-11-12 15:48:41 -08002204
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002205 // extracts the topojson data into geocoordinate-based geometry
2206 var topoData = topojson.feature(geoJson, geoJson.objects.states);
Simon Huntd3b7d512014-11-12 15:48:41 -08002207
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002208 // see: http://bl.ocks.org/mbostock/4707858
2209 geoMapProjection = d3.geo.mercator();
2210 var path = d3.geo.path().projection(geoMapProjection);
Simon Huntd3b7d512014-11-12 15:48:41 -08002211
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002212 geoMapProjection
2213 .scale(1)
2214 .translate([0, 0]);
Simon Huntd3b7d512014-11-12 15:48:41 -08002215
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002216 // [[x1,y1],[x2,y2]]
2217 var b = path.bounds(topoData);
Paul Greysonfcba0e82014-11-13 10:21:16 -08002218 // size map to 95% of minimum dimension to fill space
2219 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 -08002220 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 -08002221
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002222 geoMapProjection
2223 .scale(s)
2224 .translate(t);
2225
Paul Greysonfcba0e82014-11-13 10:21:16 -08002226 bgImg = zoomPanContainer.insert("g", '#topo-G');
Paul Greyson29cd58f2014-11-18 13:14:57 -08002227 // pointer-events: none so that browser select tools don't pick up the map svg
2228 bgImg.attr('id', 'map').attr('stroke-width', config.map.strokeWidth + 'px').style('pointer-events', 'none')
2229 .selectAll('path')
2230 .data(topoData.features)
2231 .enter()
2232 .append('path')
2233 .attr('d', path);
Simon Hunt195cb382014-11-03 17:50:51 -08002234 }
2235
Simon Huntf67722a2014-11-10 09:32:06 -08002236 function resize(view, ctx, flags) {
Simon Hunt12ce12e2014-11-15 21:13:19 -08002237 var w = view.width(),
2238 h = view.height();
2239
Simon Hunt934c3ce2014-11-05 11:45:07 -08002240 setSize(svg, view);
Simon Hunt12ce12e2014-11-15 21:13:19 -08002241
2242 d3.select('#mask-bird').attr({ width: w, height: h})
2243 .select('g').attr('transform', birdTranslate(w, h));
Simon Hunt142d0032014-11-04 20:13:09 -08002244 }
2245
Simon Hunt12ce12e2014-11-15 21:13:19 -08002246 function birdTranslate(w, h) {
2247 var bdim = config.birdDim;
2248 return 'translate('+((w-bdim)*.4)+','+((h-bdim)*.1)+')';
2249 }
Simon Hunt142d0032014-11-04 20:13:09 -08002250
2251 // ==============================
2252 // View registration
Simon Hunt195cb382014-11-03 17:50:51 -08002253
Simon Hunt25248912014-11-04 11:25:48 -08002254 onos.ui.addView('topo', {
Simon Hunt142d0032014-11-04 20:13:09 -08002255 preload: preload,
2256 load: load,
Simon Hunta255a2c2014-11-13 22:29:35 -08002257 unload: unload,
Simon Hunt142d0032014-11-04 20:13:09 -08002258 resize: resize
Simon Hunt195cb382014-11-03 17:50:51 -08002259 });
2260
Simon Hunt61d04042014-11-11 17:27:16 -08002261 detailPane = onos.ui.addFloatingPanel('topo-detail');
Simon Hunta5e89142014-11-14 07:00:33 -08002262 oiBox = onos.ui.addFloatingPanel('topo-oibox', 'TL');
Simon Hunt61d04042014-11-11 17:27:16 -08002263
Simon Hunt195cb382014-11-03 17:50:51 -08002264}(ONOS));