88a3793f69f391caf3400fa5219eef6b3bcafe68
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / mapping / PortMappingVersion221.java
1 /*
2  * Copyright © 2017 Orange, 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.common.mapping;
10
11 import com.google.common.util.concurrent.FluentFuture;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.Comparator;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Locale;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Optional;
22 import java.util.concurrent.ExecutionException;
23 import java.util.stream.Collectors;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.mdsal.binding.api.DataBroker;
26 import org.opendaylight.mdsal.binding.api.WriteTransaction;
27 import org.opendaylight.mdsal.common.api.CommitInfo;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.transportpce.common.StringConstants;
30 import org.opendaylight.transportpce.common.Timeouts;
31 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
32 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
33 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
34 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.Network;
35 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.NetworkBuilder;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.Nodes;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.NodesBuilder;
38 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.NodesKey;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.CpToDegree;
40 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.CpToDegreeBuilder;
41 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.CpToDegreeKey;
42 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.Mapping;
43 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.MappingBuilder;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.MappingKey;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.McCapabilities;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.McCapabilitiesBuilder;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.McCapabilitiesKey;
48 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.NodeInfo;
49 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.NodeInfo.OpenroadmVersion;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.NodeInfoBuilder;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.SwitchingPoolLcp;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.SwitchingPoolLcpBuilder;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.SwitchingPoolLcpKey;
54 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.switching.pool.lcp.NonBlockingList;
55 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.switching.pool.lcp.NonBlockingListBuilder;
56 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210310.network.nodes.switching.pool.lcp.NonBlockingListKey;
57 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.optical.channel.types.rev200529.FrequencyGHz;
58 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.Direction;
59 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.PortQual;
60 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.XpdrNodeTypes;
61 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.CircuitPack;
62 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.circuit.pack.Ports;
63 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.circuit.pack.PortsKey;
64 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.circuit.packs.CircuitPacks;
65 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.circuit.packs.CircuitPacksKey;
66 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.degree.ConnectionPorts;
67 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.interfaces.grp.Interface;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.interfaces.grp.InterfaceKey;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.OrgOpenroadmDevice;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.ConnectionMap;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.Degree;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.DegreeKey;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.Info;
74 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.OduSwitchingPools;
75 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.Protocols;
76 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.SharedRiskGroup;
77 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.SharedRiskGroupKey;
78 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.Xponder;
79 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.connection.map.Destination;
80 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org.openroadm.device.odu.switching.pools.non.blocking.list.PortList;
81 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.port.Interfaces;
82 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.xponder.XpdrPort;
83 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.NodeTypes;
84 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev170626.InterfaceType;
85 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev170626.OpenROADMOpticalMultiplex;
86 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev170626.OpticalTransport;
87 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev170626.OtnOdu;
88 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev181019.Protocols1;
89 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev181019.lldp.container.Lldp;
90 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev181019.lldp.container.lldp.PortConfig;
91 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev181019.SupportedIfCapability;
92 import org.opendaylight.yang.gen.v1.http.org.openroadm.switching.pool.types.rev191129.SwitchingPoolTypes;
93 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
94 import org.opendaylight.yangtools.yang.common.Uint16;
95 import org.opendaylight.yangtools.yang.common.Uint32;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98
99 // FIXME: many common pieces of code between PortMapping Versions 121 and 221 and 710
100 // some mutualization would be helpful
101 public class PortMappingVersion221 {
102     private static final Logger LOG = LoggerFactory.getLogger(PortMappingVersion221.class);
103     private static final Map<Direction, String> SUFFIX;
104
105     private final DataBroker dataBroker;
106     private final DeviceTransactionManager deviceTransactionManager;
107     private final OpenRoadmInterfaces openRoadmInterfaces;
108
109     static {
110         SUFFIX =  Map.of(
111             Direction.Tx, "TX",
112             Direction.Rx, "RX",
113             Direction.Bidirectional, "TXRX");
114     }
115
116     public PortMappingVersion221(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager,
117         OpenRoadmInterfaces openRoadmInterfaces) {
118         this.dataBroker = dataBroker;
119         this.deviceTransactionManager = deviceTransactionManager;
120         this.openRoadmInterfaces = openRoadmInterfaces;
121     }
122
123     public boolean createMappingData(String nodeId) {
124         LOG.info("{} : OpenROADM version 2.2.1 node - Creating Mapping Data", nodeId);
125         List<Mapping> portMapList = new ArrayList<>();
126         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = new HashMap<>();
127         InstanceIdentifier<Info> infoIID = InstanceIdentifier.create(OrgOpenroadmDevice.class).child(Info.class);
128         Optional<Info> deviceInfoOptional = this.deviceTransactionManager.getDataFromDevice(
129                 nodeId, LogicalDatastoreType.OPERATIONAL, infoIID,
130                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
131         if (!deviceInfoOptional.isPresent()) {
132             LOG.warn("{} : Device info subtree is absent", nodeId);
133             return false;
134         }
135         Info deviceInfo = deviceInfoOptional.get();
136         NodeInfo nodeInfo = createNodeInfo(deviceInfo);
137         if (nodeInfo == null) {
138             return false;
139         }
140         postPortMapping(nodeId, nodeInfo, null, null, null, null);
141
142         switch (deviceInfo.getNodeType()) {
143
144             case Rdm:
145                 // Get TTP port mapping
146                 if (!createTtpPortMapping(nodeId, deviceInfo, portMapList)) {
147                     // return false if mapping creation for TTP's failed
148                     LOG.warn("{} : Unable to create mapping for TTP's", nodeId);
149                     return false;
150                 }
151
152                 // Get PP port mapping
153                 if (!createPpPortMapping(nodeId, deviceInfo, portMapList)) {
154                     // return false if mapping creation for PP's failed
155                     LOG.warn("{} : Unable to create mapping for PP's", nodeId);
156                     return false;
157                 }
158                 // Get MC capabilities
159                 if (!createMcCapabilitiesList(nodeId, deviceInfo, mcCapabilities)) {
160                     // return false if MC capabilites failed
161                     LOG.warn("{} : Unable to create MC capabilities", nodeId);
162                     return false;
163                 }
164                 break;
165             case Xpdr:
166                 if (!createXpdrPortMapping(nodeId, portMapList)) {
167                     LOG.warn("{} : Unable to create mapping for the Xponder", nodeId);
168                     return false;
169                 }
170                 break;
171             default:
172                 LOG.error("{} : unknown nodetype - Unable to create mapping", nodeId);
173                 break;
174
175         }
176         return postPortMapping(nodeId, nodeInfo, portMapList, null, null, mcCapabilities);
177     }
178
179     public boolean updateMapping(String nodeId, Mapping oldMapping) {
180         InstanceIdentifier<Ports> portIId = InstanceIdentifier.create(OrgOpenroadmDevice.class)
181             .child(CircuitPacks.class, new CircuitPacksKey(oldMapping.getSupportingCircuitPackName()))
182             .child(Ports.class, new PortsKey(oldMapping.getSupportingPort()));
183         if ((oldMapping == null) || (nodeId == null)) {
184             LOG.error("Impossible to update mapping");
185             return false;
186         }
187         try {
188             Optional<Ports> portObject = deviceTransactionManager.getDataFromDevice(nodeId,
189                 LogicalDatastoreType.OPERATIONAL, portIId, Timeouts.DEVICE_READ_TIMEOUT,
190                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
191             if (!portObject.isPresent()) {
192                 return false;
193             }
194             Ports port = portObject.get();
195             Mapping newMapping = createMappingObject(nodeId, port, oldMapping.getSupportingCircuitPackName(),
196                 oldMapping.getLogicalConnectionPoint());
197             LOG.debug("{} : Updating old mapping Data {} for {} by new mapping data {}",
198                     nodeId, oldMapping, oldMapping.getLogicalConnectionPoint(), newMapping);
199             final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
200             InstanceIdentifier<Mapping> mapIID = InstanceIdentifier.create(Network.class)
201                 .child(Nodes.class, new NodesKey(nodeId))
202                 .child(Mapping.class, new MappingKey(oldMapping.getLogicalConnectionPoint()));
203             writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, mapIID, newMapping);
204             FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
205             commit.get();
206             return true;
207         } catch (InterruptedException | ExecutionException e) {
208             LOG.error("{} : exception when updating Mapping {} - ",
209                     nodeId, oldMapping.getLogicalConnectionPoint(), e);
210             return false;
211         }
212     }
213
214     private boolean createXpdrPortMapping(String nodeId, List<Mapping> portMapList) {
215         // Creating for Xponder Line and Client Ports
216         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
217         Optional<OrgOpenroadmDevice> deviceObject = deviceTransactionManager.getDataFromDevice(nodeId,
218             LogicalDatastoreType.OPERATIONAL, deviceIID,
219             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
220         if (!deviceObject.isPresent()) {
221             LOG.error("{} : Impossible to get device configuration", nodeId);
222             return false;
223         }
224         OrgOpenroadmDevice device = deviceObject.get();
225         if (device.getCircuitPacks() == null) {
226             LOG.warn("{} : Circuit Packs not present", nodeId);
227             return false;
228         }
229
230         Map<String, String> lcpMap = new HashMap<>();
231         Map<String, Mapping> mappingMap = new HashMap<>();
232         List<CircuitPacks> circuitPackList = new ArrayList<>(device.nonnullCircuitPacks().values());
233         circuitPackList.sort(Comparator.comparing(CircuitPack::getCircuitPackName));
234         if (device.getXponder() == null) {
235             LOG.warn("{} : configuration does not contain a list of Xponders", nodeId);
236             // Variables to keep track of number of line ports and client ports
237             int line = 1;
238             int client = 1;
239             // TODO the treatment here inside the 2 nested for-loop is very similar to the one
240             //     when device.getXponder() != null. Some code mutualization must be considered.
241             for (CircuitPacks cp : circuitPackList) {
242                 String circuitPackName = cp.getCircuitPackName();
243                 if (cp.getPorts() == null) {
244                     LOG.warn("{} : Ports were not found for circuit pack {}", nodeId, circuitPackName);
245                     continue;
246                 }
247                 List<Ports> portList = new ArrayList<>(cp.nonnullPorts().values());
248                 portList.sort(Comparator.comparing(Ports::getPortName));
249                 for (Ports port : portList) {
250                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
251                         1, null, circuitPackName, port,
252                         circuitPackList, lcpMap, mappingMap);
253                     line = counters[0];
254                     client = counters[1];
255                 }
256             }
257         } else {
258             LOG.info("{} : configuration contains a list of xponders", nodeId);
259             for (Xponder xponder : deviceObject.get().nonnullXponder().values()) {
260                 // Variables to keep track of number of line ports and client ports
261                 int line = 1;
262                 int client = 1;
263                 Integer xponderNb = xponder.getXpdrNumber().toJava();
264                 XpdrNodeTypes xponderType = xponder.getXpdrType();
265                 for (XpdrPort xpdrPort : xponder.nonnullXpdrPort().values().stream()
266                         .sorted((xp1, xp2) -> xp1.getIndex().compareTo(xp2.getIndex())).collect(Collectors.toList())) {
267                     String circuitPackName = xpdrPort.getCircuitPackName();
268                     String portName = xpdrPort.getPortName().toString();
269                     // If there xponder-subtree has missing circuit-packs or ports,
270                     // This gives a null-pointer expection,
271                     if (device.nonnullCircuitPacks().values().stream()
272                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
273                             .findFirst().isEmpty()) {
274                         LOG.warn("{} : Circuit-pack {} is missing in the device - ignoring it in port-mapping",
275                                 nodeId, circuitPackName);
276                         continue;
277                     }
278                     if (device.nonnullCircuitPacks().values().stream()
279                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
280                             .findFirst().get().nonnullPorts().values().stream()
281                             .filter(p -> p.getPortName().equals(portName))
282                             .findFirst().isEmpty()) {
283                         LOG.warn("{} : port {} on {} - association missing in the device - ignoring it in port-mapping",
284                                 nodeId, portName, circuitPackName);
285                         continue;
286                     }
287                     Ports port = device.nonnullCircuitPacks().values().stream()
288                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
289                             .findFirst().get().nonnullPorts().values().stream()
290                             .filter(p -> p.getPortName().equals(portName))
291                             .findFirst().get();
292                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
293                         xponderNb, xponderType, circuitPackName, port,
294                         circuitPackList, lcpMap, mappingMap);
295                     line = counters[0];
296                     client = counters[1];
297                 }
298             }
299         }
300
301         if (device.getConnectionMap() == null) {
302             LOG.warn("{} : No connection-map inside device configuration", nodeId);
303         } else {
304             Collection<ConnectionMap> connectionMap = deviceObject.get().nonnullConnectionMap().values();
305             for (ConnectionMap cm : connectionMap) {
306                 String skey = cm.getSource().getCircuitPackName() + "+" + cm.getSource().getPortName();
307                 String slcp = lcpMap.containsKey(skey) ? lcpMap.get(skey) : null;
308                 Destination destination0 = cm.nonnullDestination().values().iterator().next();
309                 String dkey = destination0.getCircuitPackName() + "+" + destination0.getPortName();
310                 if (slcp == null) {
311                     LOG.error("{} : Error in connection-map analysis for source {} and destination (CP+port) {}",
312                         nodeId, skey, dkey);
313                     continue;
314                 }
315                 String dlcp = lcpMap.containsKey(dkey) ? lcpMap.get(dkey) : null;
316                 Mapping mapping = mappingMap.get(slcp);
317                 mappingMap.remove(slcp);
318                 portMapList.add(createXpdrMappingObject(nodeId, null, null, null, null, mapping, dlcp, null));
319             }
320         }
321
322         if (device.getOduSwitchingPools() != null) {
323             Collection<OduSwitchingPools> oduSwithcingPools = device.nonnullOduSwitchingPools().values();
324             List<SwitchingPoolLcp> switchingPoolList = new ArrayList<>();
325             for (OduSwitchingPools odp : oduSwithcingPools) {
326                 Map<NonBlockingListKey,NonBlockingList> nbMap = new HashMap<>();
327                 for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.org.openroadm.device.container.org
328                     .openroadm.device.odu.switching.pools.NonBlockingList nbl : odp.nonnullNonBlockingList().values()) {
329                     if (nbl.getPortList() == null) {
330                         continue;
331                     }
332                     List<String> lcpList = new ArrayList<>();
333                     for (PortList item : nbl.nonnullPortList().values()) {
334                         String key = item.getCircuitPackName() + "+" + item.getPortName();
335                         if (!lcpMap.containsKey(key)) {
336                             LOG.error("{} : port {} on {} is not associated to a logical connection point",
337                                 nodeId, item.getPortName(), item.getCircuitPackName());
338                             continue;
339                         }
340                         lcpList.add(lcpMap.get(key));
341                     }
342                     NonBlockingList nonBlockingList = new NonBlockingListBuilder()
343                         .setNblNumber(nbl.getNblNumber())
344                         .setInterconnectBandwidth(nbl.getInterconnectBandwidth())
345                         .setInterconnectBandwidthUnit(nbl.getInterconnectBandwidthUnit())
346                         .setLcpList(lcpList)
347                         .build();
348                     nbMap.put(nonBlockingList.key(), nonBlockingList);
349                 }
350                 SwitchingPoolLcp splBldr = new SwitchingPoolLcpBuilder()
351                     .setSwitchingPoolNumber(odp.getSwitchingPoolNumber())
352                     .setSwitchingPoolType(SwitchingPoolTypes.forValue(odp.getSwitchingPoolType().getIntValue()))
353                     .setNonBlockingList(nbMap)
354                     .build();
355                 switchingPoolList.add(splBldr);
356             }
357             postPortMapping(nodeId, null, null, null, switchingPoolList, null);
358         }
359
360         if (!mappingMap.isEmpty()) {
361             mappingMap.forEach((k,v) -> portMapList.add(v));
362         }
363         return true;
364     }
365
366     private boolean checkPartnerPortNotNull(Ports port) {
367         if (port.getPartnerPort() == null
368             || port.getPartnerPort().getCircuitPackName() == null
369             || port.getPartnerPort().getPortName() == null) {
370             return false;
371         }
372         return true;
373     }
374
375     private boolean checkPartnerPortNoDir(String circuitPackName, Ports port1, Ports port2) {
376         if (!checkPartnerPortNotNull(port2)
377             || !port2.getPartnerPort().getCircuitPackName().equals(circuitPackName)
378             || !port2.getPartnerPort().getPortName().equals(port1.getPortName())) {
379             return false;
380         }
381         return true;
382     }
383
384     private boolean checkPartnerPort(String circuitPackName, Ports port1, Ports port2) {
385         if (!checkPartnerPortNoDir(circuitPackName, port1, port2)
386             || ((Direction.Rx.getIntValue() != port1.getPortDirection().getIntValue()
387                     || Direction.Tx.getIntValue() != port2.getPortDirection().getIntValue())
388                 &&
389                 (Direction.Tx.getIntValue() != port1.getPortDirection().getIntValue()
390                     || Direction.Rx.getIntValue() != port2.getPortDirection().getIntValue()))) {
391             return false;
392         }
393         return true;
394     }
395
396
397     private HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg
398             .CircuitPacks>> getSrgCps(String deviceId, Info ordmInfo) {
399         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg
400             .CircuitPacks>> cpPerSrg = new HashMap<>();
401         // Get value for max Srg from info subtree, required for iteration
402         // if not present assume to be 20 (temporary)
403         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
404         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
405             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks> srgCps
406                 = new ArrayList<>();
407             LOG.debug("{} : Getting Circuitpacks for Srg Number {}", deviceId, srgCounter);
408             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
409                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
410             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
411                 LogicalDatastoreType.OPERATIONAL, srgIID,
412                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
413             if (ordmSrgObject.isPresent()) {
414                 srgCps.addAll(ordmSrgObject.get().nonnullCircuitPacks().values());
415                 cpPerSrg.put(ordmSrgObject.get().getSrgNumber().toJava(), srgCps);
416             }
417         }
418         LOG.info("{} : Device has {} Srg", deviceId, cpPerSrg.size());
419         return cpPerSrg;
420     }
421
422     private boolean createPpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
423         // Creating mapping data for SRG's PP
424         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks>> srgCps
425             = getSrgCps(nodeId, deviceInfo);
426         for (Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks>>
427                 srgCpEntry : srgCps.entrySet()) {
428             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks> cpList =
429                 srgCps.get(srgCpEntry.getKey());
430             List<String> keys = new ArrayList<>();
431             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks cp : cpList) {
432                 String circuitPackName = cp.getCircuitPackName();
433                 InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
434                     .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
435                 Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
436                     LogicalDatastoreType.OPERATIONAL, cpIID,
437                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
438
439                 if (!circuitPackObject.isPresent() || (circuitPackObject.get().getPorts() == null)) {
440                     LOG.warn("{} : Circuit pack {} not found or without ports.", nodeId, circuitPackName);
441                     continue;
442                 }
443                 List<Ports> portList = new ArrayList<>(circuitPackObject.get().nonnullPorts().values());
444                 Collections.sort(portList, new SortPort221ByName());
445                 int portIndex = 1;
446                 for (Ports port : portList) {
447                     String currentKey = circuitPackName + "-" + port.getPortName();
448                     if (port.getPortQual() == null) {
449                         continue;
450                     }
451
452                     if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
453                         LOG.debug("{} : port {} on {} is not roadm-external - cannot assign logicalConnectionPoint.",
454                                 nodeId, port.getPortName(), circuitPackName);
455                         continue;
456                     }
457
458                     if (keys.contains(currentKey)) {
459                         LOG.debug("{} : port {} on {} has already been handled - cannot assign logicalConnectionPoint.",
460                                 nodeId, port.getPortName(), circuitPackName);
461                         continue;
462                     }
463
464                     switch (port.getPortDirection()) {
465
466                         case Bidirectional:
467                             String lcp = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
468                             LOG.info("{} : port {} on {} - associated Logical Connection Point is {}",
469                                     nodeId, port.getPortName(), circuitPackName, lcp);
470                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp));
471                             portIndex++;
472                             keys.add(currentKey);
473                             break;
474
475                         case Rx:
476                         case Tx:
477                             if (!checkPartnerPortNotNull(port)) {
478                                 LOG.info("{} : port {} on {} is unidirectional but has no valid partnerPort"
479                                         + " - cannot assign  logicalConnectionPoint.",
480                                         nodeId, port.getPortName(), circuitPackName);
481                                 continue;
482                             }
483
484                             String lcp1 = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
485                             LOG.info("{} :  port {} on {} - associated Logical Connection Point is {}",
486                                     nodeId, port.getPortName(), circuitPackName, lcp1);
487                             InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
488                                 .child(CircuitPacks.class,
489                                     new CircuitPacksKey(port.getPartnerPort().getCircuitPackName()))
490                                 .child(Ports.class, new PortsKey(port.getPartnerPort().getPortName().toString()));
491                             Optional<Ports> port2Object = this.deviceTransactionManager
492                                 .getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, port2ID,
493                                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
494                             if (!port2Object.isPresent()
495                                 || port2Object.get().getPortQual().getIntValue()
496                                     != PortQual.RoadmExternal.getIntValue()) {
497                                 LOG.error("{} : port {} on {} - error getting partner",
498                                         nodeId, port.getPartnerPort().getPortName().toString(),
499                                         port.getPartnerPort().getCircuitPackName());
500                                 continue;
501                             }
502
503                             Ports port2 = port2Object.get();
504                             if (!checkPartnerPort(circuitPackName, port, port2)) {
505                                 LOG.error("{} : port {} on {} - Error with partner port configuration",
506                                         nodeId, port.getPortName(), circuitPackName);
507                                 portIndex++;
508                                 continue;
509                             }
510                             String lcp2 = createLogicalConnectionPort(port2, srgCpEntry.getKey(),portIndex);
511                             LOG.info("{} : port {} on {} - associated Logical Connection Point is {}",
512                                     nodeId, port2.getPortName(), circuitPackName, lcp2);
513                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp1));
514                             portMapList.add(
515                                 createMappingObject(nodeId ,port2, port.getPartnerPort().getCircuitPackName(), lcp2));
516                             portIndex++;
517                             keys.add(currentKey);
518                             keys.add(port.getPartnerPort().getCircuitPackName() + "-" + port2.getPortName());
519                             break;
520
521                         default:
522                             LOG.error("{} : port {} on {} - unsupported Direction {}"
523                                     + " - cannot assign  logicalConnectionPoint.",
524                                     nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
525
526                     }
527                 }
528             }
529         }
530         return true;
531     }
532
533     private String createLogicalConnectionPort(Ports port, int index, int portIndex) {
534         if (SUFFIX.containsKey(port.getPortDirection())) {
535             return String.join("-", "SRG" + index, "PP" + portIndex, SUFFIX.get(port.getPortDirection()));
536         }
537         LOG.error("port {} : Unsupported port direction {}", port, port.getPortDirection());
538         return null;
539     }
540
541     private String createXpdrLogicalConnectionPort(int xponderNb, int lcpNb, String token) {
542         return new StringBuilder("XPDR").append(xponderNb)
543                 .append("-")
544                 .append(token).append(lcpNb)
545                 .toString();
546     }
547
548
549     private Map<Integer, Degree> getDegreesMap(String deviceId, Info ordmInfo) {
550         Map<Integer, Degree> degrees = new HashMap<>();
551
552         // Get value for max degree from info subtree, required for iteration
553         // if not present assume to be 20 (temporary)
554         Integer maxDegree = ordmInfo.getMaxDegrees() == null ? 20 : ordmInfo.getMaxDegrees().toJava();
555
556         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
557             LOG.debug("{} : Getting Connection ports for Degree Number {}", deviceId, degreeCounter);
558             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
559                 .child(Degree.class, new DegreeKey(Uint16.valueOf(degreeCounter)));
560             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
561                 LogicalDatastoreType.OPERATIONAL, deviceIID,
562                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
563             if (ordmDegreeObject.isPresent()) {
564                 degrees.put(degreeCounter, ordmDegreeObject.get());
565             }
566         }
567         LOG.info("{} : Device has {} degree(s)", deviceId, degrees.size());
568         return degrees;
569     }
570
571     private Map<Integer, List<ConnectionPorts>> getPerDegreePorts(String deviceId, Info ordmInfo) {
572         Map<Integer, List<ConnectionPorts>> conPortMap = new HashMap<>();
573         getDegreesMap(deviceId, ordmInfo).forEach(
574             (index, degree) -> conPortMap.put(index, new ArrayList<>(degree.nonnullConnectionPorts().values())));
575         return conPortMap;
576     }
577
578     private List<SharedRiskGroup> getSrgs(String deviceId, Info ordmInfo) {
579         List<SharedRiskGroup> srgs = new ArrayList<>();
580
581         // Get value for max Srg from info subtree, required for iteration
582         // if not present assume to be 20 (temporary)
583         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
584         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
585             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
586                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
587             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
588                 LogicalDatastoreType.OPERATIONAL, srgIID,
589                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
590             if (ordmSrgObject.isPresent()) {
591                 srgs.add(ordmSrgObject.get());
592
593             }
594         }
595         return srgs;
596     }
597
598     private Map<String, String> getEthInterfaceList(String nodeId) {
599         LOG.info("{} : It is calling get ethernet interface", nodeId);
600         InstanceIdentifier<Protocols> protocoliid = InstanceIdentifier.create(OrgOpenroadmDevice.class)
601             .child(Protocols.class);
602         Optional<Protocols> protocolObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
603             LogicalDatastoreType.OPERATIONAL, protocoliid, Timeouts.DEVICE_READ_TIMEOUT,
604             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
605         if (!protocolObject.isPresent() || protocolObject.get().augmentation(Protocols1.class).getLldp() == null) {
606             LOG.warn("{} : Couldnt find port config under LLDP - Processiong is done.. now returning..", nodeId);
607             return new HashMap<>();
608         }
609         Map<String, String> cpToInterfaceMap = new HashMap<>();
610         Lldp lldp = protocolObject.get().augmentation(Protocols1.class).getLldp();
611         for (PortConfig portConfig : lldp.nonnullPortConfig().values()) {
612             if (!portConfig.getAdminStatus().equals(PortConfig.AdminStatus.Txandrx)) {
613                 continue;
614             }
615             InstanceIdentifier<Interface> interfaceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
616                 .child(Interface.class, new InterfaceKey(portConfig.getIfName()));
617             Optional<Interface> interfaceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
618                 LogicalDatastoreType.OPERATIONAL, interfaceIID, Timeouts.DEVICE_READ_TIMEOUT,
619                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
620             if (!interfaceObject.isPresent() || (interfaceObject.get().getSupportingCircuitPackName() == null)) {
621                 continue;
622             }
623             String supportingCircuitPackName = interfaceObject.get().getSupportingCircuitPackName();
624             cpToInterfaceMap.put(supportingCircuitPackName, portConfig.getIfName());
625             InstanceIdentifier<CircuitPacks> circuitPacksIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
626                 .child(CircuitPacks.class, new CircuitPacksKey(supportingCircuitPackName));
627             Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(
628                 nodeId, LogicalDatastoreType.OPERATIONAL, circuitPacksIID, Timeouts.DEVICE_READ_TIMEOUT,
629                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
630             if (!circuitPackObject.isPresent() || (circuitPackObject.get().getParentCircuitPack() == null)) {
631                 continue;
632             }
633             cpToInterfaceMap.put(circuitPackObject.get().getParentCircuitPack().getCircuitPackName(),
634                 portConfig.getIfName());
635         }
636         LOG.info("{} : Processiong is done.. now returning..", nodeId);
637         return cpToInterfaceMap;
638     }
639
640     private List<CpToDegree> getCpToDegreeList(Map<Integer, Degree> degrees, Map<String, String> interfaceList) {
641         List<CpToDegree> cpToDegreeList = new ArrayList<>();
642         for (Degree degree : degrees.values()) {
643             LOG.debug("Inside CP to degree list");
644             cpToDegreeList.addAll(degree.nonnullCircuitPacks().values().stream()
645                 .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(),
646                     degree.getDegreeNumber().toString(), interfaceList))
647                 .collect(Collectors.toList()));
648         }
649         return cpToDegreeList;
650     }
651
652     private Map<McCapabilitiesKey, McCapabilities> getMcCapabilities(Map<Integer, Degree> degrees,
653             List<SharedRiskGroup> srgs, String nodeId) {
654         LOG.info("{} : Getting the MC capabilities for degrees", nodeId);
655         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = degrees.values().stream()
656             .map(degree -> createMcCapDegreeObject(degree, nodeId))
657             .collect(Collectors.toMap(McCapabilities::key, mcc -> mcc));
658         // Add the SRG mc-capabilities
659         LOG.info("{} : Getting the MC capabilities for SRGs", nodeId);
660         mcCapabilities.putAll(srgs.stream().map(srg -> createMcCapSrgObject(srg, nodeId))
661             .collect(Collectors.toMap(McCapabilities::key, mcCapabilities2 -> mcCapabilities2)));
662         return mcCapabilities;
663     }
664
665     private boolean postPortMapping(String nodeId, NodeInfo nodeInfo, List<Mapping> portMapList,
666             List<CpToDegree> cp2DegreeList, List<SwitchingPoolLcp> splList,
667             Map<McCapabilitiesKey, McCapabilities> mcCapabilities) {
668         NodesBuilder nodesBldr = new NodesBuilder().withKey(new NodesKey(nodeId)).setNodeId(nodeId);
669         if (nodeInfo != null) {
670             nodesBldr.setNodeInfo(nodeInfo);
671         }
672         if (portMapList != null) {
673             Map<MappingKey, Mapping> mappingMap = new HashMap<>();
674             // No element in the list below should be null at this stage
675             for (Mapping mapping: portMapList) {
676                 mappingMap.put(mapping.key(), mapping);
677             }
678             nodesBldr.setMapping(mappingMap);
679         }
680         if (cp2DegreeList != null) {
681             Map<CpToDegreeKey, CpToDegree> cpToDegreeMap = new HashMap<>();
682             // No element in the list below should be null at this stage
683             for (CpToDegree cp2Degree: cp2DegreeList) {
684                 cpToDegreeMap.put(cp2Degree.key(), cp2Degree);
685             }
686             nodesBldr.setCpToDegree(cpToDegreeMap);
687         }
688
689         if (splList != null) {
690             Map<SwitchingPoolLcpKey,SwitchingPoolLcp> splMap = new HashMap<>();
691             // No element in the list below should be null at this stage
692             for (SwitchingPoolLcp spl: splList) {
693                 splMap.put(spl.key(), spl);
694             }
695             nodesBldr.setSwitchingPoolLcp(splMap);
696         }
697         if (mcCapabilities != null) {
698             nodesBldr.setMcCapabilities(mcCapabilities);
699         }
700         Map<NodesKey,Nodes> nodesList = new HashMap<>();
701         Nodes nodes = nodesBldr.build();
702         nodesList.put(nodes.key(),nodes);
703
704         Network network = new NetworkBuilder().setNodes(nodesList).build();
705
706         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
707         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
708         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
709         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
710         try {
711             commit.get();
712             return true;
713         } catch (InterruptedException | ExecutionException e) {
714             LOG.warn("{} : Failed to post {}", nodeId, network, e);
715             return false;
716         }
717     }
718
719     private CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber,
720             Map<String, String> interfaceList) {
721         return new CpToDegreeBuilder()
722             .withKey(new CpToDegreeKey(circuitPackName))
723             .setCircuitPackName(circuitPackName)
724             .setDegreeNumber(Uint32.valueOf(degreeNumber))
725             .setInterfaceName(interfaceList.get(circuitPackName)).build();
726     }
727
728     private McCapabilities createMcCapDegreeObject(Degree degree, String nodeId) {
729         String mcNodeName = "DEG" + degree.getDegreeNumber().toString() + "-TTP";
730         McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
731             .withKey(new McCapabilitiesKey(mcNodeName))
732             .setMcNodeName(mcNodeName);
733         if (degree.getMcCapabilities() == null) {
734             LOG.warn("{} : Media channel capabilities are not advertised for degree {} - assuming fixed grid",
735                     nodeId, degree.getDegreeNumber());
736             mcCapabilitiesBuilder
737                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
738                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
739         } else {
740             mcCapabilitiesBuilder
741                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance(degree.getMcCapabilities()
742                     .getCenterFreqGranularity().getValue().toString()))
743                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance(degree.getMcCapabilities()
744                     .getSlotWidthGranularity().getValue().toString()));
745         }
746         return mcCapabilitiesBuilder.build();
747     }
748
749     private McCapabilities createMcCapSrgObject(SharedRiskGroup srg, String nodeId) {
750         String mcNodeName = "SRG" + srg.getSrgNumber().toString() + "-PP";
751         McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
752             .withKey(new McCapabilitiesKey(mcNodeName))
753             .setMcNodeName(mcNodeName);
754         if (srg.getMcCapabilities() == null) {
755             LOG.warn("{} : Media channel capabilities are not advertised for SRG {} - assuming fixed grid",
756                     nodeId, srg.getSrgNumber());
757             mcCapabilitiesBuilder
758                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
759                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
760         } else {
761             mcCapabilitiesBuilder
762                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance(srg.getMcCapabilities()
763                     .getCenterFreqGranularity().getValue().toString()))
764                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance(srg.getMcCapabilities()
765                     .getSlotWidthGranularity().getValue().toString()));
766         }
767         return mcCapabilitiesBuilder.build();
768     }
769
770     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
771             String logicalConnectionPoint) {
772         MappingBuilder mpBldr = new MappingBuilder()
773                 .withKey(new MappingKey(logicalConnectionPoint))
774                 .setLogicalConnectionPoint(logicalConnectionPoint)
775                 .setSupportingCircuitPackName(circuitPackName)
776                 .setSupportingPort(port.getPortName())
777                 .setPortDirection(port.getPortDirection().getName());
778         if (port.getAdministrativeState() != null) {
779             mpBldr.setPortAdminState(port.getAdministrativeState().name());
780         }
781         if (port.getOperationalState() != null) {
782             mpBldr.setPortOperState(port.getOperationalState().name());
783         }
784
785         if ((port.getInterfaces() == null)
786             || (!logicalConnectionPoint.contains(StringConstants.TTP_TOKEN)
787                 && !logicalConnectionPoint.contains(StringConstants.NETWORK_TOKEN))) {
788             return mpBldr.build();
789         }
790         // Get OMS and OTS interface provisioned on the TTP's
791         for (Interfaces interfaces : port.getInterfaces()) {
792             try {
793                 Optional<Interface> openRoadmInterface = this.openRoadmInterfaces.getInterface(nodeId,
794                     interfaces.getInterfaceName());
795                 if (!openRoadmInterface.isPresent()) {
796                     LOG.warn("{} : Interface {} was null!", nodeId, interfaces.getInterfaceName());
797                     continue;
798                 }
799                 LOG.debug("{} : interface get from device is {} and of type {}",
800                     nodeId, openRoadmInterface.get().getName(), openRoadmInterface.get().getType());
801                 Class<? extends InterfaceType> interfaceType
802                     = (Class<? extends InterfaceType>) openRoadmInterface.get().getType();
803                 // Check if interface type is OMS or OTS
804                 if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
805                     mpBldr.setSupportingOms(interfaces.getInterfaceName());
806                 }
807                 if (interfaceType.equals(OpticalTransport.class)) {
808                     mpBldr.setSupportingOts(interfaces.getInterfaceName());
809                 }
810                 if (interfaceType.equals(OtnOdu.class)) {
811                     mpBldr.setSupportingOdu4(interfaces.getInterfaceName());
812                 }
813             } catch (OpenRoadmInterfaceException ex) {
814                 LOG.warn("{} : Error while getting interface {} - ",
815                     nodeId, interfaces.getInterfaceName(), ex);
816             }
817         }
818         return mpBldr.build();
819     }
820
821     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
822             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String connectionMapLcp,
823             XpdrNodeTypes xpdrNodeType) {
824
825         if (mapping != null && connectionMapLcp != null) {
826             // update existing mapping
827             return new MappingBuilder(mapping).setConnectionMapLcp(connectionMapLcp).build();
828         }
829
830         // create a new mapping
831         String nodeIdLcp = nodeId + "-" + logicalConnectionPoint;
832         MappingBuilder mpBldr = new MappingBuilder()
833                 .withKey(new MappingKey(logicalConnectionPoint))
834                 .setLogicalConnectionPoint(logicalConnectionPoint)
835                 .setSupportingCircuitPackName(circuitPackName)
836                 .setSupportingPort(port.getPortName())
837                 .setPortDirection(port.getPortDirection().getName())
838                 .setLcpHashVal(FnvUtils.fnv1_64(nodeIdLcp));
839         if (port.getPortQual() != null) {
840             mpBldr.setPortQual(port.getPortQual().getName());
841         }
842         if (xpdrNodeType != null) {
843             mpBldr.setXponderType(
844                 org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.XpdrNodeTypes.forValue(
845                     xpdrNodeType.getIntValue()));
846         }
847         if (partnerLcp != null) {
848             mpBldr.setPartnerLcp(partnerLcp);
849         }
850         if (port.getSupportedInterfaceCapability() != null) {
851             List<Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
852                 .SupportedIfCapability>> supportedIntf = new ArrayList<>();
853             for (Class<? extends SupportedIfCapability> sup: port.getSupportedInterfaceCapability()) {
854                 @SuppressWarnings("unchecked") Class<? extends
855                     org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327.SupportedIfCapability> sup1 =
856                     (Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
857                         .SupportedIfCapability>) sup;
858                 supportedIntf.add(sup1);
859             }
860             mpBldr.setSupportedInterfaceCapability(supportedIntf);
861         }
862         if (port.getAdministrativeState() != null) {
863             mpBldr.setPortAdminState(port.getAdministrativeState().name());
864         }
865         if (port.getOperationalState() != null) {
866             mpBldr.setPortOperState(port.getOperationalState().name());
867         }
868         return mpBldr.build();
869     }
870
871     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
872             //circuitPackName2 will be updated by reference contrary to circuitPackName
873             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
874         if (!checkPartnerPortNotNull(port)) {
875             LOG.warn("{} : port {} on {} - Error in the configuration ",
876                     nodeId, port.getPortName(), circuitPackName);
877             return null;
878         }
879         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
880             return null;
881         }
882         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
883             .filter(
884                 cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
885             .findFirst();
886         if (!cpOpt.isPresent()) {
887             LOG.error("{} : Error fetching circuit-pack {}",
888                     nodeId, port.getPartnerPort().getCircuitPackName());
889             return null;
890         }
891         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
892             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName().toString()))
893             .findFirst();
894         if (!poOpt.isPresent()) {
895             LOG.error("{} : Error fetching port {} on {}",
896                     nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
897             return null;
898         }
899         Ports port2 = poOpt.get();
900         circuitPackName2.append(cpOpt.get().getCircuitPackName());
901         if (!checkPartnerPort(circuitPackName, port, port2)) {
902             LOG.error("{} : port {} on {} is not a correct partner port of {} on  {}",
903                     nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
904             return null;
905         }
906         return port2;
907     }
908
909
910     private void putXpdrLcpsInMaps(int line, String nodeId,
911             Integer xponderNb, XpdrNodeTypes xponderType,
912             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
913             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
914         String lcp1 = createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
915         String lcp2 = createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
916         if (lcpMap.containsKey(lcp1) || lcpMap.containsKey(lcp2)) {
917             LOG.warn("{} : mapping already exists for {} or {}", nodeId, lcp1, lcp2);
918             return;
919         }
920         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
921         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
922         mappingMap.put(lcp1,
923                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null, xponderType));
924         mappingMap.put(lcp2,
925                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null, xponderType));
926         return;
927     }
928
929     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
930             Integer xponderNb, XpdrNodeTypes xponderType,
931             String circuitPackName,  Ports port,
932             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
933         if (port.getPortQual() == null) {
934             LOG.warn("{} : port {} on {} - PortQual was not found",
935                     nodeId, port.getPortName(), circuitPackName);
936             return new int[] {line, client};
937         }
938
939         switch (port.getPortQual()) {
940
941             case XpdrClient:
942             case SwitchClient:
943                 String lcp0 = createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
944                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
945                 mappingMap.put(lcp0,
946                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null, null));
947                 client++;
948                 break;
949
950             case XpdrNetwork:
951             case SwitchNetwork:
952                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
953                         xponderNb, xponderType,
954                         circuitPackName,  port,
955                         circuitPackList,  lcpMap, mappingMap);
956                 break;
957
958             default:
959                 LOG.error("{} : port {} on {} - unsupported PortQual {}",
960                         nodeId, port.getPortName(), circuitPackName, port.getPortQual());
961         }
962         return new int[] {line, client};
963     }
964
965     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
966             Integer xponderNb, XpdrNodeTypes xponderType,
967             String circuitPackName,  Ports port,
968             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
969
970         switch (port.getPortDirection()) {
971
972             case Bidirectional:
973                 String lcp = createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
974                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
975                 mappingMap.put(lcp,
976                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null, xponderType));
977                 line++;
978                 break;
979
980             case Rx:
981             case Tx:
982                 StringBuilder circuitPackName2 = new StringBuilder();
983                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
984                         circuitPackList, lcpMap);
985
986                 if (port2 == null) {
987                      //key already present or an error occured and was logged
988                     return line;
989                 }
990
991                 putXpdrLcpsInMaps(line, nodeId, xponderNb, xponderType,
992                         circuitPackName, circuitPackName2.toString(), port, port2,
993                         lcpMap, mappingMap);
994                 line += 2;
995                 break;
996
997             default:
998                 LOG.error("{} : port {} on {} - unsupported Direction {}",
999                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
1000         }
1001
1002         return line;
1003     }
1004
1005     private boolean createMcCapabilitiesList(String nodeId, Info deviceInfo,
1006             Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap) {
1007         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1008         List<SharedRiskGroup> srgs = getSrgs(nodeId, deviceInfo);
1009         mcCapabilitiesMap.putAll(getMcCapabilities(degrees, srgs, nodeId));
1010         return true;
1011     }
1012
1013     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
1014         // Creating mapping data for degree TTP's
1015         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1016         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
1017         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
1018         LOG.info("{} : Map looks like this {}", nodeId, interfaceList);
1019         postPortMapping(nodeId, null, null, cpToDegreeList, null, null);
1020
1021         Map<Integer, List<ConnectionPorts>> connectionPortMap = getPerDegreePorts(nodeId, deviceInfo);
1022         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : connectionPortMap.entrySet()) {
1023             switch (connectionPortMap.get(cpMapEntry.getKey()).size()) {
1024                 case 1:
1025                     // port is bidirectional
1026                     InstanceIdentifier<Ports> portID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1027                         .child(CircuitPacks.class,
1028                             new CircuitPacksKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName()))
1029                         .child(Ports.class,
1030                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName().toString()));
1031                     LOG.debug("{} : Fetching connection-port {} at circuit pack {}",
1032                             nodeId,
1033                             connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(),
1034                             connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1035                     Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
1036                         LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
1037                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1038                     if (!portObject.isPresent()) {
1039                         LOG.error("{} : No port {} on circuit pack {}",
1040                                 nodeId,
1041                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(),
1042                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1043                         return false;
1044                     }
1045                     Ports port = portObject.get();
1046                     if (port.getPortQual() == null) {
1047                         continue;
1048                     }
1049                     if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()
1050                         || Direction.Bidirectional.getIntValue() != port.getPortDirection().getIntValue()) {
1051                         LOG.error("{} : port {} on {} - Impossible to create logical connection point"
1052                                 + " - Error in configuration with port-qual or port-direction",
1053                                 nodeId, port.getPortName(),
1054                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1055                         continue;
1056                     }
1057                     String logicalConnectionPoint = new StringBuilder("DEG")
1058                         .append(cpMapEntry.getKey())
1059                         .append("-TTP-TXRX")
1060                         .toString();
1061                     LOG.info("{} : Logical Connection Point for {} on {} is {}",
1062                             nodeId,
1063                             port.getPortName(), connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1064                             logicalConnectionPoint);
1065                     portMapList.add(createMappingObject(nodeId, port,
1066                         connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1067                         logicalConnectionPoint));
1068                     break;
1069                 case 2:
1070                     // ports are unidirectionals
1071                     String cp1Name = connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName();
1072                     String cp2Name = connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName();
1073                     InstanceIdentifier<Ports> port1ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1074                         .child(CircuitPacks.class, new CircuitPacksKey(cp1Name))
1075                         .child(Ports.class,
1076                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName().toString()));
1077                     LOG.debug("{} : Fetching connection-port {} at circuit pack {}",
1078                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(), cp1Name);
1079                     Optional<Ports> port1Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
1080                         LogicalDatastoreType.OPERATIONAL, port1ID, Timeouts.DEVICE_READ_TIMEOUT,
1081                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1082                     InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1083                         .child(CircuitPacks.class, new CircuitPacksKey(cp2Name))
1084                         .child(Ports.class,
1085                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName().toString()));
1086                     LOG.debug("{} : Fetching connection-port {} at circuit pack {}",
1087                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName(), cp2Name);
1088                     Optional<Ports> port2Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
1089                         LogicalDatastoreType.OPERATIONAL, port2ID, Timeouts.DEVICE_READ_TIMEOUT,
1090                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1091                     if (!port1Object.isPresent() || !port2Object.isPresent()) {
1092                         LOG.error("{} : No port {} on circuit pack {}",
1093                                 nodeId,
1094                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(),
1095                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1096                         return false;
1097                     }
1098
1099                     Ports port1 = port1Object.get();
1100                     Ports port2 = port2Object.get();
1101                     if (port1.getPortQual() == null || port2.getPortQual() == null) {
1102                         continue;
1103                     }
1104                     if (PortQual.RoadmExternal.getIntValue() != port1.getPortQual().getIntValue()
1105                         || PortQual.RoadmExternal.getIntValue() != port2.getPortQual().getIntValue()) {
1106                         LOG.error("{} : Impossible to create logical connection point for port {} or port {}"
1107                                 + " - Error in configuration with port-qual",
1108                                 nodeId, port1.getPortName(), port2.getPortName());
1109                         continue;
1110                     }
1111                     if (!checkPartnerPort(cp1Name, port1, port2)) {
1112                         LOG.error("{} : port {} on {} is not a correct partner port of {} on  {}",
1113                                 nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
1114                         continue;
1115                     }
1116                     // Directions checks are the same for cp1 and cp2, no need to check them twice.
1117                     if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
1118                         LOG.error("{} : port {} on {} is not a correct partner port of {} on  {}",
1119                                 nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
1120                         continue;
1121                     }
1122
1123                     String logicalConnectionPoint1 = new StringBuilder("DEG")
1124                         .append(cpMapEntry.getKey())
1125                         .append("-TTP-")
1126                         .append(port1.getPortDirection().getName().toUpperCase(Locale.getDefault()))
1127                         .toString();
1128                     LOG.info("{} : Logical Connection Point for {} {} is {}", nodeId,
1129                         connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1130                         port1.getPortName(), logicalConnectionPoint1);
1131                     portMapList.add(createMappingObject(nodeId, port1,
1132                             connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1133                             logicalConnectionPoint1));
1134                     String logicalConnectionPoint2 = new StringBuilder("DEG")
1135                         .append(cpMapEntry.getKey())
1136                         .append("-TTP-")
1137                         .append(port2.getPortDirection().getName().toUpperCase(Locale.getDefault()))
1138                         .toString();
1139                     LOG.info("{} : Logical Connection Point for {} {} is {}",
1140                             nodeId,
1141                             connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName(),
1142                             port2.getPortName(), logicalConnectionPoint2);
1143                     portMapList.add(createMappingObject(nodeId, port2,
1144                             connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName(),
1145                             logicalConnectionPoint2));
1146                     break;
1147                 default:
1148                     LOG.error("{} : Number of connection port for DEG{} is incorrect", nodeId, cpMapEntry.getKey());
1149                     continue;
1150             }
1151         }
1152         return true;
1153     }
1154
1155     private NodeInfo createNodeInfo(Info deviceInfo) {
1156
1157         if (deviceInfo.getNodeType() == null) {
1158             // TODO make mandatory in yang
1159             LOG.error("Node type field is missing");
1160             return null;
1161         }
1162
1163         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
1164                 .setOpenroadmVersion(OpenroadmVersion._221)
1165                 .setNodeType(NodeTypes.forValue(deviceInfo.getNodeType().getIntValue()));
1166         if (deviceInfo.getClli() != null && !deviceInfo.getClli().isEmpty()) {
1167             nodeInfoBldr.setNodeClli(deviceInfo.getClli());
1168         } else {
1169             nodeInfoBldr.setNodeClli("defaultCLLI");
1170         }
1171         if (deviceInfo.getModel() != null) {
1172             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
1173         }
1174         if (deviceInfo.getVendor() != null) {
1175             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
1176         }
1177         if (deviceInfo.getIpAddress() != null) {
1178             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
1179         }
1180
1181         return nodeInfoBldr.build();
1182     }
1183
1184 }