14bfb2e5fb985fb2730c8b25ffef5a2d51989426
[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         for (var i = 0; i < lst.length; i++) {
78             nodes.push({ "id": lst[i].mac, "type": "host" });
79             links.push({
80                 "source": lst[i].port.dpid, "target": lst[i].mac, "value": 2,
81                 "port": { "source": lst[i].port.port_no, "target": 0 }
82             });
83         }
84
85         return { "nodes": nodes, "links": links };
86     }
87
88     // Plot the topology using D3.js
89     // Many online tutorials explain how this works. Example: www.puzzlr.org/force-graphs-with-d3
90     function plotGraph(graph) {
91         var svg = d3.select("svg");
92         var width = +svg.attr("width");
93         var height = +svg.attr("height");
94
95         //custom force to put everything in a box
96         function box_force() {
97             var curr_node;
98             for (var i = 0, n = graph.nodes.length; i < n; ++i) {
99                 curr_node = graph.nodes[i];
100                 curr_node.x = Math.max(radius, Math.min(width - radius, curr_node.x));
101                 curr_node.y = Math.max(radius, Math.min(height - radius, curr_node.y));
102             }
103         }
104
105         // Create a force layout simulation
106
107         // Link: attraction force
108         // chanrge: repulsion force
109         // x: attracts the nodes to the horizontal centre
110         // y: attracts the hosts the bottom while other nodes are attrcated to the top
111         // centre: atracts to the centre
112         // collision: avoids node collision
113         // box: keeps all nodes inside
114         var simulation = d3.forceSimulation()
115             .nodes(graph.nodes)
116             .force("link", d3.forceLink(graph.links).id(function (d) { return d.id; }).distance(size * 2))
117             .force("charge", d3.forceManyBody().strength(-size * 30))
118             .force("x", d3.forceX(width / 2))
119             .force("y", d3.forceY(function (d) {
120                 if (d.type === "host") {
121                     return 3 * height / 4
122                 } else {
123                     return 1 * height / 4
124                 }
125             }).strength(0.25))
126             .force("centre", d3.forceCenter(width / 2, height / 2))
127             .force("collision", d3.forceCollide().radius(35))
128             .force("box", box_force);
129
130         // Create nodes with image and text
131         var node = svg.append("g")
132             .attr("class", "nodes")
133             .selectAll(".node")
134             .data(graph.nodes)
135             .enter().append("g")
136             // .attr("id", function (d) { return "N" + d.id; })
137             .attr("class", "node");
138
139         node.append("image")
140             .attr("xlink:href", function (d) {
141                 if (d.type === "switch") {
142                     return "img/switch.svg"
143                 } else if (d.type === "cloud") {
144                     return "img/cloud.svg"
145                 } else {
146                     return "img/pc.svg"
147                 }
148             })
149             .on("mouseover", handleMouseOver)
150             .on("mouseout", handleMouseOut)
151
152         node.append("text")
153             .attr("class", "label")
154             .attr("dy", size + 14)
155             .text(function (d) { return d.id; });
156             // .text(function (d) { return d.id.replace(/^0+/, ''); });
157
158
159         // Create links with lines, circles, and text
160         var link = svg.append("g")
161             .attr("class", "links")
162             .selectAll(".link")
163             .data(graph.links)
164             .enter().append("g")
165             .attr("class", "link");
166
167         link.append("line")
168             .attr("stroke-width", function (d) { return d.value; });
169
170         link.append("circle")
171             .attr("class", "start")
172             .attr("r", radius)
173
174         link.append("circle")
175             .attr("class", "end")
176             .attr("r", radius)
177
178         link.append("text")
179             .attr("class", "start")
180             .text(function (d) { return trim_zeros(d.port.source); })
181
182         link.append("text")
183             .attr("class", "end")
184             .text(function (d) { return trim_zeros(d.port.target); })
185
186         // Simulation steps
187         function tickActions() {
188             function norm(d) {
189                 return Math.sqrt((d.target.x - d.source.x) ** 2 + (d.target.y - d.source.y) ** 2);
190             }
191
192             node
193                 .attr("transform", function (d) { return "translate(" + (d.x - size / 2) + "," + (d.y - size / 2) + ")"; });
194             link
195                 .attr("transform", function (d) { return "translate(" + d.source.x + "," + d.source.y + ")"; });
196
197             link.selectAll("line")
198                 .attr("x1", function (d) { return (d.target.x - d.source.x) * size / 2 / norm(d); })
199                 .attr("y1", function (d) { return (d.target.y - d.source.y) * size / 2 / norm(d); })
200                 .attr("x2", function (d) { return (d.target.x - d.source.x) * (1 - size / 2 / norm(d)); })
201                 .attr("y2", function (d) { return (d.target.y - d.source.y) * (1 - size / 2 / norm(d)); })
202
203             // position of the link start port
204             link.selectAll("circle.start")
205                 .attr("cx", function (d) { return (d.target.x - d.source.x) * size / 2 / norm(d); })
206                 .attr("cy", function (d) { return (d.target.y - d.source.y) * size / 2 / norm(d); })
207
208             // psotion of the link end port
209             link.selectAll("circle.end")
210                 .attr("cx", function (d) { return (d.target.x - d.source.x) * (1 - size / 2 / norm(d)); })
211                 .attr("cy", function (d) { return (d.target.y - d.source.y) * (1 - size / 2 / norm(d)); })
212
213             link.selectAll("text.start")
214                 .attr("dx", function (d) { return (d.target.x - d.source.x) * size / 2 / norm(d); })
215                 .attr("dy", function (d) { return (d.target.y - d.source.y) * size / 2 / norm(d); })
216
217             link.selectAll("text.end")
218                 .attr("dx", function (d) { return (d.target.x - d.source.x) * (1 - size / 2 / norm(d)); })
219                 .attr("dy", function (d) { return (d.target.y - d.source.y) * (1 - size / 2 / norm(d)); })
220
221         }
222
223         // Handling mouse drag
224         node.call(d3.drag()
225             .on("start", drag_start)
226             .on("drag", drag_drag)
227             .on("end", drag_end));
228
229         function drag_start(d) {
230             if (!d3.event.active) simulation.alphaTarget(0.3).restart();
231             d.fx = d.x;
232             d.fy = d.y;
233         }
234
235         function drag_drag(d) {
236             d.fx = d3.event.x;
237             d.fy = d3.event.y;
238         }
239
240         function drag_end(d) {
241             if (!d3.event.active) simulation.alphaTarget(0);
242             d.fx = null;
243             d.fy = null;
244         }
245
246         // Handling mouse over
247         function handleMouseOver(d) {
248             div.transition()
249                 .duration(200)
250                 .style("opacity", .9);
251             div.html(d.type + ": " + d.id)
252                 .style("left", (d3.event.pageX) + "px")
253                 .style("top", (d3.event.pageY - 28) + "px");
254         }
255
256         function handleMouseOut(d) {
257             div.transition()
258                 .duration(500)
259                 .style("opacity", 0);
260         }
261
262         // drag_handler(node);
263
264         // run tickActions in every simulation step
265         simulation.on("tick", tickActions);
266
267     }
268
269     // Display the raw topology data
270     function listTopology(network) {
271         data = "<h1>Switches</h1>" + JSON.stringify(network.switches) + "<br>";
272         data += "<h1>Links</h1>" + JSON.stringify(network.links) + "<br>";
273         data += "<h1>Hosts</h1>" + JSON.stringify(network.hosts) + "<br>";
274         $('#data').html(data);
275     }
276
277     function getTopology() {
278         tabObj.buildTabs("#main", ["Graph", "Tables"], "Nothing to show!");
279         var $svg = $('<svg width="1616" height="900"></svg>');
280         var $data = $('<div id="data"></div>');
281         tabObj.buildContent('Graph', $svg);
282         tabObj.buildContent('Tables', $data);
283
284
285
286
287 // La funcion jsonget fue creada para sustituir el metodo json de D3
288
289         function jsonget() {
290
291           let xhr = new XMLHttpRequest();
292           xhr.open('GET', "/gettopo" , true);
293           //console.log(xhr); //para ver en la consola
294           xhr.onload = function() {
295             if (xhr.status == 200) { //can use this.status instead
296               //console.log(xhr.responseText);// para ver en la consola
297
298               listTopology(JSON.parse(xhr.responseText));
299               plotGraph(toGraph(JSON.parse(xhr.responseText)));
300             }
301           }
302           xhr.send();
303         }
304
305         jsonget();
306
307
308
309
310
311         // d3.json(location.hostname+":8080/topology").then(function (data) {
312         //     listTopology(data)
313         //     plotGraph(toGraph(data));
314         // });
315         tabObj.setActive();
316     }
317
318     // When the refresh button is clicked, clear the page and start over
319     $('.refresh').on('click', function () {
320         //$('svg').html("");
321         getTopology();
322     });
323
324     getTopology();
325
326 });