3f2210b530a8b0c9874a29f4049d7c892f4a796d
[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     private int kpathsToBring = 10;
39
40     // max #hops
41     private int mhopsPerPath = 50;
42
43     // input
44     private Map<NodeId, PceNode> allPceNodes = new HashMap<NodeId, PceNode>();
45     private PceNode apceNode = null;
46     private PceNode zpceNode = null;
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<PceLink>();
59
60     public PceGraph(PceNode aendNode, PceNode zendNode, Map<NodeId, PceNode> allPceNodes,
61             PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult pceResult) {
62         super();
63         this.apceNode = aendNode;
64         this.zpceNode = zendNode;
65         this.allPceNodes = allPceNodes;
66         this.pceResult = pceResult;
67         this.pceHardConstraints = pceHardConstraints;
68         this.pceSoftConstraints = pceSoftConstraints;
69
70         LOG.info("In GraphCalculator: A and Z = {} / {} ", aendNode.toString(), zendNode.toString());
71         LOG.debug("In GraphCalculator: allPceNodes size {}, nodes {} ", allPceNodes.size(), allPceNodes.toString());
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             PostAlgoPathValidator papv = new PostAlgoPathValidator();
92             pceResult = papv.checkPath(path, allPceNodes, pceResult, pceHardConstraints);
93             LOG.info("In calcPath after PostAlgoPathValidator {} {}",
94                     pceResult.getResponseCode(), ResponseCodes.RESPONSE_OK);
95
96             if (!pceResult.getResponseCode().equals(ResponseCodes.RESPONSE_OK)) {
97                 LOG.info("In calcPath: post algo validations DROPPED the path {}", path.toString());
98                 continue;
99             }
100
101             // build pathAtoZ
102             pathAtoZ.clear();
103             for (PceGraphEdge edge : path.getEdgeList()) {
104                 pathAtoZ.add(edge.link());
105             }
106
107             shortestPathAtoZ = new ArrayList<>(pathAtoZ);
108             LOG.info("In calcPath Path FOUND path for wl [{}], hops {}, distance per metrics {}, path AtoZ {}",
109                     pceResult.getResultWavelength(), pathAtoZ.size(), path.getWeight(), pathAtoZ.toString());
110             break;
111         }
112
113         if (shortestPathAtoZ != null) {
114             LOG.info("In calcPath CHOOSEN PATH for wl [{}], hops {}, path AtoZ {}",
115                     pceResult.getResultWavelength(), shortestPathAtoZ.size(), shortestPathAtoZ.toString());
116         }
117         LOG.info("In calcPath : pceResult {}", pceResult.toString());
118         return (pceResult.getStatus());
119     }
120
121     private boolean runKgraphs(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
122
123         if (weightedGraph.edgeSet().isEmpty() || weightedGraph.vertexSet().isEmpty()) {
124             return false;
125         }
126         PathValidator<String, PceGraphEdge> wpv = new InAlgoPathValidator();
127
128         // KShortestPaths on weightedGraph
129         KShortestSimplePaths<String, PceGraphEdge> swp =
130             new KShortestSimplePaths<String, PceGraphEdge>(weightedGraph, mhopsPerPath, wpv);
131         allWPaths = swp.getPaths(apceNode.getNodeId().getValue(), zpceNode.getNodeId().getValue(), kpathsToBring);
132
133         if (allWPaths.isEmpty()) {
134             LOG.info(" In runKgraphs : algorithm didn't find any path");
135             pceResult.setLocalCause(LocalCause.NO_PATH_EXISTS);
136             pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
137             return false;
138         }
139
140         // debug print
141         for (GraphPath<String, PceGraphEdge> path : allWPaths) {
142             LOG.debug("path Weight: {} : {}", path.getWeight(), path.getVertexList().toString());
143         }
144
145         return true;
146     }
147
148     private boolean validateLinkforGraph(PceLink pcelink) {
149
150         PceNode source = allPceNodes.get(pcelink.getSourceId());
151         PceNode dest = allPceNodes.get(pcelink.getDestId());
152
153         if (source == null) {
154             LOG.error("In addLinkToGraph link source node is null : {}", pcelink.toString());
155             return false;
156         }
157         if (dest == null) {
158             LOG.error("In addLinkToGraph link dest node is null : {}", pcelink.toString());
159             return false;
160         }
161         LOG.debug("In addLinkToGraph link to nodes : {}{} {}", pcelink.toString(), source.toString(), dest.toString());
162         return true;
163     }
164
165     private void populateWithNodes(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
166         Iterator<Map.Entry<NodeId, PceNode>> nodes = allPceNodes.entrySet().iterator();
167         while (nodes.hasNext()) {
168             Map.Entry<NodeId, PceNode> node = nodes.next();
169             weightedGraph.addVertex(node.getValue().getNodeId().getValue());
170             LOG.debug("In populateWithNodes in node :  {}", node.getValue().toString());
171         }
172     }
173
174     private boolean populateWithLinks(DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph) {
175
176         Iterator<Map.Entry<NodeId, PceNode>> nodes = allPceNodes.entrySet().iterator();
177         while (nodes.hasNext()) {
178
179             Map.Entry<NodeId, PceNode> node = nodes.next();
180
181             PceNode pcenode = node.getValue();
182             List<PceLink> links = pcenode.getOutgoingLinks();
183
184             LOG.debug("In populateGraph: use node for graph {}", pcenode.toString());
185
186             for (PceLink link : links) {
187                 LOG.debug("In populateGraph node {} : add edge to graph {}", pcenode.toString(), link.toString());
188
189                 if (!validateLinkforGraph(link)) {
190                     continue;
191                 }
192
193                 PceGraphEdge graphLink = new PceGraphEdge(link);
194                 weightedGraph.addEdge(link.getSourceId().getValue(), link.getDestId().getValue(), graphLink);
195
196                 weightedGraph.setEdgeWeight(graphLink, chooseWeight(link));
197             }
198         }
199         return true;
200     }
201
202     private double chooseWeight(PceLink link) {
203
204         // HopCount is default
205         double weight = 1;
206         switch (pceHardConstraints.getPceMetrics()) {
207             case IGPMetric :
208                 // TODO implement IGPMetric - low priority.
209                 LOG.warn("In PceGraph not implemented IGPMetric. HopCount works as a default");
210                 break;
211
212             case TEMetric :
213                 // TODO implement TEMetric - low priority
214                 LOG.warn("In PceGraph not implemented TEMetric. HopCount works as a default");
215                 break;
216
217             case HopCount :
218                 weight = 1;
219                 LOG.debug("In PceGraph HopCount is used as a metrics. {}", link.toString());
220                 break;
221
222             case PropagationDelay :
223                 weight = link.getLatency();
224                 LOG.debug("In PceGraph PropagationDelay is used as a metrics. {}", link.toString());
225                 break;
226
227             default:
228                 break;
229         }
230
231         return weight;
232     }
233
234     public int getKpathsToBring() {
235         return kpathsToBring;
236     }
237
238     public void setKpathsToBring(int kpathsToBring) {
239         this.kpathsToBring = kpathsToBring;
240     }
241
242     public void setMhopsPerPath(int mhopsPerPath) {
243         this.mhopsPerPath = mhopsPerPath;
244     }
245
246     public List<PceLink> getPathAtoZ() {
247         return shortestPathAtoZ;
248     }
249
250     public PceResult getReturnStructure() {
251         return pceResult;
252     }
253
254     public void setConstrains(PceConstraints pceHardConstraintsInput, PceConstraints pceSoftConstraintsInput) {
255         this.pceHardConstraints = pceHardConstraintsInput;
256         this.pceSoftConstraints = pceSoftConstraintsInput;
257     }
258
259 }