topo2.js
63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
/*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
ONOS network topology viewer - version 1.1
@author Simon Hunt
*/
(function (onos) {
'use strict';
// shorter names for library APIs
var d3u = onos.lib.d3util,
gly = onos.lib.glyphs,
trace;
// configuration data
var config = {
useLiveData: true,
fnTrace: true,
debugOn: false,
debug: {
showNodeXY: true,
showKeyHandler: false
},
birdDim: 400,
options: {
layering: true,
collisionPrevention: true,
showBackground: true
},
backgroundUrl: 'img/us-map.png',
webSockUrl: 'ws/topology',
data: {
live: {
jsonUrl: 'rs/topology/graph',
detailPrefix: 'rs/topology/graph/',
detailSuffix: ''
},
fake: {
jsonUrl: 'json/network2.json',
detailPrefix: 'json/',
detailSuffix: '.json'
}
},
labels: {
imgPad: 16,
padLR: 4,
padTB: 3,
marginLR: 3,
marginTB: 2,
port: {
gap: 3,
width: 18,
height: 14
}
},
topo: {
linkBaseColor: '#666',
linkInColor: '#66f',
linkInWidth: 14,
linkOutColor: '#f00',
linkOutWidth: 30
},
icons: {
w: 30,
h: 30,
xoff: -16,
yoff: -14
},
iconUrl: {
device: 'img/device.png',
host: 'img/host.png',
pkt: 'img/pkt.png',
opt: 'img/opt.png'
},
force: {
note_for_links: 'link.type is used to differentiate',
linkDistance: {
direct: 100,
optical: 120,
hostLink: 3
},
linkStrength: {
direct: 1.0,
optical: 1.0,
hostLink: 1.0
},
note_for_nodes: 'node.class is used to differentiate',
charge: {
device: -8000,
host: -5000
},
pad: 20,
translate: function() {
return 'translate(' +
config.force.pad + ',' +
config.force.pad + ')';
}
},
// see below in creation of viewBox on main svg
logicalSize: 1000
};
// radio buttons
var layerButtons = [
{ text: 'All Layers', id: 'all', cb: showAllLayers },
{ text: 'Packet Only', id: 'pkt', cb: showPacketLayer },
{ text: 'Optical Only', id: 'opt', cb: showOpticalLayer }
],
layerBtnSet,
layerBtnDispatch = {
all: showAllLayers,
pkt: showPacketLayer,
opt: showOpticalLayer
};
// key bindings
var keyDispatch = {
M: testMe, // TODO: remove (testing only)
S: injectStartupEvents, // TODO: remove (testing only)
space: injectTestEvent, // TODO: remove (testing only)
B: toggleBg,
L: cycleLabels,
P: togglePorts,
U: unpin,
R: resetZoomPan,
H: toggleHover,
esc: handleEscape
};
// state variables
var network = {
view: null, // view token reference
nodes: [],
links: [],
lookup: {},
revLinkToKey: {}
},
scenario = {
evDir: 'json/ev/',
evScenario: '/scenario.json',
evPrefix: '/ev_',
evOnos: '_onos.json',
evUi: '_ui.json',
ctx: null,
params: {},
evNumber: 0,
view: null,
debug: false
},
webSock,
sid = 0,
deviceLabelIndex = 0,
hostLabelIndex = 0,
selections = {},
selectOrder = [],
hovered = null,
detailPane,
antTimer = null,
onosInstances = {},
onosOrder = [],
oiBox,
oiShowMaster = false,
hoverEnabled = false,
portLabelsOn = false;
// D3 selections
var svg,
zoomPanContainer,
bgImg,
topoG,
nodeG,
linkG,
linkLabelG,
node,
link,
linkLabel,
mask;
// the projection for the map background
var geoMapProjection;
// the zoom function
var zoom;
// ==============================
// For Debugging / Development
function note(label, msg) {
console.log('NOTE: ' + label + ': ' + msg);
}
function debug(what) {
return config.debugOn && config.debug[what];
}
function fnTrace(msg, id) {
if (config.fnTrace) {
console.log('FN: ' + msg + ' [' + id + ']');
}
}
function evTrace(data) {
fnTrace(data.event, data.payload.id);
}
// ==============================
// Key Callbacks
function testMe(view) {
view.alert('Theme is ' + view.theme());
}
function abortIfLive() {
if (config.useLiveData) {
network.view.alert("Sorry, currently using live data..");
return true;
}
return false;
}
function testDebug(msg) {
if (scenario.debug) {
scenario.view.alert(msg);
}
}
function injectTestEvent(view) {
if (abortIfLive()) { return; }
var sc = scenario,
evn = ++sc.evNumber,
pfx = sc.evDir + sc.ctx + sc.evPrefix + evn,
onosUrl = pfx + sc.evOnos,
uiUrl = pfx + sc.evUi,
stack = [
{ url: onosUrl, cb: handleServerEvent },
{ url: uiUrl, cb: handleUiEvent }
];
recurseFetchEvent(stack, evn);
}
function recurseFetchEvent(stack, evn) {
var v = scenario.view,
frame;
if (stack.length === 0) {
v.alert('Oops!\n\nNo event #' + evn + ' found.');
return;
}
frame = stack.shift();
d3.json(frame.url, function (err, data) {
if (err) {
if (err.status === 404) {
// if we didn't find the data, try the next stack frame
recurseFetchEvent(stack, evn);
} else {
v.alert('non-404 error:\n\n' + frame.url + '\n\n' + err);
}
} else {
testDebug('loaded: ' + frame.url);
wsTrace('test', JSON.stringify(data));
frame.cb(data);
}
});
}
function handleUiEvent(data) {
scenario.view.alert('UI Tx: ' + data.event + '\n\n' +
JSON.stringify(data));
}
function injectStartupEvents(view) {
var last = scenario.params.lastAuto || 0;
if (abortIfLive()) { return; }
while (scenario.evNumber < last) {
injectTestEvent(view);
}
}
function toggleBg() {
var vis = bgImg.style('visibility');
bgImg.style('visibility', (vis === 'hidden') ? 'visible' : 'hidden');
}
function cycleLabels() {
deviceLabelIndex = (deviceLabelIndex === network.deviceLabelCount - 1)
? 0 : deviceLabelIndex + 1;
network.nodes.forEach(function (d) {
if (d.class === 'device') {
updateDeviceLabel(d);
}
});
}
function toggleHover(view) {
hoverEnabled = !hoverEnabled;
}
function togglePorts(view) {
view.alert('togglePorts() callback')
}
function unpin() {
if (hovered) {
hovered.fixed = false;
hovered.el.classed('fixed', false);
network.force.resume();
}
}
function handleEscape(view) {
if (oiShowMaster) {
cancelAffinity();
} else {
deselectAll();
}
}
// ==============================
// Radio Button Callbacks
var layerLookup = {
host: {
endstation: 'pkt', // default, if host event does not define type
router: 'pkt',
bgpSpeaker: 'pkt'
},
device: {
switch: 'pkt',
roadm: 'opt'
},
link: {
hostLink: 'pkt',
direct: 'pkt',
indirect: '',
tunnel: '',
optical: 'opt'
}
};
function inLayer(d, layer) {
var type = d.class === 'link' ? d.type() : d.type,
look = layerLookup[d.class],
lyr = look && look[type];
return lyr === layer;
}
function unsuppressLayer(which) {
node.each(function (d) {
var node = d.el;
if (inLayer(d, which)) {
node.classed('suppressed', false);
}
});
link.each(function (d) {
var link = d.el;
if (inLayer(d, which)) {
link.classed('suppressed', false);
}
});
}
function suppressLayers(b) {
node.classed('suppressed', b);
link.classed('suppressed', b);
// d3.selectAll('svg .port').classed('inactive', false);
// d3.selectAll('svg .portText').classed('inactive', false);
}
function showAllLayers() {
suppressLayers(false);
}
function showPacketLayer() {
node.classed('suppressed', true);
link.classed('suppressed', true);
unsuppressLayer('pkt');
}
function showOpticalLayer() {
node.classed('suppressed', true);
link.classed('suppressed', true);
unsuppressLayer('opt');
}
function restoreLayerState() {
layerBtnDispatch[layerBtnSet.selected()]();
}
// ==============================
// Private functions
function safeId(s) {
return s.replace(/[^a-z0-9]/gi, '-');
}
// set the size of the given element to that of the view (reduced if padded)
function setSize(el, view, pad) {
var padding = pad ? pad * 2 : 0;
el.attr({
width: view.width() - padding,
height: view.height() - padding
});
}
function makeNodeKey(d, what) {
var port = what + 'Port';
return d[what] + '/' + d[port];
}
function makeLinkKey(d, flipped) {
var one = flipped ? makeNodeKey(d, 'dst') : makeNodeKey(d, 'src'),
two = flipped ? makeNodeKey(d, 'src') : makeNodeKey(d, 'dst');
return one + '-' + two;
}
function findLinkById(id) {
// check to see if this is a reverse lookup, else default to given id
var key = network.revLinkToKey[id] || id;
return key && network.lookup[key];
}
function findLink(linkData, op) {
var key = makeLinkKey(linkData),
keyrev = makeLinkKey(linkData, 1),
link = network.lookup[key],
linkRev = network.lookup[keyrev],
result = {},
ldata = link || linkRev,
rawLink;
if (op === 'add') {
if (link) {
// trying to add a link that we already know about
result.ldata = link;
result.badLogic = 'addLink: link already added';
} else if (linkRev) {
// we found the reverse of the link to be added
result.ldata = linkRev;
if (linkRev.fromTarget) {
result.badLogic = 'addLink: link already added';
}
}
} else if (op === 'update') {
if (!ldata) {
result.badLogic = 'updateLink: link not found';
} else {
rawLink = link ? ldata.fromSource : ldata.fromTarget;
result.updateWith = function (data) {
$.extend(rawLink, data);
restyleLinkElement(ldata);
}
}
} else if (op === 'remove') {
if (!ldata) {
result.badLogic = 'removeLink: link not found';
} else {
rawLink = link ? ldata.fromSource : ldata.fromTarget;
if (!rawLink) {
result.badLogic = 'removeLink: link not found';
} else {
result.removeRawLink = function () {
if (link) {
// remove fromSource
ldata.fromSource = null;
if (ldata.fromTarget) {
// promote target into source position
ldata.fromSource = ldata.fromTarget;
ldata.fromTarget = null;
ldata.key = keyrev;
delete network.lookup[key];
network.lookup[keyrev] = ldata;
delete network.revLinkToKey[keyrev];
}
} else {
// remove fromTarget
ldata.fromTarget = null;
delete network.revLinkToKey[keyrev];
}
if (ldata.fromSource) {
restyleLinkElement(ldata);
} else {
removeLinkElement(ldata);
}
}
}
}
}
return result;
}
function addLinkUpdate(ldata, link) {
// add link event, but we already have the reverse link installed
ldata.fromTarget = link;
network.revLinkToKey[link.id] = ldata.key;
restyleLinkElement(ldata);
}
var allLinkTypes = 'direct indirect optical tunnel',
defaultLinkType = 'direct';
function restyleLinkElement(ldata) {
// this fn's job is to look at raw links and decide what svg classes
// need to be applied to the line element in the DOM
var el = ldata.el,
type = ldata.type(),
lw = ldata.linkWidth(),
online = ldata.online();
el.classed('link', true);
el.classed('inactive', !online);
el.classed(allLinkTypes, false);
if (type) {
el.classed(type, true);
}
el.transition()
.duration(1000)
.attr('stroke-width', linkScale(lw))
.attr('stroke', config.topo.linkBaseColor);
}
// ==============================
// Event handlers for server-pushed events
function logicError(msg) {
// TODO, report logic error to server, via websock, so it can be logged
//network.view.alert('Logic Error:\n\n' + msg);
console.warn(msg);
}
var eventDispatch = {
addInstance: addInstance,
addDevice: addDevice,
addLink: addLink,
addHost: addHost,
updateInstance: updateInstance,
updateDevice: updateDevice,
updateLink: updateLink,
updateHost: updateHost,
removeInstance: stillToImplement,
removeDevice: stillToImplement,
removeLink: removeLink,
removeHost: removeHost,
showDetails: showDetails,
showTraffic: showTraffic
};
function addInstance(data) {
evTrace(data);
var inst = data.payload,
id = inst.id;
if (onosInstances[id]) {
logicError('ONOS instance already added: ' + id);
return;
}
onosInstances[id] = inst;
onosOrder.push(inst);
updateInstances();
}
function addDevice(data) {
evTrace(data);
var device = data.payload,
nodeData = createDeviceNode(device);
network.nodes.push(nodeData);
network.lookup[nodeData.id] = nodeData;
updateNodes();
network.force.start();
}
function addLink(data) {
evTrace(data);
var link = data.payload,
result = findLink(link, 'add'),
bad = result.badLogic,
ldata = result.ldata;
if (bad) {
logicError(bad + ': ' + link.id);
return;
}
if (ldata) {
// we already have a backing store link for src/dst nodes
addLinkUpdate(ldata, link);
return;
}
// no backing store link yet
ldata = createLink(link);
if (ldata) {
network.links.push(ldata);
network.lookup[ldata.key] = ldata;
updateLinks();
network.force.start();
}
}
function addHost(data) {
evTrace(data);
var host = data.payload,
node = createHostNode(host),
lnk;
network.nodes.push(node);
network.lookup[host.id] = node;
updateNodes();
lnk = createHostLink(host);
if (lnk) {
node.linkData = lnk; // cache ref on its host
network.links.push(lnk);
network.lookup[host.ingress] = lnk;
network.lookup[host.egress] = lnk;
updateLinks();
}
network.force.start();
}
// TODO: fold updateX(...) methods into one base method; remove duplication
function updateInstance(data) {
evTrace(data);
var inst = data.payload,
id = inst.id,
instData = onosInstances[id];
if (instData) {
$.extend(instData, inst);
updateInstances();
} else {
logicError('updateInstance lookup fail. ID = "' + id + '"');
}
}
function updateDevice(data) {
evTrace(data);
var device = data.payload,
id = device.id,
nodeData = network.lookup[id];
if (nodeData) {
$.extend(nodeData, device);
updateDeviceState(nodeData);
} else {
logicError('updateDevice lookup fail. ID = "' + id + '"');
}
}
function updateLink(data) {
evTrace(data);
var link = data.payload,
result = findLink(link, 'update'),
bad = result.badLogic;
if (bad) {
logicError(bad + ': ' + link.id);
return;
}
result.updateWith(link);
}
function updateHost(data) {
evTrace(data);
var host = data.payload,
id = host.id,
hostData = network.lookup[id];
if (hostData) {
$.extend(hostData, host);
updateHostState(hostData);
} else {
logicError('updateHost lookup fail. ID = "' + id + '"');
}
}
// TODO: fold removeX(...) methods into base method - remove dup code
function removeLink(data) {
evTrace(data);
var link = data.payload,
result = findLink(link, 'remove'),
bad = result.badLogic;
if (bad) {
logicError(bad + ': ' + link.id);
return;
}
result.removeRawLink();
}
function removeHost(data) {
evTrace(data);
var host = data.payload,
id = host.id,
hostData = network.lookup[id];
if (hostData) {
removeHostElement(hostData);
} else {
logicError('removeHost lookup fail. ID = "' + id + '"');
}
}
function showDetails(data) {
evTrace(data);
populateDetails(data.payload);
detailPane.show();
}
function showTraffic(data) {
evTrace(data);
var paths = data.payload.paths;
// Revert any links hilighted previously.
link.classed('primary secondary animated optical', false);
// Remove all previous labels.
removeLinkLabels();
// Now hilight all links in the paths payload, and attach
// labels to them, if they are defined.
paths.forEach(function (p) {
var n = p.links.length,
i,
ldata;
for (i=0; i<n; i++) {
ldata = findLinkById(p.links[i]);
if (ldata) {
ldata.el.classed(p.class, true);
ldata.label = p.labels[i];
}
}
});
updateLinks();
}
// ...............................
function stillToImplement(data) {
var p = data.payload;
note(data.event, p.id);
network.view.alert('Not yet implemented: "' + data.event + '"');
}
function unknownEvent(data) {
network.view.alert('Unknown event type: "' + data.event + '"');
}
function handleServerEvent(data) {
var fn = eventDispatch[data.event] || unknownEvent;
fn(data);
}
// ==============================
// Out-going messages...
function userFeedback(msg) {
// for now, use the alert pane as is. Maybe different alert style in
// the future (centered on view; dismiss button?)
network.view.alert(msg);
}
function nSel() {
return selectOrder.length;
}
function getSel(idx) {
return selections[selectOrder[idx]];
}
function getSelId(idx) {
return getSel(idx).obj.id;
}
function allSelectionsClass(cls) {
for (var i=0, n=nSel(); i<n; i++) {
if (getSel(i).obj.class !== cls) {
return false;
}
}
return true;
}
// request details for the selected element
// invoked from selection of a single node.
function requestDetails() {
var data = getSel(0).obj,
payload = {
id: data.id,
class: data.class
};
sendMessage('requestDetails', payload);
}
function addIntentAction() {
sendMessage('addHostIntent', {
one: getSelId(0),
two: getSelId(1),
ids: [ getSelId(0), getSelId(1) ]
});
}
function showTrafficAction() {
// if nothing is hovered over, and nothing selected, send cancel request
if (!hovered && nSel() === 0) {
sendMessage('cancelTraffic', {});
return;
}
// NOTE: hover is only populated if "show traffic on hover" is
// toggled on, and the item hovered is a host...
var hoverId = (trafficHover() && hovered && hovered.class === 'host')
? hovered.id : '';
sendMessage('requestTraffic', {
ids: selectOrder,
hover: hoverId
});
}
// ==============================
// onos instance panel functions
function updateInstances() {
var onoses = oiBox.el.selectAll('.onosInst')
.data(onosOrder, function (d) { return d.id; });
// operate on existing onoses if necessary
onoses.classed('online', function (d) { return d.online; });
var entering = onoses.enter()
.append('div')
.attr('class', 'onosInst')
.classed('online', function (d) { return d.online; })
.on('click', clickInst);
entering.each(function (d, i) {
var el = d3.select(this),
img;
$('<img src="img/node.png">').appendTo(el);
img = el.select('img')
.attr({
width: 30
});
$('<div>').attr('class', 'onosTitle').text(d.id).appendTo(el);
// is the UI attached to this instance?
// TODO: need uiAttached boolean in instance data
//if (d.uiAttached) {
if (i === 0) {
$('<img src="img/ui.png">').attr('class','ui').appendTo(el);
}
});
// operate on existing + new onoses here
// the departed...
var exiting = onoses.exit()
.transition()
.style('opacity', 0)
.remove();
}
function clickInst(d) {
var el = d3.select(this),
aff = el.classed('affinity');
if (!aff) {
setAffinity(el, d);
} else {
cancelAffinity();
}
}
function setAffinity(el, d) {
d3.selectAll('.onosInst')
.classed('mastership', true)
.classed('affinity', false);
el.classed('affinity', true);
suppressLayers(true);
node.each(function (n) {
if (n.master === d.id) {
n.el.classed('suppressed', false);
}
});
oiShowMaster = true;
}
function cancelAffinity() {
d3.selectAll('.onosInst')
.classed('mastership affinity', false);
restoreLayerState();
oiShowMaster = false;
}
// ==============================
// force layout modification functions
function translate(x, y) {
return 'translate(' + x + ',' + y + ')';
}
function rotate(deg) {
return 'rotate(' + deg + ')';
}
function missMsg(what, id) {
return '\n[' + what + '] "' + id + '" missing ';
}
function linkEndPoints(srcId, dstId) {
var srcNode = network.lookup[srcId],
dstNode = network.lookup[dstId],
sMiss = !srcNode ? missMsg('src', srcId) : '',
dMiss = !dstNode ? missMsg('dst', dstId) : '';
if (sMiss || dMiss) {
logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
return null;
}
return {
source: srcNode,
target: dstNode,
x1: srcNode.x,
y1: srcNode.y,
x2: dstNode.x,
y2: dstNode.y
};
}
function createHostLink(host) {
var src = host.id,
dst = host.cp.device,
id = host.ingress,
lnk = linkEndPoints(src, dst);
if (!lnk) {
return null;
}
// Synthesize link ...
$.extend(lnk, {
key: id,
class: 'link',
type: function () { return 'hostLink'; },
// TODO: ideally, we should see if our edge switch is online...
online: function () { return true; },
linkWidth: function () { return 1; }
});
return lnk;
}
function createLink(link) {
var lnk = linkEndPoints(link.src, link.dst),
type = link.type;
if (!lnk) {
return null;
}
$.extend(lnk, {
key: link.id,
class: 'link',
fromSource: link,
// functions to aggregate dual link state
type: function () {
var s = lnk.fromSource,
t = lnk.fromTarget;
return (s && s.type) || (t && t.type) || defaultLinkType;
},
online: function () {
var s = lnk.fromSource,
t = lnk.fromTarget;
return (s && s.online) || (t && t.online);
},
linkWidth: function () {
var s = lnk.fromSource,
t = lnk.fromTarget,
ws = (s && s.linkWidth) || 0,
wt = (t && t.linkWidth) || 0;
return Math.max(ws, wt);
}
});
return lnk;
}
function removeLinkLabels() {
network.links.forEach(function (d) {
d.label = '';
});
}
var widthRatio = 1.4,
linkScale = d3.scale.linear()
.domain([1, 12])
.range([widthRatio, 12 * widthRatio])
.clamp(true);
function updateLinks() {
link = linkG.selectAll('.link')
.data(network.links, function (d) { return d.key; });
// operate on existing links, if necessary
// link .foo() .bar() ...
// operate on entering links:
var entering = link.enter()
.append('line')
.attr({
x1: function (d) { return d.x1; },
y1: function (d) { return d.y1; },
x2: function (d) { return d.x2; },
y2: function (d) { return d.y2; },
stroke: config.topo.linkInColor,
'stroke-width': config.topo.linkInWidth
});
// augment links
entering.each(function (d) {
var link = d3.select(this);
// provide ref to element selection from backing data....
d.el = link;
restyleLinkElement(d);
});
// operate on both existing and new links, if necessary
//link .foo() .bar() ...
// apply or remove labels
var labelData = getLabelData();
applyLinkLabels(labelData);
// operate on exiting links:
link.exit()
.attr('stroke-dasharray', '3, 3')
.style('opacity', 0.5)
.transition()
.duration(1500)
.attr({
'stroke-dasharray': '3, 12',
stroke: config.topo.linkOutColor,
'stroke-width': config.topo.linkOutWidth
})
.style('opacity', 0.0)
.remove();
// NOTE: invoke a single tick to force the labels to position
// onto their links.
tick();
}
function getLabelData() {
// create the backing data for showing labels..
var data = [];
link.each(function (d) {
if (d.label) {
data.push({
id: 'lab-' + d.key,
key: d.key,
label: d.label,
ldata: d
});
}
});
return data;
}
var linkLabelOffset = '0.3em';
function applyLinkLabels(data) {
var entering;
linkLabel = linkLabelG.selectAll('.linkLabel')
.data(data, function (d) { return d.id; });
// for elements already existing, we need to update the text
// and adjust the rectangle size to fit
linkLabel.each(function (d) {
var el = d3.select(this),
rect = el.select('rect'),
text = el.select('text');
text.text(d.label);
rect.attr(rectAroundText(el));
});
entering = linkLabel.enter().append('g')
.classed('linkLabel', true)
.attr('id', function (d) { return d.id; });
entering.each(function (d) {
var el = d3.select(this),
rect,
text,
parms = {
x1: d.ldata.x1,
y1: d.ldata.y1,
x2: d.ldata.x2,
y2: d.ldata.y2
};
d.el = el;
rect = el.append('rect');
text = el.append('text').text(d.label);
rect.attr(rectAroundText(el));
text.attr('dy', linkLabelOffset);
el.attr('transform', transformLabel(parms));
});
// Remove any links that are no longer required.
linkLabel.exit().remove();
}
function rectAroundText(el) {
var text = el.select('text'),
box = text.node().getBBox();
// translate the bbox so that it is centered on [x,y]
box.x = -box.width / 2;
box.y = -box.height / 2;
// add padding
box.x -= 1;
box.width += 2;
return box;
}
function transformLabel(p) {
var dx = p.x2 - p.x1,
dy = p.y2 - p.y1,
xMid = dx/2 + p.x1,
yMid = dy/2 + p.y1;
//length = Math.sqrt(dx*dx + dy*dy),
//rads = Math.asin(dy/length),
//degs = rads / (Math.PI*2) * 360;
return translate(xMid, yMid);
// TODO: consider making label parallel to line
//return [
// translate(xMid, yMid),
// rotate(degs),
// translate(0, 8)
//].join('');
}
function createDeviceNode(device) {
// start with the object as is
var node = device,
type = device.type,
svgCls = type ? 'node device ' + type : 'node device';
// Augment as needed...
node.class = 'device';
node.svgClass = device.online ? svgCls + ' online' : svgCls;
positionNode(node);
// cache label array length
network.deviceLabelCount = device.labels.length;
return node;
}
function createHostNode(host) {
// start with the object as is
var node = host;
// Augment as needed...
node.class = 'host';
if (!node.type) {
node.type = 'endstation';
}
node.svgClass = 'node host ' + node.type;
positionNode(node);
// cache label array length
network.hostLabelCount = host.labels.length;
return node;
}
function positionNode(node) {
var meta = node.metaUi,
x = meta && meta.x,
y = meta && meta.y,
xy;
// If we have [x,y] already, use that...
if (x && y) {
node.fixed = true;
node.x = x;
node.y = y;
return;
}
var location = node.location;
if (location && location.type === 'latlng') {
var coord = geoMapProjection([location.lng, location.lat]);
node.fixed = true;
node.x = coord[0];
node.y = coord[1];
return;
}
// Note: Placing incoming unpinned nodes at exactly the same point
// (center of the view) causes them to explode outwards when
// the force layout kicks in. So, we spread them out a bit
// initially, to provide a more serene layout convergence.
// Additionally, if the node is a host, we place it near
// the device it is connected to.
function spread(s) {
return Math.floor((Math.random() * s) - s/2);
}
function randDim(dim) {
return dim / 2 + spread(dim * 0.7071);
}
function rand() {
return {
x: randDim(network.view.width()),
y: randDim(network.view.height())
};
}
function near(node) {
var min = 12,
dx = spread(12),
dy = spread(12);
return {
x: node.x + min + dx,
y: node.y + min + dy
};
}
function getDevice(cp) {
var d = network.lookup[cp.device];
return d || rand();
}
xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
$.extend(node, xy);
}
function iconUrl(d) {
return 'img/' + d.type + '.png';
}
// returns the newly computed bounding box of the rectangle
function adjustRectToFitText(n) {
var text = n.select('text'),
box = text.node().getBBox(),
lab = config.labels;
text.attr('text-anchor', 'middle')
.attr('y', '-0.8em')
.attr('x', lab.imgPad/2);
// translate the bbox so that it is centered on [x,y]
box.x = -box.width / 2;
box.y = -box.height / 2;
// add padding
box.x -= (lab.padLR + lab.imgPad/2);
box.width += lab.padLR * 2 + lab.imgPad;
box.y -= lab.padTB;
box.height += lab.padTB * 2;
return box;
}
function mkSvgClass(d) {
return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
}
function hostLabel(d) {
var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
return d.labels[idx];
}
function deviceLabel(d) {
var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
return d.labels[idx];
}
function niceLabel(label) {
return (label && label.trim()) ? label : '.';
}
function updateDeviceLabel(d) {
var label = niceLabel(deviceLabel(d)),
node = d.el,
box;
node.select('text')
.text(label)
.style('opacity', 0)
.transition()
.style('opacity', 1);
box = adjustRectToFitText(node);
node.select('rect')
.transition()
.attr(box);
node.select('rect.iconUnderlay')
.transition()
.attr('x', box.x + config.icons.xoff)
.attr('y', box.y + config.icons.yoff);
node.select('image')
.transition()
.attr('x', box.x + config.icons.xoff + 2)
.attr('y', box.y + config.icons.yoff + 2);
}
function updateHostLabel(d) {
var label = hostLabel(d),
host = d.el;
host.select('text').text(label);
}
function updateDeviceState(nodeData) {
nodeData.el.classed('online', nodeData.online);
updateDeviceLabel(nodeData);
// TODO: review what else might need to be updated
}
function updateLinkState(linkData) {
updateLinkWidth(linkData);
linkData.el.classed('inactive', !linkData.online);
// TODO: review what else might need to be updated
// update label, if showing
}
function updateHostState(hostData) {
updateHostLabel(hostData);
// TODO: review what else might need to be updated
}
function nodeMouseOver(d) {
hovered = d;
if (trafficHover() && d.class === 'host') {
showTrafficAction();
}
}
function nodeMouseOut(d) {
hovered = null;
if (trafficHover() && d.class === 'host') {
showTrafficAction();
}
}
function addHostIcon(node, radius, iconId) {
var dim = radius * 1.5,
xlate = -dim / 2;
node.append('svg:image')
.attr('transform', translate(xlate,xlate))
.attr('xlink:href', 'img/' + iconId + '.png')
.attr('width', dim)
.attr('height', dim);
}
function updateNodes() {
node = nodeG.selectAll('.node')
.data(network.nodes, function (d) { return d.id; });
// operate on existing nodes, if necessary
// update host labels
//node .foo() .bar() ...
// operate on entering nodes:
var entering = node.enter()
.append('g')
.attr({
id: function (d) { return safeId(d.id); },
class: mkSvgClass,
transform: function (d) { return translate(d.x, d.y); },
opacity: 0
})
.call(network.drag)
.on('mouseover', nodeMouseOver)
.on('mouseout', nodeMouseOut)
.transition()
.attr('opacity', 1);
// augment device nodes...
entering.filter('.device').each(function (d) {
var node = d3.select(this),
icon = iconUrl(d),
label = niceLabel(deviceLabel(d)),
box;
// provide ref to element from backing data....
d.el = node;
node.append('rect')
.attr({
'rx': 5,
'ry': 5
});
node.append('text')
.text(label)
.attr('dy', '1.1em');
box = adjustRectToFitText(node);
node.select('rect')
.attr(box);
if (icon) {
var cfg = config.icons;
node.append('rect')
.attr({
class: 'iconUnderlay',
x: box.x + config.icons.xoff,
y: box.y + config.icons.yoff,
width: cfg.w,
height: cfg.h,
rx: 4
}).style({
stroke: '#000',
fill: '#ddd'
});
node.append('svg:image')
.attr({
x: box.x + config.icons.xoff + 2,
y: box.y + config.icons.yoff + 2,
width: cfg.w - 4,
height: cfg.h - 4,
'xlink:href': icon
});
}
// debug function to show the modelled x,y coordinates of nodes...
if (debug('showNodeXY')) {
node.select('rect').attr('fill-opacity', 0.5);
node.append('circle')
.attr({
class: 'debug',
cx: 0,
cy: 0,
r: '3px'
});
}
});
// TODO: better place for this configuration state
var defaultHostRadius = 9,
hostRadius = {
bgpSpeaker: 14,
router: 14,
host: 14
},
hostIcon = {
bgpSpeaker: 'bgpSpeaker',
router: 'router',
host: 'host'
};
// augment host nodes...
entering.filter('.host').each(function (d) {
var node = d3.select(this),
r = hostRadius[d.type] || defaultHostRadius,
textDy = r + 10,
icon = hostIcon[d.type];
// provide ref to element from backing data....
d.el = node;
node.append('circle')
.attr('r', r);
if (icon) {
addHostIcon(node, r, icon);
}
node.append('text')
.text(hostLabel)
.attr('dy', textDy)
.attr('text-anchor', 'middle');
// debug function to show the modelled x,y coordinates of nodes...
if (debug('showNodeXY')) {
node.select('circle').attr('fill-opacity', 0.5);
node.append('circle')
.attr({
class: 'debug',
cx: 0,
cy: 0,
r: '3px'
});
}
});
// operate on both existing and new nodes, if necessary
//node .foo() .bar() ...
// operate on exiting nodes:
// Note that the node is removed after 2 seconds.
// Sub element animations should be shorter than 2 seconds.
var exiting = node.exit()
.transition()
.duration(2000)
.style('opacity', 0)
.remove();
// host node exits....
exiting.filter('.host').each(function (d) {
var node = d3.select(this);
node.select('text')
.style('opacity', 0.5)
.transition()
.duration(1000)
.style('opacity', 0);
// note, leave <g>.remove to remove this element
node.select('circle')
.style('stroke-fill', '#555')
.style('fill', '#888')
.style('opacity', 0.5)
.transition()
.duration(1500)
.attr('r', 0);
// note, leave <g>.remove to remove this element
});
// TODO: device node exits
}
function find(key, array) {
for (var idx = 0, n = array.length; idx < n; idx++) {
if (array[idx].key === key) {
return idx;
}
}
return -1;
}
function removeLinkElement(linkData) {
var idx = find(linkData.key, network.links),
removed;
if (idx >=0) {
// remove from links array
removed = network.links.splice(idx, 1);
// remove from lookup cache
delete network.lookup[removed[0].key];
updateLinks();
network.force.resume();
}
}
function removeHostElement(hostData) {
// first, remove associated hostLink...
removeLinkElement(hostData.linkData);
// remove from lookup cache
delete network.lookup[hostData.id];
// remove from nodes array
var idx = find(hostData.id, network.nodes);
network.nodes.splice(idx, 1);
// remove from SVG
updateNodes();
network.force.resume();
}
function tick() {
node.attr({
transform: function (d) { return translate(d.x, d.y); }
});
link.attr({
x1: function (d) { return d.source.x; },
y1: function (d) { return d.source.y; },
x2: function (d) { return d.target.x; },
y2: function (d) { return d.target.y; }
});
linkLabel.each(function (d) {
var el = d3.select(this);
var lnk = findLinkById(d.key),
parms = {
x1: lnk.source.x,
y1: lnk.source.y,
x2: lnk.target.x,
y2: lnk.target.y
};
el.attr('transform', transformLabel(parms));
});
}
// ==============================
// Web-Socket for live data
function webSockUrl() {
return document.location.toString()
.replace(/\#.*/, '')
.replace('http://', 'ws://')
.replace('https://', 'wss://')
.replace('index2.html', config.webSockUrl);
}
webSock = {
ws : null,
connect : function() {
webSock.ws = new WebSocket(webSockUrl());
webSock.ws.onopen = function() {
noWebSock(false);
};
webSock.ws.onmessage = function(m) {
if (m.data) {
wsTraceRx(m.data);
handleServerEvent(JSON.parse(m.data));
}
};
webSock.ws.onclose = function(m) {
webSock.ws = null;
noWebSock(true);
};
},
send : function(text) {
if (text != null) {
webSock._send(text);
}
},
_send : function(message) {
if (webSock.ws) {
webSock.ws.send(message);
} else if (config.useLiveData) {
network.view.alert('no web socket open\n\n' + message);
} else {
console.log('WS Send: ' + JSON.stringify(message));
}
}
};
function noWebSock(b) {
mask.style('display',b ? 'block' : 'none');
}
function sendMessage(evType, payload) {
var toSend = {
event: evType,
sid: ++sid,
payload: payload
},
asText = JSON.stringify(toSend);
wsTraceTx(asText);
webSock.send(asText);
// Temporary measure for debugging UI behavior ...
if (!config.useLiveData) {
handleTestSend(toSend);
}
}
function wsTraceTx(msg) {
wsTrace('tx', msg);
}
function wsTraceRx(msg) {
wsTrace('rx', msg);
}
function wsTrace(rxtx, msg) {
console.log('[' + rxtx + '] ' + msg);
}
// NOTE: Temporary hardcoded example for showing detail pane
// while we fine-
// Probably should not merge this change...
function handleTestSend(msg) {
if (msg.event === 'requestDetails') {
showDetails({
event: 'showDetails',
sid: 1001,
payload: {
"id": "of:0000ffffffffff09",
"type": "roadm",
"propOrder": [
"Name",
"Vendor",
"H/W Version",
"S/W Version",
"-",
"Latitude",
"Longitude",
"Ports"
],
"props": {
"Name": null,
"Vendor": "Linc",
"H/W Version": "OE",
"S/W Version": "?",
"-": "",
"Latitude": "40.8",
"Longitude": "73.1",
"Ports": "2"
}
}
});
}
}
// ==============================
// Selection stuff
function selectObject(obj, el) {
var n,
srcEv = d3.event.sourceEvent,
meta = srcEv.metaKey,
shift = srcEv.shiftKey;
if ((panZoom() && !meta) || (!panZoom() && meta)) {
return;
}
if (el) {
n = d3.select(el);
} else {
node.each(function(d) {
if (d == obj) {
n = d3.select(el = this);
}
});
}
if (!n) return;
if (shift && n.classed('selected')) {
deselectObject(obj.id);
updateDetailPane();
return;
}
if (!shift) {
deselectAll();
}
selections[obj.id] = { obj: obj, el: el };
selectOrder.push(obj.id);
n.classed('selected', true);
updateDetailPane();
}
function deselectObject(id) {
var obj = selections[id],
idx;
if (obj) {
d3.select(obj.el).classed('selected', false);
delete selections[id];
idx = $.inArray(id, selectOrder);
if (idx >= 0) {
selectOrder.splice(idx, 1);
}
}
}
function deselectAll() {
// deselect all nodes in the network...
node.classed('selected', false);
selections = {};
selectOrder = [];
updateDetailPane();
}
// update the state of the detail pane, based on current selections
function updateDetailPane() {
var nSel = selectOrder.length;
if (!nSel) {
detailPane.hide();
showTrafficAction(); // sends cancelTraffic event
} else if (nSel === 1) {
singleSelect();
} else {
multiSelect();
}
}
function singleSelect() {
requestDetails();
// NOTE: detail pane will be shown from showDetails event callback
}
function multiSelect() {
populateMultiSelect();
}
function addSep(tbody) {
var tr = tbody.append('tr');
$('<hr>').appendTo(tr.append('td').attr('colspan', 2));
}
function addProp(tbody, label, value) {
var tr = tbody.append('tr');
tr.append('td')
.attr('class', 'label')
.text(label + ' :');
tr.append('td')
.attr('class', 'value')
.text(value);
}
function populateMultiSelect() {
detailPane.empty();
var title = detailPane.append("h2"),
table = detailPane.append("table"),
tbody = table.append("tbody");
title.text('Multi-Select...');
selectOrder.forEach(function (d, i) {
addProp(tbody, i+1, d);
});
addMultiSelectActions();
}
function populateDetails(data) {
detailPane.empty();
var title = detailPane.append("h2"),
table = detailPane.append("table"),
tbody = table.append("tbody");
$('<img src="img/' + data.type + '.png">').appendTo(title);
$('<span>').attr('class', 'icon').text(data.id).appendTo(title);
data.propOrder.forEach(function(p) {
if (p === '-') {
addSep(tbody);
} else {
addProp(tbody, p, data.props[p]);
}
});
addSingleSelectActions();
}
function addSingleSelectActions() {
detailPane.append('hr');
// always want to allow 'show traffic'
addAction(detailPane, 'Show Traffic', showTrafficAction);
}
function addMultiSelectActions() {
detailPane.append('hr');
// always want to allow 'show traffic'
addAction(detailPane, 'Show Traffic', showTrafficAction);
// if exactly two hosts are selected, also want 'add host intent'
if (nSel() === 2 && allSelectionsClass('host')) {
addAction(detailPane, 'Add Host Intent', addIntentAction);
}
}
function addAction(panel, text, cb) {
panel.append('div')
.classed('actionBtn', true)
.text(text)
.on('click', cb);
}
function zoomPan(scale, translate) {
zoomPanContainer.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
// keep the map lines constant width while zooming
bgImg.style("stroke-width", 2.0 / scale + "px");
}
function resetZoomPan() {
zoomPan(1, [0,0]);
zoom.scale(1).translate([0,0]);
}
function setupZoomPan() {
function zoomed() {
if (!panZoom() ^ !d3.event.sourceEvent.metaKey) {
zoomPan(d3.event.scale, d3.event.translate);
}
}
zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.scaleExtent([1, 8])
.on("zoom", zoomed);
svg.call(zoom);
}
// ==============================
// Test harness code
function prepareScenario(view, ctx, dbg) {
var sc = scenario,
urlSc = sc.evDir + ctx + sc.evScenario;
if (!ctx) {
view.alert("No scenario specified (null ctx)");
return;
}
sc.view = view;
sc.ctx = ctx;
sc.debug = dbg;
sc.evNumber = 0;
d3.json(urlSc, function(err, data) {
var p = data && data.params || {},
desc = data && data.description || null,
intro = data && data.title;
if (err) {
view.alert('No scenario found:\n\n' + urlSc + '\n\n' + err);
} else {
sc.params = p;
if (desc) {
intro += '\n\n ' + desc.join('\n ');
}
view.alert(intro);
}
});
}
// ==============================
// Toggle Buttons in masthead
// TODO: toggle button (and other widgets in the masthead) should be provided
// by the framework; not generated by the view.
var showInstances,
doPanZoom,
showTrafficOnHover;
function addButtonBar(view) {
var bb = d3.select('#mast')
.append('span').classed('right', true).attr('id', 'bb');
function mkTogBtn(text, cb) {
return bb.append('span')
.classed('btn', true)
.text(text)
.on('click', cb);
}
showInstances = mkTogBtn('Show Instances', toggleInst);
//doPanZoom = mkTogBtn('Pan/Zoom', togglePanZoom);
//showTrafficOnHover = mkTogBtn('Show traffic on hover', toggleTrafficHover);
}
function instShown() {
return showInstances.classed('active');
}
function toggleInst() {
showInstances.classed('active', !instShown());
if (instShown()) {
oiBox.show();
} else {
oiBox.hide();
}
}
function panZoom() {
return false;
//return doPanZoom.classed('active');
}
function togglePanZoom() {
doPanZoom.classed('active', !panZoom());
}
function trafficHover() {
return hoverEnabled;
}
function toggleTrafficHover() {
showTrafficOnHover.classed('active', !trafficHover());
}
function loadGlyphs(svg) {
var defs = svg.append('defs');
gly.defBird(defs);
gly.defBullhorn(defs);
}
// ==============================
// View life-cycle callbacks
function preload(view, ctx, flags) {
var w = view.width(),
h = view.height(),
fcfg = config.force,
fpad = fcfg.pad,
forceDim = [w - 2*fpad, h - 2*fpad];
// NOTE: view.$div is a D3 selection of the view's div
var viewBox = '0 0 ' + config.logicalSize + ' ' + config.logicalSize;
svg = view.$div.append('svg').attr('viewBox', viewBox);
setSize(svg, view);
loadGlyphs(svg);
zoomPanContainer = svg.append('g').attr('id', 'zoomPanContainer');
setupZoomPan();
// add blue glow filter to svg layer
d3u.appendGlow(zoomPanContainer);
// group for the topology
topoG = zoomPanContainer.append('g')
.attr('id', 'topo-G')
.attr('transform', fcfg.translate());
// subgroups for links, link labels, and nodes
linkG = topoG.append('g').attr('id', 'links');
linkLabelG = topoG.append('g').attr('id', 'linkLabels');
nodeG = topoG.append('g').attr('id', 'nodes');
// selection of links, linkLabels, and nodes
link = linkG.selectAll('.link');
linkLabel = linkLabelG.selectAll('.linkLabel');
node = nodeG.selectAll('.node');
function chrg(d) {
return fcfg.charge[d.class] || -12000;
}
function ldist(d) {
return fcfg.linkDistance[d.type] || 50;
}
function lstrg(d) {
// 0.0 - 1.0
return fcfg.linkStrength[d.type] || 1.0;
}
function selectCb(d, self) {
selectObject(d, self);
}
function atDragEnd(d, self) {
// once we've finished moving, pin the node in position
d.fixed = true;
d3.select(self).classed('fixed', true);
if (config.useLiveData) {
sendUpdateMeta(d);
} else {
console.log('Moving node ' + d.id + ' to [' + d.x + ',' + d.y + ']');
}
}
function sendUpdateMeta(d) {
sendMessage('updateMeta', {
id: d.id,
'class': d.class,
'memento': {
x: d.x,
y: d.y
}
});
}
// set up the force layout
network.force = d3.layout.force()
.size(forceDim)
.nodes(network.nodes)
.links(network.links)
.gravity(0.4)
.friction(0.7)
.charge(chrg)
.linkDistance(ldist)
.linkStrength(lstrg)
.on('tick', tick);
network.drag = d3u.createDragBehavior(network.force,
selectCb, atDragEnd, panZoom);
// create mask layer for when we lose connection to server.
// TODO: this should be part of the framework
mask = view.$div.append('div').attr('id','topo-mask');
para(mask, 'Oops!');
para(mask, 'Web-socket connection to server closed...');
para(mask, 'Try refreshing the page.');
mask.append('svg')
.attr({
id: 'mask-bird',
width: w,
height: h
})
.append('g')
.attr('transform', birdTranslate(w, h))
.style('opacity', 0.3)
.append('use')
.attr({
'xlink:href': '#bird',
width: config.birdDim,
height: config.birdDim,
fill: '#111'
})
}
function para(sel, text) {
sel.append('p').text(text);
}
function load(view, ctx, flags) {
// resize, in case the window was resized while we were not loaded
resize(view, ctx, flags);
// cache the view token, so network topo functions can access it
network.view = view;
config.useLiveData = !flags.local;
if (!config.useLiveData) {
prepareScenario(view, ctx, flags.debug);
}
// set our radio buttons and key bindings
layerBtnSet = view.setRadio(layerButtons);
view.setKeys(keyDispatch);
// patch in our "button bar" for now
// TODO: implement a more official frameworky way of doing this..
addButtonBar(view);
// Load map data asynchronously; complete startup after that..
loadGeoJsonData();
// start the and timer
var dashIdx = 0;
antTimer = setInterval(function () {
// TODO: figure out how to choose Src-->Dst and Dst-->Src, per link
dashIdx = dashIdx === 0 ? 14 : dashIdx - 2;
d3.selectAll('.animated').style('stroke-dashoffset', dashIdx);
}, 35);
}
function unload(view, ctx, flags) {
if (antTimer) {
clearInterval(antTimer);
antTimer = null;
}
}
// TODO: move these to config/state portion of script
var geoJsonUrl = 'json/map/continental_us.json', // TODO: Paul
geoJson;
function loadGeoJsonData() {
d3.json(geoJsonUrl, function (err, data) {
if (err) {
// fall back to USA map background
loadStaticMap();
} else {
geoJson = data;
loadGeoMap();
}
// finally, connect to the server...
if (config.useLiveData) {
webSock.connect();
}
});
}
function showBg() {
return config.options.showBackground ? 'visible' : 'hidden';
}
function loadStaticMap() {
fnTrace('loadStaticMap', config.backgroundUrl);
var w = network.view.width(),
h = network.view.height();
// load the background image
bgImg = svg.insert('svg:image', '#topo-G')
.attr({
id: 'topo-bg',
width: w,
height: h,
'xlink:href': config.backgroundUrl
})
.style({
visibility: showBg()
});
}
function loadGeoMap() {
fnTrace('loadGeoMap', geoJsonUrl);
// extracts the topojson data into geocoordinate-based geometry
var topoData = topojson.feature(geoJson, geoJson.objects.states);
// see: http://bl.ocks.org/mbostock/4707858
geoMapProjection = d3.geo.mercator();
var path = d3.geo.path().projection(geoMapProjection);
geoMapProjection
.scale(1)
.translate([0, 0]);
// [[x1,y1],[x2,y2]]
var b = path.bounds(topoData);
// size map to 95% of minimum dimension to fill space
var s = .95 / Math.min((b[1][0] - b[0][0]) / config.logicalSize, (b[1][1] - b[0][1]) / config.logicalSize);
var t = [(config.logicalSize - s * (b[1][0] + b[0][0])) / 2, (config.logicalSize - s * (b[1][1] + b[0][1])) / 2];
geoMapProjection
.scale(s)
.translate(t);
bgImg = zoomPanContainer.insert("g", '#topo-G');
bgImg.attr('id', 'map').selectAll('path')
.data(topoData.features)
.enter()
.append('path')
.attr('d', path);
}
function resize(view, ctx, flags) {
var w = view.width(),
h = view.height();
setSize(svg, view);
d3.select('#mask-bird').attr({ width: w, height: h})
.select('g').attr('transform', birdTranslate(w, h));
}
function birdTranslate(w, h) {
var bdim = config.birdDim;
return 'translate('+((w-bdim)*.4)+','+((h-bdim)*.1)+')';
}
// ==============================
// View registration
onos.ui.addView('topo', {
preload: preload,
load: load,
unload: unload,
resize: resize
});
detailPane = onos.ui.addFloatingPanel('topo-detail');
oiBox = onos.ui.addFloatingPanel('topo-oibox', 'TL');
}(ONOS));