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