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