blob: f93595f5fa2be3ee7bf71582856bfdee0b3f5922 [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,
28 trace;
Simon Hunt1a9eff92014-11-07 11:06:34 -080029
Simon Hunt195cb382014-11-03 17:50:51 -080030 // configuration data
31 var config = {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -080032 useLiveData: true,
Simon Huntfc274c92014-11-11 11:05:46 -080033 fnTrace: true,
Simon Hunt195cb382014-11-03 17:50:51 -080034 debugOn: false,
35 debug: {
Simon Hunt99c13842014-11-06 18:23:12 -080036 showNodeXY: true,
37 showKeyHandler: false
Simon Hunt195cb382014-11-03 17:50:51 -080038 },
39 options: {
40 layering: true,
41 collisionPrevention: true,
Simon Hunt142d0032014-11-04 20:13:09 -080042 showBackground: true
Simon Hunt195cb382014-11-03 17:50:51 -080043 },
44 backgroundUrl: 'img/us-map.png',
Thomas Vachuska7d638d32014-11-07 10:24:43 -080045 webSockUrl: 'ws/topology',
Simon Hunt195cb382014-11-03 17:50:51 -080046 data: {
47 live: {
48 jsonUrl: 'rs/topology/graph',
49 detailPrefix: 'rs/topology/graph/',
50 detailSuffix: ''
51 },
52 fake: {
53 jsonUrl: 'json/network2.json',
54 detailPrefix: 'json/',
55 detailSuffix: '.json'
56 }
57 },
Simon Hunt99c13842014-11-06 18:23:12 -080058 labels: {
59 imgPad: 16,
60 padLR: 4,
61 padTB: 3,
62 marginLR: 3,
63 marginTB: 2,
64 port: {
65 gap: 3,
66 width: 18,
67 height: 14
68 }
69 },
Simon Hunt1a9eff92014-11-07 11:06:34 -080070 topo: {
71 linkInColor: '#66f',
72 linkInWidth: 14
73 },
Simon Hunt99c13842014-11-06 18:23:12 -080074 icons: {
75 w: 28,
76 h: 28,
77 xoff: -12,
78 yoff: -8
79 },
Simon Hunt195cb382014-11-03 17:50:51 -080080 iconUrl: {
81 device: 'img/device.png',
82 host: 'img/host.png',
83 pkt: 'img/pkt.png',
84 opt: 'img/opt.png'
85 },
Simon Hunt195cb382014-11-03 17:50:51 -080086 force: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080087 note_for_links: 'link.type is used to differentiate',
Simon Huntc7ee0662014-11-05 16:44:37 -080088 linkDistance: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080089 direct: 100,
90 optical: 120,
Simon Huntf67722a2014-11-10 09:32:06 -080091 hostLink: 5
Simon Huntc7ee0662014-11-05 16:44:37 -080092 },
93 linkStrength: {
Simon Hunt7cd48f32014-11-09 23:42:50 -080094 direct: 1.0,
95 optical: 1.0,
96 hostLink: 1.0
Simon Huntc7ee0662014-11-05 16:44:37 -080097 },
Simon Hunt7cd48f32014-11-09 23:42:50 -080098 note_for_nodes: 'node.class is used to differentiate',
Simon Huntc7ee0662014-11-05 16:44:37 -080099 charge: {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800100 device: -8000,
101 host: -300
Simon Huntc7ee0662014-11-05 16:44:37 -0800102 },
103 pad: 20,
Simon Hunt195cb382014-11-03 17:50:51 -0800104 translate: function() {
105 return 'translate(' +
Simon Huntc7ee0662014-11-05 16:44:37 -0800106 config.force.pad + ',' +
107 config.force.pad + ')';
Simon Hunt195cb382014-11-03 17:50:51 -0800108 }
Paul Greyson6cb8ca02014-11-12 18:09:02 -0800109 },
110 // see below in creation of viewBox on main svg
111 logicalSize: 1000
Simon Hunt195cb382014-11-03 17:50:51 -0800112 };
113
Simon Hunt142d0032014-11-04 20:13:09 -0800114 // radio buttons
115 var btnSet = [
Simon Hunt934c3ce2014-11-05 11:45:07 -0800116 { text: 'All Layers', cb: showAllLayers },
117 { text: 'Packet Only', cb: showPacketLayer },
118 { text: 'Optical Only', cb: showOpticalLayer }
119 ];
120
121 // key bindings
122 var keyDispatch = {
Simon Hunt1a9eff92014-11-07 11:06:34 -0800123 M: testMe, // TODO: remove (testing only)
Simon Hunt50128c02014-11-08 13:36:15 -0800124 S: injectStartupEvents, // TODO: remove (testing only)
125 space: injectTestEvent, // TODO: remove (testing only)
Simon Hunt99c13842014-11-06 18:23:12 -0800126
Thomas Vachuska65368e32014-11-08 16:10:20 -0800127 B: toggleBg, // TODO: do we really need this?
Simon Hunt934c3ce2014-11-05 11:45:07 -0800128 L: cycleLabels,
129 P: togglePorts,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800130 U: unpin,
131
Simon Huntb53e0682014-11-12 13:32:01 -0800132 W: requestTraffic, // bag of selections
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800133 X: cancelTraffic,
134 Z: requestPath // host-to-host intent (and monitor)
Simon Hunt934c3ce2014-11-05 11:45:07 -0800135 };
Simon Hunt142d0032014-11-04 20:13:09 -0800136
Simon Hunt195cb382014-11-03 17:50:51 -0800137 // state variables
Simon Hunt99c13842014-11-06 18:23:12 -0800138 var network = {
Simon Hunt50128c02014-11-08 13:36:15 -0800139 view: null, // view token reference
Simon Hunt99c13842014-11-06 18:23:12 -0800140 nodes: [],
141 links: [],
142 lookup: {}
143 },
Simon Hunt56d51852014-11-09 13:03:35 -0800144 scenario = {
145 evDir: 'json/ev/',
146 evScenario: '/scenario.json',
147 evPrefix: '/ev_',
148 evOnos: '_onos.json',
149 evUi: '_ui.json',
150 ctx: null,
151 params: {},
152 evNumber: 0,
153 view: null,
154 debug: false
155 },
Thomas Vachuska7d638d32014-11-07 10:24:43 -0800156 webSock,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800157 sid = 0,
Simon Hunt56d51852014-11-09 13:03:35 -0800158 deviceLabelIndex = 0,
159 hostLabelIndex = 0,
Simon Hunt61d04042014-11-11 17:27:16 -0800160 detailPane,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800161 selectOrder = [],
162 selections = {},
163
Simon Hunt195cb382014-11-03 17:50:51 -0800164 highlighted = null,
165 hovered = null,
166 viewMode = 'showAll',
167 portLabelsOn = false;
168
Simon Hunt934c3ce2014-11-05 11:45:07 -0800169 // D3 selections
170 var svg,
171 bgImg,
Simon Huntc7ee0662014-11-05 16:44:37 -0800172 topoG,
173 nodeG,
174 linkG,
175 node,
Simon Hunt0c6d4192014-11-12 12:07:10 -0800176 link,
177 mask;
Simon Hunt195cb382014-11-03 17:50:51 -0800178
Paul Greyson6cb8ca02014-11-12 18:09:02 -0800179 // the projection for the map background
180 var geoMapProjection;
181
Simon Hunt142d0032014-11-04 20:13:09 -0800182 // ==============================
Simon Hunt934c3ce2014-11-05 11:45:07 -0800183 // For Debugging / Development
Simon Hunt195cb382014-11-03 17:50:51 -0800184
Simon Hunt99c13842014-11-06 18:23:12 -0800185 function note(label, msg) {
186 console.log('NOTE: ' + label + ': ' + msg);
Simon Hunt195cb382014-11-03 17:50:51 -0800187 }
188
Simon Hunt99c13842014-11-06 18:23:12 -0800189 function debug(what) {
190 return config.debugOn && config.debug[what];
Simon Hunt934c3ce2014-11-05 11:45:07 -0800191 }
192
Simon Huntfc274c92014-11-11 11:05:46 -0800193 function fnTrace(msg, id) {
194 if (config.fnTrace) {
195 console.log('FN: ' + msg + ' [' + id + ']');
196 }
197 }
Simon Hunt99c13842014-11-06 18:23:12 -0800198
Simon Hunt934c3ce2014-11-05 11:45:07 -0800199 // ==============================
200 // Key Callbacks
201
Simon Hunt99c13842014-11-06 18:23:12 -0800202 function testMe(view) {
Simon Hunt50128c02014-11-08 13:36:15 -0800203 view.alert('test');
Simon Hunt99c13842014-11-06 18:23:12 -0800204 }
205
Simon Hunt56d51852014-11-09 13:03:35 -0800206 function abortIfLive() {
Simon Hunt50128c02014-11-08 13:36:15 -0800207 if (config.useLiveData) {
Simon Huntb53e0682014-11-12 13:32:01 -0800208 network.view.alert("Sorry, currently using live data..");
Simon Hunt56d51852014-11-09 13:03:35 -0800209 return true;
Simon Hunt50128c02014-11-08 13:36:15 -0800210 }
Simon Hunt56d51852014-11-09 13:03:35 -0800211 return false;
212 }
Simon Hunt50128c02014-11-08 13:36:15 -0800213
Simon Hunt56d51852014-11-09 13:03:35 -0800214 function testDebug(msg) {
215 if (scenario.debug) {
216 scenario.view.alert(msg);
217 }
218 }
Simon Hunt99c13842014-11-06 18:23:12 -0800219
Simon Hunt56d51852014-11-09 13:03:35 -0800220 function injectTestEvent(view) {
221 if (abortIfLive()) { return; }
222 var sc = scenario,
223 evn = ++sc.evNumber,
224 pfx = sc.evDir + sc.ctx + sc.evPrefix + evn,
225 onosUrl = pfx + sc.evOnos,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800226 uiUrl = pfx + sc.evUi,
227 stack = [
228 { url: onosUrl, cb: handleServerEvent },
229 { url: uiUrl, cb: handleUiEvent }
230 ];
231 recurseFetchEvent(stack, evn);
Simon Hunt56d51852014-11-09 13:03:35 -0800232 }
233
Simon Hunt7cd48f32014-11-09 23:42:50 -0800234 function recurseFetchEvent(stack, evn) {
235 var v = scenario.view,
236 frame;
237 if (stack.length === 0) {
Simon Huntfc274c92014-11-11 11:05:46 -0800238 v.alert('Oops!\n\nNo event #' + evn + ' found.');
Simon Hunt7cd48f32014-11-09 23:42:50 -0800239 return;
240 }
241 frame = stack.shift();
242
243 d3.json(frame.url, function (err, data) {
Simon Hunt99c13842014-11-06 18:23:12 -0800244 if (err) {
Simon Hunt56d51852014-11-09 13:03:35 -0800245 if (err.status === 404) {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800246 // if we didn't find the data, try the next stack frame
247 recurseFetchEvent(stack, evn);
Simon Hunt56d51852014-11-09 13:03:35 -0800248 } else {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800249 v.alert('non-404 error:\n\n' + frame.url + '\n\n' + err);
Simon Hunt56d51852014-11-09 13:03:35 -0800250 }
Simon Hunt99c13842014-11-06 18:23:12 -0800251 } else {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800252 testDebug('loaded: ' + frame.url);
253 frame.cb(data);
Simon Hunt99c13842014-11-06 18:23:12 -0800254 }
255 });
Simon Hunt934c3ce2014-11-05 11:45:07 -0800256
Simon Hunt56d51852014-11-09 13:03:35 -0800257 }
Simon Hunt50128c02014-11-08 13:36:15 -0800258
Simon Hunt56d51852014-11-09 13:03:35 -0800259 function handleUiEvent(data) {
Simon Huntbb282f52014-11-10 11:08:19 -0800260 scenario.view.alert('UI Tx: ' + data.event + '\n\n' +
261 JSON.stringify(data));
Simon Hunt56d51852014-11-09 13:03:35 -0800262 }
263
264 function injectStartupEvents(view) {
265 var last = scenario.params.lastAuto || 0;
266 if (abortIfLive()) { return; }
267
268 while (scenario.evNumber < last) {
Simon Hunt1a9eff92014-11-07 11:06:34 -0800269 injectTestEvent(view);
270 }
271 }
272
Simon Hunt934c3ce2014-11-05 11:45:07 -0800273 function toggleBg() {
274 var vis = bgImg.style('visibility');
275 bgImg.style('visibility', (vis === 'hidden') ? 'visible' : 'hidden');
276 }
277
Simon Hunt99c13842014-11-06 18:23:12 -0800278 function cycleLabels() {
Simon Huntbb282f52014-11-10 11:08:19 -0800279 deviceLabelIndex = (deviceLabelIndex === network.deviceLabelCount - 1)
280 ? 0 : deviceLabelIndex + 1;
Simon Hunt5f36d342014-11-08 21:33:14 -0800281
Simon Hunt99c13842014-11-06 18:23:12 -0800282 network.nodes.forEach(function (d) {
Simon Huntbb282f52014-11-10 11:08:19 -0800283 if (d.class === 'device') {
284 updateDeviceLabel(d);
285 }
Simon Hunt99c13842014-11-06 18:23:12 -0800286 });
Simon Hunt934c3ce2014-11-05 11:45:07 -0800287 }
288
289 function togglePorts(view) {
Simon Hunt50128c02014-11-08 13:36:15 -0800290 view.alert('togglePorts() callback')
Simon Hunt934c3ce2014-11-05 11:45:07 -0800291 }
292
293 function unpin(view) {
Simon Hunt50128c02014-11-08 13:36:15 -0800294 view.alert('unpin() callback')
Simon Hunt934c3ce2014-11-05 11:45:07 -0800295 }
296
297 // ==============================
298 // Radio Button Callbacks
299
Simon Hunt195cb382014-11-03 17:50:51 -0800300 function showAllLayers() {
Simon Hunt142d0032014-11-04 20:13:09 -0800301// network.node.classed('inactive', false);
302// network.link.classed('inactive', false);
303// d3.selectAll('svg .port').classed('inactive', false);
304// d3.selectAll('svg .portText').classed('inactive', false);
Simon Hunt934c3ce2014-11-05 11:45:07 -0800305 // TODO ...
Simon Hunt50128c02014-11-08 13:36:15 -0800306 network.view.alert('showAllLayers() callback');
Simon Hunt195cb382014-11-03 17:50:51 -0800307 }
308
309 function showPacketLayer() {
Simon Hunt934c3ce2014-11-05 11:45:07 -0800310 showAllLayers();
311 // TODO ...
Simon Hunt50128c02014-11-08 13:36:15 -0800312 network.view.alert('showPacketLayer() callback');
Simon Hunt195cb382014-11-03 17:50:51 -0800313 }
314
315 function showOpticalLayer() {
Simon Hunt934c3ce2014-11-05 11:45:07 -0800316 showAllLayers();
317 // TODO ...
Simon Hunt50128c02014-11-08 13:36:15 -0800318 network.view.alert('showOpticalLayer() callback');
Simon Hunt195cb382014-11-03 17:50:51 -0800319 }
320
Simon Hunt142d0032014-11-04 20:13:09 -0800321 // ==============================
Simon Hunt934c3ce2014-11-05 11:45:07 -0800322 // Private functions
323
Simon Hunt99c13842014-11-06 18:23:12 -0800324 function safeId(s) {
325 return s.replace(/[^a-z0-9]/gi, '-');
326 }
327
Simon Huntc7ee0662014-11-05 16:44:37 -0800328 // set the size of the given element to that of the view (reduced if padded)
329 function setSize(el, view, pad) {
330 var padding = pad ? pad * 2 : 0;
Simon Hunt934c3ce2014-11-05 11:45:07 -0800331 el.attr({
Simon Huntc7ee0662014-11-05 16:44:37 -0800332 width: view.width() - padding,
333 height: view.height() - padding
Simon Hunt934c3ce2014-11-05 11:45:07 -0800334 });
335 }
336
Simon Hunt934c3ce2014-11-05 11:45:07 -0800337
Simon Hunt99c13842014-11-06 18:23:12 -0800338 // ==============================
339 // Event handlers for server-pushed events
340
Simon Huntbb282f52014-11-10 11:08:19 -0800341 function logicError(msg) {
342 // TODO, report logic error to server, via websock, so it can be logged
343 network.view.alert('Logic Error:\n\n' + msg);
Simon Huntfc274c92014-11-11 11:05:46 -0800344 console.warn(msg);
Simon Huntbb282f52014-11-10 11:08:19 -0800345 }
346
Simon Hunt99c13842014-11-06 18:23:12 -0800347 var eventDispatch = {
348 addDevice: addDevice,
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800349 addLink: addLink,
Simon Hunt56d51852014-11-09 13:03:35 -0800350 addHost: addHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800351
Simon Huntbb282f52014-11-10 11:08:19 -0800352 updateDevice: updateDevice,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800353 updateLink: updateLink,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800354 updateHost: updateHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800355
Simon Huntbb282f52014-11-10 11:08:19 -0800356 removeDevice: stillToImplement,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800357 removeLink: removeLink,
Simon Hunt44031102014-11-11 13:20:36 -0800358 removeHost: removeHost,
Simon Huntb53e0682014-11-12 13:32:01 -0800359
Simon Hunt61d04042014-11-11 17:27:16 -0800360 showDetails: showDetails,
Simon Huntb53e0682014-11-12 13:32:01 -0800361 showPath: showPath,
362 showTraffic: showTraffic
Simon Hunt99c13842014-11-06 18:23:12 -0800363 };
364
365 function addDevice(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800366 fnTrace('addDevice', data.payload.id);
Simon Hunt99c13842014-11-06 18:23:12 -0800367 var device = data.payload,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800368 nodeData = createDeviceNode(device);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800369 network.nodes.push(nodeData);
370 network.lookup[nodeData.id] = nodeData;
Simon Hunt99c13842014-11-06 18:23:12 -0800371 updateNodes();
372 network.force.start();
373 }
374
Simon Hunt99c13842014-11-06 18:23:12 -0800375 function addLink(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800376 fnTrace('addLink', data.payload.id);
Simon Hunt99c13842014-11-06 18:23:12 -0800377 var link = data.payload,
378 lnk = createLink(link);
Simon Hunt99c13842014-11-06 18:23:12 -0800379 if (lnk) {
Simon Hunt99c13842014-11-06 18:23:12 -0800380 network.links.push(lnk);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800381 network.lookup[lnk.id] = lnk;
Simon Hunt99c13842014-11-06 18:23:12 -0800382 updateLinks();
383 network.force.start();
384 }
385 }
386
Simon Hunt56d51852014-11-09 13:03:35 -0800387 function addHost(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800388 fnTrace('addHost', data.payload.id);
Simon Hunt56d51852014-11-09 13:03:35 -0800389 var host = data.payload,
390 node = createHostNode(host),
391 lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800392 network.nodes.push(node);
393 network.lookup[host.id] = node;
394 updateNodes();
395
396 lnk = createHostLink(host);
397 if (lnk) {
Simon Hunt44031102014-11-11 13:20:36 -0800398 node.linkData = lnk; // cache ref on its host
Simon Hunt56d51852014-11-09 13:03:35 -0800399 network.links.push(lnk);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800400 network.lookup[host.ingress] = lnk;
401 network.lookup[host.egress] = lnk;
Simon Hunt56d51852014-11-09 13:03:35 -0800402 updateLinks();
403 }
404 network.force.start();
405 }
406
Simon Hunt44031102014-11-11 13:20:36 -0800407 // TODO: fold updateX(...) methods into one base method; remove duplication
Simon Huntbb282f52014-11-10 11:08:19 -0800408 function updateDevice(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800409 fnTrace('updateDevice', data.payload.id);
Simon Huntbb282f52014-11-10 11:08:19 -0800410 var device = data.payload,
411 id = device.id,
412 nodeData = network.lookup[id];
413 if (nodeData) {
414 $.extend(nodeData, device);
415 updateDeviceState(nodeData);
416 } else {
417 logicError('updateDevice lookup fail. ID = "' + id + '"');
418 }
419 }
420
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800421 function updateLink(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800422 fnTrace('updateLink', data.payload.id);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800423 var link = data.payload,
424 id = link.id,
425 linkData = network.lookup[id];
426 if (linkData) {
427 $.extend(linkData, link);
428 updateLinkState(linkData);
429 } else {
430 logicError('updateLink lookup fail. ID = "' + id + '"');
431 }
432 }
433
Simon Hunt7cd48f32014-11-09 23:42:50 -0800434 function updateHost(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800435 fnTrace('updateHost', data.payload.id);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800436 var host = data.payload,
Simon Huntbb282f52014-11-10 11:08:19 -0800437 id = host.id,
438 hostData = network.lookup[id];
439 if (hostData) {
440 $.extend(hostData, host);
441 updateHostState(hostData);
442 } else {
443 logicError('updateHost lookup fail. ID = "' + id + '"');
444 }
Simon Hunt7cd48f32014-11-09 23:42:50 -0800445 }
446
Simon Hunt44031102014-11-11 13:20:36 -0800447 // TODO: fold removeX(...) methods into base method - remove dup code
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800448 function removeLink(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800449 fnTrace('removeLink', data.payload.id);
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800450 var link = data.payload,
451 id = link.id,
452 linkData = network.lookup[id];
453 if (linkData) {
454 removeLinkElement(linkData);
455 } else {
456 logicError('removeLink lookup fail. ID = "' + id + '"');
457 }
458 }
459
Simon Hunt44031102014-11-11 13:20:36 -0800460 function removeHost(data) {
461 fnTrace('removeHost', data.payload.id);
462 var host = data.payload,
463 id = host.id,
464 hostData = network.lookup[id];
465 if (hostData) {
466 removeHostElement(hostData);
467 } else {
468 logicError('removeHost lookup fail. ID = "' + id + '"');
469 }
470 }
471
Simon Hunt61d04042014-11-11 17:27:16 -0800472 function showDetails(data) {
473 fnTrace('showDetails', data.payload.id);
474 populateDetails(data.payload);
Simon Huntb53e0682014-11-12 13:32:01 -0800475 // TODO: Add single-select actions ...
Simon Hunt61d04042014-11-11 17:27:16 -0800476 detailPane.show();
477 }
478
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800479 function showPath(data) {
Simon Huntfc274c92014-11-11 11:05:46 -0800480 fnTrace('showPath', data.payload.id);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800481 var links = data.payload.links,
482 s = [ data.event + "\n" + links.length ];
483 links.forEach(function (d, i) {
484 s.push(d);
485 });
486 network.view.alert(s.join('\n'));
487
488 links.forEach(function (d, i) {
489 var link = network.lookup[d];
490 if (link) {
Simon Hunt7cd48f32014-11-09 23:42:50 -0800491 link.el.classed('showPath', true);
Thomas Vachuska4830d392014-11-09 17:09:56 -0800492 }
493 });
494
495 // TODO: add selection-highlite lines to links
Thomas Vachuskad1be50d2014-11-08 16:10:20 -0800496 }
497
Simon Huntb53e0682014-11-12 13:32:01 -0800498 function showTraffic(data) {
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800499 fnTrace('showTraffic', data.payload.id);
500 data.payload.paths.forEach(function () {
501 var links = data.payload.links,
502 s = [ data.event + "\n" + links.length ];
503 links.forEach(function (d, i) {
504 s.push(d);
505 });
506 network.view.alert(s.join('\n'));
507
508 links.forEach(function (d, i) {
509 var link = network.lookup[d];
510 if (link) {
511 link.el.classed('showPath', true);
512 }
513 });
514 });
515 //network.view.alert("showTraffic() -- TODO")
Simon Huntb53e0682014-11-12 13:32:01 -0800516 }
517
Simon Hunt56d51852014-11-09 13:03:35 -0800518 // ...............................
519
520 function stillToImplement(data) {
521 var p = data.payload;
522 note(data.event, p.id);
Simon Hunt7cd48f32014-11-09 23:42:50 -0800523 network.view.alert('Not yet implemented: "' + data.event + '"');
Simon Hunt56d51852014-11-09 13:03:35 -0800524 }
Simon Hunt99c13842014-11-06 18:23:12 -0800525
526 function unknownEvent(data) {
Simon Hunt50128c02014-11-08 13:36:15 -0800527 network.view.alert('Unknown event type: "' + data.event + '"');
Simon Hunt99c13842014-11-06 18:23:12 -0800528 }
529
530 function handleServerEvent(data) {
531 var fn = eventDispatch[data.event] || unknownEvent;
532 fn(data);
533 }
534
535 // ==============================
Simon Hunt61d04042014-11-11 17:27:16 -0800536 // Out-going messages...
537
Simon Huntb53e0682014-11-12 13:32:01 -0800538 function userFeedback(msg) {
539 // for now, use the alert pane as is. Maybe different alert style in
540 // the future (centered on view; dismiss button?)
541 network.view.alert(msg);
542 }
543
544 function nSel() {
545 return selectOrder.length;
546 }
Simon Hunt61d04042014-11-11 17:27:16 -0800547 function getSel(idx) {
548 return selections[selectOrder[idx]];
549 }
Simon Huntb53e0682014-11-12 13:32:01 -0800550 function getSelId(idx) {
551 return getSel(idx).obj.id;
552 }
553 function allSelectionsClass(cls) {
554 for (var i=0, n=nSel(); i<n; i++) {
555 if (getSel(i).obj.class !== cls) {
556 return false;
557 }
558 }
559 return true;
560 }
Simon Hunt61d04042014-11-11 17:27:16 -0800561
Simon Huntb53e0682014-11-12 13:32:01 -0800562 function requestTraffic() {
563 if (nSel() > 0) {
564 sendMessage('requestTraffic', {
565 ids: selectOrder
566 });
567 } else {
568 userFeedback('Request-Traffic requires one or\n' +
569 'more items to be selected.');
570 }
571 }
572
Simon Hunt61d04042014-11-11 17:27:16 -0800573 function requestPath() {
Simon Huntb53e0682014-11-12 13:32:01 -0800574 if (nSel() === 2 && allSelectionsClass('host')) {
575 sendMessage('requestPath', {
576 one: getSelId(0),
577 two: getSelId(1)
578 });
579 } else {
580 userFeedback('Request-Path requires two\n' +
581 'hosts to be selected.');
582 }
Simon Hunt61d04042014-11-11 17:27:16 -0800583 }
584
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800585 function cancelTraffic() {
Simon Huntb53e0682014-11-12 13:32:01 -0800586 // FIXME: from where do we get the intent id(s) to send to the server?
Thomas Vachuskadea45ff2014-11-12 18:35:46 -0800587 sendMessage('cancelTraffic', {
Simon Huntb53e0682014-11-12 13:32:01 -0800588 ids: ["need_the_intent_id"]
589 });
Simon Huntac9e24f2014-11-12 10:12:21 -0800590 }
591
Simon Hunt61d04042014-11-11 17:27:16 -0800592 // request details for the selected element
593 function requestDetails() {
594 var data = getSel(0).obj,
595 payload = {
596 id: data.id,
597 class: data.class
598 };
599 sendMessage('requestDetails', payload);
600 }
601
602 // ==============================
Simon Hunt99c13842014-11-06 18:23:12 -0800603 // force layout modification functions
604
605 function translate(x, y) {
606 return 'translate(' + x + ',' + y + ')';
607 }
608
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800609 function missMsg(what, id) {
610 return '\n[' + what + '] "' + id + '" missing ';
611 }
612
613 function linkEndPoints(srcId, dstId) {
614 var srcNode = network.lookup[srcId],
615 dstNode = network.lookup[dstId],
616 sMiss = !srcNode ? missMsg('src', srcId) : '',
617 dMiss = !dstNode ? missMsg('dst', dstId) : '';
618
619 if (sMiss || dMiss) {
620 logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
621 return null;
622 }
623 return {
624 source: srcNode,
625 target: dstNode,
626 x1: srcNode.x,
627 y1: srcNode.y,
628 x2: dstNode.x,
629 y2: dstNode.y
630 };
631 }
632
Simon Hunt56d51852014-11-09 13:03:35 -0800633 function createHostLink(host) {
634 var src = host.id,
635 dst = host.cp.device,
Simon Hunt7cd48f32014-11-09 23:42:50 -0800636 id = host.ingress,
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800637 lnk = linkEndPoints(src, dst);
Simon Hunt56d51852014-11-09 13:03:35 -0800638
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800639 if (!lnk) {
Simon Hunt56d51852014-11-09 13:03:35 -0800640 return null;
641 }
642
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800643 // Synthesize link ...
644 $.extend(lnk, {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800645 id: id,
Simon Hunt56d51852014-11-09 13:03:35 -0800646 class: 'link',
Simon Hunt7cd48f32014-11-09 23:42:50 -0800647 type: 'hostLink',
Simon Hunt56d51852014-11-09 13:03:35 -0800648 svgClass: 'link hostLink',
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800649 linkWidth: 1
Simon Hunt7cd48f32014-11-09 23:42:50 -0800650 });
Simon Hunt99c13842014-11-06 18:23:12 -0800651 return lnk;
652 }
653
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800654 function createLink(link) {
655 var lnk = linkEndPoints(link.src, link.dst),
656 type = link.type;
657
658 if (!lnk) {
659 return null;
660 }
661
662 // merge in remaining data
663 $.extend(lnk, link, {
664 class: 'link',
665 svgClass: type ? 'link ' + type : 'link'
666 });
667 return lnk;
Simon Hunt1a9eff92014-11-07 11:06:34 -0800668 }
669
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800670 var widthRatio = 1.4,
671 linkScale = d3.scale.linear()
672 .domain([1, 12])
673 .range([widthRatio, 12 * widthRatio])
674 .clamp(true);
675
676 function updateLinkWidth (d) {
677 // TODO: watch out for .showPath/.showTraffic classes
678 d.el.transition()
679 .duration(1000)
680 .attr('stroke-width', linkScale(d.linkWidth));
681 }
682
683
Simon Hunt99c13842014-11-06 18:23:12 -0800684 function updateLinks() {
685 link = linkG.selectAll('.link')
686 .data(network.links, function (d) { return d.id; });
687
688 // operate on existing links, if necessary
689 // link .foo() .bar() ...
690
691 // operate on entering links:
692 var entering = link.enter()
693 .append('line')
694 .attr({
Simon Hunt99c13842014-11-06 18:23:12 -0800695 class: function (d) { return d.svgClass; },
696 x1: function (d) { return d.x1; },
697 y1: function (d) { return d.y1; },
698 x2: function (d) { return d.x2; },
699 y2: function (d) { return d.y2; },
Simon Hunt1a9eff92014-11-07 11:06:34 -0800700 stroke: config.topo.linkInColor,
701 'stroke-width': config.topo.linkInWidth
Simon Hunt99c13842014-11-06 18:23:12 -0800702 })
703 .transition().duration(1000)
704 .attr({
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800705 'stroke-width': function (d) { return linkScale(d.linkWidth); },
Simon Hunt99c13842014-11-06 18:23:12 -0800706 stroke: '#666' // TODO: remove explicit stroke, rather...
707 });
708
709 // augment links
Simon Hunt7cd48f32014-11-09 23:42:50 -0800710 entering.each(function (d) {
711 var link = d3.select(this);
712 // provide ref to element selection from backing data....
713 d.el = link;
Simon Hunt99c13842014-11-06 18:23:12 -0800714
Simon Hunt7cd48f32014-11-09 23:42:50 -0800715 // TODO: add src/dst port labels etc.
716 });
Thomas Vachuska4830d392014-11-09 17:09:56 -0800717
718 // operate on both existing and new links, if necessary
719 //link .foo() .bar() ...
720
721 // operate on exiting links:
Thomas Vachuska4830d392014-11-09 17:09:56 -0800722 link.exit()
Thomas Vachuska4830d392014-11-09 17:09:56 -0800723 .attr({
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800724 'stroke-dasharray': '3, 3'
Thomas Vachuska4830d392014-11-09 17:09:56 -0800725 })
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800726 .style('opacity', 0.4)
727 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -0800728 .duration(1500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800729 .attr({
730 'stroke-dasharray': '3, 12'
731 })
732 .transition()
Simon Huntea80eb42014-11-11 13:46:57 -0800733 .duration(500)
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800734 .style('opacity', 0.0)
Thomas Vachuska4830d392014-11-09 17:09:56 -0800735 .remove();
Simon Hunt99c13842014-11-06 18:23:12 -0800736 }
737
738 function createDeviceNode(device) {
739 // start with the object as is
740 var node = device,
Simon Huntbb282f52014-11-10 11:08:19 -0800741 type = device.type,
742 svgCls = type ? 'node device ' + type : 'node device';
Simon Hunt99c13842014-11-06 18:23:12 -0800743
744 // Augment as needed...
745 node.class = 'device';
Simon Huntbb282f52014-11-10 11:08:19 -0800746 node.svgClass = device.online ? svgCls + ' online' : svgCls;
Simon Hunt99c13842014-11-06 18:23:12 -0800747 positionNode(node);
748
749 // cache label array length
750 network.deviceLabelCount = device.labels.length;
Simon Hunt99c13842014-11-06 18:23:12 -0800751 return node;
752 }
753
Simon Hunt56d51852014-11-09 13:03:35 -0800754 function createHostNode(host) {
755 // start with the object as is
756 var node = host;
757
758 // Augment as needed...
759 node.class = 'host';
Simon Hunt7cd48f32014-11-09 23:42:50 -0800760 if (!node.type) {
761 // TODO: perhaps type would be: {phone, tablet, laptop, endstation} ?
762 node.type = 'endstation';
763 }
Simon Hunt56d51852014-11-09 13:03:35 -0800764 node.svgClass = 'node host';
765 // TODO: consider placing near its switch, if [x,y] not defined
766 positionNode(node);
767
768 // cache label array length
769 network.hostLabelCount = host.labels.length;
Simon Hunt56d51852014-11-09 13:03:35 -0800770 return node;
771 }
772
Simon Hunt99c13842014-11-06 18:23:12 -0800773 function positionNode(node) {
774 var meta = node.metaUi,
Simon Huntac9e24f2014-11-12 10:12:21 -0800775 x = meta && meta.x,
776 y = meta && meta.y,
777 xy;
Simon Hunt99c13842014-11-06 18:23:12 -0800778
Simon Huntac9e24f2014-11-12 10:12:21 -0800779 // If we have [x,y] already, use that...
Simon Hunt99c13842014-11-06 18:23:12 -0800780 if (x && y) {
781 node.fixed = true;
Simon Huntac9e24f2014-11-12 10:12:21 -0800782 node.x = x;
783 node.y = y;
784 return;
Simon Hunt99c13842014-11-06 18:23:12 -0800785 }
Simon Huntac9e24f2014-11-12 10:12:21 -0800786
Paul Greyson6cb8ca02014-11-12 18:09:02 -0800787 var location = node.location;
788 if (location && location.type === 'latlng') {
789 var coord = geoMapProjection([location.lng, location.lat]);
790 node.fixed = true;
791 node.x = coord[0];
792 node.y = coord[1];
793 return;
794 }
795
Simon Huntac9e24f2014-11-12 10:12:21 -0800796 // Note: Placing incoming unpinned nodes at exactly the same point
797 // (center of the view) causes them to explode outwards when
798 // the force layout kicks in. So, we spread them out a bit
799 // initially, to provide a more serene layout convergence.
800 // Additionally, if the node is a host, we place it near
801 // the device it is connected to.
802
803 function spread(s) {
804 return Math.floor((Math.random() * s) - s/2);
805 }
806
807 function randDim(dim) {
808 return dim / 2 + spread(dim * 0.7071);
809 }
810
811 function rand() {
812 return {
813 x: randDim(network.view.width()),
814 y: randDim(network.view.height())
815 };
816 }
817
818 function near(node) {
819 var min = 12,
820 dx = spread(12),
821 dy = spread(12);
822 return {
823 x: node.x + min + dx,
824 y: node.y + min + dy
825 };
826 }
827
828 function getDevice(cp) {
829 var d = network.lookup[cp.device];
830 return d || rand();
831 }
832
833 xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
834 $.extend(node, xy);
Simon Hunt99c13842014-11-06 18:23:12 -0800835 }
836
Simon Hunt99c13842014-11-06 18:23:12 -0800837 function iconUrl(d) {
838 return 'img/' + d.type + '.png';
839 }
840
841 // returns the newly computed bounding box of the rectangle
842 function adjustRectToFitText(n) {
843 var text = n.select('text'),
844 box = text.node().getBBox(),
845 lab = config.labels;
846
847 text.attr('text-anchor', 'middle')
848 .attr('y', '-0.8em')
849 .attr('x', lab.imgPad/2);
850
851 // translate the bbox so that it is centered on [x,y]
852 box.x = -box.width / 2;
853 box.y = -box.height / 2;
854
855 // add padding
856 box.x -= (lab.padLR + lab.imgPad/2);
857 box.width += lab.padLR * 2 + lab.imgPad;
858 box.y -= lab.padTB;
859 box.height += lab.padTB * 2;
860
861 return box;
862 }
863
Simon Hunt1a9eff92014-11-07 11:06:34 -0800864 function mkSvgClass(d) {
865 return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
866 }
867
Simon Hunt7cd48f32014-11-09 23:42:50 -0800868 function hostLabel(d) {
869 var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
870 return d.labels[idx];
871 }
872 function deviceLabel(d) {
873 var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
874 return d.labels[idx];
875 }
876 function niceLabel(label) {
877 return (label && label.trim()) ? label : '.';
878 }
879
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800880 function updateDeviceLabel(d) {
881 var label = niceLabel(deviceLabel(d)),
882 node = d.el,
883 box;
884
885 node.select('text')
886 .text(label)
887 .style('opacity', 0)
888 .transition()
889 .style('opacity', 1);
890
891 box = adjustRectToFitText(node);
892
893 node.select('rect')
894 .transition()
895 .attr(box);
896
897 node.select('image')
898 .transition()
899 .attr('x', box.x + config.icons.xoff)
900 .attr('y', box.y + config.icons.yoff);
901 }
902
903 function updateHostLabel(d) {
904 var label = hostLabel(d),
905 host = d.el;
906
907 host.select('text').text(label);
908 }
909
Simon Huntbb282f52014-11-10 11:08:19 -0800910 function updateDeviceState(nodeData) {
911 nodeData.el.classed('online', nodeData.online);
912 updateDeviceLabel(nodeData);
913 // TODO: review what else might need to be updated
914 }
915
Simon Hunt3f03d4a2014-11-10 20:14:37 -0800916 function updateLinkState(linkData) {
917 updateLinkWidth(linkData);
918 // TODO: review what else might need to be updated
919 // update label, if showing
920 }
921
Simon Huntbb282f52014-11-10 11:08:19 -0800922 function updateHostState(hostData) {
923 updateHostLabel(hostData);
924 // TODO: review what else might need to be updated
925 }
926
927
Simon Hunt99c13842014-11-06 18:23:12 -0800928 function updateNodes() {
929 node = nodeG.selectAll('.node')
930 .data(network.nodes, function (d) { return d.id; });
931
932 // operate on existing nodes, if necessary
Simon Hunt7cd48f32014-11-09 23:42:50 -0800933 // update host labels
Simon Hunt99c13842014-11-06 18:23:12 -0800934 //node .foo() .bar() ...
935
936 // operate on entering nodes:
937 var entering = node.enter()
938 .append('g')
939 .attr({
940 id: function (d) { return safeId(d.id); },
Simon Hunt1a9eff92014-11-07 11:06:34 -0800941 class: mkSvgClass,
Simon Hunt99c13842014-11-06 18:23:12 -0800942 transform: function (d) { return translate(d.x, d.y); },
943 opacity: 0
944 })
Simon Hunt1a9eff92014-11-07 11:06:34 -0800945 .call(network.drag)
Simon Hunt99c13842014-11-06 18:23:12 -0800946 //.on('mouseover', function (d) {})
947 //.on('mouseover', function (d) {})
948 .transition()
949 .attr('opacity', 1);
950
951 // augment device nodes...
952 entering.filter('.device').each(function (d) {
953 var node = d3.select(this),
954 icon = iconUrl(d),
Simon Hunt7cd48f32014-11-09 23:42:50 -0800955 label = niceLabel(deviceLabel(d)),
Simon Hunt99c13842014-11-06 18:23:12 -0800956 box;
957
Simon Hunt7cd48f32014-11-09 23:42:50 -0800958 // provide ref to element from backing data....
959 d.el = node;
960
Simon Hunt99c13842014-11-06 18:23:12 -0800961 node.append('rect')
962 .attr({
963 'rx': 5,
964 'ry': 5
965 });
966
967 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -0800968 .text(label)
Simon Hunt99c13842014-11-06 18:23:12 -0800969 .attr('dy', '1.1em');
970
971 box = adjustRectToFitText(node);
972
973 node.select('rect')
974 .attr(box);
975
976 if (icon) {
977 var cfg = config.icons;
978 node.append('svg:image')
979 .attr({
980 x: box.x + config.icons.xoff,
981 y: box.y + config.icons.yoff,
982 width: cfg.w,
983 height: cfg.h,
984 'xlink:href': icon
985 });
986 }
987
988 // debug function to show the modelled x,y coordinates of nodes...
989 if (debug('showNodeXY')) {
990 node.select('rect').attr('fill-opacity', 0.5);
991 node.append('circle')
992 .attr({
993 class: 'debug',
994 cx: 0,
995 cy: 0,
996 r: '3px'
997 });
Simon Huntc7ee0662014-11-05 16:44:37 -0800998 }
999 });
Simon Hunt934c3ce2014-11-05 11:45:07 -08001000
Simon Hunt56d51852014-11-09 13:03:35 -08001001 // augment host nodes...
1002 entering.filter('.host').each(function (d) {
1003 var node = d3.select(this),
Simon Hunt56d51852014-11-09 13:03:35 -08001004 box;
1005
Simon Hunt7cd48f32014-11-09 23:42:50 -08001006 // provide ref to element from backing data....
1007 d.el = node;
1008
Simon Hunt56d51852014-11-09 13:03:35 -08001009 node.append('circle')
1010 .attr('r', 8); // TODO: define host circle radius
1011
1012 // TODO: are we attaching labels to hosts?
1013 node.append('text')
Simon Hunt7cd48f32014-11-09 23:42:50 -08001014 .text(hostLabel)
1015 .attr('dy', '1.3em')
1016 .attr('text-anchor', 'middle');
Simon Hunt56d51852014-11-09 13:03:35 -08001017
1018 // debug function to show the modelled x,y coordinates of nodes...
1019 if (debug('showNodeXY')) {
1020 node.select('circle').attr('fill-opacity', 0.5);
1021 node.append('circle')
1022 .attr({
1023 class: 'debug',
1024 cx: 0,
1025 cy: 0,
1026 r: '3px'
1027 });
1028 }
1029 });
Simon Huntc7ee0662014-11-05 16:44:37 -08001030
Simon Hunt99c13842014-11-06 18:23:12 -08001031 // operate on both existing and new nodes, if necessary
1032 //node .foo() .bar() ...
Simon Huntc7ee0662014-11-05 16:44:37 -08001033
Simon Hunt99c13842014-11-06 18:23:12 -08001034 // operate on exiting nodes:
Simon Huntea80eb42014-11-11 13:46:57 -08001035 // Note that the node is removed after 2 seconds.
1036 // Sub element animations should be shorter than 2 seconds.
1037 var exiting = node.exit()
Simon Hunt44031102014-11-11 13:20:36 -08001038 .transition()
1039 .duration(2000)
Simon Huntea80eb42014-11-11 13:46:57 -08001040 .style('opacity', 0)
Simon Hunt99c13842014-11-06 18:23:12 -08001041 .remove();
Simon Huntea80eb42014-11-11 13:46:57 -08001042
1043 // host node exits....
1044 exiting.filter('.host').each(function (d) {
1045 var node = d3.select(this);
1046
1047 node.select('text')
1048 .style('opacity', 0.5)
1049 .transition()
1050 .duration(1000)
1051 .style('opacity', 0);
1052 // note, leave <g>.remove to remove this element
1053
1054 node.select('circle')
1055 .style('stroke-fill', '#555')
1056 .style('fill', '#888')
1057 .style('opacity', 0.5)
1058 .transition()
1059 .duration(1500)
1060 .attr('r', 0);
1061 // note, leave <g>.remove to remove this element
1062
1063 });
1064
1065 // TODO: device node exits
Simon Huntc7ee0662014-11-05 16:44:37 -08001066 }
1067
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001068 function find(id, array) {
1069 for (var idx = 0, n = array.length; idx < n; idx++) {
1070 if (array[idx].id === id) {
1071 return idx;
1072 }
1073 }
1074 return -1;
1075 }
1076
1077 function removeLinkElement(linkData) {
1078 // remove from lookup cache
1079 delete network.lookup[linkData.id];
1080 // remove from links array
1081 var idx = find(linkData.id, network.links);
Simon Huntfc274c92014-11-11 11:05:46 -08001082 network.links.splice(idx, 1);
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001083 // remove from SVG
1084 updateLinks();
Simon Hunt44031102014-11-11 13:20:36 -08001085 network.force.resume();
Simon Hunt3f03d4a2014-11-10 20:14:37 -08001086 }
Simon Huntc7ee0662014-11-05 16:44:37 -08001087
Simon Hunt44031102014-11-11 13:20:36 -08001088 function removeHostElement(hostData) {
1089 // first, remove associated hostLink...
1090 removeLinkElement(hostData.linkData);
1091
1092 // remove from lookup cache
1093 delete network.lookup[hostData.id];
1094 // remove from nodes array
1095 var idx = find(hostData.id, network.nodes);
1096 network.nodes.splice(idx, 1);
1097 // remove from SVG
1098 updateNodes();
1099 network.force.resume();
1100 }
1101
1102
Simon Huntc7ee0662014-11-05 16:44:37 -08001103 function tick() {
1104 node.attr({
Simon Hunt99c13842014-11-06 18:23:12 -08001105 transform: function (d) { return translate(d.x, d.y); }
Simon Huntc7ee0662014-11-05 16:44:37 -08001106 });
1107
1108 link.attr({
1109 x1: function (d) { return d.source.x; },
1110 y1: function (d) { return d.source.y; },
1111 x2: function (d) { return d.target.x; },
1112 y2: function (d) { return d.target.y; }
1113 });
1114 }
Simon Hunt934c3ce2014-11-05 11:45:07 -08001115
1116 // ==============================
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001117 // Web-Socket for live data
1118
1119 function webSockUrl() {
1120 return document.location.toString()
1121 .replace(/\#.*/, '')
1122 .replace('http://', 'ws://')
1123 .replace('https://', 'wss://')
1124 .replace('index2.html', config.webSockUrl);
1125 }
1126
1127 webSock = {
1128 ws : null,
1129
1130 connect : function() {
1131 webSock.ws = new WebSocket(webSockUrl());
1132
1133 webSock.ws.onopen = function() {
Simon Hunt0c6d4192014-11-12 12:07:10 -08001134 noWebSock(false);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001135 };
1136
1137 webSock.ws.onmessage = function(m) {
1138 if (m.data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001139 wsTraceRx(m.data);
Thomas Vachuskad472c6e2014-11-07 19:11:05 -08001140 handleServerEvent(JSON.parse(m.data));
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001141 }
1142 };
1143
1144 webSock.ws.onclose = function(m) {
1145 webSock.ws = null;
Simon Hunt0c6d4192014-11-12 12:07:10 -08001146 noWebSock(true);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001147 };
1148 },
1149
1150 send : function(text) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001151 if (text != null) {
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001152 webSock._send(text);
1153 }
1154 },
1155
1156 _send : function(message) {
1157 if (webSock.ws) {
1158 webSock.ws.send(message);
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001159 } else {
Simon Hunt56d51852014-11-09 13:03:35 -08001160 network.view.alert('no web socket open\n\n' + message);
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001161 }
1162 }
1163
1164 };
1165
Simon Hunt0c6d4192014-11-12 12:07:10 -08001166 function noWebSock(b) {
1167 mask.style('display',b ? 'block' : 'none');
1168 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001169
Simon Hunt61d04042014-11-11 17:27:16 -08001170 // TODO: use cache of pending messages (key = sid) to reconcile responses
1171
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001172 function sendMessage(evType, payload) {
1173 var toSend = {
Simon Huntbb282f52014-11-10 11:08:19 -08001174 event: evType,
1175 sid: ++sid,
1176 payload: payload
1177 },
1178 asText = JSON.stringify(toSend);
1179 wsTraceTx(asText);
1180 webSock.send(asText);
1181 }
1182
1183 function wsTraceTx(msg) {
1184 wsTrace('tx', msg);
1185 }
1186 function wsTraceRx(msg) {
1187 wsTrace('rx', msg);
1188 }
1189 function wsTrace(rxtx, msg) {
Simon Huntbb282f52014-11-10 11:08:19 -08001190 console.log('[' + rxtx + '] ' + msg);
1191 // TODO: integrate with trace view
1192 //if (trace) {
1193 // trace.output(rxtx, msg);
1194 //}
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001195 }
1196
1197
1198 // ==============================
1199 // Selection stuff
1200
1201 function selectObject(obj, el) {
1202 var n,
1203 meta = d3.event.sourceEvent.metaKey;
1204
1205 if (el) {
1206 n = d3.select(el);
1207 } else {
1208 node.each(function(d) {
1209 if (d == obj) {
1210 n = d3.select(el = this);
1211 }
1212 });
1213 }
1214 if (!n) return;
1215
1216 if (meta && n.classed('selected')) {
1217 deselectObject(obj.id);
Simon Hunt61d04042014-11-11 17:27:16 -08001218 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001219 return;
1220 }
1221
1222 if (!meta) {
1223 deselectAll();
1224 }
1225
Simon Huntc31d5692014-11-12 13:27:18 -08001226 selections[obj.id] = { obj: obj, el: el };
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001227 selectOrder.push(obj.id);
1228
1229 n.classed('selected', true);
Simon Hunt61d04042014-11-11 17:27:16 -08001230 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001231 }
1232
1233 function deselectObject(id) {
Simon Huntc31d5692014-11-12 13:27:18 -08001234 var obj = selections[id],
1235 idx;
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001236 if (obj) {
1237 d3.select(obj.el).classed('selected', false);
Simon Hunt61d04042014-11-11 17:27:16 -08001238 delete selections[id];
Simon Huntc31d5692014-11-12 13:27:18 -08001239 idx = $.inArray(id, selectOrder);
1240 if (idx >= 0) {
1241 selectOrder.splice(idx, 1);
1242 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001243 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001244 }
1245
1246 function deselectAll() {
1247 // deselect all nodes in the network...
1248 node.classed('selected', false);
1249 selections = {};
1250 selectOrder = [];
Simon Hunt61d04042014-11-11 17:27:16 -08001251 updateDetailPane();
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001252 }
1253
Simon Hunt61d04042014-11-11 17:27:16 -08001254 // FIXME: this click handler does not get unloaded when the view does
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001255 $('#view').on('click', function(e) {
1256 if (!$(e.target).closest('.node').length) {
1257 if (!e.metaKey) {
1258 deselectAll();
1259 }
1260 }
1261 });
1262
Simon Hunt61d04042014-11-11 17:27:16 -08001263 // update the state of the detail pane, based on current selections
1264 function updateDetailPane() {
1265 var nSel = selectOrder.length;
1266 if (!nSel) {
1267 detailPane.hide();
1268 } else if (nSel === 1) {
1269 singleSelect();
1270 } else {
1271 multiSelect();
1272 }
1273 }
1274
1275 function singleSelect() {
1276 requestDetails();
Simon Huntb53e0682014-11-12 13:32:01 -08001277 // NOTE: detail pane will be shown from showDetails event callback
Simon Hunt61d04042014-11-11 17:27:16 -08001278 }
1279
1280 function multiSelect() {
Simon Huntb53e0682014-11-12 13:32:01 -08001281 populateMultiSelect();
1282 // TODO: Add multi-select actions ...
1283 }
1284
1285 function addSep(tbody) {
1286 var tr = tbody.append('tr');
1287 $('<hr>').appendTo(tr.append('td').attr('colspan', 2));
1288 }
1289
1290 function addProp(tbody, label, value) {
1291 var tr = tbody.append('tr');
1292
1293 tr.append('td')
1294 .attr('class', 'label')
1295 .text(label + ' :');
1296
1297 tr.append('td')
1298 .attr('class', 'value')
1299 .text(value);
1300 }
1301
1302 function populateMultiSelect() {
1303 detailPane.empty();
1304
1305 var title = detailPane.append("h2"),
1306 table = detailPane.append("table"),
1307 tbody = table.append("tbody");
1308
1309 title.text('Multi-Select...');
1310
1311 selectOrder.forEach(function (d, i) {
1312 addProp(tbody, i+1, d);
1313 });
Simon Hunt61d04042014-11-11 17:27:16 -08001314 }
1315
1316 function populateDetails(data) {
1317 detailPane.empty();
1318
1319 var title = detailPane.append("h2"),
1320 table = detailPane.append("table"),
1321 tbody = table.append("tbody");
1322
1323 $('<img src="img/' + data.type + '.png">').appendTo(title);
1324 $('<span>').attr('class', 'icon').text(data.id).appendTo(title);
1325
1326 data.propOrder.forEach(function(p) {
1327 if (p === '-') {
1328 addSep(tbody);
1329 } else {
1330 addProp(tbody, p, data.props[p]);
1331 }
1332 });
Simon Hunt61d04042014-11-11 17:27:16 -08001333 }
1334
1335 // ==============================
1336 // Test harness code
Simon Hunt56d51852014-11-09 13:03:35 -08001337
1338 function prepareScenario(view, ctx, dbg) {
1339 var sc = scenario,
1340 urlSc = sc.evDir + ctx + sc.evScenario;
1341
1342 if (!ctx) {
1343 view.alert("No scenario specified (null ctx)");
1344 return;
1345 }
1346
1347 sc.view = view;
1348 sc.ctx = ctx;
1349 sc.debug = dbg;
1350 sc.evNumber = 0;
1351
1352 d3.json(urlSc, function(err, data) {
Simon Huntbb282f52014-11-10 11:08:19 -08001353 var p = data && data.params || {},
1354 desc = data && data.description || null,
Simon Huntfc274c92014-11-11 11:05:46 -08001355 intro = data && data.title;
Simon Huntbb282f52014-11-10 11:08:19 -08001356
Simon Hunt56d51852014-11-09 13:03:35 -08001357 if (err) {
1358 view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
1359 } else {
1360 sc.params = p;
Simon Huntbb282f52014-11-10 11:08:19 -08001361 if (desc) {
1362 intro += '\n\n ' + desc.join('\n ');
1363 }
1364 view.alert(intro);
Simon Hunt56d51852014-11-09 13:03:35 -08001365 }
1366 });
1367
1368 }
1369
Simon Hunt0c6d4192014-11-12 12:07:10 -08001370
1371 function para(sel, text) {
1372 sel.append('p').text(text);
1373 }
1374
Thomas Vachuska7d638d32014-11-07 10:24:43 -08001375 // ==============================
Simon Hunt142d0032014-11-04 20:13:09 -08001376 // View life-cycle callbacks
Simon Hunt195cb382014-11-03 17:50:51 -08001377
Simon Huntf67722a2014-11-10 09:32:06 -08001378 function preload(view, ctx, flags) {
Simon Hunt142d0032014-11-04 20:13:09 -08001379 var w = view.width(),
1380 h = view.height(),
Simon Huntc7ee0662014-11-05 16:44:37 -08001381 fcfg = config.force,
1382 fpad = fcfg.pad,
1383 forceDim = [w - 2*fpad, h - 2*fpad];
Simon Hunt195cb382014-11-03 17:50:51 -08001384
Simon Huntbb282f52014-11-10 11:08:19 -08001385 // TODO: set trace api
1386 //trace = onos.exported.webSockTrace;
1387
Simon Hunt142d0032014-11-04 20:13:09 -08001388 // NOTE: view.$div is a D3 selection of the view's div
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001389 var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
1390 svg = view.$div.append('svg').attr('viewBox', viewBox);
Simon Hunt934c3ce2014-11-05 11:45:07 -08001391 setSize(svg, view);
1392
Simon Hunt1a9eff92014-11-07 11:06:34 -08001393 // add blue glow filter to svg layer
1394 d3u.appendGlow(svg);
1395
Simon Huntc7ee0662014-11-05 16:44:37 -08001396 // group for the topology
1397 topoG = svg.append('g')
Simon Huntd3b7d512014-11-12 15:48:41 -08001398 .attr('id', 'topo-G')
Simon Huntc7ee0662014-11-05 16:44:37 -08001399 .attr('transform', fcfg.translate());
1400
1401 // subgroups for links and nodes
1402 linkG = topoG.append('g').attr('id', 'links');
1403 nodeG = topoG.append('g').attr('id', 'nodes');
1404
1405 // selection of nodes and links
1406 link = linkG.selectAll('.link');
1407 node = nodeG.selectAll('.node');
1408
Simon Hunt7cd48f32014-11-09 23:42:50 -08001409 function chrg(d) {
1410 return fcfg.charge[d.class] || -12000;
1411 }
Simon Hunt99c13842014-11-06 18:23:12 -08001412 function ldist(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001413 return fcfg.linkDistance[d.type] || 50;
Simon Hunt99c13842014-11-06 18:23:12 -08001414 }
1415 function lstrg(d) {
Simon Hunt7cd48f32014-11-09 23:42:50 -08001416 // 0.0 - 1.0
1417 return fcfg.linkStrength[d.type] || 1.0;
Simon Hunt99c13842014-11-06 18:23:12 -08001418 }
1419
Simon Hunt1a9eff92014-11-07 11:06:34 -08001420 function selectCb(d, self) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001421 selectObject(d, self);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001422 }
1423
1424 function atDragEnd(d, self) {
Simon Hunt56d51852014-11-09 13:03:35 -08001425 // once we've finished moving, pin the node in position
1426 d.fixed = true;
1427 d3.select(self).classed('fixed', true);
1428 if (config.useLiveData) {
Simon Hunt902c9922014-11-11 11:59:31 -08001429 sendUpdateMeta(d);
Simon Hunt1a9eff92014-11-07 11:06:34 -08001430 }
1431 }
1432
Simon Hunt902c9922014-11-11 11:59:31 -08001433 function sendUpdateMeta(d) {
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001434 sendMessage('updateMeta', {
1435 id: d.id,
1436 'class': d.class,
Simon Hunt902c9922014-11-11 11:59:31 -08001437 'memento': {
1438 x: Math.floor(d.x),
1439 y: Math.floor(d.y)
1440 }
Thomas Vachuskad1be50d2014-11-08 16:10:20 -08001441 });
1442 }
1443
Simon Huntc7ee0662014-11-05 16:44:37 -08001444 // set up the force layout
1445 network.force = d3.layout.force()
1446 .size(forceDim)
1447 .nodes(network.nodes)
1448 .links(network.links)
Simon Hunt7cd48f32014-11-09 23:42:50 -08001449 .gravity(0.4)
1450 .friction(0.7)
1451 .charge(chrg)
Simon Hunt99c13842014-11-06 18:23:12 -08001452 .linkDistance(ldist)
1453 .linkStrength(lstrg)
Simon Huntc7ee0662014-11-05 16:44:37 -08001454 .on('tick', tick);
Simon Hunt195cb382014-11-03 17:50:51 -08001455
Simon Hunt1a9eff92014-11-07 11:06:34 -08001456 network.drag = d3u.createDragBehavior(network.force, selectCb, atDragEnd);
Simon Hunt0c6d4192014-11-12 12:07:10 -08001457
1458 // create mask layer for when we lose connection to server.
1459 mask = view.$div.append('div').attr('id','topo-mask');
1460 para(mask, 'Oops!');
1461 para(mask, 'Web-socket connection to server closed...');
1462 para(mask, 'Try refreshing the page.');
Simon Hunt1a9eff92014-11-07 11:06:34 -08001463 }
Simon Hunt195cb382014-11-03 17:50:51 -08001464
Simon Hunt56d51852014-11-09 13:03:35 -08001465 function load(view, ctx, flags) {
Simon Huntf67722a2014-11-10 09:32:06 -08001466 // resize, in case the window was resized while we were not loaded
1467 resize(view, ctx, flags);
1468
Simon Hunt99c13842014-11-06 18:23:12 -08001469 // cache the view token, so network topo functions can access it
1470 network.view = view;
Simon Hunt56d51852014-11-09 13:03:35 -08001471 config.useLiveData = !flags.local;
1472
1473 if (!config.useLiveData) {
1474 prepareScenario(view, ctx, flags.debug);
1475 }
Simon Hunt99c13842014-11-06 18:23:12 -08001476
1477 // set our radio buttons and key bindings
Simon Hunt934c3ce2014-11-05 11:45:07 -08001478 view.setRadio(btnSet);
1479 view.setKeys(keyDispatch);
Simon Hunt195cb382014-11-03 17:50:51 -08001480
Simon Huntd3b7d512014-11-12 15:48:41 -08001481 // Load map data asynchronously; complete startup after that..
1482 loadGeoJsonData();
1483 }
1484
1485 // TODO: move these to config/state portion of script
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001486 var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
Simon Huntd3b7d512014-11-12 15:48:41 -08001487 geoJson;
1488
1489 function loadGeoJsonData() {
1490 d3.json(geoJsonUrl, function (err, data) {
1491 if (err) {
1492 // fall back to USA map background
1493 loadStaticMap();
1494 } else {
1495 geoJson = data;
1496 loadGeoMap();
1497 }
1498
1499 // finally, connect to the server...
1500 if (config.useLiveData) {
1501 webSock.connect();
1502 }
1503 });
1504 }
1505
1506 function showBg() {
1507 return config.options.showBackground ? 'visible' : 'hidden';
1508 }
1509
1510 function loadStaticMap() {
1511 fnTrace('loadStaticMap', config.backgroundUrl);
1512 var w = network.view.width(),
1513 h = network.view.height();
1514
1515 // load the background image
1516 bgImg = svg.insert('svg:image', '#topo-G')
1517 .attr({
1518 id: 'topo-bg',
1519 width: w,
1520 height: h,
1521 'xlink:href': config.backgroundUrl
1522 })
1523 .style({
1524 visibility: showBg()
1525 });
1526 }
1527
1528 function loadGeoMap() {
1529 fnTrace('loadGeoMap', geoJsonUrl);
Simon Huntd3b7d512014-11-12 15:48:41 -08001530
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001531 // extracts the topojson data into geocoordinate-based geometry
1532 var topoData = topojson.feature(geoJson, geoJson.objects.states);
Simon Huntd3b7d512014-11-12 15:48:41 -08001533
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001534 // see: http://bl.ocks.org/mbostock/4707858
1535 geoMapProjection = d3.geo.mercator();
1536 var path = d3.geo.path().projection(geoMapProjection);
Simon Huntd3b7d512014-11-12 15:48:41 -08001537
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001538 geoMapProjection
1539 .scale(1)
1540 .translate([0, 0]);
Simon Huntd3b7d512014-11-12 15:48:41 -08001541
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001542 // [[x1,y1],[x2,y2]]
1543 var b = path.bounds(topoData);
1544 // TODO: why 1.75?
1545 var s = 1.75 / Math.max((b[1][0] - b[0][0]) / config.logicalSize, (b[1][1] - b[0][1]) / config.logicalSize);
1546 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 -08001547
Paul Greyson6cb8ca02014-11-12 18:09:02 -08001548 geoMapProjection
1549 .scale(s)
1550 .translate(t);
1551
1552 bgImg = svg.insert("g", '#topo-G');
1553 bgImg.attr('id', 'map').selectAll('path')
1554 .data(topoData.features)
1555 .enter()
1556 .append('path')
1557 .attr('d', path);
Simon Hunt195cb382014-11-03 17:50:51 -08001558 }
1559
Simon Huntf67722a2014-11-10 09:32:06 -08001560 function resize(view, ctx, flags) {
Simon Hunt934c3ce2014-11-05 11:45:07 -08001561 setSize(svg, view);
Simon Hunt99c13842014-11-06 18:23:12 -08001562
1563 // TODO: hook to recompute layout, perhaps? work with zoom/pan code
1564 // adjust force layout size
Simon Hunt142d0032014-11-04 20:13:09 -08001565 }
1566
1567
1568 // ==============================
1569 // View registration
Simon Hunt195cb382014-11-03 17:50:51 -08001570
Simon Hunt25248912014-11-04 11:25:48 -08001571 onos.ui.addView('topo', {
Simon Hunt142d0032014-11-04 20:13:09 -08001572 preload: preload,
1573 load: load,
1574 resize: resize
Simon Hunt195cb382014-11-03 17:50:51 -08001575 });
1576
Simon Hunt61d04042014-11-11 17:27:16 -08001577 detailPane = onos.ui.addFloatingPanel('topo-detail');
1578
Simon Hunt195cb382014-11-03 17:50:51 -08001579}(ONOS));