fix some javadoc warnings
[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;
10
11 import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
12 import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Map;
18 import org.apache.commons.collections15.Transformer;
19 import org.opendaylight.transportpce.common.ResponseCodes;
20 import org.opendaylight.transportpce.pce.PceResult.LocalCause;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25
26 public class PceGraph {
27     /* Logging. */
28     private static final Logger LOG = LoggerFactory.getLogger(PceCalculation.class);
29
30     ////////////////////////// for Graph ///////////////////////////
31     private DirectedSparseMultigraph<PceNode, PceLink> nwGraph = new DirectedSparseMultigraph<PceNode, PceLink>();
32     private DijkstraShortestPath<PceNode, PceLink> shortestPath = null;
33
34     // input
35     private Map<NodeId, PceNode> allPceNodes = new HashMap<NodeId, PceNode>();
36     private PceNode apceNode = null;
37     private PceNode zpceNode = null;
38
39     PceConstraints pceHardConstraints;
40     PceConstraints pceSoftConstraints;
41
42     // results
43     private PceResult pceResult = null;
44     private List<PceLink> shortestPathAtoZ = null;
45
46     // TODO hard-coded 96
47     private static final int MAX_WAWELENGTH = 96;
48
49     // for path calculation
50     private List<PceLink> pathAtoZ = null;
51     private int minFoundDistance;
52     private int tmpAtozDistance = 0;
53     private int tmpAtozLatency = 0;
54     private int bestDistance;
55     private boolean noPathExists = false;
56
57     private boolean foundButTooHighLatency = false;
58
59     private List<ListOfNodes> listOfNodesPerWL = new ArrayList<ListOfNodes>();
60
61     public PceGraph(PceNode aendNode, PceNode zendNode, Map<NodeId, PceNode> allPceNodes,
62             PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult pceResult) {
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
71         // TODO - fix the assumption that wavelengths are from 1 to 96 and can be used
72         // as index
73         this.listOfNodesPerWL.add(new ListOfNodes());
74         for (int i = 1; i <= MAX_WAWELENGTH; i++) {
75             // create list of nodes per wavelength
76             ListOfNodes wls = new ListOfNodes();
77             this.listOfNodesPerWL.add(wls);
78         }
79
80         LOG.debug("In GraphCalculator: A and Z = {} / {}", aendNode.toString(), zendNode.toString());
81         LOG.debug("In GraphCalculator: allPceNodes = {}", allPceNodes.toString());
82     }
83
84     public boolean calcPath() {
85
86         LOG.info("In calcPath: metric {} is used ", this.pceHardConstraints.getPceMetrics());
87
88         populateGraph(this.allPceNodes);
89
90         LOG.info(" In PCE GRAPH : QUICK algorithm ");
91
92         // quick algorithm
93         if (runGraph()) {
94
95             this.bestDistance = this.tmpAtozDistance;
96
97             if (chooseWavelength()) {
98                 this.pceResult.setRC(ResponseCodes.RESPONSE_OK);
99                 this.shortestPathAtoZ = this.pathAtoZ;
100                 LOG.info("In GraphCalculator QUICK CalcPath: AtoZ {}", this.pathAtoZ.toString());
101                 LOG.info("In GraphCalculator QUICK CalcPath: pceResult {}", this.pceResult.toString());
102                 return true;
103             }
104
105             // continue work per wavelength
106             LOG.warn(" In PCE GRAPH : QUICK algorithm didn't find shared wavelength over the shortest path");
107
108         }
109
110         LOG.warn(" In PCE GRAPH : QUICK algorithm didn't find shortest path with single wavelength");
111         if (this.noPathExists) {
112             // quick algo looks for path independently on wavelength. therefore no path
113             // means fatal problem
114             LOG.warn(" In PCE GRAPH : QUICK algorithm didn't find any path");
115             this.pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
116             return false;
117         }
118
119         // rearrange all nodes per the relevant wavelength indexes
120         extractWLs(this.allPceNodes);
121
122         this.pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
123         boolean firstPath = true;
124
125         for (int i = 1; i <= MAX_WAWELENGTH; i++) {
126             LOG.info(" In PCE GRAPH : FUll algorithm for WL {}", i);
127             List<PceNode> nodes = this.listOfNodesPerWL.get(i).getNodes();
128             populateGraph(nodes);
129
130             if (!runGraph()) {
131                 continue;
132             }
133
134             if (firstPath) {
135                 // set minFoundDistance for the first time
136                 rememberPath(i);
137                 firstPath = false;
138             }
139
140             if (this.tmpAtozDistance < this.minFoundDistance) {
141                 rememberPath(i);
142             }
143
144             if (this.tmpAtozDistance == this.bestDistance) {
145                 // optimization: stop on the first WL with result == the best
146                 break;
147             }
148         }
149
150         // return codes can come in different orders. this method fixes it a bit
151         // TODO build it better
152         analyzeResult();
153
154         LOG.info("In GraphCalculator FUll CalcPath: pceResult {}", this.pceResult.toString());
155         return (this.pceResult.getStatus());
156     }
157
158     private boolean populateGraph(Map<NodeId, PceNode> allNodes) {
159
160         cleanupGraph();
161         Iterator<Map.Entry<NodeId, PceNode>> nodes = allNodes.entrySet().iterator();
162         while (nodes.hasNext()) {
163             Map.Entry<NodeId, PceNode> node = nodes.next();
164             PceNode pcenode = node.getValue();
165             List<PceLink> links = pcenode.getOutgoingLinks();
166             LOG.info("In populateGraph: use node for graph {}", pcenode.toString());
167             for (PceLink link : links) {
168                 LOG.info("In populateGraph: add edge to graph {}", link.toString());
169                 addLinkToGraph(link);
170             }
171         }
172         return true;
173     }
174
175     private boolean populateGraph(List<PceNode> allNodes) {
176
177         cleanupGraph();
178
179         for (PceNode node : allNodes) {
180             List<PceLink> links = node.getOutgoingLinks();
181             LOG.debug("In populateGraph: use node for graph {}", node.toString());
182             for (PceLink link : links) {
183                 LOG.debug("In populateGraph: add edge to graph {}", link.toString());
184                 addLinkToGraph(link);
185             }
186
187         }
188
189         return true;
190     }
191
192     private boolean runGraph() {
193         LOG.info("In runGraph Vertices: {}; Eges: {} ", this.nwGraph.getVertexCount(), this.nwGraph.getEdgeCount());
194
195         this.pathAtoZ = null;
196
197         try {
198             this.shortestPath = calcAlgo();
199
200             if (this.shortestPath == null) {
201                 this.noPathExists = true;
202                 LOG.error("In runGraph: shortest path alg is null ");// ,
203                 return false;
204             }
205
206             this.pathAtoZ = this.shortestPath.getPath(this.apceNode, this.zpceNode);
207
208             if ((this.pathAtoZ == null) || (this.pathAtoZ.size() == 0)) {
209                 LOG.info("In runGraph: AtoZ path is empty");
210                 this.pceResult.setLocalCause(LocalCause.NO_PATH_EXISTS);
211                 return false;
212             }
213
214             pathMetricsToCompare();
215
216             return compareMaxLatency();
217
218         } catch (IllegalArgumentException e) {
219             LOG.error("In runGraph: can't calculate the path. A or Z node don't have any links {}", e);
220             this.noPathExists = true;
221             return false;
222
223         }
224     }
225
226     private DijkstraShortestPath<PceNode, PceLink> calcAlgo() {
227
228         Transformer<PceLink, Double> wtTransformer = new Transformer<PceLink, Double>() {
229             @Override
230             public Double transform(PceLink link) {
231                 return link.getLatency();
232             }
233         };
234
235         this.shortestPath = null;
236
237         switch (this.pceHardConstraints.getPceMetrics()) {
238             case PropagationDelay:
239                 this.shortestPath = new DijkstraShortestPath<>(this.nwGraph, wtTransformer);
240                 LOG.debug("In calcShortestPath: PropagationDelay method run ");
241                 break;
242             case HopCount:
243                 this.shortestPath = new DijkstraShortestPath<>(this.nwGraph);
244                 LOG.debug("In calcShortestPath: HopCount method run ");
245                 break;
246
247             default:
248                 this.shortestPath = new DijkstraShortestPath<>(this.nwGraph);
249                 LOG.warn("In calcShortestPath: instead IGPMetric/TEMetric method Hop-Count runs as a default ");
250                 break;
251         }
252
253         return this.shortestPath;
254
255     }
256
257     private void addLinkToGraph(PceLink pcelink) {
258
259         PceNode source = this.allPceNodes.get(pcelink.getSourceId());
260         PceNode dest = this.allPceNodes.get(pcelink.getDestId());
261
262         if (source == null) {
263             LOG.error("In addLinkToGraph link source node is null  :   {}", pcelink.toString());
264             return;
265         }
266         if (dest == null) {
267             LOG.error("In addLinkToGraph link dest node is null  :   {}", pcelink.toString());
268             return;
269         }
270
271         LOG.debug("In addLinkToGraph link and nodes :  {} ; {} / {}", pcelink.toString(), source.toString(),
272                 dest.toString());
273         this.nwGraph.addEdge(pcelink, source, dest);
274
275     }
276
277     /*
278      * "QUICK" approach build shortest path. and then look for a single wavelength
279      * on it
280      */
281     private boolean chooseWavelength() {
282         for (long i = 1; i <= MAX_WAWELENGTH; i++) {
283             boolean completed = true;
284             for (PceLink link : this.pathAtoZ) {
285                 PceNode pceNode = this.allPceNodes.get(link.getSourceId());
286                 if (!pceNode.checkWL(i)) {
287                     completed = false;
288                     break;
289                 }
290             }
291             if (completed) {
292                 this.pceResult.setResultWavelength(i);
293                 break;
294             }
295         }
296         return (this.pceResult.getResultWavelength() > 0);
297     }
298
299     public List<PceLink> getPathAtoZ() {
300         return this.shortestPathAtoZ;
301     }
302
303     public PceResult getReturnStructure() {
304         return this.pceResult;
305     }
306
307     // TODO build ordered set ordered per the index. Current assumption is that
308     // wavelenght serves as an index
309     private class ListOfNodes {
310         private List<PceNode> listOfNodes = new ArrayList<PceNode>();
311
312         private void addNodetoWL(PceNode node) {
313             this.listOfNodes.add(node);
314         }
315
316         private List<PceNode> getNodes() {
317             return this.listOfNodes;
318         }
319
320     }
321
322     private boolean extractWLs(Map<NodeId, PceNode> allNodes) {
323
324         Iterator<Map.Entry<NodeId, PceNode>> nodes = allNodes.entrySet().iterator();
325         while (nodes.hasNext()) {
326
327             Map.Entry<NodeId, PceNode> node = nodes.next();
328
329             PceNode pcenode = node.getValue();
330             List<Long> wls = pcenode.getAvailableWLs();
331
332             LOG.debug("In extractWLs wls in node : {} {}", pcenode.toString(), wls.size());
333             LOG.debug("In extractWLs listOfWLs total :   {}", this.listOfNodesPerWL.size());
334             for (Long i : wls) {
335                 LOG.debug("In extractWLs i in wls :  {}", i);
336                 ListOfNodes lwl = this.listOfNodesPerWL.get(i.intValue());
337                 lwl.addNodetoWL(pcenode);
338             }
339         }
340
341         return true;
342     }
343
344     private void cleanupGraph() {
345         LOG.debug("In cleanupGraph remove {} nodes ", this.nwGraph.getEdgeCount());
346         Iterable<PceNode> toRemove = new ArrayList<PceNode>(this.nwGraph.getVertices());
347         for (PceNode node : toRemove) {
348             this.nwGraph.removeVertex(node);
349         }
350         LOG.debug("In cleanupGraph after {} removed ", this.nwGraph.getEdgeCount());
351     }
352
353     private void analyzeResult() {
354         // very simple for the start
355
356         if (this.pceResult.getStatus()) {
357             return;
358         }
359
360         // if request is rejected but at least once there was path found, try to save
361         // the real reason of reject
362         if (this.foundButTooHighLatency) {
363             this.pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
364             this.pceResult.setLocalCause(LocalCause.TOO_HIGH_LATENCY);
365             this.pceResult.setCalcMessage("No path available due to constraint Hard/Latency");
366         }
367         return;
368     }
369
370     private boolean compareMaxLatency() {
371
372         Long latencyConstraint = this.pceHardConstraints.getMaxLatency();
373
374         if ((latencyConstraint > 0) && (this.tmpAtozLatency > latencyConstraint)) {
375             this.foundButTooHighLatency = true;
376             this.pceResult.setLocalCause(LocalCause.TOO_HIGH_LATENCY);
377             LOG.info("In validateLatency: AtoZ path has too high LATENCY {} > {}", this.tmpAtozLatency,
378                 latencyConstraint);
379             return false;
380         }
381         LOG.info("In validateLatency: AtoZ path  is {}", this.pathAtoZ.toString());
382         return true;
383     }
384
385     private void pathMetricsToCompare() {
386
387         this.tmpAtozDistance = this.shortestPath.getDistance(this.apceNode, this.zpceNode).intValue();
388
389         // TODO this code is for HopCount. excluded from switch for not implemented
390         // IGPMetric and TEMetric
391         this.tmpAtozLatency = 0;
392         for (PceLink pcelink : this.pathAtoZ) {
393             this.tmpAtozLatency = this.tmpAtozLatency + pcelink.getLatency().intValue();
394         }
395
396         switch (this.pceHardConstraints.getPceMetrics()) {
397             case IGPMetric:
398                 // TODO implement IGPMetric - low priority
399                 LOG.error("In PceGraph not implemented IGPMetric. HopCount works as a default");
400                 break;
401
402             case TEMetric:
403                 // TODO implement TEMetric - low priority
404                 LOG.error("In PceGraph not implemented TEMetric. HopCount works as a default");
405                 break;
406
407             case HopCount:
408                 break;
409
410             case PropagationDelay:
411                 this.tmpAtozLatency = this.tmpAtozDistance;
412                 break;
413
414             default:
415                 LOG.error("In PceGraph {}: unknown metric. ", this.pceHardConstraints.getPceMetrics());
416                 break;
417         }
418
419         LOG.info("In runGraph: AtoZ size {}, distance {}, latency {} ", this.pathAtoZ.size(), this.tmpAtozDistance,
420                 this.tmpAtozLatency);
421         LOG.debug("In runGraph: AtoZ {}", this.pathAtoZ.toString());
422
423         return;
424     }
425
426     private void rememberPath(int index) {
427         this.minFoundDistance = this.tmpAtozDistance;
428         this.shortestPathAtoZ = this.pathAtoZ;
429         this.pceResult.setResultWavelength(Long.valueOf(index));
430         this.pceResult.setRC(ResponseCodes.RESPONSE_OK);
431         LOG.info("In GraphCalculator FUll CalcPath for wl [{}]: found AtoZ {}", index, this.pathAtoZ.toString());
432
433     }
434
435     public void setConstrains(PceConstraints pceHardConstraintsIn, PceConstraints pceSoftConstraintsIn) {
436         this.pceHardConstraints = pceHardConstraintsIn;
437         this.pceSoftConstraints = pceSoftConstraintsIn;
438     }
439
440 }