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