Abort power setup if setting gainloss fails
[transportpce.git] / pce / src / main / java / org / opendaylight / transportpce / pce / networkanalyzer / PceCalculation.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.networkanalyzer;
10
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.math.BigDecimal;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Optional;
18 import java.util.concurrent.ExecutionException;
19 import java.util.stream.Collectors;
20 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
21 import org.opendaylight.transportpce.common.NetworkUtils;
22 import org.opendaylight.transportpce.common.ResponseCodes;
23 import org.opendaylight.transportpce.common.StringConstants;
24 import org.opendaylight.transportpce.common.fixedflex.GridConstant;
25 import org.opendaylight.transportpce.common.mapping.MappingUtils;
26 import org.opendaylight.transportpce.common.mapping.MappingUtilsImpl;
27 import org.opendaylight.transportpce.common.mapping.PortMapping;
28 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
29 import org.opendaylight.transportpce.common.service.ServiceTypes;
30 import org.opendaylight.transportpce.pce.PceComplianceCheck;
31 import org.opendaylight.transportpce.pce.constraints.PceConstraints;
32 import org.opendaylight.transportpce.pce.networkanalyzer.port.Factory;
33 import org.opendaylight.transportpce.pce.networkanalyzer.port.Preference;
34 import org.opendaylight.transportpce.pce.networkanalyzer.port.PreferenceFactory;
35 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev240205.PathComputationRequestInput;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev240205.path.computation.reroute.request.input.Endpoints;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev231221.mc.capabilities.McCapabilities;
38 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev230526.Link1;
39 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev230526.Node1;
40 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev191129.State;
41 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.NodeTypes;
42 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev230526.OpenroadmLinkType;
43 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev230526.OpenroadmNodeType;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NetworkId;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.Networks;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.Network;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.NetworkKey;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.Node;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.LinkId;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.Network1;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network.Link;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.opendaylight.yangtools.yang.common.Uint32;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 public class PceCalculation {
59     /* Logging. */
60     private static final Logger LOG = LoggerFactory.getLogger(PceCalculation.class);
61     private NetworkTransactionService networkTransactionService;
62
63     ///////////// data parsed from Input/////////////////
64     private PathComputationRequestInput input;
65     private String anodeId = "";
66     private String znodeId = "";
67     private String serviceFormatA = "";
68     private String serviceFormatZ = "";
69     private String serviceType = "";
70     private Uint32 serviceRate = Uint32.valueOf(0);
71
72     private PceConstraints pceHardConstraints;
73
74     ///////////// Intermediate data/////////////////
75     private List<PceLink> addLinks = new ArrayList<>();
76     private List<PceLink> dropLinks = new ArrayList<>();
77     private List<NodeId> azSrgs = new ArrayList<>();
78
79     private PceNode aendPceNode = null;
80     private PceNode zendPceNode = null;
81
82     private List<Link> allLinks = null;
83     private List<Node> allNodes = null;
84
85     // this List serves graph calculation
86     private Map<NodeId, PceNode> allPceNodes = new HashMap<>();
87     // this List serves calculation of ZtoA path description
88     // TODO maybe better solution is possible
89     private Map<LinkId, PceLink> allPceLinks = new HashMap<>();
90     private List<LinkId> linksToExclude = new ArrayList<>();
91     private PceResult returnStructure;
92     private PortMapping portMapping;
93     // Define the termination points whose reservation status is not taken into account during the pruning process
94     private Endpoints endpoints;
95
96     private enum ConstraintTypes {
97         NONE, HARD_EXCLUDE, HARD_INCLUDE, HARD_DIVERSITY, SOFT_EXCLUDE, SOFT_INCLUDE, SOFT_DIVERSITY;
98     }
99
100     private MappingUtils mappingUtils;
101
102     public PceCalculation(PathComputationRequestInput input, NetworkTransactionService networkTransactionService,
103                           PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult rc,
104                           PortMapping portMapping) {
105         this.input = input;
106         this.networkTransactionService = networkTransactionService;
107         this.returnStructure = rc;
108         this.pceHardConstraints = pceHardConstraints;
109         this.mappingUtils = new MappingUtilsImpl(networkTransactionService.getDataBroker());
110         this.portMapping = portMapping;
111         this.endpoints = null;
112         parseInput();
113     }
114
115     public PceCalculation(PathComputationRequestInput input, NetworkTransactionService networkTransactionService,
116                           PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult rc,
117                           PortMapping portMapping, Endpoints endpoints) {
118         this.input = input;
119         this.networkTransactionService = networkTransactionService;
120         this.returnStructure = rc;
121         this.pceHardConstraints = pceHardConstraints;
122         this.mappingUtils = new MappingUtilsImpl(networkTransactionService.getDataBroker());
123         this.portMapping = portMapping;
124         this.endpoints = endpoints;
125         parseInput();
126     }
127
128     public void retrievePceNetwork() {
129
130         LOG.debug("In PceCalculation retrieveNetwork");
131
132         if (!readMdSal()) {
133             returnStructure.setRC(ResponseCodes.RESPONSE_FAILED);
134             return;
135         }
136         MapUtils.mapDiversityConstraints(allNodes, allLinks, pceHardConstraints);
137
138         if (!analyzeNw()) {
139             returnStructure.setRC(ResponseCodes.RESPONSE_FAILED);
140             return;
141         }
142         printNodesInfo(allPceNodes);
143
144         returnStructure.setRC(ResponseCodes.RESPONSE_OK);
145     }
146
147     private boolean parseInput() {
148         if (!PceComplianceCheck.checkString(input.getServiceAEnd().getServiceFormat().getName())
149                 || !PceComplianceCheck.checkString(input.getServiceZEnd().getServiceFormat().getName())
150                 || !PceComplianceCheck.checkString(input.getServiceAEnd().getServiceRate().toString())) {
151             LOG.error("Service Format and Service Rate are required for a path calculation");
152             return false;
153         }
154         serviceFormatA = input.getServiceAEnd().getServiceFormat().getName();
155         serviceFormatZ = input.getServiceZEnd().getServiceFormat().getName();
156         serviceRate = input.getServiceAEnd().getServiceRate();
157         serviceType = ServiceTypes.getServiceType(
158             serviceFormatA,
159             serviceRate,
160             NodeTypes.Xpdr.equals(portMapping.getNode(input.getServiceAEnd().getNodeId()).getNodeInfo().getNodeType())
161                     && checkAendInputTxPortName()
162                 ? portMapping.getMapping(
163                     input.getServiceAEnd().getNodeId(),
164                     input.getServiceAEnd().getTxDirection().getPort().getPortName())
165                 : null);
166
167         LOG.debug("parseInput: A and Z :[{}] and [{}]", anodeId, znodeId);
168
169         getAZnodeId();
170
171         returnStructure.setRate(input.getServiceAEnd().getServiceRate().toJava());
172         returnStructure.setServiceFormat(input.getServiceAEnd().getServiceFormat());
173         return true;
174     }
175
176     private boolean checkAendInputTxPortName() {
177         return checkAendInputTxPort()
178             && input.getServiceAEnd().getTxDirection().getPort().getPortName() != null;
179     }
180
181     private boolean checkAendInputTxPortDeviceName() {
182         return checkAendInputTxPort()
183             && input.getServiceAEnd().getTxDirection().getPort().getPortDeviceName() != null;
184     }
185
186     private boolean checkAendInputTxPort() {
187         return input.getServiceAEnd() != null
188             && input.getServiceAEnd().getTxDirection() != null
189             && input.getServiceAEnd().getTxDirection().getPort() != null;
190     }
191
192     private boolean checkZendInputTxPortDeviceName() {
193         return input.getServiceZEnd() != null
194             && input.getServiceZEnd().getTxDirection() != null
195             && input.getServiceZEnd().getTxDirection().getPort() != null
196             && input.getServiceZEnd().getTxDirection().getPort().getPortDeviceName() != null;
197     }
198
199     private void getAZnodeId() {
200         anodeId =
201             checkAendInputTxPortDeviceName()
202                 ? input.getServiceAEnd().getTxDirection().getPort().getPortDeviceName()
203                 : input.getServiceAEnd().getNodeId();
204         znodeId =
205             checkZendInputTxPortDeviceName()
206                 ? input.getServiceZEnd().getTxDirection().getPort().getPortDeviceName()
207                 : input.getServiceZEnd().getNodeId();
208     }
209
210     private boolean readMdSal() {
211         InstanceIdentifier<Network> nwInstanceIdentifier = null;
212         switch (serviceType) {
213             case StringConstants.SERVICE_TYPE_100GE_T:
214             case StringConstants.SERVICE_TYPE_400GE:
215             case StringConstants.SERVICE_TYPE_OTU4:
216             case StringConstants.SERVICE_TYPE_OTUC2:
217             case StringConstants.SERVICE_TYPE_OTUC3:
218             case StringConstants.SERVICE_TYPE_OTUC4:
219                 LOG.debug("readMdSal: network {}", NetworkUtils.OVERLAY_NETWORK_ID);
220                 nwInstanceIdentifier = InstanceIdentifier.builder(Networks.class)
221                     .child(Network.class, new NetworkKey(new NetworkId(NetworkUtils.OVERLAY_NETWORK_ID))).build();
222                 break;
223             case StringConstants.SERVICE_TYPE_100GE_M:
224             case StringConstants.SERVICE_TYPE_100GE_S:
225             case StringConstants.SERVICE_TYPE_ODU4:
226             case StringConstants.SERVICE_TYPE_ODUC2:
227             case StringConstants.SERVICE_TYPE_ODUC3:
228             case StringConstants.SERVICE_TYPE_ODUC4:
229             case StringConstants.SERVICE_TYPE_10GE:
230             case StringConstants.SERVICE_TYPE_1GE:
231                 LOG.debug("readMdSal: network {}", NetworkUtils.OTN_NETWORK_ID);
232                 nwInstanceIdentifier = InstanceIdentifier.builder(Networks.class)
233                     .child(Network.class, new NetworkKey(new NetworkId(NetworkUtils.OTN_NETWORK_ID))).build();
234                 break;
235             default:
236                 LOG.warn("readMdSal: unknown service-type for service-rate {} and service-format {}", serviceRate,
237                     serviceFormatA);
238                 break;
239         }
240
241         if (readTopology(nwInstanceIdentifier) == null) {
242             LOG.error("readMdSal: network is null: {}", nwInstanceIdentifier);
243             return false;
244         }
245
246         allNodes = readTopology(nwInstanceIdentifier).nonnullNode().values().stream().sorted((n1, n2)
247             -> n1.getNodeId().getValue().compareTo(n2.getNodeId().getValue())).collect(Collectors.toList());
248         Network1 nw1 = readTopology(nwInstanceIdentifier).augmentation(Network1.class);
249         if (nw1 == null) {
250             LOG.warn("no otn links in otn-topology");
251         } else {
252             allLinks = nw1.nonnullLink().values().stream().sorted((l1, l2)
253                 -> l1.getSource().getSourceTp().getValue().compareTo(l2.getSource().getSourceTp().getValue()))
254                     .collect(Collectors.toList());
255         }
256         if (allNodes == null || allNodes.isEmpty()) {
257             LOG.error("readMdSal: no nodes ");
258             return false;
259         }
260         LOG.info("readMdSal: network nodes: {} nodes added", allNodes.size());
261         LOG.debug("readMdSal: network nodes: {} nodes added", allNodes);
262
263         if (allLinks == null || allLinks.isEmpty()) {
264             LOG.error("readMdSal: no links ");
265             return false;
266         }
267         LOG.info("readMdSal: network links: {} links added", allLinks.size());
268         LOG.debug("readMdSal: network links: {} links added", allLinks);
269
270         return true;
271     }
272
273     private Network readTopology(InstanceIdentifier<Network> nwInstanceIdentifier) {
274         Network nw = null;
275         try {
276             Optional<Network> nwOptional =
277                 networkTransactionService.read(LogicalDatastoreType.CONFIGURATION, nwInstanceIdentifier).get();
278             if (nwOptional.isPresent()) {
279                 nw = nwOptional.orElseThrow();
280                 LOG.debug("readMdSal: network nodes: nwOptional.isPresent = true {}", nw);
281             }
282         } catch (InterruptedException | ExecutionException e) {
283             LOG.error("readMdSal: Error reading topology {}", nwInstanceIdentifier);
284             returnStructure.setRC(ResponseCodes.RESPONSE_FAILED);
285         }
286         return nw;
287     }
288
289     private boolean analyzeNw() {
290
291         LOG.debug("analyzeNw: allNodes size {}, allLinks size {}", allNodes.size(), allLinks.size());
292         switch (serviceType) {
293             case StringConstants.SERVICE_TYPE_100GE_T:
294             case  StringConstants.SERVICE_TYPE_OTU4:
295             case  StringConstants.SERVICE_TYPE_400GE:
296             case StringConstants.SERVICE_TYPE_OTUC2:
297             case StringConstants.SERVICE_TYPE_OTUC3:
298             case  StringConstants.SERVICE_TYPE_OTUC4:
299                 Factory portPreferenceFactory = new PreferenceFactory();
300                 Preference portPreference = portPreferenceFactory.portPreference(input);
301                 // 100GE service and OTU4 service are handled at the openroadm-topology layer
302                 for (Node node : allNodes) {
303                     validateNode(node, portPreference);
304                 }
305
306                 LOG.debug("analyzeNw: allPceNodes size {}", allPceNodes.size());
307
308                 if (aendPceNode == null || zendPceNode == null) {
309                     LOG.error("analyzeNw: Error in reading nodes: A or Z do not present in the network");
310                     return false;
311                 }
312                 for (Link link : allLinks) {
313                     validateLink(link);
314                 }
315                 // debug prints
316                 LOG.debug("analyzeNw: addLinks size {}, dropLinks size {}", addLinks.size(), dropLinks.size());
317                 // debug prints
318                 LOG.debug("analyzeNw: azSrgs size = {}", azSrgs.size());
319                 for (NodeId srg : azSrgs) {
320                     LOG.debug("analyzeNw: A/Z Srgs SRG = {}", srg.getValue());
321                 }
322                 // debug prints
323                 for (PceLink link : addLinks) {
324                     filteraddLinks(link);
325                 }
326                 for (PceLink link : dropLinks) {
327                     filterdropLinks(link);
328                 }
329                 break;
330
331             default:
332                 // ODU4, 10GE/ODU2e or 1GE/ODU0 services are handled at openroadm-otn layer
333
334                 for (Node node : allNodes) {
335                     validateOtnNode(node);
336                 }
337
338                 LOG.info("analyzeNw: allPceNodes {}", allPceNodes);
339
340                 if (aendPceNode == null || zendPceNode == null) {
341                     LOG.error("analyzeNw: Error in reading nodes: A or Z do not present in the network");
342                     return false;
343                 }
344                 for (Link link : allLinks) {
345                     validateLink(link);
346                 }
347                 break;
348         }
349
350         LOG.info("analyzeNw: allPceNodes size {}, allPceLinks size {}", allPceNodes.size(), allPceLinks.size());
351
352         if ((allPceNodes.size() == 0) || (allPceLinks.size() == 0)) {
353             return false;
354         }
355
356         LOG.debug("analyzeNw: allPceNodes {}", allPceNodes);
357         LOG.debug("analyzeNw: allPceLinks {}", allPceLinks);
358
359         return true;
360     }
361
362     private boolean filteraddLinks(PceLink pcelink) {
363
364         NodeId nodeId = pcelink.getSourceId();
365
366         if (azSrgs.contains(nodeId)) {
367             allPceLinks.put(pcelink.getLinkId(), pcelink);
368             allPceNodes.get(nodeId).addOutgoingLink(pcelink);
369             LOG.debug("analyzeNw: Add_LINK added to source and to allPceLinks {}", pcelink.getLinkId());
370             return true;
371         }
372
373         // remove the SRG from PceNodes, as it is not directly connected to A/Z
374         allPceNodes.remove(nodeId);
375         LOG.debug("analyzeNw: SRG removed {}", nodeId.getValue());
376
377         return false;
378     }
379
380     private boolean filterdropLinks(PceLink pcelink) {
381
382         NodeId nodeId = pcelink.getDestId();
383
384         if (azSrgs.contains(nodeId)) {
385             allPceLinks.put(pcelink.getLinkId(), pcelink);
386             allPceNodes.get(nodeId).addOutgoingLink(pcelink);
387             LOG.debug("analyzeNw: Drop_LINK added to dest and to allPceLinks {}", pcelink.getLinkId());
388             return true;
389         }
390
391         // remove the SRG from PceNodes, as it is not directly connected to A/Z
392         allPceNodes.remove(pcelink.getDestId());
393         LOG.debug("analyzeNw: SRG removed {}", nodeId.getValue());
394
395         return false;
396     }
397
398     private boolean validateLink(Link link) {
399         LOG.debug("validateLink: link {} ", link);
400
401         NodeId sourceId = link.getSource().getSourceNode();
402         NodeId destId = link.getDestination().getDestNode();
403         PceNode source = allPceNodes.get(sourceId);
404         PceNode dest = allPceNodes.get(destId);
405         State state = link.augmentation(Link1.class).getOperationalState();
406
407         if (source == null) {
408             LOG.debug("validateLink: Link is ignored due source node is rejected by node validation - {}",
409                 link.getSource().getSourceNode().getValue());
410             return false;
411         }
412         if (dest == null) {
413             LOG.debug("validateLink: Link is ignored due dest node is rejected by node validation - {}",
414                 link.getDestination().getDestNode().getValue());
415             return false;
416         }
417
418         if (State.OutOfService.equals(state)) {
419             LOG.debug("validateLink: Link is ignored due operational state - {}",
420                     state.getName());
421             return false;
422         }
423
424         switch (serviceType) {
425             case StringConstants.SERVICE_TYPE_100GE_T:
426             case StringConstants.SERVICE_TYPE_OTU4:
427             case StringConstants.SERVICE_TYPE_OTUC2:
428             case StringConstants.SERVICE_TYPE_OTUC3:
429             case StringConstants.SERVICE_TYPE_OTUC4:
430             case StringConstants.SERVICE_TYPE_400GE:
431                 return processPceLink(link, sourceId, destId, source, dest);
432             case StringConstants.SERVICE_TYPE_ODU4:
433             case StringConstants.SERVICE_TYPE_10GE:
434             case StringConstants.SERVICE_TYPE_100GE_M:
435             case StringConstants.SERVICE_TYPE_100GE_S:
436             case StringConstants.SERVICE_TYPE_ODUC2:
437             case StringConstants.SERVICE_TYPE_ODUC3:
438             case StringConstants.SERVICE_TYPE_ODUC4:
439             case StringConstants.SERVICE_TYPE_1GE:
440                 return processPceOtnLink(link, source, dest);
441             default:
442                 LOG.error(" validateLink: Unmanaged service type {}", serviceType);
443                 return false;
444         }
445     }
446
447     private void validateNode(Node node, Preference portPreference) {
448         LOG.debug("validateNode: node {} ", node);
449         // PceNode will be used in Graph algorithm
450         Node1 node1 = node.augmentation(Node1.class);
451         if (node1 == null) {
452             LOG.error("getNodeType: no Node1 (type) Augmentation for node: [{}]. Node is ignored", node.getNodeId());
453             return;
454         }
455         if (State.OutOfService.equals(node1.getOperationalState())) {
456             LOG.error("getNodeType: node is ignored due to operational state - {}", node1.getOperationalState()
457                     .getName());
458             return;
459         }
460         OpenroadmNodeType nodeType = node1.getNodeType();
461         String deviceNodeId = MapUtils.getSupNetworkNode(node);
462         // Should never happen but because of existing topology test files
463         // we have to manage this case
464         if (deviceNodeId == null || deviceNodeId.isBlank()) {
465             deviceNodeId = node.getNodeId().getValue();
466         }
467
468         LOG.debug("Device node id {} for {}", deviceNodeId, node);
469         PceOpticalNode pceNode = new PceOpticalNode(deviceNodeId, this.serviceType, portMapping, node, nodeType,
470             mappingUtils.getOpenRoadmVersion(deviceNodeId), getSlotWidthGranularity(deviceNodeId, node.getNodeId()),
471             getCentralFreqGranularity(deviceNodeId, node.getNodeId()));
472         if (endpoints != null) {
473             pceNode.setEndpoints(endpoints);
474         }
475         pceNode.validateAZxponder(anodeId, znodeId, input.getServiceAEnd().getServiceFormat());
476         pceNode.initFrequenciesBitSet();
477
478         if (!pceNode.isValid()) {
479             LOG.debug(" validateNode: Node {} is ignored", node.getNodeId().getValue());
480             return;
481         }
482         if (validateNodeConstraints(pceNode).equals(ConstraintTypes.HARD_EXCLUDE)) {
483             return;
484         }
485
486         if (endPceNode(nodeType, pceNode.getNodeId(), pceNode, portPreference)) {
487             if (this.aendPceNode == null && isAZendPceNode(this.serviceFormatA, pceNode, anodeId, "A")) {
488                 // Added to ensure A-node has a addlink in the topology
489                 List<Link> links = this.allLinks.stream()
490                     .filter(x -> x.getSource().getSourceNode().getValue().contains(pceNode.getNodeId().getValue()))
491                     .collect(Collectors.toList());
492                 if (!links.isEmpty()) {
493                     this.aendPceNode = pceNode;
494                 }
495             }
496             if (this.zendPceNode == null && isAZendPceNode(this.serviceFormatZ, pceNode, znodeId, "Z")) {
497                 // Added to ensure Z-node has a droplink in the topology
498                 List<Link> links = this.allLinks.stream()
499                     .filter(x -> x.getDestination().getDestNode().getValue().contains(pceNode.getNodeId().getValue()))
500                     .collect(Collectors.toList());
501                 if (!links.isEmpty()) {
502                     this.zendPceNode = pceNode;
503                 }
504             }
505         }
506
507         allPceNodes.put(pceNode.getNodeId(), pceNode);
508         LOG.debug("validateNode: node is saved {}", pceNode.getNodeId().getValue());
509     }
510
511     @SuppressWarnings("fallthrough")
512     @SuppressFBWarnings(
513         value = "SF_SWITCH_FALLTHROUGH",
514         justification = "intentional fallthrough")
515     private boolean isAZendPceNode(String serviceFormat, PceOpticalNode pceNode, String azNodeId, String azEndPoint) {
516         switch (serviceFormat) {
517             case "Ethernet":
518             case "OC":
519                 if (pceNode.getSupNetworkNodeId().equals(azNodeId)) {
520                     return true;
521                 }
522             //fallthrough
523             case "OTU":
524                 switch (azEndPoint) {
525                     case "A":
526                         return checkAendInputTxPortDeviceName()
527                             && pceNode.getNodeId().getValue()
528                                 .equals(this.input.getServiceAEnd().getTxDirection().getPort().getPortDeviceName());
529                     case "Z":
530                         return checkZendInputTxPortDeviceName()
531                             && pceNode.getNodeId().getValue()
532                                 .equals(this.input.getServiceZEnd().getTxDirection().getPort().getPortDeviceName());
533                     default:
534                         return false;
535                 }
536             default:
537                 LOG.debug("Unsupported service Format {} for node {}", serviceFormat, pceNode.getNodeId().getValue());
538                 return false;
539         }
540     }
541
542     private void validateOtnNode(Node node) {
543         LOG.info("validateOtnNode: {} ", node.getNodeId().getValue());
544         // PceOtnNode will be used in Graph algorithm
545         if (node.augmentation(Node1.class) == null) {
546             LOG.error("ValidateOtnNode: no node-type augmentation. Node {} is ignored", node.getNodeId().getValue());
547             return;
548         }
549
550         OpenroadmNodeType nodeType = node.augmentation(Node1.class).getNodeType();
551         String clientPort = null;
552         if (node.getNodeId().getValue().equals(anodeId)
553                 && this.aendPceNode == null
554                 && input.getServiceAEnd() != null
555                 && input.getServiceAEnd().getRxDirection() != null
556                 && input.getServiceAEnd().getRxDirection().getPort() != null
557                 && input.getServiceAEnd().getRxDirection().getPort().getPortName() != null) {
558             clientPort = input.getServiceAEnd().getRxDirection().getPort().getPortName();
559         } else if (node.getNodeId().getValue().equals(znodeId)
560                 && this.zendPceNode == null
561                 && input.getServiceZEnd() != null
562                 && input.getServiceZEnd().getRxDirection() != null
563                 && input.getServiceZEnd().getRxDirection().getPort() != null
564                 && input.getServiceZEnd().getRxDirection().getPort().getPortName() != null) {
565             clientPort = input.getServiceZEnd().getRxDirection().getPort().getPortName();
566         }
567
568         PceOtnNode pceOtnNode = new PceOtnNode(node, nodeType, node.getNodeId(), "otn", serviceType, clientPort);
569         pceOtnNode.validateXponder(anodeId, znodeId);
570
571         if (!pceOtnNode.isValid()) {
572             LOG.warn(" validateOtnNode: Node {} is ignored", node.getNodeId().getValue());
573             return;
574         }
575         if (validateNodeConstraints(pceOtnNode).equals(ConstraintTypes.HARD_EXCLUDE)) {
576             return;
577         }
578         if (pceOtnNode.getNodeId().getValue().equals(anodeId) && this.aendPceNode == null) {
579             this.aendPceNode = pceOtnNode;
580         }
581         if (pceOtnNode.getNodeId().getValue().equals(znodeId) && this.zendPceNode == null) {
582             this.zendPceNode = pceOtnNode;
583         }
584         allPceNodes.put(pceOtnNode.getNodeId(), pceOtnNode);
585         LOG.info("validateOtnNode: node {} is saved", node.getNodeId().getValue());
586     }
587
588     private ConstraintTypes validateNodeConstraints(PceNode pcenode) {
589         if (pceHardConstraints.getExcludeSupNodes().isEmpty() && pceHardConstraints.getExcludeCLLI().isEmpty()) {
590             return ConstraintTypes.NONE;
591         }
592         if (pceHardConstraints.getExcludeSupNodes().contains(pcenode.getSupNetworkNodeId())) {
593             LOG.debug("validateNodeConstraints: {}", pcenode.getNodeId().getValue());
594             return ConstraintTypes.HARD_EXCLUDE;
595         }
596         if (pceHardConstraints.getExcludeCLLI().contains(pcenode.getSupClliNodeId())) {
597             LOG.debug("validateNodeConstraints: {}", pcenode.getNodeId().getValue());
598             return ConstraintTypes.HARD_EXCLUDE;
599         }
600         return ConstraintTypes.NONE;
601     }
602
603     private ConstraintTypes validateLinkConstraints(PceLink link) {
604         if (pceHardConstraints.getExcludeSRLG().isEmpty()) {
605             return ConstraintTypes.NONE;
606         }
607
608         // for now SRLG is the only constraint for link
609         if (link.getlinkType() != OpenroadmLinkType.ROADMTOROADM) {
610             return ConstraintTypes.NONE;
611         }
612
613         List<Long> constraints = new ArrayList<>(pceHardConstraints.getExcludeSRLG());
614         constraints.retainAll(link.getsrlgList());
615         if (!constraints.isEmpty()) {
616             LOG.debug("validateLinkConstraints: {}", link.getLinkId().getValue());
617             return ConstraintTypes.HARD_EXCLUDE;
618         }
619
620         return ConstraintTypes.NONE;
621     }
622
623     private void dropOppositeLink(Link link) {
624         LinkId opplink = MapUtils.extractOppositeLink(link);
625
626         if (allPceLinks.containsKey(opplink)) {
627             allPceLinks.remove(opplink);
628         } else {
629             linksToExclude.add(opplink);
630         }
631     }
632
633     private Boolean endPceNode(OpenroadmNodeType openroadmNodeType, NodeId nodeId, PceOpticalNode pceNode,
634                                Preference portPreference) {
635         switch (openroadmNodeType) {
636             case SRG:
637                 pceNode.initSrgTps(portPreference);
638                 this.azSrgs.add(nodeId);
639                 break;
640             case XPONDER:
641                 pceNode.initXndrTps(input.getServiceAEnd().getServiceFormat());
642                 break;
643             default:
644                 LOG.debug("endPceNode: Node {} is not SRG or XPONDER !", nodeId);
645                 return false;
646         }
647
648         if (!pceNode.isValid()) {
649             LOG.error("validateNode : there are no available frequencies in node {}", pceNode.getNodeId().getValue());
650             return false;
651         }
652         return true;
653     }
654
655     private boolean processPceLink(Link link, NodeId sourceId, NodeId destId, PceNode source, PceNode dest) {
656         PceLink pcelink = new PceLink(link, source, dest);
657         if (!pcelink.isValid()) {
658             dropOppositeLink(link);
659             LOG.error(" validateLink: Link is ignored due errors in network data or in opposite link");
660             return false;
661         }
662         LinkId linkId = pcelink.getLinkId();
663         if (validateLinkConstraints(pcelink).equals(ConstraintTypes.HARD_EXCLUDE)) {
664             dropOppositeLink(link);
665             LOG.debug("validateLink: constraints : link is ignored == {}", linkId.getValue());
666             return false;
667         }
668         switch (pcelink.getlinkType()) {
669             case ROADMTOROADM:
670             case EXPRESSLINK:
671                 allPceLinks.put(linkId, pcelink);
672                 source.addOutgoingLink(pcelink);
673                 LOG.debug("validateLink: {}-LINK added to allPceLinks {}",
674                     pcelink.getlinkType(), pcelink);
675                 break;
676             case ADDLINK:
677                 pcelink.setClientA(
678                     source.getRdmSrgClient(pcelink.getSourceTP().getValue(), StringConstants.SERVICE_DIRECTION_AZ));
679                 addLinks.add(pcelink);
680                 LOG.debug("validateLink: ADD-LINK saved  {}", pcelink);
681                 break;
682             case DROPLINK:
683                 pcelink.setClientZ(
684                     dest.getRdmSrgClient(pcelink.getDestTP().getValue(), StringConstants.SERVICE_DIRECTION_ZA));
685                 dropLinks.add(pcelink);
686                 LOG.debug("validateLink: DROP-LINK saved  {}", pcelink);
687                 break;
688             case XPONDERINPUT:
689                 // store separately all SRG links directly
690                 azSrgs.add(sourceId);
691                 // connected to A/Z
692                 if (!dest.checkTP(pcelink.getDestTP().getValue())) {
693                     LOG.debug(
694                         "validateLink: XPONDER-INPUT is rejected as NW port is busy - {} ", pcelink);
695                     return false;
696                 }
697                 if (dest.getXpdrClient(pcelink.getDestTP().getValue()) != null) {
698                     pcelink.setClientZ(dest.getXpdrClient(pcelink.getDestTP().getValue()));
699                 }
700                 allPceLinks.put(linkId, pcelink);
701                 source.addOutgoingLink(pcelink);
702                 LOG.debug("validateLink: XPONDER-INPUT link added to allPceLinks {}", pcelink);
703                 break;
704             // does it mean XPONDER==>>SRG ?
705             case XPONDEROUTPUT:
706                 // store separately all SRG links directly
707                 azSrgs.add(destId);
708                 // connected to A/Z
709                 if (!source.checkTP(pcelink.getSourceTP().getValue())) {
710                     LOG.debug(
711                         "validateLink: XPONDER-OUTPUT is rejected as NW port is busy - {} ", pcelink);
712                     return false;
713                 }
714                 if (source.getXpdrClient(pcelink.getSourceTP().getValue()) != null) {
715                     pcelink.setClientA(source.getXpdrClient(pcelink.getSourceTP().getValue()));
716                 }
717                 allPceLinks.put(linkId, pcelink);
718                 source.addOutgoingLink(pcelink);
719                 LOG.debug("validateLink: XPONDER-OUTPUT link added to allPceLinks {}", pcelink);
720                 break;
721             default:
722                 LOG.warn("validateLink: link type is not supported {}", pcelink);
723         }
724         return true;
725     }
726
727     private boolean processPceOtnLink(Link link, PceNode source, PceNode dest) {
728         PceLink pceOtnLink = new PceLink(link, source, dest);
729
730         if (!pceOtnLink.isOtnValid(link, serviceType)) {
731             dropOppositeLink(link);
732             LOG.error(" validateLink: Link is ignored due errors in network data or in opposite link");
733             return false;
734         }
735
736         LinkId linkId = pceOtnLink.getLinkId();
737         if (validateLinkConstraints(pceOtnLink).equals(ConstraintTypes.HARD_EXCLUDE)) {
738             dropOppositeLink(link);
739             LOG.debug("validateLink: constraints : link is ignored == {}", linkId.getValue());
740             return false;
741         }
742
743         switch (pceOtnLink.getlinkType()) {
744             case OTNLINK:
745                 if (source.getXpdrClient(pceOtnLink.getSourceTP().getValue()) != null) {
746                     pceOtnLink.setClientA(source.getXpdrClient(pceOtnLink.getSourceTP().getValue()));
747                 }
748                 if (dest.getXpdrClient(pceOtnLink.getDestTP().getValue()) != null) {
749                     pceOtnLink.setClientZ(dest.getXpdrClient(pceOtnLink.getDestTP().getValue()));
750                 }
751                 allPceLinks.put(linkId, pceOtnLink);
752                 source.addOutgoingLink(pceOtnLink);
753                 LOG.debug("validateLink: OTN-LINK added to allPceLinks {}", pceOtnLink);
754                 break;
755             default:
756                 LOG.warn("validateLink: link type is not supported {}", pceOtnLink);
757         }
758         return true;
759     }
760
761     public PceNode getaendPceNode() {
762         return aendPceNode;
763     }
764
765     public PceNode getzendPceNode() {
766         return zendPceNode;
767     }
768
769     public Map<NodeId, PceNode> getAllPceNodes() {
770         return this.allPceNodes;
771     }
772
773     public Map<LinkId, PceLink> getAllPceLinks() {
774         return this.allPceLinks;
775     }
776
777     public String getServiceType() {
778         return serviceType;
779     }
780
781     public PceResult getReturnStructure() {
782         return returnStructure;
783     }
784
785     private static void printNodesInfo(Map<NodeId, PceNode> allPceNodes) {
786         allPceNodes.forEach(((nodeId, pceNode) -> {
787             LOG.debug("In printNodes in node {} : outgoing links {} ", pceNode.getNodeId().getValue(),
788                     pceNode.getOutgoingLinks());
789         }));
790     }
791
792     /**
793      * Get mc capability slot width granularity for device.
794      * @param deviceNodeId String
795      * @param nodeId NodeId
796      * @return slot width granularity
797      */
798     private BigDecimal getSlotWidthGranularity(String deviceNodeId, NodeId nodeId) {
799         // nodeId: openroadm-topology level node
800         // deviceNodeId: openroadm-network level node
801         List<McCapabilities> mcCapabilities = mappingUtils.getMcCapabilitiesForNode(deviceNodeId);
802         String[] params = nodeId.getValue().split("-");
803         // DEGx or SRGx or XPDRx
804         String moduleName = params[params.length - 1];
805         for (McCapabilities mcCapabitility : mcCapabilities) {
806             if (mcCapabitility.getMcNodeName().contains("XPDR")
807                     && mcCapabitility.getSlotWidthGranularity() != null) {
808                 return mcCapabitility.getSlotWidthGranularity().getValue().decimalValue();
809             }
810             if (mcCapabitility.getMcNodeName().contains(moduleName)
811                     && mcCapabitility.getSlotWidthGranularity() != null) {
812                 return mcCapabitility.getSlotWidthGranularity().getValue().decimalValue();
813             }
814         }
815         return GridConstant.SLOT_WIDTH_50;
816     }
817
818     /**
819      * Get mc capability central-width granularity for device.
820      * @param deviceNodeId String
821      * @param nodeId NodeId
822      * @return center-freq granularity
823      */
824     private BigDecimal getCentralFreqGranularity(String deviceNodeId, NodeId nodeId) {
825         // nodeId: openroadm-topology level node
826         // deviceNodeId: openroadm-network level node
827         List<McCapabilities> mcCapabilities = mappingUtils.getMcCapabilitiesForNode(deviceNodeId);
828         String[] params = nodeId.getValue().split("-");
829         // DEGx or SRGx or XPDRx
830         String moduleName = params[params.length - 1];
831         for (McCapabilities mcCapabitility : mcCapabilities) {
832             if (mcCapabitility.getMcNodeName().contains("XPDR")
833                     && mcCapabitility.getCenterFreqGranularity() != null) {
834                 return mcCapabitility.getCenterFreqGranularity().getValue().decimalValue();
835             }
836             if (mcCapabitility.getMcNodeName().contains(moduleName)
837                     && mcCapabitility.getCenterFreqGranularity() != null) {
838                 return mcCapabitility.getCenterFreqGranularity().getValue().decimalValue();
839             }
840         }
841         return GridConstant.SLOT_WIDTH_50;
842     }
843 }