Supporting new paths computed by GNPy
[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
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class PceGraph {
33     /* Logging. */
34     private static final Logger LOG = LoggerFactory.getLogger(PceGraph.class);
35
36     ////////////////////////// for Graph ///////////////////////////
37     // how many paths to bring
38     int kpathsToBring = 10;
39     // max #hops
40     int mhopsPerPath = 50;
41
42     // input
43     private Map<NodeId, PceNode> allPceNodes = new HashMap<NodeId, PceNode>();
44     private PceNode apceNode = null;
45     private PceNode zpceNode = null;
46
47     PceConstraints pceHardConstraints;
48     PceConstraints pceSoftConstraints;
49
50     // results
51     private PceResult pceResult = null;
52     private List<PceLink> shortestPathAtoZ = null;
53
54     // for path calculation
55     List<GraphPath<String, PceGraphEdge>> allWPaths = null;
56
57     private List<PceLink> pathAtoZ = new ArrayList<PceLink>();
58
59     public PceGraph(PceNode aendNode, PceNode zendNode, Map<NodeId, PceNode> allPceNodes,
60             PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult pceResult) {
61         super();
62         this.apceNode = aendNode;
63         this.zpceNode = zendNode;
64         this.allPceNodes = allPceNodes;
65         this.pceResult = pceResult;
66         this.pceHardConstraints = pceHardConstraints;
67         this.pceSoftConstraints = pceSoftConstraints;
68
69         LOG.info("In GraphCalculator: A and Z = {} / {} ", aendNode.toString(), zendNode.toString());
70         LOG.debug("In GraphCalculator: allPceNodes size {}, nodes {} ", allPceNodes.size(), allPceNodes.toString());
71
72     }
73
74     public boolean calcPath() {
75
76         LOG.info(" In PCE GRAPH calcPath : K SHORT PATHS algorithm ");
77
78         DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph =
79                 new DefaultDirectedWeightedGraph<String, PceGraphEdge>(PceGraphEdge.class);
80         populateWithNodes(weightedGraph);
81         populateWithLinks(weightedGraph);
82
83         if (!runKgraphs(weightedGraph)) {
84             LOG.info("In calcPath : pceResult {}", pceResult.toString());
85             return false;
86         }
87
88         // validate found paths
89         pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
90         for (GraphPath<String, PceGraphEdge> path : allWPaths) {
91
92             PostAlgoPathValidator papv = new PostAlgoPathValidator();
93             pceResult = papv.checkPath(path, allPceNodes, pceResult);
94             LOG.info("In calcPath after PostAlgoPathValidator {} {}",
95                     pceResult.getResponseCode(), ResponseCodes.RESPONSE_OK);
96
97             if (!pceResult.getResponseCode().equals(ResponseCodes.RESPONSE_OK)) {
98                 LOG.info("In calcPath: post algo validations DROPPED the path {}", path.toString());
99                 continue;
100             }
101
102             // build pathAtoZ
103             pathAtoZ.clear();
104             for (PceGraphEdge edge : path.getEdgeList()) {
105                 pathAtoZ.add(edge.link());
106             }
107
108             shortestPathAtoZ = new ArrayList<>(pathAtoZ);
109             LOG.info("In calcPath Path FOUND path for wl [{}], hops {}, distance per metrics {}, path AtoZ {}",
110                     pceResult.getResultWavelength(), pathAtoZ.size(), path.getWeight(), pathAtoZ.toString());
111             break;
112         }
113
114         if (shortestPathAtoZ != null) {
115             LOG.info("In calcPath CHOOSEN PATH for wl [{}], hops {}, path AtoZ {}",
116                     pceResult.getResultWavelength(), shortestPathAtoZ.size(), shortestPathAtoZ.toString());
117         }
118         LOG.info("In calcPath : pceResult {}", pceResult.toString());
119         return (pceResult.getStatus());
120     }
121
122     private boolean runKgraphs(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
123
124         if (weightedGraph.edgeSet().isEmpty() || weightedGraph.vertexSet().isEmpty()) {
125             return false;
126         }
127
128         PathValidator<String, PceGraphEdge> wpv = new InAlgoPathValidator(pceHardConstraints, zpceNode);
129
130         // local optimization. if 'include' constraint exists then increase amount of paths to return.
131         // it's because this constraint is checked at the last step when part of good paths
132         // are dropped by other constraints
133         if (!pceHardConstraints.getListToInclude().isEmpty()) {
134             kpathsToBring = kpathsToBring * 10;
135             LOG.info("k = {}",kpathsToBring);
136         }
137
138         // KShortestPaths on weightedGraph
139         KShortestSimplePaths<String, PceGraphEdge> swp =
140             new KShortestSimplePaths<String, PceGraphEdge>(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.info("path Weight: {} : {}", path.getWeight(), path.getVertexList().toString());
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.toString());
165             return false;
166         }
167         if (dest == null) {
168             LOG.error("In addLinkToGraph link dest node is null : {}", pcelink.toString());
169             return false;
170         }
171         LOG.debug("In addLinkToGraph link to nodes : {}{} {}", pcelink.toString(), source.toString(), dest.toString());
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().toString());
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.toString());
195
196             for (PceLink link : links) {
197                 LOG.debug("In populateGraph node {} : add edge to graph {}", pcenode.toString(), link.toString());
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
214         // HopCount is default
215         double weight = 1;
216         switch (pceHardConstraints.getPceMetrics()) {
217             case IGPMetric :
218                 // TODO implement IGPMetric - low priority.
219                 LOG.warn("In PceGraph not implemented IGPMetric. HopCount works as a default");
220                 break;
221
222             case TEMetric :
223                 // TODO implement TEMetric - low priority
224                 LOG.warn("In PceGraph not implemented TEMetric. HopCount works as a default");
225                 break;
226
227             case HopCount :
228                 weight = 1;
229                 LOG.debug("In PceGraph HopCount is used as a metrics. {}", link.toString());
230                 break;
231
232             case PropagationDelay :
233                 weight = link.getLatency();
234                 LOG.debug("In PceGraph PropagationDelay is used as a metrics. {}", link.toString());
235                 break;
236
237             default:
238                 break;
239         }
240
241         return weight;
242     }
243
244     ////////////////////////////////////////////////////////////////////////////////////////////////////////////
245     public List<PceLink> getPathAtoZ() {
246         return shortestPathAtoZ;
247     }
248
249     public PceResult getReturnStructure() {
250         return pceResult;
251     }
252
253     public void setConstrains(PceConstraints pceHardConstraintsInput, PceConstraints pceSoftConstraintsInput) {
254         this.pceHardConstraints = pceHardConstraintsInput;
255         this.pceSoftConstraints = pceSoftConstraintsInput;
256     }
257
258 }