Merge "Master branch is now Aluminium"
[transportpce.git] / pce / src / main / java / org / opendaylight / transportpce / pce / graph / PceGraph.java
1 /*
2  * Copyright © 2017 AT&T, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.transportpce.pce.graph;
10
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.List;
15 import java.util.Map;
16
17 import org.jgrapht.GraphPath;
18 import org.jgrapht.alg.shortestpath.KShortestSimplePaths;
19 import org.jgrapht.alg.shortestpath.PathValidator;
20 import org.jgrapht.graph.DefaultDirectedWeightedGraph;
21 import org.opendaylight.transportpce.common.ResponseCodes;
22 import org.opendaylight.transportpce.pce.constraints.PceConstraints;
23 import org.opendaylight.transportpce.pce.networkanalyzer.PceLink;
24 import org.opendaylight.transportpce.pce.networkanalyzer.PceNode;
25 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult;
26 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult.LocalCause;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public class PceGraph {
32     /* Logging. */
33     private static final Logger LOG = LoggerFactory.getLogger(PceGraph.class);
34
35     ////////////////////////// for Graph ///////////////////////////
36     // how many paths to bring
37     private int kpathsToBring = 10;
38
39     // max #hops
40     private int mhopsPerPath = 50;
41
42     // input
43     private Map<NodeId, PceNode> allPceNodes = new HashMap<>();
44     private PceNode apceNode = null;
45     private PceNode zpceNode = null;
46     private String serviceType = "";
47
48     PceConstraints pceHardConstraints;
49     PceConstraints pceSoftConstraints;
50
51     // results
52     private PceResult pceResult = null;
53     private List<PceLink> shortestPathAtoZ = null;
54
55     // for path calculation
56     List<GraphPath<String, PceGraphEdge>> allWPaths = null;
57
58     private List<PceLink> pathAtoZ = new ArrayList<>();
59
60     public PceGraph(PceNode aendNode, PceNode zendNode, Map<NodeId, PceNode> allPceNodes,
61             PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult pceResult,
62             String serviceType) {
63         super();
64         this.apceNode = aendNode;
65         this.zpceNode = zendNode;
66         this.allPceNodes = allPceNodes;
67         this.pceResult = pceResult;
68         this.pceHardConstraints = pceHardConstraints;
69         this.pceSoftConstraints = pceSoftConstraints;
70         this.serviceType = serviceType;
71
72         LOG.info("In GraphCalculator: A and Z = {} / {} ", aendNode, zendNode);
73         LOG.debug("In GraphCalculator: allPceNodes size {}, nodes {} ", allPceNodes.size(), allPceNodes);
74     }
75
76     public boolean calcPath() {
77
78         LOG.info(" In PCE GRAPH calcPath : K SHORT PATHS algorithm ");
79
80         DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph =
81                 new DefaultDirectedWeightedGraph<>(PceGraphEdge.class);
82         populateWithNodes(weightedGraph);
83         populateWithLinks(weightedGraph);
84
85         if (!runKgraphs(weightedGraph)) {
86             LOG.info("In calcPath : pceResult {}", pceResult);
87             return false;
88         }
89
90         // validate found paths
91         pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
92         for (GraphPath<String, PceGraphEdge> path : allWPaths) {
93             PostAlgoPathValidator papv = new PostAlgoPathValidator();
94             pceResult = papv.checkPath(path, allPceNodes, pceResult, pceHardConstraints, serviceType);
95             LOG.info("In calcPath after PostAlgoPathValidator {} {}",
96                     pceResult.getResponseCode(), ResponseCodes.RESPONSE_OK);
97
98             if (!pceResult.getResponseCode().equals(ResponseCodes.RESPONSE_OK)) {
99                 LOG.info("In calcPath: post algo validations DROPPED the path {}", path);
100                 continue;
101             }
102
103             // build pathAtoZ
104             pathAtoZ.clear();
105             for (PceGraphEdge edge : path.getEdgeList()) {
106                 pathAtoZ.add(edge.link());
107             }
108
109             shortestPathAtoZ = new ArrayList<>(pathAtoZ);
110             if (("100GE".equals(serviceType)) || ("OTU4".equals(serviceType))) {
111                 LOG.info("In calcPath Path FOUND path for wl [{}], hops {}, distance per metrics {}, path AtoZ {}",
112                         pceResult.getResultWavelength(), pathAtoZ.size(), path.getWeight(), pathAtoZ);
113                 break;
114             } else {
115                 // Service is at OTN layer and is relying on a supporting wavelength service
116                 LOG.info("In calcPath Path FOUND path for hops {}, distance per metrics {}, path AtoZ {}",
117                         pathAtoZ.size(), path.getWeight(), pathAtoZ);
118                 break;
119             }
120
121         }
122
123         if (shortestPathAtoZ != null) {
124             LOG.info("In calcPath CHOOSEN PATH for wl [{}], hops {}, path AtoZ {}",
125                     pceResult.getResultWavelength(), shortestPathAtoZ.size(), shortestPathAtoZ);
126         }
127         LOG.info("In calcPath : pceResult {}", pceResult);
128         return (pceResult.getStatus());
129     }
130
131     private boolean runKgraphs(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
132
133         if (weightedGraph.edgeSet().isEmpty() || weightedGraph.vertexSet().isEmpty()) {
134             return false;
135         }
136         PathValidator<String, PceGraphEdge> wpv = new InAlgoPathValidator();
137
138         // KShortestPaths on weightedGraph
139         KShortestSimplePaths<String, PceGraphEdge> swp =
140             new KShortestSimplePaths<>(weightedGraph, mhopsPerPath, wpv);
141         allWPaths = swp.getPaths(apceNode.getNodeId().getValue(), zpceNode.getNodeId().getValue(), kpathsToBring);
142
143         if (allWPaths.isEmpty()) {
144             LOG.info(" In runKgraphs : algorithm didn't find any path");
145             pceResult.setLocalCause(LocalCause.NO_PATH_EXISTS);
146             pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
147             return false;
148         }
149
150         // debug print
151         for (GraphPath<String, PceGraphEdge> path : allWPaths) {
152             LOG.debug("path Weight: {} : {}", path.getWeight(), path.getVertexList());
153         }
154
155         return true;
156     }
157
158     private boolean validateLinkforGraph(PceLink pcelink) {
159
160         PceNode source = allPceNodes.get(pcelink.getSourceId());
161         PceNode dest = allPceNodes.get(pcelink.getDestId());
162
163         if (source == null) {
164             LOG.error("In addLinkToGraph link source node is null : {}", pcelink);
165             return false;
166         }
167         if (dest == null) {
168             LOG.error("In addLinkToGraph link dest node is null : {}", pcelink);
169             return false;
170         }
171         LOG.debug("In addLinkToGraph link to nodes : {}{} {}", pcelink, source, dest);
172         return true;
173     }
174
175     private void populateWithNodes(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
176         Iterator<Map.Entry<NodeId, PceNode>> nodes = allPceNodes.entrySet().iterator();
177         while (nodes.hasNext()) {
178             Map.Entry<NodeId, PceNode> node = nodes.next();
179             weightedGraph.addVertex(node.getValue().getNodeId().getValue());
180             LOG.debug("In populateWithNodes in node :  {}", node.getValue());
181         }
182     }
183
184     private boolean populateWithLinks(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
185
186         Iterator<Map.Entry<NodeId, PceNode>> nodes = allPceNodes.entrySet().iterator();
187         while (nodes.hasNext()) {
188
189             Map.Entry<NodeId, PceNode> node = nodes.next();
190
191             PceNode pcenode = node.getValue();
192             List<PceLink> links = pcenode.getOutgoingLinks();
193
194             LOG.debug("In populateGraph: use node for graph {}", pcenode);
195
196             for (PceLink link : links) {
197                 LOG.debug("In populateGraph node {} : add edge to graph {}", pcenode, link);
198
199                 if (!validateLinkforGraph(link)) {
200                     continue;
201                 }
202
203                 PceGraphEdge graphLink = new PceGraphEdge(link);
204                 weightedGraph.addEdge(link.getSourceId().getValue(), link.getDestId().getValue(), graphLink);
205
206                 weightedGraph.setEdgeWeight(graphLink, chooseWeight(link));
207             }
208         }
209         return true;
210     }
211
212     private double chooseWeight(PceLink link) {
213         // HopCount is default
214         double weight = 1;
215         switch (pceHardConstraints.getPceMetrics()) {
216             case HopCount :
217                 weight = 1;
218                 LOG.debug("In PceGraph HopCount is used as a metrics. {}", link);
219                 break;
220             case PropagationDelay :
221                 weight = link.getLatency();
222                 LOG.debug("In PceGraph PropagationDelay is used as a metrics. {}", link);
223                 if ((("1GE".equals(serviceType)) || ("10GE".equals(serviceType)) || ("ODU4".equals(serviceType)))
224                         && (weight == 0)) {
225                     LOG.warn("PropagationDelay set as metric, but latency is null: is latency set for OTN link {}?",
226                         link);
227                 }
228                 break;
229             // TODO implement IGPMetric and TEMetric - low priority.
230             case IGPMetric :
231             case TEMetric :
232             default:
233                 LOG.warn("In PceGraph {} not implemented. HopCount works as a default",
234                     pceHardConstraints.getPceMetrics());
235                 break;
236         }
237         return weight;
238     }
239
240     public int getKpathsToBring() {
241         return kpathsToBring;
242     }
243
244     public void setKpathsToBring(int kpathsToBring) {
245         this.kpathsToBring = kpathsToBring;
246     }
247
248     public void setMhopsPerPath(int mhopsPerPath) {
249         this.mhopsPerPath = mhopsPerPath;
250     }
251
252     public List<PceLink> getPathAtoZ() {
253         return shortestPathAtoZ;
254     }
255
256     public PceResult getReturnStructure() {
257         return pceResult;
258     }
259
260     public void setConstrains(PceConstraints pceHardConstraintsInput, PceConstraints pceSoftConstraintsInput) {
261         this.pceHardConstraints = pceHardConstraintsInput;
262         this.pceSoftConstraints = pceSoftConstraintsInput;
263     }
264 }