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