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