45040e107c1709d4bfd6353d5f94950520fc3a07
[VSoRC/.git] / js / topology / topology.js
1 // Copyright (c) 2018 Maen Artimy
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //   http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 $(function () {
16     const tabObj = Tabs('topology');
17     const size = 60;
18     const radius = 8;
19
20     // Define the div for the tooltip
21     const div = d3.select("body").append("div")
22         .attr("class", "tooltip")
23         .style("opacity", 0);
24
25     function add_prefix(obj) {
26         return String(obj).replace(/^0+/, "Switch_");
27     }
28
29     function trim_zeros(obj) {
30         return String(obj).replace(/^0+/, "");
31     }
32
33     // Takes JSON data and convert to a graph format that D3 understands:
34     // var topDesc = {
35     //     "nodes": [
36     //       {"id": "0000000000000001", "type": "switch"},
37     //       {"id": "0000000000000002", "type": "switch"},
38     //       {"id": "16:18:83:a8:4d:1c", "type": "host"},
39     //       ...
40     //     ],
41     //     "links": [
42     //         {"source": "0000000000000002", "target": "0000000000000003",
43     //          "port": {"source": "00000003", "target": "00000002"}, "value": 4},
44     //       ...
45     //     ]}
46     function toGraph(top) {
47         var nodes = [];
48         var links = [];
49
50         var lst = top.switches;
51
52         for (var i = 0; i < lst.length; i++) {
53             nodes.push({ "id": lst[i].dpid, "type": "switch" });
54         }
55
56         if (top.links.length > 0) {
57             lst = top.links;
58             for (var i = 0; i < lst.length; i++) {
59                 if (lst[i].src.dpid < lst[i].dst.dpid) { // prevent duplicate links
60                     links.push({
61                         "source": lst[i].src.dpid, "target": lst[i].dst.dpid, "value": 4,
62                         "port": { "source": lst[i].src.port_no, "target": lst[i].dst.port_no }
63                     });
64                 }
65             }
66         } else if (top.switches.length > 1) { // represent the network with a cloud
67             nodes.push({ "id": 0, "type": "cloud" });
68             for (var i = 0; i < lst.length; i++) {
69                 links.push({
70                     "source": 0, "target": lst[i].dpid, "value": 4,
71                     "port": { "source": 0, "target": 0 }
72                 });
73             }
74         }
75
76         lst = top.hosts;
77         console.log(top.hosts);
78         for (var i = 0; i < lst.length; i++) {
79             nodes.push({ "id": lst[i].mac, "type": "host","ip": lst[i].ipv4});
80             links.push({
81                 "source": lst[i].port.dpid, "target": lst[i].mac, "value": 2,
82                 "port": { "source": lst[i].port.port_no, "target": 0 }
83             });
84         }
85
86         return { "nodes": nodes, "links": links };
87     }
88
89     // Plot the topology using D3.js
90     // Many online tutorials explain how this works. Example: www.puzzlr.org/force-graphs-with-d3
91     function plotGraph(graph) {
92         var svg = d3.select("svg");
93         var width = +svg.attr("width");
94         var height = +svg.attr("height");
95
96         //custom force to put everything in a box
97         function box_force() {
98             var curr_node;
99             for (var i = 0, n = graph.nodes.length; i < n; ++i) {
100                 curr_node = graph.nodes[i];
101                 curr_node.x = Math.max(radius, Math.min(width - radius, curr_node.x));
102                 curr_node.y = Math.max(radius, Math.min(height - radius, curr_node.y));
103             }
104         }
105
106         // Create a force layout simulation
107
108         // Link: attraction force
109         // chanrge: repulsion force
110         // x: attracts the nodes to the horizontal centre
111         // y: attracts the hosts the bottom while other nodes are attrcated to the top
112         // centre: atracts to the centre
113         // collision: avoids node collision
114         // box: keeps all nodes inside
115         var simulation = d3.forceSimulation()
116             .nodes(graph.nodes)
117             .force("link", d3.forceLink(graph.links).id(function (d) { return d.id; }).distance(size * 2))
118             .force("charge", d3.forceManyBody().strength(-size * 30))
119             .force("x", d3.forceX(width / 2))
120             .force("y", d3.forceY(function (d) {
121                 if (d.type === "host") {
122                     return 3 * height / 4
123                 } else {
124                     return 1 * height / 4
125                 }
126             }).strength(0.25))
127             .force("centre", d3.forceCenter(width / 2, height / 2))
128             .force("collision", d3.forceCollide().radius(35))
129             .force("box", box_force);
130
131         // Create nodes with image and text
132         var node = svg.append("g")
133             .attr("class", "nodes")
134             .selectAll(".node")
135             .data(graph.nodes)
136             .enter().append("g")
137             // .attr("id", function (d) { return "N" + d.id; })
138             .attr("class", "node");
139
140         node.append("image")
141             .attr("xlink:href", function (d) {
142                 if (d.type === "switch") {
143                     return "img/switch.png"
144                 } else if (d.type === "cloud") {
145                     return "img/cloud.svg"
146                 } else {
147                     return "img/pc.svg"
148                 }
149             })
150             .on("mouseover", handleMouseOver)
151             .on("mouseout", handleMouseOut)
152
153         node.append("text")
154             .attr("class", "label")
155             .attr("dy", size + 14)
156             .text(function (d) { return d.id; });
157
158
159        node.append("text")
160             .attr("class", "label")
161             .attr("dy", size + 26)
162             .text(function (d) { if (d.type === "host")return (d.ip); });
163             // .text(function (d) { return d.id.replace(/^0+/, ''); });
164
165
166         // Create links with lines, circles, and text
167         var link = svg.append("g")
168             .attr("class", "links")
169             .selectAll(".link")
170             .data(graph.links)
171             .enter().append("g")
172             .attr("class", "link");
173
174         link.append("line")
175             .attr("stroke-width", function (d) { return d.value; });
176
177         link.append("circle")
178             .attr("class", "start")
179             .attr("r", radius)
180
181         link.append("circle")
182             .attr("class", "end")
183             .attr("r", radius)
184
185         link.append("text")
186             .attr("class", "start")
187             .text(function (d) { return trim_zeros(d.port.source); })
188
189         link.append("text")
190             .attr("class", "end")
191             .text(function (d) { return trim_zeros(d.port.target); })
192
193         // Simulation steps
194         function tickActions() {
195             function norm(d) {
196                 return Math.sqrt((d.target.x - d.source.x) ** 2 + (d.target.y - d.source.y) ** 2);
197             }
198
199             node
200                 .attr("transform", function (d) { return "translate(" + (d.x - size / 2) + "," + (d.y - size / 2) + ")"; });
201             link
202                 .attr("transform", function (d) { return "translate(" + d.source.x + "," + d.source.y + ")"; });
203
204             link.selectAll("line")
205                 .attr("x1", function (d) { return (d.target.x - d.source.x) * size / 2 / norm(d); })
206                 .attr("y1", function (d) { return (d.target.y - d.source.y) * size / 2 / norm(d); })
207                 .attr("x2", function (d) { return (d.target.x - d.source.x) * (1 - size / 2 / norm(d)); })
208                 .attr("y2", function (d) { return (d.target.y - d.source.y) * (1 - size / 2 / norm(d)); })
209
210             // position of the link start port
211             link.selectAll("circle.start")
212                 .attr("cx", function (d) { return (d.target.x - d.source.x) * size / 2 / norm(d); })
213                 .attr("cy", function (d) { return (d.target.y - d.source.y) * size / 2 / norm(d); })
214
215             // psotion of the link end port
216             link.selectAll("circle.end")
217                 .attr("cx", function (d) { return (d.target.x - d.source.x) * (1 - size / 2 / norm(d)); })
218                 .attr("cy", function (d) { return (d.target.y - d.source.y) * (1 - size / 2 / norm(d)); })
219
220             link.selectAll("text.start")
221                 .attr("dx", function (d) { return (d.target.x - d.source.x) * size / 2 / norm(d); })
222                 .attr("dy", function (d) { return (d.target.y - d.source.y) * size / 2 / norm(d); })
223
224             link.selectAll("text.end")
225                 .attr("dx", function (d) { return (d.target.x - d.source.x) * (1 - size / 2 / norm(d)); })
226                 .attr("dy", function (d) { return (d.target.y - d.source.y) * (1 - size / 2 / norm(d)); })
227
228         }
229
230         // Handling mouse drag
231         node.call(d3.drag()
232             .on("start", drag_start)
233             .on("drag", drag_drag)
234             .on("end", drag_end));
235
236         function drag_start(d) {
237             if (!d3.event.active) simulation.alphaTarget(0.3).restart();
238             d.fx = d.x;
239             d.fy = d.y;
240         }
241
242         function drag_drag(d) {
243             d.fx = d3.event.x;
244             d.fy = d3.event.y;
245         }
246
247         function drag_end(d) {
248             if (!d3.event.active) simulation.alphaTarget(0);
249             d.fx = null;
250             d.fy = null;
251         }
252
253         // Handling mouse over
254         function handleMouseOver(d) {
255             div.transition()
256                 .duration(200)
257                 .style("opacity", .9);
258             div.html(d.type + ": " + d.id)
259                 .style("left", (d3.event.pageX) + "px")
260                 .style("top", (d3.event.pageY - 28) + "px");
261         }
262
263         function handleMouseOut(d) {
264             div.transition()
265                 .duration(500)
266                 .style("opacity", 0);
267         }
268
269         // drag_handler(node);
270
271         // run tickActions in every simulation step
272         simulation.on("tick", tickActions);
273
274     }
275
276     // Display the raw topology data
277     function listTopology(network) {
278         data = "<h1>Switches</h1>" + JSON.stringify(network.switches) + "<br>";
279         data += "<h1>Links</h1>" + JSON.stringify(network.links) + "<br>";
280         data += "<h1>Hosts</h1>" + JSON.stringify(network.hosts) + "<br>";
281         $('#data').html(data);
282     }
283
284     function getTopology() {
285         tabObj.buildTabs("#main", ["Graph", "Tables"], "Nothing to show!");
286         var $svg = $('<svg width="800" height="600"></svg>');
287         var $data = $('<div id="data"></div>');
288         tabObj.buildContent('Graph', $svg);
289         tabObj.buildContent('Tables', $data);
290
291
292
293
294 // La funcion jsonget fue creada para sustituir el metodo json de D3
295
296         function jsonget() {
297
298           let xhr = new XMLHttpRequest();
299           xhr.open('GET', "/gettopo" , true);
300           //console.log(xhr); //para ver en la consola
301           xhr.onload = function() {
302             if (xhr.status == 200) { //can use this.status instead
303               //console.log(xhr.responseText);// para ver en la consola
304
305               listTopology(JSON.parse(xhr.responseText));
306               plotGraph(toGraph(JSON.parse(xhr.responseText)));
307             }
308           }
309           xhr.send();
310         }
311
312         jsonget();
313
314
315
316
317
318         // d3.json(location.hostname+":8080/topology").then(function (data) {
319         //     listTopology(data)
320         //     plotGraph(toGraph(data));
321         // });
322         tabObj.setActive();
323     }
324
325     // When the refresh button is clicked, clear the page and start over
326     $('.refresh').on('click', function () {
327         //$('svg').html("");
328         getTopology();
329     });
330
331     getTopology();
332
333 });