blob: f818e2f1eb3780839b248071e075ee40e41e98b6 [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
Simon Hunt61d04042014-11-11 17:27:16 -08001634 // TODO: use cache of pending messages (key = sid) to reconcile responses
1635
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001636 function sendMessage(evType, payload) {
1637 var toSend = {
Simon Huntbb282f52014-11-10 11:08:19 -08001638 event: evType,
1639 sid: ++sid,
1640 payload: payload
1641 },
1642 asText = JSON.stringify(toSend);
1643 wsTraceTx(asText);
1644 webSock.send(asText);
1645 }
1646
1647 function wsTraceTx(msg) {
1648 wsTrace('tx', msg);
1649 }
1650 function wsTraceRx(msg) {
1651 wsTrace('rx', msg);
1652 }
1653 function wsTrace(rxtx, msg) {
Simon Huntbb282f52014-11-10 11:08:19 -08001654 console.log('[' + rxtx + '] ' + msg);
1655 // TODO: integrate with trace view
1656 //if (trace) {
1657 // trace.output(rxtx, msg);
1658 //}
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001659 }
1660
1661
1662 // ==============================
1663 // Selection stuff
1664
1665 function selectObject(obj, el) {
1666 var n,
Simon Hunt01095ff2014-11-13 16:37:29 -08001667 srcEv = d3.event.sourceEvent,
1668 meta = srcEv.metaKey,
1669 shift = srcEv.shiftKey;
1670
Simon Huntdeab4322014-11-13 18:49:07 -08001671 if ((panZoom() && !meta) || (!panZoom() && meta)) {
Simon Hunt01095ff2014-11-13 16:37:29 -08001672 return;
1673 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001674
1675 if (el) {
1676 n = d3.select(el);
1677 } else {
1678 node.each(function(d) {
1679 if (d == obj) {
1680 n = d3.select(el = this);
1681 }
1682 });
1683 }
1684 if (!n) return;
1685
Simon Hunt01095ff2014-11-13 16:37:29 -08001686 if (shift && n.classed('selected')) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001687 deselectObject(obj.id);
Simon Hunt61d04042014-11-11 17:27:16 -08001688 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001689 return;
1690 }
1691
Simon Hunt01095ff2014-11-13 16:37:29 -08001692 if (!shift) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001693 deselectAll();
1694 }
1695
Simon Huntc31d5692014-11-12 13:27:18 -08001696 selections[obj.id] = { obj: obj, el: el };
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001697 selectOrder.push(obj.id);
1698
1699 n.classed('selected', true);
Simon Hunt61d04042014-11-11 17:27:16 -08001700 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001701 }
1702
1703 function deselectObject(id) {
Simon Huntc31d5692014-11-12 13:27:18 -08001704 var obj = selections[id],
1705 idx;
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001706 if (obj) {
1707 d3.select(obj.el).classed('selected', false);
Simon Hunt61d04042014-11-11 17:27:16 -08001708 delete selections[id];
Simon Huntc31d5692014-11-12 13:27:18 -08001709 idx = $.inArray(id, selectOrder);
1710 if (idx >= 0) {
1711 selectOrder.splice(idx, 1);
1712 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001713 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001714 }
1715
1716 function deselectAll() {
1717 // deselect all nodes in the network...
1718 node.classed('selected', false);
1719 selections = {};
1720 selectOrder = [];
Simon Hunt61d04042014-11-11 17:27:16 -08001721 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001722 }
1723
Simon Hunt61d04042014-11-11 17:27:16 -08001724 // update the state of the detail pane, based on current selections
1725 function updateDetailPane() {
1726 var nSel = selectOrder.length;
1727 if (!nSel) {
1728 detailPane.hide();
Simon Huntd72bc702014-11-13 18:38:04 -08001729 showTrafficAction(); // sends cancelTraffic event
Simon Hunt61d04042014-11-11 17:27:16 -08001730 } else if (nSel === 1) {
1731 singleSelect();
1732 } else {
1733 multiSelect();
1734 }
1735 }
1736
1737 function singleSelect() {
1738 requestDetails();
Simon Huntb53e0682014-11-12 13:32:01 -08001739 // NOTE: detail pane will be shown from showDetails event callback
Simon Hunt61d04042014-11-11 17:27:16 -08001740 }
1741
1742 function multiSelect() {
Simon Huntb53e0682014-11-12 13:32:01 -08001743 populateMultiSelect();
Simon Huntb53e0682014-11-12 13:32:01 -08001744 }
1745
1746 function addSep(tbody) {
1747 var tr = tbody.append('tr');
1748 $('<hr>').appendTo(tr.append('td').attr('colspan', 2));
1749 }
1750
1751 function addProp(tbody, label, value) {
1752 var tr = tbody.append('tr');
1753
1754 tr.append('td')
1755 .attr('class', 'label')
1756 .text(label + ' :');
1757
1758 tr.append('td')
1759 .attr('class', 'value')
1760 .text(value);
1761 }
1762
1763 function populateMultiSelect() {
1764 detailPane.empty();
1765
1766 var title = detailPane.append("h2"),
1767 table = detailPane.append("table"),
1768 tbody = table.append("tbody");
1769
1770 title.text('Multi-Select...');
1771
1772 selectOrder.forEach(function (d, i) {
1773 addProp(tbody, i+1, d);
1774 });
Simon Huntd72bc702014-11-13 18:38:04 -08001775
1776 addMultiSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001777 }
1778
1779 function populateDetails(data) {
1780 detailPane.empty();
1781
1782 var title = detailPane.append("h2"),
1783 table = detailPane.append("table"),
1784 tbody = table.append("tbody");
1785
1786 $('<img src="img/' + data.type + '.png">').appendTo(title);
1787 $('<span>').attr('class', 'icon').text(data.id).appendTo(title);
1788
1789 data.propOrder.forEach(function(p) {
1790 if (p === '-') {
1791 addSep(tbody);
1792 } else {
1793 addProp(tbody, p, data.props[p]);
1794 }
1795 });
Simon Huntd72bc702014-11-13 18:38:04 -08001796
1797 addSingleSelectActions();
Simon Hunt61d04042014-11-11 17:27:16 -08001798 }
1799
Simon Huntd72bc702014-11-13 18:38:04 -08001800 function addSingleSelectActions() {
1801 detailPane.append('hr');
1802 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001803 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001804 }
1805
1806 function addMultiSelectActions() {
1807 detailPane.append('hr');
1808 // always want to allow 'show traffic'
Simon Hunta5e89142014-11-14 07:00:33 -08001809 addAction(detailPane, 'Show Traffic', showTrafficAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001810 // if exactly two hosts are selected, also want 'add host intent'
1811 if (nSel() === 2 && allSelectionsClass('host')) {
Simon Hunta5e89142014-11-14 07:00:33 -08001812 addAction(detailPane, 'Add Host Intent', addIntentAction);
Simon Huntd72bc702014-11-13 18:38:04 -08001813 }
1814 }
1815
Simon Hunta5e89142014-11-14 07:00:33 -08001816 function addAction(panel, text, cb) {
1817 panel.append('div')
Simon Huntd72bc702014-11-13 18:38:04 -08001818 .classed('actionBtn', true)
1819 .text(text)
1820 .on('click', cb);
1821 }
1822
1823
Paul Greysonfcba0e82014-11-13 10:21:16 -08001824 function zoomPan(scale, translate) {
1825 zoomPanContainer.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
1826 // keep the map lines constant width while zooming
Paul Greyson29cd58f2014-11-18 13:14:57 -08001827 bgImg.attr("stroke-width", config.map.strokeWidth / scale + "px");
Paul Greysonfcba0e82014-11-13 10:21:16 -08001828 }
1829
1830 function resetZoomPan() {
1831 zoomPan(1, [0,0]);
1832 zoom.scale(1).translate([0,0]);
1833 }
1834
1835 function setupZoomPan() {
1836 function zoomed() {
Simon Huntdeab4322014-11-13 18:49:07 -08001837 if (!panZoom() ^ !d3.event.sourceEvent.metaKey) {
Paul Greysonfcba0e82014-11-13 10:21:16 -08001838 zoomPan(d3.event.scale, d3.event.translate);
1839 }
1840 }
1841
1842 zoom = d3.behavior.zoom()
1843 .translate([0, 0])
1844 .scale(1)
1845 .scaleExtent([1, 8])
1846 .on("zoom", zoomed);
1847
1848 svg.call(zoom);
1849 }
1850
Simon Hunt61d04042014-11-11 17:27:16 -08001851 // ==============================
1852 // Test harness code
Simon Hunt56d51852014-11-09 13:03:35 -08001853
1854 function prepareScenario(view, ctx, dbg) {
1855 var sc = scenario,
1856 urlSc = sc.evDir + ctx + sc.evScenario;
1857
1858 if (!ctx) {
1859 view.alert("No scenario specified (null ctx)");
1860 return;
1861 }
1862
1863 sc.view = view;
1864 sc.ctx = ctx;
1865 sc.debug = dbg;
1866 sc.evNumber = 0;
1867
1868 d3.json(urlSc, function(err, data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001869 var p = data && data.params || {},
1870 desc = data && data.description || null,
Simon Huntfc274c92014-11-11 11:05:46 -08001871 intro = data && data.title;
Simon Huntbb282f52014-11-10 11:08:19 -08001872
Simon Hunt56d51852014-11-09 13:03:35 -08001873 if (err) {
1874 view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
1875 } else {
1876 sc.params = p;
Simon Huntbb282f52014-11-10 11:08:19 -08001877 if (desc) {
1878 intro += '\n\n ' + desc.join('\n ');
1879 }
1880 view.alert(intro);
Simon Hunt56d51852014-11-09 13:03:35 -08001881 }
1882 });
1883
1884 }
1885
Simon Hunt01095ff2014-11-13 16:37:29 -08001886 // ==============================
1887 // Toggle Buttons in masthead
Simon Hunt0c6d4192014-11-12 12:07:10 -08001888
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001889 // TODO: toggle button (and other widgets in the masthead) should be provided
1890 // by the framework; not generated by the view.
1891
Simon Hunta5e89142014-11-14 07:00:33 -08001892 var showInstances,
1893 doPanZoom,
1894 showTrafficOnHover;
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001895
1896 function addButtonBar(view) {
1897 var bb = d3.select('#mast')
1898 .append('span').classed('right', true).attr('id', 'bb');
1899
Simon Hunta5e89142014-11-14 07:00:33 -08001900 function mkTogBtn(text, cb) {
1901 return bb.append('span')
1902 .classed('btn', true)
1903 .text(text)
1904 .on('click', cb);
1905 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001906
Simon Hunta5e89142014-11-14 07:00:33 -08001907 showInstances = mkTogBtn('Show Instances', toggleInst);
1908 doPanZoom = mkTogBtn('Pan/Zoom', togglePanZoom);
1909 showTrafficOnHover = mkTogBtn('Show traffic on hover', toggleTrafficHover);
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001910 }
1911
Simon Hunta5e89142014-11-14 07:00:33 -08001912 function instShown() {
1913 return showInstances.classed('active');
Simon Huntf8e5b4e02014-11-13 11:17:57 -08001914 }
Simon Hunta5e89142014-11-14 07:00:33 -08001915 function toggleInst() {
1916 showInstances.classed('active', !instShown());
1917 if (instShown()) {
1918 oiBox.show();
1919 } else {
1920 oiBox.hide();
1921 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001922 }
1923
Simon Huntdeab4322014-11-13 18:49:07 -08001924 function panZoom() {
1925 return doPanZoom.classed('active');
Simon Hunt01095ff2014-11-13 16:37:29 -08001926 }
Simon Hunta5e89142014-11-14 07:00:33 -08001927 function togglePanZoom() {
1928 doPanZoom.classed('active', !panZoom());
1929 }
1930
1931 function trafficHover() {
1932 return showTrafficOnHover.classed('active');
1933 }
1934 function toggleTrafficHover() {
1935 showTrafficOnHover.classed('active', !trafficHover());
1936 }
1937
Simon Hunt7fa116d2014-11-17 14:16:55 -08001938 function loadGlyphs(svg) {
1939 var defs = svg.append('defs');
1940 gly.defBird(defs);
1941 gly.defBullhorn(defs);
1942 }
Simon Hunt01095ff2014-11-13 16:37:29 -08001943
Paul Greyson29cd58f2014-11-18 13:14:57 -08001944 // create references to bring these into cache so that getBBox() works when they
1945 // are inserted later
1946 function preloadIcons(svg) {
1947 var icons = [
1948 "router",
1949 "switch",
1950 "roadm",
1951 "endstation",
1952 "bgpSpeaker"
1953 ];
1954
1955 var g = svg.append('g');
1956 for (var icon in icons) {
1957 g.append('use')
1958 .attr({
1959 'xlink:href': 'icons.svg#' + icon
1960 });
1961 }
1962 g.style('visibility', 'hidden');
1963 }
1964
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001965 // ==============================
Simon Hunt142d0032014-11-04 20:13:09 -08001966 // View life-cycle callbacks
Simon Hunt195cb382014-11-03 17:50:51 -08001967
Simon Huntf67722a2014-11-10 09:32:06 -08001968 function preload(view, ctx, flags) {
Simon Hunt142d0032014-11-04 20:13:09 -08001969 var w = view.width(),
1970 h = view.height(),
Simon Huntc7ee0662014-11-05 16:44:37 -08001971 fcfg = config.force,
1972 fpad = fcfg.pad,
1973 forceDim = [w - 2*fpad, h - 2*fpad];
Simon Hunt195cb382014-11-03 17:50:51 -08001974
Simon Hunt142d0032014-11-04 20:13:09 -08001975 // NOTE: view.$div is a D3 selection of the view's div
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001976 var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
1977 svg = view.$div.append('svg').attr('viewBox', viewBox);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001978 setSize(svg, view);
1979
Simon Hunt7fa116d2014-11-17 14:16:55 -08001980 loadGlyphs(svg);
Paul Greyson29cd58f2014-11-18 13:14:57 -08001981 preloadIcons(svg);
Simon Hunt12ce12e2014-11-15 21:13:19 -08001982
Paul Greysonfcba0e82014-11-13 10:21:16 -08001983 zoomPanContainer = svg.append('g').attr('id', 'zoomPanContainer');
Paul Greysonfcba0e82014-11-13 10:21:16 -08001984 setupZoomPan();
1985
Simon Hunt1a9eff92014-11-07 11:06:34 -08001986 // add blue glow filter to svg layer
Paul Greysonfcba0e82014-11-13 10:21:16 -08001987 d3u.appendGlow(zoomPanContainer);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001988
Simon Huntc7ee0662014-11-05 16:44:37 -08001989 // group for the topology
Paul Greysonfcba0e82014-11-13 10:21:16 -08001990 topoG = zoomPanContainer.append('g')
Simon Huntd3b7d512014-11-12 15:48:41 -08001991 .attr('id', 'topo-G')
Simon Huntc7ee0662014-11-05 16:44:37 -08001992 .attr('transform', fcfg.translate());
1993
Simon Hunte2575b62014-11-18 15:25:53 -08001994 // subgroups for links, link labels, and nodes
Simon Huntc7ee0662014-11-05 16:44:37 -08001995 linkG = topoG.append('g').attr('id', 'links');
Simon Hunte2575b62014-11-18 15:25:53 -08001996 linkLabelG = topoG.append('g').attr('id', 'linkLabels');
Simon Huntc7ee0662014-11-05 16:44:37 -08001997 nodeG = topoG.append('g').attr('id', 'nodes');
1998
Simon Hunte2575b62014-11-18 15:25:53 -08001999 // selection of links, linkLabels, and nodes
Simon Huntc7ee0662014-11-05 16:44:37 -08002000 link = linkG.selectAll('.link');
Simon Hunte2575b62014-11-18 15:25:53 -08002001 linkLabel = linkLabelG.selectAll('.linkLabel');
Simon Huntc7ee0662014-11-05 16:44:37 -08002002 node = nodeG.selectAll('.node');
2003
Simon Hunt7cd48f32014-11-09 23:42:50 -08002004 function chrg(d) {
2005 return fcfg.charge[d.class] || -12000;
2006 }
Simon Hunt99c13842014-11-06 18:23:12 -08002007 function ldist(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08002008 return fcfg.linkDistance[d.type] || 50;
Simon Hunt99c13842014-11-06 18:23:12 -08002009 }
2010 function lstrg(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08002011 // 0.0 - 1.0
2012 return fcfg.linkStrength[d.type] || 1.0;
Simon Hunt99c13842014-11-06 18:23:12 -08002013 }
2014
Simon Hunt1a9eff92014-11-07 11:06:34 -08002015 function selectCb(d, self) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08002016 selectObject(d, self);
Simon Hunt1a9eff92014-11-07 11:06:34 -08002017 }
2018
2019 function atDragEnd(d, self) {
Simon Hunt56d51852014-11-09 13:03:35 -08002020 // once we've finished moving, pin the node in position
2021 d.fixed = true;
2022 d3.select(self).classed('fixed', true);
2023 if (config.useLiveData) {
Simon Hunt902c9922014-11-11 11:59:31 -08002024 sendUpdateMeta(d);
Simon Hunta255a2c2014-11-13 22:29:35 -08002025 } else {
2026 console.log('Moving node ' + d.id + ' to [' + d.x + ',' + d.y + ']');
Simon Hunt1a9eff92014-11-07 11:06:34 -08002027 }
2028 }
2029
Simon Hunt902c9922014-11-11 11:59:31 -08002030 function sendUpdateMeta(d) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08002031 sendMessage('updateMeta', {
2032 id: d.id,
2033 'class': d.class,
Simon Hunt902c9922014-11-11 11:59:31 -08002034 'memento': {
Simon Hunt01095ff2014-11-13 16:37:29 -08002035 x: d.x,
2036 y: d.y
Simon Hunt902c9922014-11-11 11:59:31 -08002037 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08002038 });
2039 }
2040
Simon Huntc7ee0662014-11-05 16:44:37 -08002041 // set up the force layout
2042 network.force = d3.layout.force()
2043 .size(forceDim)
2044 .nodes(network.nodes)
2045 .links(network.links)
Simon Hunt7cd48f32014-11-09 23:42:50 -08002046 .gravity(0.4)
2047 .friction(0.7)
2048 .charge(chrg)
Simon Hunt99c13842014-11-06 18:23:12 -08002049 .linkDistance(ldist)
2050 .linkStrength(lstrg)
Simon Huntc7ee0662014-11-05 16:44:37 -08002051 .on('tick', tick);
Simon Hunt195cb382014-11-03 17:50:51 -08002052
Simon Hunt01095ff2014-11-13 16:37:29 -08002053 network.drag = d3u.createDragBehavior(network.force,
Simon Huntdeab4322014-11-13 18:49:07 -08002054 selectCb, atDragEnd, panZoom);
Simon Hunt0c6d4192014-11-12 12:07:10 -08002055
2056 // create mask layer for when we lose connection to server.
Simon Hunta5e89142014-11-14 07:00:33 -08002057 // TODO: this should be part of the framework
Simon Hunt0c6d4192014-11-12 12:07:10 -08002058 mask = view.$div.append('div').attr('id','topo-mask');
2059 para(mask, 'Oops!');
2060 para(mask, 'Web-socket connection to server closed...');
2061 para(mask, 'Try refreshing the page.');
Simon Hunt12ce12e2014-11-15 21:13:19 -08002062
2063 mask.append('svg')
2064 .attr({
2065 id: 'mask-bird',
2066 width: w,
2067 height: h
2068 })
2069 .append('g')
2070 .attr('transform', birdTranslate(w, h))
2071 .style('opacity', 0.3)
2072 .append('use')
2073 .attr({
2074 'xlink:href': '#bird',
2075 width: config.birdDim,
2076 height: config.birdDim,
2077 fill: '#111'
Paul Greyson29cd58f2014-11-18 13:14:57 -08002078 });
Simon Hunt1a9eff92014-11-07 11:06:34 -08002079 }
Simon Hunt195cb382014-11-03 17:50:51 -08002080
Simon Hunt01095ff2014-11-13 16:37:29 -08002081 function para(sel, text) {
2082 sel.append('p').text(text);
2083 }
2084
2085
Simon Hunt56d51852014-11-09 13:03:35 -08002086 function load(view, ctx, flags) {
Simon Huntf67722a2014-11-10 09:32:06 -08002087 // resize, in case the window was resized while we were not loaded
2088 resize(view, ctx, flags);
2089
Simon Hunt99c13842014-11-06 18:23:12 -08002090 // cache the view token, so network topo functions can access it
2091 network.view = view;
Simon Hunt56d51852014-11-09 13:03:35 -08002092 config.useLiveData = !flags.local;
2093
2094 if (!config.useLiveData) {
2095 prepareScenario(view, ctx, flags.debug);
2096 }
Simon Hunt99c13842014-11-06 18:23:12 -08002097
2098 // set our radio buttons and key bindings
Simon Hunt9462e8c2014-11-14 17:28:09 -08002099 layerBtnSet = view.setRadio(layerButtons);
Simon Hunt934c3ce2014-11-05 11:45:07 -08002100 view.setKeys(keyDispatch);
Simon Hunt195cb382014-11-03 17:50:51 -08002101
Simon Huntf8e5b4e02014-11-13 11:17:57 -08002102 // patch in our "button bar" for now
2103 // TODO: implement a more official frameworky way of doing this..
2104 addButtonBar(view);
2105
Simon Huntd3b7d512014-11-12 15:48:41 -08002106 // Load map data asynchronously; complete startup after that..
2107 loadGeoJsonData();
Simon Hunta255a2c2014-11-13 22:29:35 -08002108
2109 // start the and timer
2110 var dashIdx = 0;
2111 antTimer = setInterval(function () {
2112 // TODO: figure out how to choose Src-->Dst and Dst-->Src, per link
2113 dashIdx = dashIdx === 0 ? 14 : dashIdx - 2;
2114 d3.selectAll('.animated').style('stroke-dashoffset', dashIdx);
2115 }, 35);
2116 }
2117
2118 function unload(view, ctx, flags) {
2119 if (antTimer) {
2120 clearInterval(antTimer);
2121 antTimer = null;
2122 }
Simon Huntd3b7d512014-11-12 15:48:41 -08002123 }
2124
2125 // TODO: move these to config/state portion of script
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002126 var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
Simon Huntd3b7d512014-11-12 15:48:41 -08002127 geoJson;
2128
2129 function loadGeoJsonData() {
2130 d3.json(geoJsonUrl, function (err, data) {
2131 if (err) {
2132 // fall back to USA map background
2133 loadStaticMap();
2134 } else {
2135 geoJson = data;
2136 loadGeoMap();
2137 }
2138
2139 // finally, connect to the server...
2140 if (config.useLiveData) {
2141 webSock.connect();
2142 }
2143 });
2144 }
2145
2146 function showBg() {
2147 return config.options.showBackground ? 'visible' : 'hidden';
2148 }
2149
2150 function loadStaticMap() {
2151 fnTrace('loadStaticMap', config.backgroundUrl);
2152 var w = network.view.width(),
2153 h = network.view.height();
2154
2155 // load the background image
2156 bgImg = svg.insert('svg:image', '#topo-G')
2157 .attr({
2158 id: 'topo-bg',
2159 width: w,
2160 height: h,
2161 'xlink:href': config.backgroundUrl
2162 })
2163 .style({
2164 visibility: showBg()
2165 });
2166 }
2167
2168 function loadGeoMap() {
2169 fnTrace('loadGeoMap', geoJsonUrl);
Simon Huntd3b7d512014-11-12 15:48:41 -08002170
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002171 // extracts the topojson data into geocoordinate-based geometry
2172 var topoData = topojson.feature(geoJson, geoJson.objects.states);
Simon Huntd3b7d512014-11-12 15:48:41 -08002173
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002174 // see: http://bl.ocks.org/mbostock/4707858
2175 geoMapProjection = d3.geo.mercator();
2176 var path = d3.geo.path().projection(geoMapProjection);
Simon Huntd3b7d512014-11-12 15:48:41 -08002177
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002178 geoMapProjection
2179 .scale(1)
2180 .translate([0, 0]);
Simon Huntd3b7d512014-11-12 15:48:41 -08002181
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002182 // [[x1,y1],[x2,y2]]
2183 var b = path.bounds(topoData);
Paul Greysonfcba0e82014-11-13 10:21:16 -08002184 // size map to 95% of minimum dimension to fill space
2185 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 -08002186 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 -08002187
Paul Greyson6cb8ca02014-11-12 18:09:02 -08002188 geoMapProjection
2189 .scale(s)
2190 .translate(t);
2191
Paul Greysonfcba0e82014-11-13 10:21:16 -08002192 bgImg = zoomPanContainer.insert("g", '#topo-G');
Paul Greyson29cd58f2014-11-18 13:14:57 -08002193 // pointer-events: none so that browser select tools don't pick up the map svg
2194 bgImg.attr('id', 'map').attr('stroke-width', config.map.strokeWidth + 'px').style('pointer-events', 'none')
2195 .selectAll('path')
2196 .data(topoData.features)
2197 .enter()
2198 .append('path')
2199 .attr('d', path);
Simon Hunt195cb382014-11-03 17:50:51 -08002200 }
2201
Simon Huntf67722a2014-11-10 09:32:06 -08002202 function resize(view, ctx, flags) {
Simon Hunt12ce12e2014-11-15 21:13:19 -08002203 var w = view.width(),
2204 h = view.height();
2205
Simon Hunt934c3ce2014-11-05 11:45:07 -08002206 setSize(svg, view);
Simon Hunt12ce12e2014-11-15 21:13:19 -08002207
2208 d3.select('#mask-bird').attr({ width: w, height: h})
2209 .select('g').attr('transform', birdTranslate(w, h));
Simon Hunt142d0032014-11-04 20:13:09 -08002210 }
2211
Simon Hunt12ce12e2014-11-15 21:13:19 -08002212 function birdTranslate(w, h) {
2213 var bdim = config.birdDim;
2214 return 'translate('+((w-bdim)*.4)+','+((h-bdim)*.1)+')';
2215 }
Simon Hunt142d0032014-11-04 20:13:09 -08002216
2217 // ==============================
2218 // View registration
Simon Hunt195cb382014-11-03 17:50:51 -08002219
Simon Hunt25248912014-11-04 11:25:48 -08002220 onos.ui.addView('topo', {
Simon Hunt142d0032014-11-04 20:13:09 -08002221 preload: preload,
2222 load: load,
Simon Hunta255a2c2014-11-13 22:29:35 -08002223 unload: unload,
Simon Hunt142d0032014-11-04 20:13:09 -08002224 resize: resize
Simon Hunt195cb382014-11-03 17:50:51 -08002225 });
2226
Simon Hunt61d04042014-11-11 17:27:16 -08002227 detailPane = onos.ui.addFloatingPanel('topo-detail');
Simon Hunta5e89142014-11-14 07:00:33 -08002228 oiBox = onos.ui.addFloatingPanel('topo-oibox', 'TL');
Simon Hunt61d04042014-11-11 17:27:16 -08002229
Simon Hunt195cb382014-11-03 17:50:51 -08002230}(ONOS));