Merge "Change the ODU4 type to ODU-TTP-CTP"
[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.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.Network;
33 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.NetworkBuilder;
34 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.OpenroadmNodeVersion;
35 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.cp.to.degree.CpToDegree;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.cp.to.degree.CpToDegreeBuilder;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.cp.to.degree.CpToDegreeKey;
38 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.mapping.Mapping;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.mapping.MappingBuilder;
40 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.mapping.MappingKey;
41 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.network.Nodes;
42 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.network.NodesBuilder;
43 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.network.NodesKey;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.network.nodes.NodeInfo;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.network.nodes.NodeInfoBuilder;
46 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.Direction;
47 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.CircuitPack;
48 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.Port;
49 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.pack.Ports;
50 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.pack.PortsKey;
51 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.packs.CircuitPacks;
52 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.packs.CircuitPacksKey;
53 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.degree.ConnectionPorts;
54 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.Interface;
55 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.InterfaceKey;
56 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
57 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.ConnectionMap;
58 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Degree;
59 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.DegreeKey;
60 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Info;
61 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Protocols;
62 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.SharedRiskGroup;
63 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.SharedRiskGroupKey;
64 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.connection.map.Destination;
65 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.port.Interfaces;
66 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.NodeTypes;
67 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.XpdrNodeTypes;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.EthernetCsmacd;
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.interfaces.rev161014.OtnOdu;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.OtnOtu;
74 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev161014.Protocols1;
75 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev161014.lldp.container.Lldp;
76 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev161014.lldp.container.lldp.PortConfig;
77 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev170929.SupportedIfCapability;
78 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
79 import org.opendaylight.yangtools.yang.common.Uint16;
80 import org.opendaylight.yangtools.yang.common.Uint32;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 // FIXME: many common pieces of code between PortMapping Versions 121 and 221 and 710
85 // some mutualization would be helpful
86 @SuppressWarnings("CPD-START")
87 public class PortMappingVersion121 {
88
89     private static final Logger LOG = LoggerFactory.getLogger(PortMappingVersion121.class);
90     private static final Map<Direction, String> SUFFIX;
91     private static final Set<Integer> TXRX_SET = Set.of(Direction.Tx.getIntValue(), Direction.Rx.getIntValue());
92
93     private final DataBroker dataBroker;
94     private final DeviceTransactionManager deviceTransactionManager;
95
96     static {
97         SUFFIX =  Map.of(
98             Direction.Tx, "TX",
99             Direction.Rx, "RX",
100             Direction.Bidirectional, "TXRX");
101     }
102
103     public PortMappingVersion121(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager) {
104         this.dataBroker = dataBroker;
105         this.deviceTransactionManager = deviceTransactionManager;
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, PortMappingUtils.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, PortMappingUtils.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, PortMappingUtils.CREATE, "Xponder");
145                     return false;
146                 }
147                 break;
148             default:
149                 LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
150                     nodeId, PortMappingUtils.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" , PortMappingUtils.UPDATE, "a null value");
160             return false;
161         }
162         if (oldMapping == null) {
163             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, PortMappingUtils.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, PortMappingUtils.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, PortMappingUtils.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, PortMappingUtils.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             int portIndex = 1;
300             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg.CircuitPacks
301                     cp : srgCpEntry.getValue()) {
302                 String circuitPackName = cp.getCircuitPackName();
303                 List<Ports> portList = getPortList(circuitPackName, nodeId);
304                 Collections.sort(portList, new SortPort121ByName());
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                             Ports port2 = getPartnerPort(port, circuitPackName, nodeId);
327                             if (port2 == null) {
328                                 continue;
329                             }
330                             String lcp1 = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
331                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
332                                 nodeId, port.getPortName(), circuitPackName, lcp1);
333                             String lcp2 = createLogicalConnectionPort(port2, srgCpEntry.getKey(),portIndex);
334                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
335                                 nodeId, port2.getPortName(), circuitPackName, lcp2);
336                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp1));
337                             portMapList.add(
338                                 createMappingObject(nodeId ,port2, port.getPartnerPort().getCircuitPackName(), lcp2));
339                             portIndex++;
340                             keys.add(currentKey);
341                             keys.add(port.getPartnerPort().getCircuitPackName() + "-" + port2.getPortName());
342                             break;
343                         default:
344                             LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
345                                 nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
346                     }
347                 }
348             }
349         }
350         return true;
351     }
352
353     private Ports getPartnerPort(Ports port, String circuitPackName, String nodeId) {
354         if (!checkPartnerPortNotNull(port)) {
355             LOG.info(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
356                 nodeId, port.getPortName(), circuitPackName);
357             return null;
358         }
359         InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
360             .child(CircuitPacks.class, new CircuitPacksKey(port.getPartnerPort().getCircuitPackName()))
361             .child(Ports.class, new PortsKey(port.getPartnerPort().getPortName()));
362         Optional<Ports> port2Object = this.deviceTransactionManager
363             .getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, port2ID,
364                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
365         if (port2Object.isEmpty()
366                 || port2Object.get().getPortQual().getIntValue() != Port.PortQual.RoadmExternal.getIntValue()) {
367             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG + PortMappingUtils.PARTNERPORT_GET_ERROR_LOGMSG,
368                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName(),
369                 port.getPortName(), circuitPackName);
370             return null;
371         }
372         Ports port2 = port2Object.get();
373         if (!checkPartnerPort(circuitPackName, port, port2)) {
374             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG + PortMappingUtils.PARTNERPORT_CONF_ERROR_LOGMSG,
375                 nodeId, port2.getPortName(), port.getPartnerPort().getCircuitPackName(),
376                 port.getPortName(), circuitPackName);
377             //TODO check if we really needed to increment portIndex in this condition
378             //     if yes this block should not be in getPartnerPort and must move back to createPpPortMapping
379             return null;
380         }
381         return port2;
382     }
383
384     private List<Ports> getPortList(String circuitPackName, String nodeId) {
385         InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
386             .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
387         Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
388              LogicalDatastoreType.OPERATIONAL, cpIID,
389              Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
390         if (circuitPackObject.isEmpty()) {
391             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
392                 nodeId, circuitPackName);
393             return new ArrayList<>();
394         }
395         if (circuitPackObject.get().getPorts() == null) {
396             LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, PortMappingUtils.FOUND, circuitPackName);
397             return new ArrayList<>();
398         }
399         return new ArrayList<>(circuitPackObject.get().nonnullPorts().values());
400     }
401
402     private String createLogicalConnectionPort(Ports port, int index, int portIndex) {
403         if (SUFFIX.containsKey(port.getPortDirection())) {
404             return String.join("-", "SRG" + index, "PP" + portIndex, SUFFIX.get(port.getPortDirection()));
405         }
406         LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
407             "createLogicalConnectionPort", port, "SRG" + index + "-PP" + portIndex, port.getPortDirection());
408         return null;
409     }
410
411     private Map<Integer, Degree> getDegreesMap(String deviceId, Info ordmInfo) {
412         Map<Integer, Degree> degrees = new HashMap<>();
413
414         // Get value for max degree from info subtree, required for iteration
415         // if not present assume to be 20 (temporary)
416         Integer maxDegree = ordmInfo.getMaxDegrees() == null ? 20 : ordmInfo.getMaxDegrees().toJava();
417
418         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
419             LOG.debug(PortMappingUtils.GETTING_CONPORT_LOGMSG, deviceId, degreeCounter);
420             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
421                 .child(Degree.class, new DegreeKey(Uint16.valueOf(degreeCounter)));
422             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
423                 LogicalDatastoreType.OPERATIONAL, deviceIID,
424                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
425             if (ordmDegreeObject.isPresent()) {
426                 degrees.put(degreeCounter, ordmDegreeObject.get());
427             }
428         }
429         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG,
430                 deviceId, degrees.size(), degrees.size() <= 1 ? "degree" : "degrees");
431         return degrees;
432     }
433
434     private Map<Integer, List<ConnectionPorts>> getPerDegreePorts(String deviceId, Info ordmInfo) {
435         Map<Integer, List<ConnectionPorts>> conPortMap = new HashMap<>();
436         getDegreesMap(deviceId, ordmInfo).forEach(
437             (index, degree) -> conPortMap.put(index, new ArrayList<>(degree.nonnullConnectionPorts().values())));
438         return conPortMap;
439     }
440
441     private Map<String, String> getEthInterfaceList(String nodeId) {
442         LOG.info(PortMappingUtils.GETTING_ETH_LIST_LOGMSG, nodeId);
443         InstanceIdentifier<Protocols> protocoliid = InstanceIdentifier.create(OrgOpenroadmDevice.class)
444             .child(Protocols.class);
445         Optional<Protocols> protocolObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
446             LogicalDatastoreType.OPERATIONAL, protocoliid, Timeouts.DEVICE_READ_TIMEOUT,
447             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
448         if (protocolObject.isEmpty() || protocolObject.get().augmentation(Protocols1.class).getLldp() == null) {
449             LOG.warn(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, PortMappingUtils.CANNOT_GET_LLDP_CONF_LOGMSG);
450             return new HashMap<>();
451         }
452         Map<String, String> cpToInterfaceMap = new HashMap<>();
453         Lldp lldp = protocolObject.get().augmentation(Protocols1.class).getLldp();
454         for (PortConfig portConfig : lldp.nonnullPortConfig().values()) {
455             if (!portConfig.getAdminStatus().equals(PortConfig.AdminStatus.Txandrx)) {
456                 continue;
457             }
458             InstanceIdentifier<Interface> interfaceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
459                 .child(Interface.class, new InterfaceKey(portConfig.getIfName()));
460             Optional<Interface> interfaceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
461                 LogicalDatastoreType.OPERATIONAL, interfaceIID, Timeouts.DEVICE_READ_TIMEOUT,
462                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
463             if (interfaceObject.isEmpty() || interfaceObject.get().getSupportingCircuitPackName() == null) {
464                 continue;
465             }
466             String supportingCircuitPackName = interfaceObject.get().getSupportingCircuitPackName();
467             cpToInterfaceMap.put(supportingCircuitPackName, portConfig.getIfName());
468             InstanceIdentifier<CircuitPacks> circuitPacksIID = InstanceIdentifier
469                 .create(OrgOpenroadmDevice.class)
470                 .child(CircuitPacks.class, new CircuitPacksKey(supportingCircuitPackName));
471             Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(
472                 nodeId, LogicalDatastoreType.OPERATIONAL, circuitPacksIID, Timeouts.DEVICE_READ_TIMEOUT,
473                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
474             if (circuitPackObject.isEmpty() || circuitPackObject.get().getParentCircuitPack() == null) {
475                 continue;
476             }
477             cpToInterfaceMap.put(circuitPackObject.get().getParentCircuitPack().getCircuitPackName(),
478                 portConfig.getIfName());
479         }
480         LOG.info(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, " - success");
481         return cpToInterfaceMap;
482     }
483
484     private List<CpToDegree> getCpToDegreeList(Map<Integer, Degree> degrees, Map<String, String> interfaceList) {
485         List<CpToDegree> cpToDegreeList = new ArrayList<>();
486         for (Degree degree : degrees.values()) {
487             cpToDegreeList.addAll(degree.nonnullCircuitPacks().values().stream()
488                 .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(),
489                     degree.getDegreeNumber().toString(), interfaceList))
490                 .collect(Collectors.toList()));
491         }
492         return cpToDegreeList;
493     }
494
495     private boolean postPortMapping(String nodeId, NodeInfo nodeInfo, List<Mapping> portMapList,
496             List<CpToDegree> cp2DegreeList) {
497         NodesBuilder nodesBldr = new NodesBuilder().withKey(new NodesKey(nodeId)).setNodeId(nodeId);
498         if (nodeInfo != null) {
499             nodesBldr.setNodeInfo(nodeInfo);
500         }
501         if (portMapList != null) {
502             Map<MappingKey, Mapping> mappingMap = new HashMap<>();
503             // No element in the list below should be null at this stage
504             for (Mapping mapping: portMapList) {
505                 mappingMap.put(mapping.key(), mapping);
506             }
507             nodesBldr.setMapping(mappingMap);
508         }
509         if (cp2DegreeList != null) {
510             Map<CpToDegreeKey, CpToDegree> cpToDegreeMap = new HashMap<>();
511             // No element in the list below should be null at this stage
512             for (CpToDegree cp2Degree: cp2DegreeList) {
513                 cpToDegreeMap.put(cp2Degree.key(), cp2Degree);
514             }
515             nodesBldr.setCpToDegree(cpToDegreeMap);
516         }
517
518         Map<NodesKey,Nodes> nodesList = new HashMap<>();
519         Nodes nodes = nodesBldr.build();
520         nodesList.put(nodes.key(),nodes);
521
522         Network network = new NetworkBuilder().setNodes(nodesList).build();
523
524         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
525         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
526         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
527         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
528         try {
529             commit.get();
530             return true;
531         } catch (InterruptedException | ExecutionException e) {
532             LOG.warn(PortMappingUtils.PORTMAPPING_POST_FAIL_LOGMSG, nodeId, network, e);
533             return false;
534         }
535     }
536
537     private CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber,
538             Map<String, String> interfaceList) {
539         return new CpToDegreeBuilder()
540             .withKey(new CpToDegreeKey(circuitPackName))
541             .setCircuitPackName(circuitPackName)
542             .setDegreeNumber(Uint32.valueOf(degreeNumber))
543             .setInterfaceName(interfaceList.get(circuitPackName)).build();
544     }
545
546     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
547             String logicalConnectionPoint) {
548         MappingBuilder mpBldr = new MappingBuilder()
549                 .withKey(new MappingKey(logicalConnectionPoint))
550                 .setLogicalConnectionPoint(logicalConnectionPoint)
551                 .setSupportingCircuitPackName(circuitPackName)
552                 .setSupportingPort(port.getPortName())
553                 .setPortDirection(port.getPortDirection().getName());
554         if (port.getAdministrativeState() != null) {
555             mpBldr.setPortAdminState(port.getAdministrativeState().name());
556         }
557         if (port.getOperationalState() != null) {
558             mpBldr.setPortOperState(port.getOperationalState().name());
559         }
560         if (!logicalConnectionPoint.contains(StringConstants.TTP_TOKEN) || (port.getInterfaces() == null)) {
561             return mpBldr.build();
562         }
563         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
564         return mpBldr.build();
565     }
566
567     private Mapping updateMappingObject(String nodeId, Ports port, Mapping oldmapping) {
568         MappingBuilder mpBldr = new MappingBuilder(oldmapping);
569         updateMappingStates(mpBldr, port, oldmapping);
570         if (port.getInterfaces() == null) {
571             return mpBldr.build();
572         }
573         // Get interfaces provisioned on the port
574         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
575         return mpBldr.build();
576     }
577
578     private MappingBuilder updateMappingStates(MappingBuilder mpBldr, Ports port, Mapping oldmapping) {
579         if (port.getAdministrativeState() != null
580             && !port.getAdministrativeState().getName().equals(oldmapping.getPortAdminState())) {
581             mpBldr.setPortAdminState(port.getAdministrativeState().name());
582         }
583         if (port.getOperationalState() != null
584             && !port.getOperationalState().getName().equals(oldmapping.getPortOperState())) {
585             mpBldr.setPortOperState(port.getOperationalState().name());
586         }
587         return mpBldr;
588     }
589
590     private MappingBuilder updateMappingInterfaces(String nodeId, MappingBuilder mpBldr, Ports port) {
591         mpBldr.setSupportingOtu4(null)
592             .setSupportingOdu4(null);
593         for (Interfaces interfaces : port.getInterfaces()) {
594             Optional<Interface> openRoadmInterface = getInterfaceFromDevice(nodeId, interfaces.getInterfaceName());
595             if (openRoadmInterface.isEmpty()) {
596                 LOG.warn(PortMappingUtils.INTF_ISSUE_LOGMSG,
597                     nodeId, interfaces.getInterfaceName() + "- empty interface");
598                 continue;
599             }
600             LOG.debug(PortMappingUtils.GOT_INTF_LOGMSG,
601                 nodeId, openRoadmInterface.get().getName(), openRoadmInterface.get().getType());
602             Class<? extends InterfaceType> interfaceType
603                 = (Class<? extends InterfaceType>) openRoadmInterface.get().getType();
604             // Check if interface type is OMS or OTS
605             if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
606                 mpBldr.setSupportingOms(interfaces.getInterfaceName());
607             }
608             if (interfaceType.equals(OpticalTransport.class)) {
609                 mpBldr.setSupportingOts(interfaces.getInterfaceName());
610             }
611             if (interfaceType.equals(OtnOtu.class)) {
612                 mpBldr.setSupportingOtu4(interfaces.getInterfaceName());
613             }
614             if (interfaceType.equals(OtnOdu.class)) {
615                 mpBldr.setSupportingOdu4(interfaces.getInterfaceName());
616             }
617             if (interfaceType.equals(EthernetCsmacd.class)) {
618                 mpBldr.setSupportingEthernet(interfaces.getInterfaceName());
619             }
620         }
621         return mpBldr;
622     }
623
624     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
625             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String assoLcp) {
626
627         if (mapping != null && assoLcp != null) {
628             // update existing mapping
629             return new MappingBuilder(mapping).setConnectionMapLcp(assoLcp).build();
630         }
631         return createNewXpdrMapping(nodeId, port, circuitPackName, logicalConnectionPoint, partnerLcp);
632     }
633
634     private Mapping createNewXpdrMapping(String nodeId, Ports port, String circuitPackName,
635             String logicalConnectionPoint, String partnerLcp) {
636         List<Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
637             .SupportedIfCapability>> supportedIntf = new ArrayList<>();
638         for (String sup: getSupIfCapList(port)) {
639             if (MappingUtilsImpl.convertSupIfCapa(sup) != null) {
640                 supportedIntf.add(MappingUtilsImpl.convertSupIfCapa(sup));
641             }
642         }
643         MappingBuilder mpBldr = new MappingBuilder()
644                 .withKey(new MappingKey(logicalConnectionPoint))
645                 .setLogicalConnectionPoint(logicalConnectionPoint)
646                 .setSupportingCircuitPackName(circuitPackName)
647                 .setSupportingPort(port.getPortName())
648                 .setPortDirection(port.getPortDirection().getName())
649                 .setXponderType(XpdrNodeTypes.Tpdr)
650                 .setLcpHashVal(PortMappingUtils.fnv1size64(nodeId + "-" + logicalConnectionPoint))
651                 .setSupportedInterfaceCapability(supportedIntf);
652         if (port.getPortQual() != null) {
653             mpBldr.setPortQual(port.getPortQual().getName());
654         }
655         if (partnerLcp != null) {
656             mpBldr.setPartnerLcp(partnerLcp);
657         }
658         if (port.getAdministrativeState() != null) {
659             mpBldr.setPortAdminState(port.getAdministrativeState().name());
660         }
661         if (port.getOperationalState() != null) {
662             mpBldr.setPortOperState(port.getOperationalState().name());
663         }
664         return mpBldr.build();
665     }
666
667     private List<String> getSupIfCapList(Ports port) {
668         List<Class<? extends SupportedIfCapability>> supIfCapClassList = port.getSupportedInterfaceCapability();
669         return
670             supIfCapClassList == null
671                 ? Collections.emptyList()
672                 : supIfCapClassList
673                     .stream().map(e -> e.getSimpleName())
674                     .collect(Collectors.toList());
675     }
676
677     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
678             //circuitPackName2 will be updated by reference contrary to circuitPackName
679             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
680         if (!checkPartnerPortNotNull(port)) {
681             LOG.warn(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG, nodeId, port.getPortName(), circuitPackName);
682             return null;
683         }
684         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
685             return null;
686         }
687         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
688             .filter(cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
689             .findFirst();
690         if (cpOpt.isEmpty()) {
691             LOG.error(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, port.getPartnerPort().getCircuitPackName());
692             return null;
693         }
694         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
695             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName()))
696             .findFirst();
697         if (poOpt.isEmpty()) {
698             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
699                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
700             return null;
701         }
702         Ports port2 = poOpt.get();
703         circuitPackName2.append(cpOpt.get().getCircuitPackName());
704         if (!checkPartnerPort(circuitPackName, port, port2)) {
705             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
706                 nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
707             return null;
708         }
709         return port2;
710     }
711
712     private void putXpdrLcpsInMaps(int line, String nodeId,
713             Integer xponderNb,
714             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
715             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
716         String lcp1 =
717             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
718         if (lcpMap.containsKey(lcp1)) {
719             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp1 + " - already exist");
720             return;
721         }
722         String lcp2 =
723             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
724         if (lcpMap.containsKey(lcp2)) {
725             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp2 + " - already exist");
726             return;
727         }
728         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
729         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
730         mappingMap.put(lcp1,
731                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null));
732         mappingMap.put(lcp2,
733                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null));
734         return;
735     }
736
737     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
738             Integer xponderNb,
739             String circuitPackName,  Ports port,
740             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
741
742         if (port.getPortQual() == null) {
743             LOG.warn(PortMappingUtils.PORTQUAL_LOGMSG, nodeId, port.getPortName(), circuitPackName, "not found");
744             return new int[] {line, client};
745         }
746
747         switch (port.getPortQual()) {
748
749             case XpdrClient:
750                 String lcp0 =
751                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
752                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
753                 mappingMap.put(lcp0,
754                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null));
755                 client++;
756                 break;
757
758             case XpdrNetwork:
759                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
760                         xponderNb,
761                         circuitPackName,  port,
762                         circuitPackList,  lcpMap, mappingMap);
763                 break;
764
765             default:
766                 LOG.error(PortMappingUtils.PORTQUAL_LOGMSG,
767                     nodeId, port.getPortName(), circuitPackName, port.getPortQual() + " not supported");
768         }
769         return new int[] {line, client};
770     }
771
772     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
773             Integer xponderNb,
774             String circuitPackName,  Ports port,
775             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
776
777         switch (port.getPortDirection()) {
778
779             case Bidirectional:
780                 String lcp =
781                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
782                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
783                 mappingMap.put(lcp,
784                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null));
785                 line++;
786                 break;
787
788             case Rx:
789             case Tx:
790                 StringBuilder circuitPackName2 = new StringBuilder();
791                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
792                         circuitPackList, lcpMap);
793
794                 if (port2 == null) {
795                      //key already present or an error occured and was logged
796                     return line;
797                 }
798
799                 putXpdrLcpsInMaps(line, nodeId, xponderNb,
800                         circuitPackName, circuitPackName2.toString(), port, port2,
801                         lcpMap, mappingMap);
802
803                 line += 2;
804                 break;
805
806             default:
807                 LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
808                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
809         }
810
811         return line;
812     }
813
814     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
815         // Creating mapping data for degree TTP's
816         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
817         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
818         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
819         LOG.info(PortMappingUtils.MAP_LOOKS_LOGMSG, nodeId, interfaceList);
820         postPortMapping(nodeId, null, null, cpToDegreeList);
821
822         Map<Integer, List<ConnectionPorts>> connectionPortMap = getPerDegreePorts(nodeId, deviceInfo);
823         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : connectionPortMap.entrySet()) {
824             List<ConnectionPorts> cpMapValue = cpMapEntry.getValue();
825             ConnectionPorts cp1 = cpMapValue.get(0);
826             String cp1Name = cp1.getCircuitPackName();
827             switch (cpMapValue.size()) {
828                 case 1:
829                     // port is bidirectional
830                     Ports port = getTtpPort(cp1, cp1Name, nodeId);
831                     if (port == null) {
832                         return false;
833                     }
834                     if (!checkTtpPort(port, cp1Name, nodeId, true)) {
835                         continue;
836                     }
837                     String logicalConnectionPoint =
838                             PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(), "TXRX");
839                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
840                         nodeId, port.getPortName(), cp1Name, logicalConnectionPoint);
841                     portMapList.add(createMappingObject(nodeId, port, cp1Name, logicalConnectionPoint));
842                     break;
843                 case 2:
844                     // ports are unidirectionals
845                     Ports port1 = getTtpPort(cp1, cp1Name, nodeId);
846                     if (port1 == null) {
847                         return false;
848                     }
849                     ConnectionPorts cp2 = cpMapValue.get(1);
850                     String cp2Name = cp2.getCircuitPackName();
851                     Ports port2 = getTtpPort(cp2, cp2Name, nodeId);
852                     if (port2 == null) {
853                         return false;
854                     }
855                     if (!checkTtpPortsUnidir(port1, port2, cp1Name, cp2Name, nodeId)) {
856                         continue;
857                     }
858                     String logicalConnectionPoint1 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
859                             port1.getPortDirection().getName().toUpperCase(Locale.getDefault()));
860                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
861                         nodeId, port1.getPortName(), cp1Name, logicalConnectionPoint1);
862                     portMapList.add(createMappingObject(nodeId, port1, cp1Name, logicalConnectionPoint1));
863                     String logicalConnectionPoint2 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
864                             port2.getPortDirection().getName().toUpperCase(Locale.getDefault()));
865                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
866                         nodeId, port2.getPortName(), cp2Name, logicalConnectionPoint2);
867                     portMapList.add(createMappingObject(nodeId, port2, cp2Name, logicalConnectionPoint2));
868                     break;
869                 default:
870                     LOG.error(PortMappingUtils.NOT_CORRECT_CONPORT_LOGMSG, nodeId, cpMapEntry.getKey());
871                     continue;
872                     //TODO should it be continue or return false ?
873             }
874         }
875         return true;
876     }
877
878     private Ports getTtpPort(ConnectionPorts cp, String cpName, String nodeId) {
879         InstanceIdentifier<Ports> portID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
880             .child(CircuitPacks.class, new CircuitPacksKey(cpName))
881             .child(Ports.class, new PortsKey(cp.getPortName()));
882         LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG, nodeId, cp.getPortName(), cpName);
883         Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
884             LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
885             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
886         if (portObject.isEmpty()) {
887             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, cp.getPortName(), cpName);
888             return null;
889         }
890         return portObject.get();
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 boolean checkTtpPortsUnidir(Ports port1, Ports port2, String cp1Name, String cp2Name, String nodeId) {
920         if (!checkTtpPort(port1, cp1Name, nodeId, false)) {
921             return false;
922         }
923         if (!checkTtpPort(port2, cp2Name, nodeId, false)) {
924             return false;
925         }
926         if (!checkPartnerPort(cp1Name, port1, port2)) {
927             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
928                 nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
929             return false;
930         }
931         // Directions checks are the same for cp1 and cp2, no need to check them twice.
932         if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
933             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
934                 nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
935             return false;
936         }
937         return true;
938     }
939
940     private NodeInfo createNodeInfo(Info deviceInfo) {
941         if (deviceInfo.getNodeType() == null) {
942             // TODO make mandatory in yang
943             LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "field missing");
944             return null;
945         }
946         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
947                 .setOpenroadmVersion(OpenroadmNodeVersion._121)
948                 .setNodeClli(
949                     deviceInfo.getClli() == null || deviceInfo.getClli().isEmpty()
950                         ? "defaultCLLI"
951                         : deviceInfo.getClli());
952         // TODO check if we can use here .setNodeType(NodeTypes.forValue(..) such as with 221
953         switch (deviceInfo.getNodeType().getIntValue()) {
954             case 1:
955             case 2:
956                 nodeInfoBldr.setNodeType(NodeTypes.forValue(deviceInfo.getNodeType().getIntValue()));
957                 break;
958             default:
959                 LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "value not supported");
960                 // TODO: is this protection useful ? it is not present in Portmapping 221
961         }
962         if (deviceInfo.getModel() != null) {
963             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
964         }
965         if (deviceInfo.getVendor() != null) {
966             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
967         }
968         if (deviceInfo.getIpAddress() != null) {
969             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
970         }
971         return nodeInfoBldr.build();
972     }
973
974     private Optional<Interface> getInterfaceFromDevice(String nodeId, String interfaceName) {
975         InstanceIdentifier<Interface> interfacesIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
976             .child(Interface.class, new InterfaceKey(interfaceName));
977         return deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.CONFIGURATION,
978             interfacesIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
979     }
980 }