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