d1e1d30216e2e27b9a9a446a145d3e24704ea0e9
[transportpce.git] / pce / src / main / java / org / opendaylight / transportpce / pce / graph / PostAlgoPathValidator.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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.BitSet;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import org.jgrapht.GraphPath;
20 import org.opendaylight.transportpce.common.ResponseCodes;
21 import org.opendaylight.transportpce.common.StringConstants;
22 import org.opendaylight.transportpce.common.fixedflex.GridConstant;
23 import org.opendaylight.transportpce.common.fixedflex.GridUtils;
24 import org.opendaylight.transportpce.pce.constraints.PceConstraints;
25 import org.opendaylight.transportpce.pce.constraints.PceConstraints.ResourcePair;
26 import org.opendaylight.transportpce.pce.model.SpectrumAssignment;
27 import org.opendaylight.transportpce.pce.networkanalyzer.PceNode;
28 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult;
29 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev200529.OpenroadmLinkType;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
31 import org.opendaylight.yangtools.yang.common.Uint16;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 public class PostAlgoPathValidator {
36     /* Logging. */
37     private static final Logger LOG = LoggerFactory.getLogger(PostAlgoPathValidator.class);
38
39     private static final double MIN_OSNR_W100G = 17;
40     private static final double TRX_OSNR = 33;
41     private static final double ADD_OSNR = 30;
42     public static final Long CONST_OSNR = 1L;
43     public static final double SYS_MARGIN = 0;
44
45     @SuppressFBWarnings(
46         value = "SF_SWITCH_FALLTHROUGH",
47         justification = "intentional fallthrough")
48     public PceResult checkPath(GraphPath<String, PceGraphEdge> path, Map<NodeId, PceNode> allPceNodes,
49         PceResult pceResult, PceConstraints pceHardConstraints, String serviceType) {
50
51         // check if the path is empty
52         if (path.getEdgeList().isEmpty()) {
53             pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
54             return pceResult;
55         }
56         int tribSlotNb = 1;
57         //variable to deal with 1GE (Nb=1) and 10GE (Nb=10) cases
58         switch (serviceType) {
59
60             case StringConstants.SERVICE_TYPE_100GE:
61             case StringConstants.SERVICE_TYPE_OTU4:
62                 int spectralWidthSlotNumber = GridConstant.SPECTRAL_WIDTH_SLOT_NUMBER_MAP
63                     .getOrDefault(serviceType, GridConstant.NB_SLOTS_100G);
64                 SpectrumAssignment spectrumAssignment = getSpectrumAssignment(path,
65                         allPceNodes, spectralWidthSlotNumber);
66                 pceResult.setServiceType(serviceType);
67                 if (spectrumAssignment.getBeginIndex() == 0 && spectrumAssignment.getStopIndex() == 0) {
68                     pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
69                     pceResult.setLocalCause(PceResult.LocalCause.NO_PATH_EXISTS);
70                     return pceResult;
71                 }
72                 //TODO: until change to manage connection name, logical connection point name and service path
73                 // keep set wavelength number
74                 pceResult.setResultWavelength(
75                       GridUtils.getWaveLengthIndexFromSpectrumAssigment(spectrumAssignment.getBeginIndex()));
76                 pceResult.setMinFreq(GridUtils.getStartFrequencyFromIndex(spectrumAssignment.getBeginIndex()));
77                 pceResult.setMaxFreq(GridUtils.getStopFrequencyFromIndex(spectrumAssignment.getStopIndex()));
78                 LOG.info("In PostAlgoPathValidator: spectrum assignment found {} {}", spectrumAssignment, path);
79
80                 // Check the OSNR
81                 if (!checkOSNR(path)) {
82                     pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
83                     pceResult.setLocalCause(PceResult.LocalCause.OUT_OF_SPEC_OSNR);
84                     return pceResult;
85                 }
86
87                 // Check if MaxLatency is defined in the hard constraints
88                 if ((pceHardConstraints.getMaxLatency() != -1)
89                         && (!checkLatency(pceHardConstraints.getMaxLatency(), path))) {
90                     pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
91                     pceResult.setLocalCause(PceResult.LocalCause.TOO_HIGH_LATENCY);
92                     return pceResult;
93                 }
94
95                 // Check if nodes are included in the hard constraints
96                 if (!checkInclude(path, pceHardConstraints)) {
97                     pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
98                     pceResult.setLocalCause(PceResult.LocalCause.HD_NODE_INCLUDE);
99                     return pceResult;
100                 }
101
102                 // TODO here other post algo validations can be added
103                 // more data can be sent to PceGraph module via PceResult structure if required
104
105                 pceResult.setRC(ResponseCodes.RESPONSE_OK);
106                 pceResult.setLocalCause(PceResult.LocalCause.NONE);
107
108                 break;
109
110             case StringConstants.SERVICE_TYPE_10GE:
111                 tribSlotNb = 8;
112             //fallthrough
113             case StringConstants.SERVICE_TYPE_1GE:
114                 pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
115                 pceResult.setServiceType(serviceType);
116                 Map<String, Uint16> tribPort = chooseTribPort(path, allPceNodes);
117                 Map<String, List<Uint16>> tribSlot = chooseTribSlot(path, allPceNodes, tribSlotNb);
118
119                 if (tribPort != null && tribSlot != null) {
120                     pceResult.setResultTribPort(tribPort);
121                     pceResult.setResultTribSlot(tribSlot);
122                     pceResult.setResultTribSlotNb(tribSlotNb);
123                     pceResult.setRC(ResponseCodes.RESPONSE_OK);
124                     LOG.info("In PostAlgoPathValidator: found TribPort {} - tribSlot {} - tribSlotNb {}",
125                         tribPort, tribSlot, tribSlotNb);
126                 }
127                 break;
128
129             case StringConstants.SERVICE_TYPE_ODU4:
130                 pceResult.setRC(ResponseCodes.RESPONSE_OK);
131                 LOG.info("In PostAlgoPathValidator: ODU4 path found {}", path);
132                 break;
133
134             default:
135                 pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
136                 LOG.warn("In PostAlgoPathValidator checkPath: unsupported serviceType {} found {}",
137                     serviceType, path);
138                 break;
139         }
140
141         return pceResult;
142     }
143
144     // Check the latency
145     private boolean checkLatency(Long maxLatency, GraphPath<String, PceGraphEdge> path) {
146         double latency = 0;
147
148         for (PceGraphEdge edge : path.getEdgeList()) {
149             try {
150                 latency += edge.link().getLatency();
151                 LOG.debug("- In checkLatency: latency of {} = {} units", edge.link().getLinkId().getValue(), latency);
152             } catch (NullPointerException e) {
153                 LOG.warn("- In checkLatency: the link {} does not contain latency field",
154                     edge.link().getLinkId().getValue());
155             }
156         }
157         return (latency < maxLatency);
158     }
159
160     // Check the inclusion if it is defined in the hard constraints
161     private boolean checkInclude(GraphPath<String, PceGraphEdge> path, PceConstraints pceHardConstraintsInput) {
162         List<ResourcePair> listToInclude = pceHardConstraintsInput.getListToInclude();
163         if (listToInclude.isEmpty()) {
164             return true;
165         }
166
167         List<PceGraphEdge> pathEdges = path.getEdgeList();
168         LOG.debug(" in checkInclude vertex list: [{}]", path.getVertexList());
169
170         List<String> listOfElementsSubNode = new ArrayList<>();
171         listOfElementsSubNode.add(pathEdges.get(0).link().getsourceNetworkSupNodeId());
172         listOfElementsSubNode.addAll(listOfElementsBuild(pathEdges, PceConstraints.ResourceType.NODE,
173             pceHardConstraintsInput));
174
175         List<String> listOfElementsCLLI = new ArrayList<>();
176         listOfElementsCLLI.add(pathEdges.get(0).link().getsourceCLLI());
177         listOfElementsCLLI.addAll(listOfElementsBuild(pathEdges, PceConstraints.ResourceType.CLLI,
178             pceHardConstraintsInput));
179
180         List<String> listOfElementsSRLG = new ArrayList<>();
181         // first link is XPONDEROUTPUT, no SRLG for it
182         listOfElementsSRLG.add("NONE");
183         listOfElementsSRLG.addAll(listOfElementsBuild(pathEdges, PceConstraints.ResourceType.SRLG,
184             pceHardConstraintsInput));
185
186         // validation: check each type for each element
187         for (ResourcePair next : listToInclude) {
188             int indx = -1;
189             switch (next.getType()) {
190                 case NODE:
191                     if (listOfElementsSubNode.contains(next.getName())) {
192                         indx = listOfElementsSubNode.indexOf(next.getName());
193                     }
194                     break;
195                 case SRLG:
196                     if (listOfElementsSRLG.contains(next.getName())) {
197                         indx = listOfElementsSRLG.indexOf(next.getName());
198                     }
199                     break;
200                 case CLLI:
201                     if (listOfElementsCLLI.contains(next.getName())) {
202                         indx = listOfElementsCLLI.indexOf(next.getName());
203                     }
204                     break;
205                 default:
206                     LOG.warn(" in checkInclude vertex list unsupported resource type: [{}]", next.getType());
207             }
208
209             if (indx < 0) {
210                 LOG.debug(" in checkInclude stopped : {} ", next.getName());
211                 return false;
212             }
213
214             LOG.debug(" in checkInclude next found {} in {}", next.getName(), path.getVertexList());
215
216             listOfElementsSubNode.subList(0, indx).clear();
217             listOfElementsCLLI.subList(0, indx).clear();
218             listOfElementsSRLG.subList(0, indx).clear();
219         }
220
221         LOG.info(" in checkInclude passed : {} ", path.getVertexList());
222         return true;
223     }
224
225     private List<String> listOfElementsBuild(List<PceGraphEdge> pathEdges, PceConstraints.ResourceType type,
226         PceConstraints pceHardConstraints) {
227
228         List<String> listOfElements = new ArrayList<>();
229         for (PceGraphEdge link : pathEdges) {
230             switch (type) {
231                 case NODE:
232                     listOfElements.add(link.link().getdestNetworkSupNodeId());
233                     break;
234                 case CLLI:
235                     listOfElements.add(link.link().getdestCLLI());
236                     break;
237                 case SRLG:
238                     if (link.link().getlinkType() != OpenroadmLinkType.ROADMTOROADM) {
239                         listOfElements.add("NONE");
240                         break;
241                     }
242                     // srlg of link is List<Long>. But in this algo we need string representation of
243                     // one SRLG
244                     // this should be any SRLG mentioned in include constraints if any of them if
245                     // mentioned
246                     boolean found = false;
247                     for (Long srlg : link.link().getsrlgList()) {
248                         String srlgStr = String.valueOf(srlg);
249                         if (pceHardConstraints.getSRLGnames().contains(srlgStr)) {
250                             listOfElements.add(srlgStr);
251                             LOG.info("listOfElementsBuild. FOUND SRLG {} in link {}", srlgStr, link.link());
252                             found = true;
253                         }
254                     }
255                     if (!found) {
256                         // there is no specific srlg to include. thus add to list just the first one
257                         listOfElements.add("NONE");
258                     }
259                     break;
260                 default:
261                     LOG.debug("listOfElementsBuild unsupported resource type");
262             }
263         }
264         return listOfElements;
265     }
266
267     private Map<String, Uint16> chooseTribPort(GraphPath<String,
268         PceGraphEdge> path, Map<NodeId, PceNode> allPceNodes) {
269         LOG.info("In choosetribPort: edgeList = {} ", path.getEdgeList());
270         Map<String, Uint16> tribPortMap = new HashMap<>();
271
272         for (PceGraphEdge edge : path.getEdgeList()) {
273             NodeId linkSrcNode = edge.link().getSourceId();
274             String linkSrcTp = edge.link().getSourceTP().toString();
275             NodeId linkDestNode = edge.link().getDestId();
276             String linkDestTp = edge.link().getDestTP().toString();
277             PceNode pceOtnNodeSrc = allPceNodes.get(linkSrcNode);
278             PceNode pceOtnNodeDest = allPceNodes.get(linkDestNode);
279             List<Uint16> srcTpnPool = pceOtnNodeSrc.getAvailableTribPorts().get(linkSrcTp);
280             List<Uint16> destTpnPool = pceOtnNodeDest.getAvailableTribPorts().get(linkDestTp);
281             List<Uint16> commonEdgeTpnPool = new ArrayList<>();
282             for (Uint16 integer : srcTpnPool) {
283                 if (destTpnPool.contains(integer)) {
284                     commonEdgeTpnPool.add(integer);
285                 }
286             }
287             Collections.sort(commonEdgeTpnPool);
288             if (!commonEdgeTpnPool.isEmpty()) {
289                 tribPortMap.put(edge.link().getLinkId().getValue(), commonEdgeTpnPool.get(0));
290             }
291         }
292         tribPortMap.forEach((k,v) -> LOG.info("TribPortMap : k = {}, v = {}", k, v));
293         return tribPortMap;
294     }
295
296     private Map<String, List<Uint16>> chooseTribSlot(GraphPath<String,
297         PceGraphEdge> path, Map<NodeId, PceNode> allPceNodes, int nbSlot) {
298         LOG.info("In choosetribSlot: edgeList = {} ", path.getEdgeList());
299         Map<String, List<Uint16>> tribSlotMap = new HashMap<>();
300
301         for (PceGraphEdge edge : path.getEdgeList()) {
302             NodeId linkSrcNode = edge.link().getSourceId();
303             String linkSrcTp = edge.link().getSourceTP().toString();
304             NodeId linkDestNode = edge.link().getDestId();
305             String linkDestTp = edge.link().getDestTP().toString();
306             PceNode pceOtnNodeSrc = allPceNodes.get(linkSrcNode);
307             PceNode pceOtnNodeDest = allPceNodes.get(linkDestNode);
308             List<Uint16> srcTsPool = pceOtnNodeSrc.getAvailableTribSlots().get(linkSrcTp);
309             List<Uint16> destTsPool = pceOtnNodeDest.getAvailableTribSlots().get(linkDestTp);
310             List<Uint16> commonEdgeTsPool = new ArrayList<>();
311             List<Uint16> tribSlotList = new ArrayList<>();
312             for (Uint16 integer : srcTsPool) {
313                 if (destTsPool.contains(integer)) {
314                     commonEdgeTsPool.add(integer);
315                 }
316             }
317             Collections.sort(commonEdgeTsPool);
318             boolean discontinue = true;
319             int index = 0;
320             while (discontinue && (commonEdgeTsPool.size() - index >= nbSlot)) {
321                 discontinue = false;
322                 Integer val = commonEdgeTsPool.get(index).toJava();
323                 for (int i = 0; i < nbSlot; i++) {
324                     if (commonEdgeTsPool.get(index + i).equals(Uint16.valueOf(val + i))) {
325                         tribSlotList.add(commonEdgeTsPool.get(index + i));
326                     } else {
327                         discontinue = true;
328                         tribSlotList.clear();
329                         index += i;
330                         break;
331                     }
332                 }
333             }
334             tribSlotMap.put(edge.link().getLinkId().getValue(), tribSlotList);
335         }
336         tribSlotMap.forEach((k,v) -> LOG.info("TribSlotMap : k = {}, v = {}", k, v));
337         return tribSlotMap;
338     }
339
340     // Check the path OSNR
341     private boolean checkOSNR(GraphPath<String, PceGraphEdge> path) {
342         double linkOsnrDb;
343         double osnrDb = 0;
344         LOG.info("- In checkOSNR: OSNR of the transmitter = {} dB", TRX_OSNR);
345         LOG.info("- In checkOSNR: add-path incremental OSNR = {} dB", ADD_OSNR);
346         double inverseLocalOsnr = getInverseOsnrLinkLu(TRX_OSNR) + getInverseOsnrLinkLu(ADD_OSNR);
347         for (PceGraphEdge edge : path.getEdgeList()) {
348             if (edge.link().getlinkType() == OpenroadmLinkType.ROADMTOROADM) {
349                 // link OSNR in dB
350                 linkOsnrDb = edge.link().getosnr();
351                 LOG.info("- In checkOSNR: OSNR of {} = {} dB", edge.link().getLinkId().getValue(), linkOsnrDb);
352                 // 1 over the local OSNR, in linear units
353                 inverseLocalOsnr += getInverseOsnrLinkLu(linkOsnrDb);
354             }
355         }
356         try {
357             osnrDb = getOsnrDb(1 / inverseLocalOsnr);
358         } catch (ArithmeticException e) {
359             LOG.debug("In checkOSNR: OSNR is equal to 0 and the number of links is: {}", path.getEdgeList().size());
360             return false;
361         }
362         LOG.info("In checkOSNR: OSNR of the path is {} dB", osnrDb);
363         return ((osnrDb + SYS_MARGIN) > MIN_OSNR_W100G);
364     }
365
366     private double getOsnrDb(double osnrLu) {
367         double osnrDb;
368         osnrDb = 10 * Math.log10(osnrLu);
369         return osnrDb;
370     }
371
372     private double getInverseOsnrLinkLu(double linkOsnrDb) {
373         // 1 over the link OSNR, in linear units
374         double linkOsnrLu;
375         linkOsnrLu = Math.pow(10, (linkOsnrDb / 10.0));
376         LOG.debug("In retrieveosnr: the inverse of link osnr is {} (Linear Unit)", linkOsnrLu);
377         return (CONST_OSNR / linkOsnrLu);
378     }
379
380     /**
381      * Get spectrum assignment for path.
382      *
383      * @param path                    the path for which we get spectrum assignment.
384      * @param allPceNodes             all optical nodes.
385      * @param spectralWidthSlotNumber number of slot for spectral width. Depends on
386      *                                service type.
387      * @return a spectrum assignment object which contains begin and end index. If
388      *         no spectrum assignment found, beginIndex = stopIndex = 0
389      */
390     private SpectrumAssignment getSpectrumAssignment(GraphPath<String, PceGraphEdge> path,
391             Map<NodeId, PceNode> allPceNodes, int spectralWidthSlotNumber) {
392         byte[] freqMap = new byte[GridConstant.NB_OCTECTS];
393         Arrays.fill(freqMap, (byte) GridConstant.AVAILABLE_SLOT_VALUE);
394         BitSet result = BitSet.valueOf(freqMap);
395         boolean isFlexGrid = true;
396         LOG.info("Processing path {} with length {}", path, path.getLength());
397         BitSet pceNodeFreqMap;
398         for (PceGraphEdge edge : path.getEdgeList()) {
399             LOG.info("Processing source {} ", edge.link().getSourceId());
400             if (allPceNodes.containsKey(edge.link().getSourceId())) {
401                 PceNode pceNode = allPceNodes.get(edge.link().getSourceId());
402                 LOG.info("Processing PCE node {}", pceNode);
403                 if (StringConstants.OPENROADM_DEVICE_VERSION_1_2_1.equals(pceNode.getVersion())
404                         || pceNode.getSlotWidthGranularity().compareTo(GridConstant.SLOT_WIDTH_50) == 0) {
405                     LOG.info("Node {}: version is {} and slot width granularity is {} -> fixed grid mode",
406                             pceNode.getNodeId(), pceNode.getVersion(), pceNode.getSlotWidthGranularity());
407                     isFlexGrid = false;
408                 }
409                 pceNodeFreqMap = pceNode.getBitSetData();
410                 LOG.debug("Pce node bitset {}", pceNodeFreqMap);
411                 if (pceNodeFreqMap != null) {
412                     result.and(pceNodeFreqMap);
413                     LOG.debug("intermediate bitset {}", result);
414                 }
415             }
416         }
417         LOG.debug("Bitset result {}", result);
418         return computeBestSpectrumAssignment(result, spectralWidthSlotNumber, isFlexGrid);
419     }
420
421     /**
422      * Compute spectrum assignment from spectrum occupation for spectral width.
423      *
424      * @param spectrumOccupation      the spectrum occupation BitSet.
425      * @param spectralWidthSlotNumber the nb slots for spectral width.
426      * @param isFlexGrid              true if flexible grid, false otherwise.
427      * @return a spectrum assignment object which contains begin and stop index. If
428      *         no spectrum assignment found, beginIndex = stopIndex = 0
429      */
430     private SpectrumAssignment computeBestSpectrumAssignment(BitSet spectrumOccupation, int spectralWidthSlotNumber,
431             boolean isFlexGrid) {
432         SpectrumAssignment spectrumAssignment = new SpectrumAssignment(0, 0);
433         spectrumAssignment.setFlexGrid(isFlexGrid);
434         BitSet referenceBitSet = new BitSet(spectralWidthSlotNumber);
435         referenceBitSet.set(0, spectralWidthSlotNumber);
436         int nbSteps = 1;
437         if (isFlexGrid) {
438             nbSteps = spectralWidthSlotNumber;
439         }
440         //higher is the frequency, smallest is the wavelength number
441         //in operational, the allocation is done through wavelength starting from the smallest
442         //so we have to loop from the last element of the spectrum occupation
443         for (int i = spectrumOccupation.size(); i >= spectralWidthSlotNumber; i -= nbSteps) {
444             if (spectrumOccupation.get(i - spectralWidthSlotNumber, i).equals(referenceBitSet)) {
445                 spectrumAssignment.setBeginIndex(i - spectralWidthSlotNumber);
446                 spectrumAssignment.setStopIndex(i - 1);
447                 break;
448             }
449         }
450         return spectrumAssignment;
451     }
452
453 }