cded0f0779dff2d7e1089aa6dc9ed7a65b0c1b1d
[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             InterfaceType interfaceType = openRoadmInterface.get().getType();
625             // Check if interface type is OMS or OTS
626             if (interfaceType.equals(OpenROADMOpticalMultiplex.VALUE)) {
627                 mpBldr.setSupportingOms(interfaces.getInterfaceName());
628             }
629             if (interfaceType.equals(OpticalTransport.VALUE)) {
630                 mpBldr.setSupportingOts(interfaces.getInterfaceName());
631             }
632             if (interfaceType.equals(OtnOtu.VALUE)) {
633                 mpBldr.setSupportingOtu4(interfaces.getInterfaceName());
634             }
635             if (interfaceType.equals(OtnOdu.VALUE)) {
636                 mpBldr.setSupportingOdu4(interfaces.getInterfaceName());
637             }
638             if (interfaceType.equals(EthernetCsmacd.VALUE)) {
639                 mpBldr.setSupportingEthernet(interfaces.getInterfaceName());
640             }
641         }
642         return mpBldr;
643     }
644
645     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
646             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String assoLcp) {
647
648         if (mapping != null && assoLcp != null) {
649             // update existing mapping
650             return new MappingBuilder(mapping).setConnectionMapLcp(assoLcp).build();
651         }
652         return createNewXpdrMapping(nodeId, port, circuitPackName, logicalConnectionPoint, partnerLcp);
653     }
654
655     private Mapping createNewXpdrMapping(String nodeId, Ports port, String circuitPackName,
656             String logicalConnectionPoint, String partnerLcp) {
657         Set<org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev201211.SupportedIfCapability> supportedIntf =
658             new HashSet<>();
659         for (String sup: getSupIfCapList(port)) {
660             if (MappingUtilsImpl.convertSupIfCapa(sup) != null) {
661                 supportedIntf.add(MappingUtilsImpl.convertSupIfCapa(sup));
662             }
663         }
664         MappingBuilder mpBldr = new MappingBuilder()
665                 .withKey(new MappingKey(logicalConnectionPoint))
666                 .setLogicalConnectionPoint(logicalConnectionPoint)
667                 .setSupportingCircuitPackName(circuitPackName)
668                 .setSupportingPort(port.getPortName())
669                 .setPortDirection(port.getPortDirection().getName())
670                 .setXponderType(XpdrNodeTypes.Tpdr)
671                 .setLcpHashVal(PortMappingUtils.fnv1size64(nodeId + "-" + logicalConnectionPoint))
672                 .setSupportedInterfaceCapability(supportedIntf);
673         if (port.getPortQual() != null) {
674             mpBldr.setPortQual(port.getPortQual().getName());
675         }
676         if (partnerLcp != null) {
677             mpBldr.setPartnerLcp(partnerLcp);
678         }
679         if (port.getAdministrativeState() != null) {
680             mpBldr.setPortAdminState(port.getAdministrativeState().name());
681         }
682         if (port.getOperationalState() != null) {
683             mpBldr.setPortOperState(port.getOperationalState().name());
684         }
685         return mpBldr.build();
686     }
687
688     private List<String> getSupIfCapList(Ports port) {
689         Set<SupportedIfCapability> supIfCapClassList = port.getSupportedInterfaceCapability();
690         return
691             supIfCapClassList == null
692                 ? Collections.emptyList()
693                 : supIfCapClassList
694                     .stream().map(e -> e.toString())
695                     .collect(Collectors.toList());
696     }
697
698     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
699             //circuitPackName2 will be updated by reference contrary to circuitPackName
700             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
701         if (!checkPartnerPortNotNull(port)) {
702             LOG.warn(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG, nodeId, port.getPortName(), circuitPackName);
703             return null;
704         }
705         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
706             return null;
707         }
708         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
709             .filter(cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
710             .findFirst();
711         if (cpOpt.isEmpty()) {
712             LOG.error(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, port.getPartnerPort().getCircuitPackName());
713             return null;
714         }
715         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
716             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName()))
717             .findFirst();
718         if (poOpt.isEmpty()) {
719             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
720                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
721             return null;
722         }
723         Ports port2 = poOpt.get();
724         circuitPackName2.append(cpOpt.get().getCircuitPackName());
725         if (!checkPartnerPort(circuitPackName, port, port2)) {
726             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
727                 nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
728             return null;
729         }
730         return port2;
731     }
732
733     private void putXpdrLcpsInMaps(int line, String nodeId,
734             Integer xponderNb,
735             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
736             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
737         String lcp1 =
738             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
739         if (lcpMap.containsKey(lcp1)) {
740             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp1 + " - already exist");
741             return;
742         }
743         String lcp2 =
744             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
745         if (lcpMap.containsKey(lcp2)) {
746             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp2 + " - already exist");
747             return;
748         }
749         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
750         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
751         mappingMap.put(lcp1,
752                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null));
753         mappingMap.put(lcp2,
754                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null));
755         return;
756     }
757
758     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
759             Integer xponderNb,
760             String circuitPackName,  Ports port,
761             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
762
763         if (port.getPortQual() == null) {
764             LOG.warn(PortMappingUtils.PORTQUAL_LOGMSG, nodeId, port.getPortName(), circuitPackName, "not found");
765             return new int[] {line, client};
766         }
767
768         switch (port.getPortQual()) {
769
770             case XpdrClient:
771                 String lcp0 =
772                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
773                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
774                 mappingMap.put(lcp0,
775                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null));
776                 client++;
777                 break;
778
779             case XpdrNetwork:
780                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
781                         xponderNb,
782                         circuitPackName,  port,
783                         circuitPackList,  lcpMap, mappingMap);
784                 break;
785
786             default:
787                 LOG.error(PortMappingUtils.PORTQUAL_LOGMSG,
788                     nodeId, port.getPortName(), circuitPackName, port.getPortQual() + " not supported");
789         }
790         return new int[] {line, client};
791     }
792
793     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
794             Integer xponderNb,
795             String circuitPackName,  Ports port,
796             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
797
798         switch (port.getPortDirection()) {
799
800             case Bidirectional:
801                 String lcp =
802                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
803                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
804                 mappingMap.put(lcp,
805                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null));
806                 line++;
807                 break;
808
809             case Rx:
810             case Tx:
811                 StringBuilder circuitPackName2 = new StringBuilder();
812                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
813                         circuitPackList, lcpMap);
814
815                 if (port2 == null) {
816                      //key already present or an error occured and was logged
817                     return line;
818                 }
819
820                 putXpdrLcpsInMaps(line, nodeId, xponderNb,
821                         circuitPackName, circuitPackName2.toString(), port, port2,
822                         lcpMap, mappingMap);
823
824                 line += 2;
825                 break;
826
827             default:
828                 LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
829                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
830         }
831
832         return line;
833     }
834
835     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
836         // Creating mapping data for degree TTP's
837         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
838         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
839         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
840         LOG.info(PortMappingUtils.MAP_LOOKS_LOGMSG, nodeId, interfaceList);
841         postPortMapping(nodeId, null, null, cpToDegreeList);
842
843         Map<Integer, List<ConnectionPorts>> connectionPortMap = getPerDegreePorts(nodeId, deviceInfo);
844         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : connectionPortMap.entrySet()) {
845             List<ConnectionPorts> cpMapValue = cpMapEntry.getValue();
846             ConnectionPorts cp1 = cpMapValue.get(0);
847             String cp1Name = cp1.getCircuitPackName();
848             switch (cpMapValue.size()) {
849                 case 1:
850                     // port is bidirectional
851                     Ports port = getTtpPort(cp1, cp1Name, nodeId);
852                     if (port == null) {
853                         return false;
854                     }
855                     if (!checkTtpPort(port, cp1Name, nodeId, true)) {
856                         continue;
857                     }
858                     String logicalConnectionPoint =
859                             PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(), "TXRX");
860                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
861                         nodeId, port.getPortName(), cp1Name, logicalConnectionPoint);
862                     portMapList.add(createMappingObject(nodeId, port, cp1Name, logicalConnectionPoint));
863                     break;
864                 case 2:
865                     // ports are unidirectionals
866                     Ports port1 = getTtpPort(cp1, cp1Name, nodeId);
867                     if (port1 == null) {
868                         return false;
869                     }
870                     ConnectionPorts cp2 = cpMapValue.get(1);
871                     String cp2Name = cp2.getCircuitPackName();
872                     Ports port2 = getTtpPort(cp2, cp2Name, nodeId);
873                     if (port2 == null) {
874                         return false;
875                     }
876                     if (!checkTtpPortsUnidir(port1, port2, cp1Name, cp2Name, nodeId)) {
877                         continue;
878                     }
879                     String logicalConnectionPoint1 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
880                             port1.getPortDirection().getName().toUpperCase(Locale.getDefault()));
881                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
882                         nodeId, port1.getPortName(), cp1Name, logicalConnectionPoint1);
883                     portMapList.add(createMappingObject(nodeId, port1, cp1Name, logicalConnectionPoint1));
884                     String logicalConnectionPoint2 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
885                             port2.getPortDirection().getName().toUpperCase(Locale.getDefault()));
886                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
887                         nodeId, port2.getPortName(), cp2Name, logicalConnectionPoint2);
888                     portMapList.add(createMappingObject(nodeId, port2, cp2Name, logicalConnectionPoint2));
889                     break;
890                 default:
891                     LOG.error(PortMappingUtils.NOT_CORRECT_CONPORT_LOGMSG, nodeId, cpMapEntry.getKey());
892                     continue;
893                     //TODO should it be continue or return false ?
894             }
895         }
896         return true;
897     }
898
899     private Ports getTtpPort(ConnectionPorts cp, String cpName, String nodeId) {
900         InstanceIdentifier<Ports> portID = InstanceIdentifier
901             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
902             .child(CircuitPacks.class, new CircuitPacksKey(cpName))
903             .child(Ports.class, new PortsKey(cp.getPortName()))
904             .build();
905         LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG, nodeId, cp.getPortName(), cpName);
906         Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
907             LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
908             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
909         if (portObject.isEmpty()) {
910             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, cp.getPortName(), cpName);
911             return null;
912         }
913         return portObject.get();
914     }
915
916     private boolean checkPortQual(Ports port, String cpName, String nodeId) {
917         if (port.getPortQual() == null) {
918             return false;
919         }
920         if (Port.PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
921             //used to be LOG.error when called from createTtpPortMapping
922             LOG.debug(PortMappingUtils.PORT_NOT_RDMEXT_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
923                 nodeId, port.getPortName(), cpName);
924             return false;
925         }
926         return true;
927     }
928
929     private boolean checkTtpPort(Ports port, String cpName, String nodeId, boolean bidirectional) {
930         if (!checkPortQual(port, cpName, nodeId)) {
931             return false;
932         }
933         if (Direction.Bidirectional.getIntValue() == port.getPortDirection().getIntValue() ^ bidirectional) {
934         // (a ^ b) makes more sense than (!a && b) here since it can also work for unidirectional links
935             LOG.error(PortMappingUtils.PORTDIR_ERROR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
936                 nodeId, port.getPortName(), cpName);
937             return false;
938         }
939         return true;
940     }
941
942     private boolean checkTtpPortsUnidir(Ports port1, Ports port2, String cp1Name, String cp2Name, String nodeId) {
943         if (!checkTtpPort(port1, cp1Name, nodeId, false)) {
944             return false;
945         }
946         if (!checkTtpPort(port2, cp2Name, nodeId, false)) {
947             return false;
948         }
949         if (!checkPartnerPort(cp1Name, port1, port2)) {
950             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
951                 nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
952             return false;
953         }
954         // Directions checks are the same for cp1 and cp2, no need to check them twice.
955         if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
956             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
957                 nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
958             return false;
959         }
960         return true;
961     }
962
963     private NodeInfo createNodeInfo(Info deviceInfo) {
964         if (deviceInfo.getNodeType() == null) {
965             // TODO make mandatory in yang
966             LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "field missing");
967             return null;
968         }
969         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
970                 .setOpenroadmVersion(OpenroadmNodeVersion._121)
971                 .setNodeClli(
972                     deviceInfo.getClli() == null || deviceInfo.getClli().isEmpty()
973                         ? "defaultCLLI"
974                         : deviceInfo.getClli());
975         // TODO check if we can use here .setNodeType(NodeTypes.forValue(..) such as with 221
976         switch (deviceInfo.getNodeType().getIntValue()) {
977             case 1:
978             case 2:
979                 nodeInfoBldr.setNodeType(NodeTypes.forValue(deviceInfo.getNodeType().getIntValue()));
980                 break;
981             default:
982                 LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "value not supported");
983                 // TODO: is this protection useful ? it is not present in Portmapping 221
984         }
985         if (deviceInfo.getModel() != null) {
986             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
987         }
988         if (deviceInfo.getVendor() != null) {
989             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
990         }
991         if (deviceInfo.getIpAddress() != null) {
992             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
993         }
994         return nodeInfoBldr.build();
995     }
996
997     private Optional<Interface> getInterfaceFromDevice(String nodeId, String interfaceName) {
998         InstanceIdentifier<Interface> interfacesIID = InstanceIdentifier
999             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
1000             .child(Interface.class, new InterfaceKey(interfaceName))
1001             .build();
1002         return deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.CONFIGURATION,
1003             interfacesIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1004     }
1005 }