Bump jgrapht upstream dependency to 1.5.2
[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 import java.util.Map.Entry;
17 import java.util.function.Function;
18 import java.util.stream.Collectors;
19 import java.util.stream.IntStream;
20 import org.jgrapht.Graph;
21 import org.jgrapht.GraphPath;
22 import org.jgrapht.alg.shortestpath.PathValidator;
23 import org.jgrapht.alg.shortestpath.YenKShortestPath;
24 import org.jgrapht.graph.DefaultDirectedWeightedGraph;
25 import org.opendaylight.transportpce.common.ResponseCodes;
26 import org.opendaylight.transportpce.common.StringConstants;
27 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
28 import org.opendaylight.transportpce.pce.constraints.PceConstraints;
29 import org.opendaylight.transportpce.pce.networkanalyzer.PceLink;
30 import org.opendaylight.transportpce.pce.networkanalyzer.PceNode;
31 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult;
32 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult.LocalCause;
33 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev230925.PceConstraintMode;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev191129.State;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.LinkId;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class PceGraph {
41     /* Logging. */
42     private static final Logger LOG = LoggerFactory.getLogger(PceGraph.class);
43
44     ////////////////////////// for Graph ///////////////////////////
45     // how many paths to bring
46     private int kpathsToBring = 15;
47
48     // input
49     private Map<NodeId, PceNode> allPceNodes = new HashMap<>();
50     private Map<LinkId, PceLink> allPceLinks = new HashMap<>();
51     private PceNode apceNode = null;
52     private PceNode zpceNode = null;
53     private String serviceType = "";
54     private Double margin = null;
55     PceConstraints pceHardConstraints;
56     PceConstraints pceSoftConstraints;
57     private PceConstraintMode pceConstraintMode;
58
59     // results
60     private PceResult pceResult = null;
61     private List<PceLink> shortestPathAtoZ = null;
62
63     // for path calculation
64     Map<Integer, GraphPath<String, PceGraphEdge>> allWPaths = null;
65
66     private List<PceLink> pathAtoZ = new ArrayList<>();
67
68     private final NetworkTransactionService networkTransactionService;
69
70     public PceGraph(PceNode aendNode, PceNode zendNode, Map<NodeId, PceNode> allPceNodes,
71             Map<LinkId, PceLink> allPceLinks, PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints,
72             PceResult pceResult, String serviceType, NetworkTransactionService networkTransactionService,
73             PceConstraintMode mode) {
74         super();
75         this.apceNode = aendNode;
76         this.zpceNode = zendNode;
77         this.allPceNodes = allPceNodes;
78         this.allPceLinks = allPceLinks;
79         this.pceResult = pceResult;
80         this.pceHardConstraints = pceHardConstraints;
81         this.pceSoftConstraints = pceSoftConstraints;
82         this.serviceType = serviceType;
83         this.networkTransactionService = networkTransactionService;
84         this.pceConstraintMode = mode;
85
86         LOG.info("In GraphCalculator: A and Z = {} / {} ", aendNode, zendNode);
87         LOG.debug("In GraphCalculator: allPceNodes size {}, nodes {} ", allPceNodes.size(), allPceNodes);
88     }
89
90     public boolean calcPath() {
91
92         LOG.info(" In PCE GRAPH calcPath : K SHORT PATHS algorithm ");
93
94         Graph<String, PceGraphEdge> weightedGraph =
95                 new DefaultDirectedWeightedGraph<>(PceGraphEdge.class);
96         populateWithNodes(weightedGraph);
97         populateWithLinks(weightedGraph);
98
99         if (!runKgraphs(weightedGraph)) {
100             LOG.error("In calcPath : pceResult {}", pceResult);
101             return false;
102         }
103         // validate found paths
104         pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
105         for (Entry<Integer, GraphPath<String, PceGraphEdge>> entry : allWPaths.entrySet()) {
106             GraphPath<String, PceGraphEdge> path = entry.getValue();
107             LOG.info("validating path n° {} - {}", entry.getKey(), path.getVertexList());
108             PostAlgoPathValidator papv = new PostAlgoPathValidator(networkTransactionService);
109             pceResult = papv.checkPath(
110                     path, allPceNodes, allPceLinks, pceResult, pceHardConstraints, serviceType, pceConstraintMode);
111             this.margin = papv.getTpceCalculatedMargin();
112             if (ResponseCodes.RESPONSE_OK.equals(pceResult.getResponseCode())) {
113                 LOG.info("Path is validated");
114             } else {
115                 LOG.warn("In calcPath: post algo validations DROPPED the path {}; for following cause: {}",
116                     path, pceResult.getLocalCause());
117                 continue;
118             }
119
120             // build pathAtoZ
121             pathAtoZ.clear();
122             for (PceGraphEdge edge : path.getEdgeList()) {
123                 pathAtoZ.add(edge.link());
124             }
125
126             shortestPathAtoZ = new ArrayList<>(pathAtoZ);
127             switch (serviceType) {
128
129                 case StringConstants.SERVICE_TYPE_100GE_T:
130                 case StringConstants.SERVICE_TYPE_OTUC2:
131                 case StringConstants.SERVICE_TYPE_OTUC3:
132                 case StringConstants.SERVICE_TYPE_OTUC4:
133                 case StringConstants.SERVICE_TYPE_400GE:
134                 case StringConstants.SERVICE_TYPE_OTU4:
135                     LOG.debug(
136                         "In calcPath Path FOUND path for wl [{}], min Freq assignment {}, max Freq assignment {},"
137                         + " hops {}, distance per metrics {}, path AtoZ {}",
138                         pceResult.getResultWavelength(), pceResult.getMinFreq(), pceResult.getMaxFreq(),
139                         pathAtoZ.size(), path.getWeight(), pathAtoZ);
140                     break;
141
142                 default:
143                     LOG.debug(
144                         "In calcPath Path FOUND path for hops {}, distance per metrics {}, path AtoZ {}",
145                         pathAtoZ.size(), path.getWeight(), pathAtoZ);
146                     break;
147             }
148             break;
149
150         }
151
152         if (shortestPathAtoZ != null) {
153             LOG.info("In calcPath CHOOSEN PATH for wl [{}], min freq {}, max freq {}, hops {}, path AtoZ {}",
154                     pceResult.getResultWavelength(), pceResult.getMinFreq(), pceResult.getMaxFreq(),
155                     shortestPathAtoZ.size(), shortestPathAtoZ);
156         }
157         LOG.info("In calcPath : pceResult {}", pceResult);
158         return (pceResult.getStatus());
159     }
160
161     private boolean runKgraphs(Graph<String, PceGraphEdge> weightedGraph) {
162
163         if (weightedGraph.edgeSet().isEmpty() || weightedGraph.vertexSet().isEmpty()) {
164             return false;
165         }
166         PathValidator<String, PceGraphEdge> wpv = new InAlgoPathValidator();
167
168         // YenShortestPath on weightedGraph
169         YenKShortestPath<String, PceGraphEdge> swp = new YenKShortestPath<>(weightedGraph, wpv);
170         List<GraphPath<String, PceGraphEdge>> weightedPathList = swp
171             .getPaths(apceNode.getNodeId().getValue(), zpceNode.getNodeId().getValue(), kpathsToBring);
172         allWPaths = IntStream
173             .range(0, weightedPathList.size())
174             .boxed()
175             .collect(Collectors.toMap(Function.identity(), weightedPathList::get));
176
177         if (allWPaths.isEmpty()) {
178             LOG.info(" In runKgraphs : algorithm didn't find any path");
179             pceResult.setLocalCause(LocalCause.NO_PATH_EXISTS);
180             pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
181             return false;
182         }
183
184         // debug print
185         allWPaths
186             .forEach((k, v) -> LOG.info("path n° {} - weight: {} - path: {}", k, v.getWeight(), v.getVertexList()));
187         return true;
188     }
189
190     private boolean validateLinkforGraph(PceLink pcelink) {
191
192         PceNode source = allPceNodes.get(pcelink.getSourceId());
193         PceNode dest = allPceNodes.get(pcelink.getDestId());
194
195         if (source == null) {
196             LOG.error("In addLinkToGraph link source node is null : {}", pcelink);
197             return false;
198         }
199         if (dest == null) {
200             LOG.error("In addLinkToGraph link dest node is null : {}", pcelink);
201             return false;
202         }
203         LOG.debug("In addLinkToGraph link to nodes : {}{} {}", pcelink, source, dest);
204         return true;
205     }
206
207     private void populateWithNodes(Graph<String, PceGraphEdge> weightedGraph) {
208         Iterator<Map.Entry<NodeId, PceNode>> nodes = allPceNodes.entrySet().iterator();
209         while (nodes.hasNext()) {
210             Map.Entry<NodeId, PceNode> node = nodes.next();
211             if (State.InService.equals(node.getValue().getState())) {
212                 weightedGraph.addVertex(node.getValue().getNodeId().getValue());
213                 LOG.debug("In populateWithNodes in node :  {}", node.getValue());
214             }
215         }
216     }
217
218     private boolean populateWithLinks(Graph<String, PceGraphEdge> weightedGraph) {
219
220         Iterator<Map.Entry<NodeId, PceNode>> nodes = allPceNodes.entrySet().iterator();
221         while (nodes.hasNext()) {
222
223             Map.Entry<NodeId, PceNode> node = nodes.next();
224
225             PceNode pcenode = node.getValue();
226             List<PceLink> links = pcenode.getOutgoingLinks();
227
228             LOG.debug("In populateGraph: use node for graph {}", pcenode);
229
230             for (PceLink link : links) {
231                 LOG.debug("In populateGraph node {} : add edge to graph {}", pcenode, link);
232
233                 if (!validateLinkforGraph(link)) {
234                     continue;
235                 }
236                 if (State.InService.equals(link.getState())) {
237                     PceGraphEdge graphLink = new PceGraphEdge(link);
238                     weightedGraph.addEdge(link.getSourceId().getValue(), link.getDestId().getValue(), graphLink);
239
240                     weightedGraph.setEdgeWeight(graphLink, chooseWeight(link));
241                 }
242             }
243         }
244         return true;
245     }
246
247     private double chooseWeight(PceLink link) {
248         // HopCount is default
249         double weight = 1;
250         switch (pceHardConstraints.getPceMetrics()) {
251             case HopCount :
252                 weight = 1;
253                 LOG.debug("In PceGraph HopCount is used as a metrics. {}", link);
254                 break;
255             case PropagationDelay :
256                 weight = link.getLatency();
257                 LOG.debug("In PceGraph PropagationDelay is used as a metrics. {}", link);
258                 if ((weight == 0)
259                         && ("1GE".equals(serviceType) || "10GE".equals(serviceType) || "ODU4".equals(serviceType))) {
260                     LOG.warn("PropagationDelay set as metric, but latency is null: is latency set for OTN link {}?",
261                         link);
262                 }
263                 break;
264             // TODO implement IGPMetric and TEMetric - low priority.
265             case IGPMetric :
266             case TEMetric :
267             default:
268                 LOG.warn("In PceGraph {} not implemented. HopCount works as a default",
269                     pceHardConstraints.getPceMetrics());
270                 break;
271         }
272         return weight;
273     }
274
275     public int getKpathsToBring() {
276         return kpathsToBring;
277     }
278
279     public void setKpathsToBring(int kpathsToBring) {
280         this.kpathsToBring = kpathsToBring;
281     }
282
283     public List<PceLink> getPathAtoZ() {
284         return shortestPathAtoZ;
285     }
286
287     public PceResult getReturnStructure() {
288         return pceResult;
289     }
290
291     public Double getmargin() {
292         return margin;
293     }
294
295     public void setConstrains(PceConstraints pceHardConstraintsInput, PceConstraints pceSoftConstraintsInput) {
296         this.pceHardConstraints = pceHardConstraintsInput;
297         this.pceSoftConstraints = pceSoftConstraintsInput;
298     }
299 }