PortMapping Refactoring step 3
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / mapping / PortMappingVersion121.java
1 /*
2  * Copyright © 2017 AT&T 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.Collections;
14 import java.util.Comparator;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Locale;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Optional;
21 import java.util.Set;
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.network.Nodes;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.NodesBuilder;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.NodesKey;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.nodes.NodeInfo;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.nodes.NodeInfoBuilder;
48 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.Direction;
49 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.CircuitPack;
50 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.Port;
51 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.pack.Ports;
52 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.pack.PortsKey;
53 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.packs.CircuitPacks;
54 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.packs.CircuitPacksKey;
55 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.degree.ConnectionPorts;
56 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.Interface;
57 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.InterfaceKey;
58 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
59 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.ConnectionMap;
60 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Degree;
61 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.DegreeKey;
62 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Info;
63 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Protocols;
64 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.SharedRiskGroup;
65 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.SharedRiskGroupKey;
66 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.connection.map.Destination;
67 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.port.Interfaces;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.NodeTypes;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.InterfaceType;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.OpenROADMOpticalMultiplex;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.OpticalTransport;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev161014.Protocols1;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev161014.lldp.container.Lldp;
74 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev161014.lldp.container.lldp.PortConfig;
75 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
76 import org.opendaylight.yangtools.yang.common.Uint16;
77 import org.opendaylight.yangtools.yang.common.Uint32;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 // FIXME: many common pieces of code between PortMapping Versions 121 and 221 and 710
82 // some mutualization would be helpful
83 @SuppressWarnings("CPD-START")
84 public class PortMappingVersion121 {
85
86     private static final Logger LOG = LoggerFactory.getLogger(PortMappingVersion121.class);
87     private static final Map<Direction, String> SUFFIX;
88     private static final Set<Integer> TXRX_SET = Set.of(Direction.Tx.getIntValue(), Direction.Rx.getIntValue());
89
90     private final DataBroker dataBroker;
91     private final DeviceTransactionManager deviceTransactionManager;
92     private final OpenRoadmInterfaces openRoadmInterfaces;
93
94     static {
95         SUFFIX =  Map.of(
96             Direction.Tx, "TX",
97             Direction.Rx, "RX",
98             Direction.Bidirectional, "TXRX");
99     }
100
101     public PortMappingVersion121(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager,
102             OpenRoadmInterfaces openRoadmInterfaces) {
103         this.dataBroker = dataBroker;
104         this.deviceTransactionManager = deviceTransactionManager;
105         this.openRoadmInterfaces = openRoadmInterfaces;
106     }
107
108     public boolean createMappingData(String nodeId) {
109         LOG.info(PortMappingUtils.CREATE_MAPPING_DATA_LOGMSG, nodeId, "1.2.1");
110         List<Mapping> portMapList = new ArrayList<>();
111         InstanceIdentifier<Info> infoIID = InstanceIdentifier.create(OrgOpenroadmDevice.class).child(Info.class);
112         Optional<Info> deviceInfoOptional = this.deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType
113             .OPERATIONAL, infoIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
114         if (deviceInfoOptional.isEmpty()) {
115             LOG.warn(PortMappingUtils.DEVICE_HAS_LOGMSG, nodeId, "no info", "subtree");
116             return false;
117         }
118         Info deviceInfo = deviceInfoOptional.get();
119         NodeInfo nodeInfo = createNodeInfo(deviceInfo);
120         if (nodeInfo == null) {
121             return false;
122         }
123         postPortMapping(nodeId, nodeInfo, null, null);
124
125         switch (deviceInfo.getNodeType()) {
126
127             case Rdm:
128                 // Get TTP port mapping
129                 if (!createTtpPortMapping(nodeId, deviceInfo, portMapList)) {
130                     // return false if mapping creation for TTP's failed
131                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "create", "TTP's");
132                     return false;
133                 }
134
135                 // Get PP port mapping
136                 if (!createPpPortMapping(nodeId, deviceInfo, portMapList)) {
137                     // return false if mapping creation for PP's failed
138                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "create", "PP's");
139                     return false;
140                 }
141                 break;
142             case Xpdr:
143                 if (!createXpdrPortMapping(nodeId, portMapList)) {
144                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "create", "Xponder");
145                     return false;
146                 }
147                 break;
148             default:
149                 LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
150                     nodeId, "create", deviceInfo.getNodeType() + " - unknown nodetype");
151                 break;
152
153         }
154         return postPortMapping(nodeId, nodeInfo, portMapList, null);
155     }
156
157     public boolean updateMapping(String nodeId, Mapping oldMapping) {
158         if (nodeId == null) {
159             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, "node id null" , "update", "a null value");
160             return false;
161         }
162         if (oldMapping == null) {
163             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "update", "a null value");
164             return false;
165         }
166         InstanceIdentifier<Ports> portId = InstanceIdentifier.create(OrgOpenroadmDevice.class)
167             .child(CircuitPacks.class, new CircuitPacksKey(oldMapping.getSupportingCircuitPackName()))
168             .child(Ports.class, new PortsKey(oldMapping.getSupportingPort()));
169         try {
170             Ports port = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
171                 portId, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
172             Mapping newMapping = updateMappingObject(nodeId, port, oldMapping);
173             LOG.debug(PortMappingUtils.UPDATE_MAPPING_LOGMSG,
174                 nodeId, oldMapping, oldMapping.getLogicalConnectionPoint(), newMapping);
175             final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
176             InstanceIdentifier<Mapping> mapIID = InstanceIdentifier.create(Network.class)
177                 .child(Nodes.class, new NodesKey(nodeId))
178                 .child(Mapping.class, new MappingKey(oldMapping.getLogicalConnectionPoint()));
179             writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, mapIID, newMapping);
180             FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
181             commit.get();
182             return true;
183         } catch (InterruptedException | ExecutionException e) {
184             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
185                 nodeId, "update", oldMapping.getLogicalConnectionPoint(), e);
186             return false;
187         }
188     }
189
190     private boolean createXpdrPortMapping(String nodeId, List<Mapping> portMapList) {
191         // Creating for Xponder Line and Client Ports
192         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
193         Optional<OrgOpenroadmDevice> deviceObject = deviceTransactionManager.getDataFromDevice(nodeId,
194             LogicalDatastoreType.OPERATIONAL, deviceIID,
195             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
196         if (deviceObject.isEmpty()) {
197             LOG.error(PortMappingUtils.CANNOT_GET_DEV_CONF_LOGMSG, nodeId);
198             return false;
199         }
200         OrgOpenroadmDevice device = deviceObject.get();
201         if (device.getCircuitPacks() == null) {
202             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, "found");
203             return false;
204         }
205         // Variable to keep track of number of line ports
206         int line = 1;
207         // Variable to keep track of number of client ports
208         int client = 1;
209         Map<String, String> lcpMap = new HashMap<>();
210         Map<String, Mapping> mappingMap = new HashMap<>();
211         List<CircuitPacks> circuitPackList = new ArrayList<>(device.nonnullCircuitPacks().values());
212         circuitPackList.sort(Comparator.comparing(CircuitPack::getCircuitPackName));
213
214         for (CircuitPacks cp : circuitPackList) {
215             String circuitPackName = cp.getCircuitPackName();
216             if (cp.getPorts() == null) {
217                 LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, "found", circuitPackName);
218                 continue;
219             }
220             List<Ports> portList = new ArrayList<>(cp.nonnullPorts().values());
221             portList.sort(Comparator.comparing(Ports::getPortName));
222             for (Ports port : portList) {
223                 int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
224                     1, circuitPackName, port,
225                     circuitPackList, lcpMap, mappingMap);
226                 line = counters[0];
227                 client = counters[1];
228             }
229         }
230
231         for (ConnectionMap cm : deviceObject.get().nonnullConnectionMap().values()) {
232             String skey = cm.getSource().getCircuitPackName() + "+" + cm.getSource().getPortName();
233             Destination destination0 = cm.nonnullDestination().values().iterator().next();
234             String dkey = destination0.getCircuitPackName() + "+" + destination0.getPortName();
235             if (!lcpMap.containsKey(skey)) {
236                 LOG.error(PortMappingUtils.CONMAP_ISSUE_LOGMSG, nodeId, skey, dkey);
237                 continue;
238             }
239             String slcp = lcpMap.get(skey);
240             Mapping mapping = mappingMap.get(slcp);
241             mappingMap.remove(slcp);
242             portMapList.add(createXpdrMappingObject(nodeId, null, null, null, null, mapping,
243                 //dlcp
244                 lcpMap.containsKey(dkey) ? lcpMap.get(dkey) : null));
245         }
246
247         mappingMap.forEach((k,v) -> portMapList.add(v));
248         return true;
249     }
250
251     private boolean checkPartnerPortNotNull(Ports port) {
252         return (port.getPartnerPort() != null
253             && port.getPartnerPort().getCircuitPackName() != null
254             && port.getPartnerPort().getPortName() != null);
255     }
256
257     private boolean checkPartnerPortNoDir(String circuitPackName, Ports port1, Ports port2) {
258         return (checkPartnerPortNotNull(port2)
259             && port2.getPartnerPort().getCircuitPackName().equals(circuitPackName)
260             && port2.getPartnerPort().getPortName().equals(port1.getPortName()));
261     }
262
263     private boolean checkPartnerPort(String circuitPackName, Ports port1, Ports port2) {
264         return checkPartnerPortNoDir(circuitPackName, port1, port2)
265             && Set.of(port1.getPortDirection().getIntValue(), port2.getPortDirection().getIntValue())
266                 .equals(TXRX_SET);
267     }
268
269     private HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg
270             .CircuitPacks>> getSrgCps(String deviceId, Info ordmInfo) {
271         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg
272             .CircuitPacks>> cpPerSrg = new HashMap<>();
273         // Get value for max Srg from info subtree, required for iteration
274         // if not present assume to be 20 (temporary)
275         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
276         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
277             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg.CircuitPacks> srgCps
278                 = new ArrayList<>();
279             LOG.debug(PortMappingUtils.GETTING_CP_LOGMSG, deviceId, srgCounter);
280             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
281                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
282             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
283                 LogicalDatastoreType.OPERATIONAL, srgIID,
284                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
285             if (ordmSrgObject.isPresent()) {
286                 srgCps.addAll(ordmSrgObject.get().nonnullCircuitPacks().values());
287                 cpPerSrg.put(ordmSrgObject.get().getSrgNumber().toJava(), srgCps);
288             }
289         }
290         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG, deviceId, cpPerSrg.size(), "SRG");
291         return cpPerSrg;
292     }
293
294     private boolean createPpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
295         // Creating mapping data for SRG's PP
296         for (Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg.CircuitPacks>>
297                 srgCpEntry : getSrgCps(nodeId, deviceInfo).entrySet()) {
298             List<String> keys = new ArrayList<>();
299             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg.CircuitPacks
300                     cp : srgCpEntry.getValue()) {
301                 String circuitPackName = cp.getCircuitPackName();
302                 List<Ports> portList = getPortList(circuitPackName, nodeId);
303                 Collections.sort(portList, new SortPort121ByName());
304                 int portIndex = 1;
305                 for (Ports port : portList) {
306                     if (!checkPortQual(port, circuitPackName, nodeId)) {
307                         continue;
308                     }
309                     String currentKey = circuitPackName + "-" + port.getPortName();
310                     if (keys.contains(currentKey)) {
311                         LOG.debug(PortMappingUtils.PORT_ALREADY_HANDLED_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
312                             nodeId, port.getPortName(), circuitPackName);
313                         continue;
314                     }
315                     switch (port.getPortDirection()) {
316                         case Bidirectional:
317                             String lcp = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
318                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
319                                 nodeId, port.getPortName(), circuitPackName, lcp);
320                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp));
321                             portIndex++;
322                             keys.add(currentKey);
323                             break;
324                         case Rx:
325                         case Tx:
326                             if (!checkPartnerPortNotNull(port)) {
327                                 LOG.info(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG
328                                         + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
329                                     nodeId, port.getPortName(), circuitPackName);
330                                 continue;
331                             }
332                             String lcp1 = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
333                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
334                                     nodeId, port.getPortName(), circuitPackName, lcp1);
335                             InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
336                                 .child(CircuitPacks.class,
337                                     new CircuitPacksKey(port.getPartnerPort().getCircuitPackName()))
338                                 .child(Ports.class, new PortsKey(port.getPartnerPort().getPortName()));
339                             Optional<Ports> port2Object = this.deviceTransactionManager
340                                 .getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, port2ID,
341                                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
342                             if (port2Object.isEmpty()
343                                 || port2Object.get().getPortQual().getIntValue()
344                                     != Port.PortQual.RoadmExternal.getIntValue()) {
345                                 LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG
346                                         + PortMappingUtils.PARTNERPORT_GET_ERROR_LOGMSG,
347                                     nodeId, port.getPartnerPort().getPortName(),
348                                     port.getPartnerPort().getCircuitPackName(),
349                                     port.getPortName(), circuitPackName);
350                                 continue;
351                             }
352                             Ports port2 = port2Object.get();
353                             if (!checkPartnerPort(circuitPackName, port, port2)) {
354                                 LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG
355                                         + PortMappingUtils.PARTNERPORT_CONF_ERROR_LOGMSG,
356                                     nodeId, port2.getPortName(), port.getPartnerPort().getCircuitPackName(),
357                                     port.getPortName(), circuitPackName);
358                                 portIndex++;
359                                 continue;
360                             }
361                             String lcp2 = createLogicalConnectionPort(port2, srgCpEntry.getKey(),portIndex);
362                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
363                                 nodeId, port2.getPortName(), circuitPackName, lcp2);
364                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp1));
365                             portMapList.add(
366                                 createMappingObject(nodeId ,port2, port.getPartnerPort().getCircuitPackName(), lcp2));
367                             portIndex++;
368                             keys.add(currentKey);
369                             keys.add(port.getPartnerPort().getCircuitPackName() + "-" + port2.getPortName());
370                             break;
371                         default:
372                             LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
373                                 nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
374                     }
375                 }
376             }
377         }
378         return true;
379     }
380
381     private List<Ports> getPortList(String circuitPackName, String nodeId) {
382         InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
383             .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
384         Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
385              LogicalDatastoreType.OPERATIONAL, cpIID,
386              Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
387         if (circuitPackObject.isEmpty()) {
388             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
389                 nodeId, circuitPackName);
390             return new ArrayList<>();
391         }
392         if (circuitPackObject.get().getPorts() == null) {
393             LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, "found", circuitPackName);
394             return new ArrayList<>();
395         }
396         return new ArrayList<>(circuitPackObject.get().nonnullPorts().values());
397     }
398
399     private String createLogicalConnectionPort(Ports port, int index, int portIndex) {
400         if (SUFFIX.containsKey(port.getPortDirection())) {
401             return String.join("-", "SRG" + index, "PP" + portIndex, SUFFIX.get(port.getPortDirection()));
402         }
403         LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
404             "createLogicalConnectionPort", port, "SRG" + index + "-PP" + portIndex, port.getPortDirection());
405         return null;
406     }
407
408     private Map<Integer, Degree> getDegreesMap(String deviceId, Info ordmInfo) {
409         Map<Integer, Degree> degrees = new HashMap<>();
410
411         // Get value for max degree from info subtree, required for iteration
412         // if not present assume to be 20 (temporary)
413         Integer maxDegree = ordmInfo.getMaxDegrees() == null ? 20 : ordmInfo.getMaxDegrees().toJava();
414
415         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
416             LOG.debug(PortMappingUtils.GETTING_CONPORT_LOGMSG, deviceId, degreeCounter);
417             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
418                 .child(Degree.class, new DegreeKey(Uint16.valueOf(degreeCounter)));
419             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
420                 LogicalDatastoreType.OPERATIONAL, deviceIID,
421                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
422             if (ordmDegreeObject.isPresent()) {
423                 degrees.put(degreeCounter, ordmDegreeObject.get());
424             }
425         }
426         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG,
427                 deviceId, degrees.size(), degrees.size() <= 1 ? "degree" : "degrees");
428         return degrees;
429     }
430
431     private Map<Integer, List<ConnectionPorts>> getPerDegreePorts(String deviceId, Info ordmInfo) {
432         Map<Integer, List<ConnectionPorts>> conPortMap = new HashMap<>();
433         getDegreesMap(deviceId, ordmInfo).forEach(
434             (index, degree) -> conPortMap.put(index, new ArrayList<>(degree.nonnullConnectionPorts().values())));
435         return conPortMap;
436     }
437
438     private Map<String, String> getEthInterfaceList(String nodeId) {
439         LOG.info(PortMappingUtils.GETTING_ETH_LIST_LOGMSG, nodeId);
440         InstanceIdentifier<Protocols> protocoliid = InstanceIdentifier.create(OrgOpenroadmDevice.class)
441             .child(Protocols.class);
442         Optional<Protocols> protocolObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
443             LogicalDatastoreType.OPERATIONAL, protocoliid, Timeouts.DEVICE_READ_TIMEOUT,
444             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
445         if (protocolObject.isEmpty() || protocolObject.get().augmentation(Protocols1.class).getLldp() == null) {
446             LOG.warn(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, PortMappingUtils.CANNOT_GET_LLDP_CONF_LOGMSG);
447             return new HashMap<>();
448         }
449         Map<String, String> cpToInterfaceMap = new HashMap<>();
450         Lldp lldp = protocolObject.get().augmentation(Protocols1.class).getLldp();
451         for (PortConfig portConfig : lldp.nonnullPortConfig().values()) {
452             if (!portConfig.getAdminStatus().equals(PortConfig.AdminStatus.Txandrx)) {
453                 continue;
454             }
455             InstanceIdentifier<Interface> interfaceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
456                 .child(Interface.class, new InterfaceKey(portConfig.getIfName()));
457             Optional<Interface> interfaceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
458                 LogicalDatastoreType.OPERATIONAL, interfaceIID, Timeouts.DEVICE_READ_TIMEOUT,
459                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
460             if (interfaceObject.isEmpty() || interfaceObject.get().getSupportingCircuitPackName() == null) {
461                 continue;
462             }
463             String supportingCircuitPackName = interfaceObject.get().getSupportingCircuitPackName();
464             cpToInterfaceMap.put(supportingCircuitPackName, portConfig.getIfName());
465             InstanceIdentifier<CircuitPacks> circuitPacksIID = InstanceIdentifier
466                 .create(OrgOpenroadmDevice.class)
467                 .child(CircuitPacks.class, new CircuitPacksKey(supportingCircuitPackName));
468             Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(
469                 nodeId, LogicalDatastoreType.OPERATIONAL, circuitPacksIID, Timeouts.DEVICE_READ_TIMEOUT,
470                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
471             if (circuitPackObject.isEmpty() || circuitPackObject.get().getParentCircuitPack() == null) {
472                 continue;
473             }
474             cpToInterfaceMap.put(circuitPackObject.get().getParentCircuitPack().getCircuitPackName(),
475                 portConfig.getIfName());
476         }
477         LOG.info(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, " - success");
478         return cpToInterfaceMap;
479     }
480
481     private List<CpToDegree> getCpToDegreeList(Map<Integer, Degree> degrees, Map<String, String> interfaceList) {
482         List<CpToDegree> cpToDegreeList = new ArrayList<>();
483         for (Degree degree : degrees.values()) {
484             cpToDegreeList.addAll(degree.nonnullCircuitPacks().values().stream()
485                 .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(),
486                     degree.getDegreeNumber().toString(), interfaceList))
487                 .collect(Collectors.toList()));
488         }
489         return cpToDegreeList;
490     }
491
492     private boolean postPortMapping(String nodeId, NodeInfo nodeInfo, List<Mapping> portMapList,
493             List<CpToDegree> cp2DegreeList) {
494         NodesBuilder nodesBldr = new NodesBuilder().withKey(new NodesKey(nodeId)).setNodeId(nodeId);
495         if (nodeInfo != null) {
496             nodesBldr.setNodeInfo(nodeInfo);
497         }
498         if (portMapList != null) {
499             Map<MappingKey, Mapping> mappingMap = new HashMap<>();
500             // No element in the list below should be null at this stage
501             for (Mapping mapping: portMapList) {
502                 mappingMap.put(mapping.key(), mapping);
503             }
504             nodesBldr.setMapping(mappingMap);
505         }
506         if (cp2DegreeList != null) {
507             Map<CpToDegreeKey, CpToDegree> cpToDegreeMap = new HashMap<>();
508             // No element in the list below should be null at this stage
509             for (CpToDegree cp2Degree: cp2DegreeList) {
510                 cpToDegreeMap.put(cp2Degree.key(), cp2Degree);
511             }
512             nodesBldr.setCpToDegree(cpToDegreeMap);
513         }
514
515         Map<NodesKey,Nodes> nodesList = new HashMap<>();
516         Nodes nodes = nodesBldr.build();
517         nodesList.put(nodes.key(),nodes);
518
519         Network network = new NetworkBuilder().setNodes(nodesList).build();
520
521         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
522         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
523         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
524         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
525         try {
526             commit.get();
527             return true;
528         } catch (InterruptedException | ExecutionException e) {
529             LOG.warn(PortMappingUtils.PORTMAPPING_POST_FAIL_LOGMSG, nodeId, network, e);
530             return false;
531         }
532     }
533
534     private CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber,
535             Map<String, String> interfaceList) {
536         return new CpToDegreeBuilder()
537             .withKey(new CpToDegreeKey(circuitPackName))
538             .setCircuitPackName(circuitPackName)
539             .setDegreeNumber(Uint32.valueOf(degreeNumber))
540             .setInterfaceName(interfaceList.get(circuitPackName)).build();
541     }
542
543     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
544             String logicalConnectionPoint) {
545         MappingBuilder mpBldr = new MappingBuilder()
546                 .withKey(new MappingKey(logicalConnectionPoint))
547                 .setLogicalConnectionPoint(logicalConnectionPoint)
548                 .setSupportingCircuitPackName(circuitPackName)
549                 .setSupportingPort(port.getPortName())
550                 .setPortDirection(port.getPortDirection().getName());
551         if (port.getAdministrativeState() != null) {
552             mpBldr.setPortAdminState(port.getAdministrativeState().name());
553         }
554         if (port.getOperationalState() != null) {
555             mpBldr.setPortOperState(port.getOperationalState().name());
556         }
557         if (!logicalConnectionPoint.contains(StringConstants.TTP_TOKEN) || (port.getInterfaces() == null)) {
558             return mpBldr.build();
559         }
560         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
561         return mpBldr.build();
562     }
563
564     private Mapping updateMappingObject(String nodeId, Ports port, Mapping oldmapping) {
565         MappingBuilder mpBldr = new MappingBuilder(oldmapping);
566         updateMappingStates(mpBldr, port, oldmapping);
567         if ((port.getInterfaces() == null)
568             || (!oldmapping.getLogicalConnectionPoint().contains(StringConstants.TTP_TOKEN)
569                 && !oldmapping.getLogicalConnectionPoint().contains(StringConstants.NETWORK_TOKEN))) {
570             return mpBldr.build();
571         }
572         // Get interfaces provisioned on the port
573         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
574         return mpBldr.build();
575     }
576
577     private MappingBuilder updateMappingStates(MappingBuilder mpBldr, Ports port, Mapping oldmapping) {
578         if (port.getAdministrativeState() != null
579             && !port.getAdministrativeState().getName().equals(oldmapping.getPortAdminState())) {
580             mpBldr.setPortAdminState(port.getAdministrativeState().name());
581         }
582         if (port.getOperationalState() != null
583             && !port.getOperationalState().getName().equals(oldmapping.getPortOperState())) {
584             mpBldr.setPortOperState(port.getOperationalState().name());
585         }
586         return mpBldr;
587     }
588
589     private MappingBuilder updateMappingInterfaces(String nodeId, MappingBuilder mpBldr, Ports port) {
590         for (Interfaces interfaces : port.getInterfaces()) {
591             try {
592                 Optional<Interface> openRoadmInterface = this.openRoadmInterfaces.getInterface(nodeId,
593                     interfaces.getInterfaceName());
594                 if (openRoadmInterface.isEmpty()) {
595                     LOG.warn(PortMappingUtils.INTF_ISSUE_LOGMSG,
596                         nodeId, interfaces.getInterfaceName() + "- empty interface");
597                     continue;
598                 }
599                 LOG.debug(PortMappingUtils.GOT_INTF_LOGMSG,
600                     nodeId, openRoadmInterface.get().getName(), openRoadmInterface.get().getType());
601                 Class<? extends InterfaceType> interfaceType
602                     = (Class<? extends InterfaceType>) openRoadmInterface.get().getType();
603                 // Check if interface type is OMS or OTS
604                 if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
605                     mpBldr.setSupportingOms(interfaces.getInterfaceName());
606                 }
607                 if (interfaceType.equals(OpticalTransport.class)) {
608                     mpBldr.setSupportingOts(interfaces.getInterfaceName());
609                 }
610             } catch (OpenRoadmInterfaceException ex) {
611                 LOG.warn(PortMappingUtils.INTF_ISSUE_LOGMSG, nodeId, interfaces.getInterfaceName(), ex);
612             }
613         }
614         return mpBldr;
615     }
616
617     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
618             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String assoLcp) {
619
620         if (mapping != null && assoLcp != null) {
621             // update existing mapping
622             return new MappingBuilder(mapping).setConnectionMapLcp(assoLcp).build();
623         }
624         return createNewXpdrMapping(nodeId, port, circuitPackName, logicalConnectionPoint, partnerLcp);
625     }
626
627     private Mapping createNewXpdrMapping(String nodeId, Ports port, String circuitPackName,
628             String logicalConnectionPoint, String partnerLcp) {
629         MappingBuilder mpBldr = new MappingBuilder()
630                 .withKey(new MappingKey(logicalConnectionPoint))
631                 .setLogicalConnectionPoint(logicalConnectionPoint)
632                 .setSupportingCircuitPackName(circuitPackName)
633                 .setSupportingPort(port.getPortName())
634                 .setPortDirection(port.getPortDirection().getName())
635                 .setLcpHashVal(PortMappingUtils.fnv1size64(nodeId + "-" + logicalConnectionPoint));
636         if (port.getPortQual() != null) {
637             mpBldr.setPortQual(port.getPortQual().getName());
638         }
639         if (partnerLcp != null) {
640             mpBldr.setPartnerLcp(partnerLcp);
641         }
642         if (port.getAdministrativeState() != null) {
643             mpBldr.setPortAdminState(port.getAdministrativeState().name());
644         }
645         if (port.getOperationalState() != null) {
646             mpBldr.setPortOperState(port.getOperationalState().name());
647         }
648         return mpBldr.build();
649     }
650
651     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
652             //circuitPackName2 will be updated by reference contrary to circuitPackName
653             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
654         if (!checkPartnerPortNotNull(port)) {
655             LOG.warn(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG, nodeId, port.getPortName(), circuitPackName);
656             return null;
657         }
658         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
659             return null;
660         }
661         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
662             .filter(cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
663             .findFirst();
664         if (cpOpt.isEmpty()) {
665             LOG.error(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, port.getPartnerPort().getCircuitPackName());
666             return null;
667         }
668         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
669             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName()))
670             .findFirst();
671         if (poOpt.isEmpty()) {
672             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
673                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
674             return null;
675         }
676         Ports port2 = poOpt.get();
677         circuitPackName2.append(cpOpt.get().getCircuitPackName());
678         if (!checkPartnerPort(circuitPackName, port, port2)) {
679             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
680                 nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
681             return null;
682         }
683         return port2;
684     }
685
686     private void putXpdrLcpsInMaps(int line, String nodeId,
687             Integer xponderNb,
688             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
689             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
690         String lcp1 =
691             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
692         if (lcpMap.containsKey(lcp1)) {
693             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp1 + " - already exist");
694             return;
695         }
696         String lcp2 =
697             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
698         if (lcpMap.containsKey(lcp2)) {
699             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp2 + " - already exist");
700             return;
701         }
702         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
703         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
704         mappingMap.put(lcp1,
705                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null));
706         mappingMap.put(lcp2,
707                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null));
708         return;
709     }
710
711     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
712             Integer xponderNb,
713             String circuitPackName,  Ports port,
714             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
715
716         if (port.getPortQual() == null) {
717             LOG.warn(PortMappingUtils.PORTQUAL_LOGMSG, nodeId, port.getPortName(), circuitPackName, "not found");
718             return new int[] {line, client};
719         }
720
721         switch (port.getPortQual()) {
722
723             case XpdrClient:
724                 String lcp0 =
725                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
726                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
727                 mappingMap.put(lcp0,
728                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null));
729                 client++;
730                 break;
731
732             case XpdrNetwork:
733                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
734                         xponderNb,
735                         circuitPackName,  port,
736                         circuitPackList,  lcpMap, mappingMap);
737                 break;
738
739             default:
740                 LOG.error(PortMappingUtils.PORTQUAL_LOGMSG,
741                     nodeId, port.getPortName(), circuitPackName, port.getPortQual() + " not supported");
742         }
743         return new int[] {line, client};
744     }
745
746     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
747             Integer xponderNb,
748             String circuitPackName,  Ports port,
749             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
750
751         switch (port.getPortDirection()) {
752
753             case Bidirectional:
754                 String lcp =
755                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
756                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
757                 mappingMap.put(lcp,
758                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null));
759                 line++;
760                 break;
761
762             case Rx:
763             case Tx:
764                 StringBuilder circuitPackName2 = new StringBuilder();
765                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
766                         circuitPackList, lcpMap);
767
768                 if (port2 == null) {
769                      //key already present or an error occured and was logged
770                     return line;
771                 }
772
773                 putXpdrLcpsInMaps(line, nodeId, xponderNb,
774                         circuitPackName, circuitPackName2.toString(), port, port2,
775                         lcpMap, mappingMap);
776
777                 line += 2;
778                 break;
779
780             default:
781                 LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
782                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
783         }
784
785         return line;
786     }
787
788     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
789         // Creating mapping data for degree TTP's
790         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
791         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
792         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
793         LOG.info(PortMappingUtils.MAP_LOOKS_LOGMSG, nodeId, interfaceList);
794         postPortMapping(nodeId, null, null, cpToDegreeList);
795
796         Map<Integer, List<ConnectionPorts>> connectionPortMap = getPerDegreePorts(nodeId, deviceInfo);
797         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : connectionPortMap.entrySet()) {
798             List<ConnectionPorts> cpMapValue = cpMapEntry.getValue();
799             ConnectionPorts cp1 = cpMapValue.get(0);
800             String cp1Name = cp1.getCircuitPackName();
801             switch (cpMapValue.size()) {
802                 case 1:
803                     // port is bidirectional
804                     InstanceIdentifier<Ports> portID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
805                         .child(CircuitPacks.class, new CircuitPacksKey(cp1Name))
806                         .child(Ports.class, new PortsKey(cp1.getPortName()));
807                     LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG, nodeId, cp1.getPortName(), cp1Name);
808                     Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
809                         LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
810                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
811                     if (portObject.isEmpty()) {
812                         LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, cp1.getPortName(), cp1Name);
813                         return false;
814                     }
815                     Ports port = portObject.get();
816                     if (!checkTtpPort(port, cp1Name, nodeId, true)) {
817                         continue;
818                     }
819
820                     String logicalConnectionPoint =
821                             PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(), "TXRX");
822                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
823                         nodeId, port.getPortName(), cp1Name, logicalConnectionPoint);
824                     portMapList.add(createMappingObject(nodeId, port, cp1Name, logicalConnectionPoint));
825                     break;
826                 case 2:
827                     // ports are unidirectionals
828                     ConnectionPorts cp2 = cpMapValue.get(1);
829                     String cp2Name = cp2.getCircuitPackName();
830                     InstanceIdentifier<Ports> port1ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
831                         .child(CircuitPacks.class, new CircuitPacksKey(cp1Name))
832                         .child(Ports.class, new PortsKey(cp1.getPortName()));
833                     LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG, nodeId, cp1.getPortName(), cp1Name);
834                     Optional<Ports> port1Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
835                         LogicalDatastoreType.OPERATIONAL, port1ID, Timeouts.DEVICE_READ_TIMEOUT,
836                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
837                     InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
838                         .child(CircuitPacks.class, new CircuitPacksKey(cp2Name))
839                         .child(Ports.class, new PortsKey(cp2.getPortName()));
840                     LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG, nodeId, cp2.getPortName(), cp2Name);
841                     Optional<Ports> port2Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
842                         LogicalDatastoreType.OPERATIONAL, port2ID, Timeouts.DEVICE_READ_TIMEOUT,
843                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
844                     if (port1Object.isEmpty()) {
845                         LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, cp1.getPortName(), cp1Name);
846                         return false;
847                     }
848                     if (port2Object.isEmpty()) {
849                         LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, cp2.getPortName(), cp2Name);
850                         return false;
851                     }
852
853                     Ports port1 = port1Object.get();
854                     if (!checkTtpPort(port1, cp1Name, nodeId, false)) {
855                         continue;
856                     }
857                     Ports port2 = port2Object.get();
858                     if (!checkTtpPort(port2, cp2Name, nodeId, false)) {
859                         continue;
860                     }
861
862                     if (!checkPartnerPort(cp1Name, port1, port2)) {
863                         LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
864                             nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
865                         continue;
866                     }
867                     // Directions checks are the same for cp1 and cp2, no need to check them twice.
868                     if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
869                         LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
870                             nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
871                         continue;
872                     }
873
874                     String logicalConnectionPoint1 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
875                             port1.getPortDirection().getName().toUpperCase(Locale.getDefault()));
876                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
877                         nodeId, port1.getPortName(), cp1Name, logicalConnectionPoint1);
878                     portMapList.add(createMappingObject(nodeId, port1, cp1Name, logicalConnectionPoint1));
879                     String logicalConnectionPoint2 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
880                             port2.getPortDirection().getName().toUpperCase(Locale.getDefault()));
881                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
882                         nodeId, port2.getPortName(), cp2Name, logicalConnectionPoint2);
883                     portMapList.add(createMappingObject(nodeId, port2, cp2Name, logicalConnectionPoint2));
884                     break;
885                 default:
886                     LOG.error(PortMappingUtils.NOT_CORRECT_CONPORT_LOGMSG, nodeId, cpMapEntry.getKey());
887                     continue;
888             }
889         }
890         return true;
891     }
892
893     private boolean checkPortQual(Ports port, String cpName, String nodeId) {
894         if (port.getPortQual() == null) {
895             return false;
896         }
897         if (Port.PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
898             //used to be LOG.error when called from createTtpPortMapping
899             LOG.debug(PortMappingUtils.PORT_NOT_RDMEXT_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
900                 nodeId, port.getPortName(), cpName);
901             return false;
902         }
903         return true;
904     }
905
906     private boolean checkTtpPort(Ports port, String cpName, String nodeId, boolean bidirectional) {
907         if (!checkPortQual(port, cpName, nodeId)) {
908             return false;
909         }
910         if (Direction.Bidirectional.getIntValue() == port.getPortDirection().getIntValue() ^ bidirectional) {
911         // (a ^ b) makes more sense than (!a && b) here since it can also work for unidirectional links
912             LOG.error(PortMappingUtils.PORTDIR_ERROR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
913                 nodeId, port.getPortName(), cpName);
914             return false;
915         }
916         return true;
917     }
918
919     private NodeInfo createNodeInfo(Info deviceInfo) {
920
921         if (deviceInfo.getNodeType() == null) {
922             // TODO make mandatory in yang
923             LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "field missing");
924             return null;
925         }
926
927         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
928                 .setOpenroadmVersion(OpenroadmNodeVersion._121)
929                 .setNodeClli(
930                     deviceInfo.getClli() == null || deviceInfo.getClli().isEmpty()
931                         ? "defaultCLLI"
932                         : deviceInfo.getClli());
933         // TODO check if we can use here .setNodeType(NodeTypes.forValue(..) such as with 221
934         switch (deviceInfo.getNodeType().getIntValue()) {
935             case 1:
936             case 2:
937                 nodeInfoBldr.setNodeType(NodeTypes.forValue(deviceInfo.getNodeType().getIntValue()));
938                 break;
939             default:
940                 LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "value not supported");
941                 // TODO: is this protection useful ? it is not present in Portmapping 221
942         }
943         if (deviceInfo.getModel() != null) {
944             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
945         }
946         if (deviceInfo.getVendor() != null) {
947             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
948         }
949         if (deviceInfo.getIpAddress() != null) {
950             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
951         }
952
953         return nodeInfoBldr.build();
954     }
955
956 }