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