3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.topology.web;
12 import java.awt.Dimension;
13 import java.io.FileNotFoundException;
14 import java.io.IOException;
15 import java.io.ObjectInputStream;
16 import java.nio.ByteBuffer;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.LinkedList;
21 import java.util.List;
25 import javax.servlet.http.HttpServletRequest;
27 import org.opendaylight.controller.configuration.IConfigurationAware;
28 import org.opendaylight.controller.sal.authorization.Privilege;
29 import org.opendaylight.controller.sal.core.Bandwidth;
30 import org.opendaylight.controller.sal.core.Description;
31 import org.opendaylight.controller.sal.core.Edge;
32 import org.opendaylight.controller.sal.core.Host;
33 import org.opendaylight.controller.sal.core.Name;
34 import org.opendaylight.controller.sal.core.Node;
35 import org.opendaylight.controller.sal.core.Node.NodeIDType;
36 import org.opendaylight.controller.sal.core.NodeConnector;
37 import org.opendaylight.controller.sal.core.Property;
38 import org.opendaylight.controller.sal.packet.address.EthernetAddress;
39 import org.opendaylight.controller.sal.utils.GlobalConstants;
40 import org.opendaylight.controller.sal.utils.IObjectReader;
41 import org.opendaylight.controller.sal.utils.ObjectReader;
42 import org.opendaylight.controller.sal.utils.ObjectWriter;
43 import org.opendaylight.controller.sal.utils.ServiceHelper;
44 import org.opendaylight.controller.sal.utils.Status;
45 import org.opendaylight.controller.sal.utils.StatusCode;
46 import org.opendaylight.controller.switchmanager.ISwitchManager;
47 import org.opendaylight.controller.switchmanager.Switch;
48 import org.opendaylight.controller.switchmanager.SwitchConfig;
49 import org.opendaylight.controller.topologymanager.ITopologyManager;
50 import org.opendaylight.controller.web.DaylightWebUtil;
51 import org.springframework.stereotype.Controller;
52 import org.springframework.web.bind.annotation.PathVariable;
53 import org.springframework.web.bind.annotation.RequestMapping;
54 import org.springframework.web.bind.annotation.RequestMethod;
55 import org.springframework.web.bind.annotation.RequestParam;
56 import org.springframework.web.bind.annotation.ResponseBody;
58 import edu.uci.ics.jung.algorithms.layout.CircleLayout;
59 import edu.uci.ics.jung.graph.Graph;
60 import edu.uci.ics.jung.graph.SparseMultigraph;
64 public class Topology implements IObjectReader, IConfigurationAware {
65 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
66 private String topologyWebFileName = null;
68 protected Map<String, Map<String, Map<String, Object>>> metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
69 protected Map<String, Map<String, Object>> stagedNodes;
70 protected Map<String, Map<String, Object>> newNodes;
72 protected Map<String, Integer> metaNodeHash = new HashMap<String, Integer>();
73 protected Map<String, Integer> metaHostHash = new HashMap<String, Integer>();
74 protected Map<String, Integer> metaNodeSingleHash = new HashMap<String, Integer>();
75 protected Map<String, Integer> metaNodeConfigurationHash = new HashMap<String, Integer>();
78 ServiceHelper.registerGlobalService(IConfigurationAware.class, this, null);
79 topologyWebFileName = ROOT + "topologyCache.sav";
84 * Topology of nodes and hosts in the network in JSON format.
86 * Mainly intended for consumption by the visual topology.
88 * @return - JSON output for visual topology
90 @RequestMapping(value = "/visual.json", method = RequestMethod.GET)
92 public Collection<Map<String, Object>> getLinkData(@RequestParam(required = false) String container, HttpServletRequest request) {
93 String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
95 // Derive the privilege this user has on the current container
96 String userName = request.getUserPrincipal().getName();
97 Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
99 if (privilege == Privilege.NONE) {
103 ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
104 .getInstance(ITopologyManager.class, containerName, this);
105 if (topologyManager == null) {
108 ISwitchManager switchManager = (ISwitchManager) ServiceHelper
109 .getInstance(ISwitchManager.class, containerName, this);
110 if (switchManager == null) {
114 Map<Node, Set<Edge>> nodeEdges = topologyManager.getNodeEdges();
115 Map<Node, Set<NodeConnector>> hostEdges = topologyManager
116 .getNodesWithNodeConnectorHost();
117 List<Switch> nodes = switchManager.getNetworkDevices();
119 List<SwitchConfig> switchConfigurations = new ArrayList<SwitchConfig>();
120 for(Switch sw : nodes) {
121 Node n = sw.getNode();
122 SwitchConfig config = switchManager.getSwitchConfig(n.toString());
123 switchConfigurations.add(config);
126 // initialize cache if needed
127 if (!metaCache.containsKey(containerName)) {
128 metaCache.put(containerName, new HashMap<String, Map<String, Object>>());
130 metaNodeHash.put(containerName, null);
131 metaHostHash.put(containerName, null);
132 metaNodeSingleHash.put(containerName, null);
133 metaNodeConfigurationHash.put(containerName, null);
136 // return cache if topology hasn't changed
138 (metaNodeHash.get(containerName) != null && metaHostHash.get(containerName) != null && metaNodeSingleHash.get(containerName) != null && metaNodeConfigurationHash.get(containerName) != null) &&
139 metaNodeHash.get(containerName).equals(nodeEdges.hashCode()) && metaHostHash.get(containerName).equals(hostEdges.hashCode()) && metaNodeSingleHash.get(containerName).equals(nodes.hashCode()) && metaNodeConfigurationHash.get(containerName).equals(switchConfigurations.hashCode())
141 return metaCache.get(containerName).values();
144 // cache has changed, we must assign the new values
145 metaNodeHash.put(containerName, nodeEdges.hashCode());
146 metaHostHash.put(containerName, hostEdges.hashCode());
147 metaNodeSingleHash.put(containerName, nodes.hashCode());
148 metaNodeConfigurationHash.put(containerName, switchConfigurations.hashCode());
150 stagedNodes = new HashMap<String, Map<String, Object>>();
151 newNodes = new HashMap<String, Map<String, Object>>();
153 // nodeEdges addition
154 addNodes(nodeEdges, topologyManager, switchManager, containerName);
156 // single nodes addition
157 addSingleNodes(nodes, switchManager, containerName);
159 // hostNodes addition
160 addHostNodes(hostEdges, topologyManager, containerName);
162 repositionTopology(containerName);
164 return metaCache.get(containerName).values();
168 * Add regular nodes to main topology
170 * @param nodeEdges - node-edges mapping derived from topology
171 * @param topology - the topology instance
173 private void addNodes(Map<Node, Set<Edge>> nodeEdges,
174 ITopologyManager topology, ISwitchManager switchManager, String containerName) {
175 Bandwidth bandwidth = new Bandwidth(0);
176 Map<Edge, Set<Property>> properties = topology.getEdges();
178 for (Map.Entry<Node, Set<Edge>> e : nodeEdges.entrySet()) {
180 String description = getNodeDesc(n, switchManager);
182 NodeBean node = createNodeBean(description, n);
184 // skip production node
189 List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
190 Set<Edge> links = e.getValue();
191 for (Edge link : links) {
192 if (edgeIgnore(link)) {
195 for (Property p : properties.get(link)) {
196 if (p instanceof Bandwidth) {
197 bandwidth = (Bandwidth) p;
201 NodeConnector headNodeConnector = link.getHeadNodeConnector();
202 NodeConnector tailNodeConnector = link.getTailNodeConnector();
204 String headDescription = this.getNodeConnectorDescription(headNodeConnector, switchManager);
205 String tailDescription = this.getNodeConnectorDescription(tailNodeConnector, switchManager);
206 String headPortDescription = this.getNodeConnectorPortDescription(headNodeConnector, switchManager);
207 String tailPortDescription = this.getNodeConnectorPortDescription(tailNodeConnector, switchManager);
208 EdgeBean edge = new EdgeBean(link, bandwidth, headDescription, tailDescription, headPortDescription, tailPortDescription);
209 adjacencies.add(edge.out());
212 node.setLinks(adjacencies);
213 if (metaCache.get(containerName).containsKey(node.id())) {
214 // retrieve node from cache
215 Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
217 Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
218 data.put("$desc", description);
219 nodeEntry.put("data", data);
221 // always update adjacencies
222 nodeEntry.put("adjacencies", adjacencies);
223 // stage this cached node (with position)
224 stagedNodes.put(node.id(), nodeEntry);
226 newNodes.put(node.id(), node.out());
232 * Check if this node shouldn't appear in the visual topology
237 private boolean nodeIgnore(Node node) {
238 String nodeType = node.getType();
240 // add other node types to ignore later
241 if (nodeType.equals(NodeIDType.PRODUCTION)) {
249 * Check if this edge shouldn't appear in the visual topology
254 private boolean edgeIgnore(Edge edge) {
255 NodeConnector headNodeConnector = edge.getHeadNodeConnector();
256 Node headNode = headNodeConnector.getNode();
257 if (nodeIgnore(headNode)) {
261 NodeConnector tailNodeConnector = edge.getTailNodeConnector();
262 Node tailNode = tailNodeConnector.getNode();
263 if (nodeIgnore(tailNode)) {
270 protected NodeBean createNodeBean(String description, Node node) {
271 String name = this.getDescription(description, node);
272 return new NodeBean(node.toString(), name, NodeType.NODE);
275 private String getDescription(String description, Node node) {
276 String name = (description == null ||
277 description.trim().isEmpty() ||
278 description.equalsIgnoreCase("none"))?
279 node.toString() : description;
283 private String getNodeConnectorDescription(NodeConnector nodeConnector, ISwitchManager switchManager) {
284 Node node = nodeConnector.getNode();
285 String name = this.getDescription(getNodeDesc(node, switchManager), node);
289 private String getNodeConnectorPortDescription(NodeConnector nodeConnector, ISwitchManager switchManager) {
290 Name ncName = (Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName);
291 String nodeConnectorName = nodeConnector.getNodeConnectorIDString();
292 if (ncName != null) {
293 nodeConnectorName = ncName.getValue();
295 return nodeConnectorName;
298 @SuppressWarnings("unchecked")
299 private void addSingleNodes(List<Switch> nodes, ISwitchManager switchManager, String containerName) {
303 for (Switch sw : nodes) {
304 Node n = sw.getNode();
306 // skip production node
311 String description = getNodeDesc(n, switchManager);
313 if ((stagedNodes.containsKey(n.toString()) && metaCache.get(containerName).containsKey(n.toString())) || newNodes.containsKey(n.toString())) {
316 NodeBean node = createNodeBean(description, n);
318 // FIXME still doesn't display standalone node when last remaining link is removed
319 if (metaCache.get(containerName).containsKey(node.id()) && !stagedNodes.containsKey(node.id())) {
320 Map<String, Object> nodeEntry = metaCache.get(containerName).get(node.id());
321 Map<String, String> data = (Map<String, String>) nodeEntry.get("data");
322 data.put("$desc", description);
323 nodeEntry.put("data", data);
324 // clear adjacencies since this is now a single node
325 nodeEntry.put("adjacencies", new LinkedList<Map<String, Object>>());
326 stagedNodes.put(node.id(), nodeEntry);
328 newNodes.put(node.id(), node.out());
334 * Add regular hosts to main topology
336 * @param hostEdges - node-nodeconnectors host-specific mapping from topology
337 * @param topology - topology instance
339 private void addHostNodes(Map<Node, Set<NodeConnector>> hostEdges,
340 ITopologyManager topology, String containerName) {
341 for (Map.Entry<Node, Set<NodeConnector>> e : hostEdges.entrySet()) {
342 for (NodeConnector connector : e.getValue()) {
343 List<Host> hosts = topology.getHostsAttachedToNodeConnector(connector);
344 for (Host host : hosts) {
345 EthernetAddress dmac = (EthernetAddress) host.getDataLayerAddress();
347 ByteBuffer addressByteBuffer = ByteBuffer.allocate(8);
348 addressByteBuffer.putShort((short) 0);
349 addressByteBuffer.put(dmac.getValue());
350 addressByteBuffer.rewind();
352 long hid = addressByteBuffer.getLong();
353 String hostId = String.valueOf(hid);
355 NodeBean hostBean = new NodeBean(hostId, host.getNetworkAddressAsString(), NodeType.HOST);
356 List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
357 EdgeBean edge = new EdgeBean(connector, hid);
358 adjacencies.add(edge.out());
359 hostBean.setLinks(adjacencies);
361 if (metaCache.get(containerName).containsKey(hostId)) {
362 Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId);
363 hostEntry.put("adjacencies", adjacencies);
364 stagedNodes.put(hostId, hostEntry);
366 newNodes.put(String.valueOf(hid), hostBean.out());
374 * Re-position nodes in circular layout
376 private void repositionTopology(String containerName) {
377 Graph<String, String> graph = new SparseMultigraph<String, String>();
379 metaCache.get(containerName).clear();
380 metaCache.get(containerName).putAll(stagedNodes);
381 metaCache.get(containerName).putAll(newNodes);
383 for (Map<String, Object> on : metaCache.get(containerName).values()) {
384 graph.addVertex(on.toString());
386 List<Map<String, Object>> adjacencies = (List<Map<String, Object>>) on.get("adjacencies");
388 for (Map<String, Object> adj : adjacencies) {
390 adj.toString(), adj.get("nodeFrom").toString(),
391 adj.get("nodeTo").toString()
396 CircleLayout<String, String> layout = new CircleLayout<String, String>(graph);
397 layout.setSize(new Dimension(1200, 365));
398 for (Map.Entry<String, Map<String, Object>> v : newNodes.entrySet()) {
399 Double x = layout.transform(v.getKey()).getX();
400 Double y = layout.transform(v.getKey()).getY();
402 Map<String, String> nodeData = (HashMap<String, String>) v.getValue().get("data");
403 nodeData.put("$x", (x - 600) + "");
404 nodeData.put("$y", (y - 225) + "");
406 newNodes.get(v.getKey()).put("data", nodeData);
411 * Update node position
413 * This method is mainly used by the visual topology
415 * @param nodeId - The node to update
416 * @return The node object
418 @RequestMapping(value = "/node/{nodeId}", method = RequestMethod.POST)
420 public Map<String, Object> post(@PathVariable String nodeId, @RequestParam(required = true) String x,
421 @RequestParam(required = true) String y, @RequestParam(required = false) String container,
422 HttpServletRequest request) {
423 String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
425 // Derive the privilege this user has on the current container
426 String userName = request.getUserPrincipal().getName();
427 Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
429 if (privilege != Privilege.WRITE) {
430 return new HashMap<String, Object>(); // silently disregard new node position
433 String id = new String(nodeId);
435 if (!metaCache.get(containerName).containsKey(id)) {
439 Map<String, Object> node = metaCache.get(containerName).get(id);
440 Map<String, String> data = (Map<String, String>) node.get("data");
445 node.put("data", data);
451 * Node object for visual topology
453 protected class NodeBean {
455 protected String name;
456 protected Map<String, String> data;
457 protected List<Map<String, Object>> links;
460 data = new HashMap<String, String>();
461 links = new ArrayList<Map<String, Object>>();
464 public NodeBean(String id, String name, String type) {
468 data.put("$desc", name);
469 data.put("$type", type);
472 public void setLinks(List<Map<String, Object>> links) {
476 public Map<String, Object> out() {
477 Map<String, Object> node = new HashMap<String, Object>();
478 node.put("id", this.id);
479 node.put("name", this.name);
480 node.put("data", this.data);
481 node.put("adjacencies", this.links);
486 public String name() {
496 * Edge object for visual topology
498 protected class EdgeBean {
499 protected NodeConnector source;
500 protected NodeConnector destination;
501 protected Map<String, String> data;
502 protected Long hostId;
505 data = new HashMap<String, String>();
509 * EdgeBean object that includes complete node description
513 * @param headDescription
514 * @param tailDescription
516 public EdgeBean(Edge link, Bandwidth bandwidth, String headDescription,
517 String tailDescription, String headPortDescription, String tailPortDescription) {
519 this.source = link.getHeadNodeConnector();
520 this.destination = link.getTailNodeConnector();
523 data.put("$bandwidth", bandwidth.toString());
524 data.put("$color", bandwidthColor(bandwidth));
525 data.put("$nodeToPort", destination.getID().toString());
526 data.put("$nodeFromPort", source.getID().toString());
527 data.put("$descFrom", headDescription);
528 data.put("$descTo", tailDescription);
529 data.put("$nodeFromPortName", source.toString());
530 data.put("$nodeToPortName", destination.toString());
531 data.put("$nodeFromPortDescription", headPortDescription);
532 data.put("$nodeToPortDescription", tailPortDescription);
535 public EdgeBean(NodeConnector connector, Long hostId) {
538 this.destination = connector;
539 this.hostId = hostId;
541 data.put("$bandwidth", "N/A");
542 data.put("$color", bandwidthColor(new Bandwidth(0)));
543 data.put("$nodeToPort", connector.getNodeConnectorIDString());
544 data.put("$nodeFromPort", connector.getNodeConnectorIDString());
545 data.put("$descTo", "");
546 data.put("$descFrom", "");
547 data.put("$nodeToPortName", "");
548 data.put("$nodeFromPortName", "");
551 public Map<String, Object> out() {
552 Map<String, Object> edge = new HashMap<String, Object>();
554 edge.put("data", data);
555 if (source == null) {
556 edge.put("nodeFrom", String.valueOf(this.hostId));
558 edge.put("nodeFrom", source.getNode().toString());
560 edge.put("nodeTo", destination.getNode().toString());
566 private String bandwidthColor(Bandwidth bandwidth) {
568 long bandwidthValue = bandwidth.getValue();
570 if (bandwidthValue == 0) {
572 } else if (bandwidthValue < Bandwidth.BW1Kbps) {
574 } else if (bandwidthValue < Bandwidth.BW1Mbps) {
576 } else if (bandwidthValue < Bandwidth.BW1Gbps) {
578 } else if (bandwidthValue < Bandwidth.BW1Tbps) {
580 } else if (bandwidthValue < Bandwidth.BW1Pbps) {
588 protected class NodeType {
589 public static final String NODE = "swtch";
590 public static final String HOST = "host";
593 @SuppressWarnings("unchecked")
594 private void loadConfiguration() {
595 ObjectReader objReader = new ObjectReader();
596 metaCache = (Map<String, Map<String, Map<String, Object>>>) objReader.read(this, topologyWebFileName);
597 if (metaCache == null) {
598 metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
603 public Status saveConfiguration() {
604 ObjectWriter objWriter = new ObjectWriter();
605 objWriter.write(metaCache, topologyWebFileName);
606 return new Status(StatusCode.SUCCESS, null);
610 public Object readObject(ObjectInputStream ois)
611 throws FileNotFoundException, IOException, ClassNotFoundException {
612 // Perform the class deserialization locally, from inside the package where the class is defined
613 return ois.readObject();
616 private String getNodeDesc(Node node, ISwitchManager switchManager) {
617 Description desc = (Description) switchManager.getNodeProp(node, Description.propertyName);
618 return (desc == null) ? "" : desc.getValue();