134840ddaceb8cd24e48b656e78467a37fd807c1
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / mapping / PortMappingVersion710.java
1 /*
2  * Copyright © 2020 AT&T, Inc. 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.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.ReadTransaction;
28 import org.opendaylight.mdsal.binding.api.WriteTransaction;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.transportpce.common.StringConstants;
32 import org.opendaylight.transportpce.common.Timeouts;
33 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
34 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
35 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.Network;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.NetworkBuilder;
38 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.OpenroadmNodeVersion;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.cp.to.degree.CpToDegree;
40 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.cp.to.degree.CpToDegreeBuilder;
41 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.cp.to.degree.CpToDegreeKey;
42 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mapping.Mapping;
43 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mapping.MappingBuilder;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mapping.MappingKey;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mc.capabilities.McCapabilities;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mc.capabilities.McCapabilitiesBuilder;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mc.capabilities.McCapabilitiesKey;
48 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mpdr.restrictions.grp.MpdrRestrictionsBuilder;
49 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.Nodes;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.NodesBuilder;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.NodesKey;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.nodes.NodeInfo;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.nodes.NodeInfoBuilder;
54 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.SwitchingPoolLcp;
55 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.SwitchingPoolLcpBuilder;
56 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.SwitchingPoolLcpKey;
57 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.switching.pool.lcp.NonBlockingList;
58 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.switching.pool.lcp.NonBlockingListBuilder;
59 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.switching.pool.lcp.NonBlockingListKey;
60 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.alarm.pm.types.rev191129.Direction;
61 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.optical.channel.types.rev200529.FrequencyGHz;
62 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.CircuitPack;
63 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.pack.Ports;
64 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.pack.PortsKey;
65 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacks;
66 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacksKey;
67 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.degree.ConnectionPorts;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.Interface;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.InterfaceKey;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.OrgOpenroadmDevice;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.ConnectionMap;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Degree;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.DegreeKey;
74 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Info;
75 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.McCapabilityProfile;
76 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.McCapabilityProfileKey;
77 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.MuxpProfile;
78 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.MuxpProfileKey;
79 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.OduSwitchingPools;
80 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Protocols;
81 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.SharedRiskGroup;
82 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.SharedRiskGroupKey;
83 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Xponder;
84 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.connection.map.Destination;
85 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.odu.switching.pools.non.blocking.list.PortList;
86 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.port.Interfaces;
87 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.xponder.XpdrPort;
88 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.NodeTypes;
89 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.PortQual;
90 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.XpdrNodeTypes;
91 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.InterfaceType;
92 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.OpenROADMOpticalMultiplex;
93 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.OpticalTransport;
94 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.OtnOdu;
95 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev200529.Protocols1;
96 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev200529.lldp.container.Lldp;
97 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev200529.lldp.container.lldp.PortConfig;
98 import org.opendaylight.yang.gen.v1.http.org.openroadm.otn.common.types.rev200327.OpucnTribSlotDef;
99 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.capability.rev200529.Ports1;
100 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.capability.rev200529.port.capability.grp.port.capabilities.SupportedInterfaceCapability;
101 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
102 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
103 import org.opendaylight.yangtools.yang.common.Uint16;
104 import org.opendaylight.yangtools.yang.common.Uint32;
105 import org.slf4j.Logger;
106 import org.slf4j.LoggerFactory;
107
108
109 // FIXME: many common pieces of code between PortMapping Versions 121 and 221 and 710
110 // some mutualization would be helpful
111 @SuppressWarnings("CPD-START")
112 public class PortMappingVersion710 {
113
114     private static final Logger LOG = LoggerFactory.getLogger(PortMappingVersion710.class);
115     private static final Map<Direction, String> SUFFIX;
116     private static final Set<Integer> TXRX_SET = Set.of(Direction.Tx.getIntValue(), Direction.Rx.getIntValue());
117
118     private final DataBroker dataBroker;
119     private final DeviceTransactionManager deviceTransactionManager;
120     private final OpenRoadmInterfaces openRoadmInterfaces;
121
122     static {
123         SUFFIX =  Map.of(
124             Direction.Tx, "TX",
125             Direction.Rx, "RX",
126             Direction.Bidirectional, "TXRX");
127     }
128
129     public PortMappingVersion710(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager,
130             OpenRoadmInterfaces openRoadmInterfaces) {
131         this.dataBroker = dataBroker;
132         this.deviceTransactionManager = deviceTransactionManager;
133         this.openRoadmInterfaces = openRoadmInterfaces;
134     }
135
136     public boolean createMappingData(String nodeId) {
137         LOG.info(PortMappingUtils.CREATE_MAPPING_DATA_LOGMSG, nodeId, "7.1");
138         List<Mapping> portMapList = new ArrayList<>();
139         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = new HashMap<>();
140         InstanceIdentifier<Info> infoIID = InstanceIdentifier.create(OrgOpenroadmDevice.class).child(Info.class);
141         Optional<Info> deviceInfoOptional = this.deviceTransactionManager.getDataFromDevice(
142                 nodeId, LogicalDatastoreType.OPERATIONAL, infoIID,
143                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
144         if (deviceInfoOptional.isEmpty()) {
145             LOG.warn(PortMappingUtils.DEVICE_HAS_LOGMSG, nodeId, "no info", "subtree");
146             return false;
147         }
148         Info deviceInfo = deviceInfoOptional.get();
149         NodeInfo nodeInfo = createNodeInfo(deviceInfo);
150         if (nodeInfo == null) {
151             return false;
152         }
153         postPortMapping(nodeId, nodeInfo, null, null, null, null);
154
155         switch (deviceInfo.getNodeType()) {
156
157             case Rdm:
158                 // Get TTP port mapping
159                 if (!createTtpPortMapping(nodeId, deviceInfo, portMapList)) {
160                     // return false if mapping creation for TTP's failed
161                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, PortMappingUtils.CREATE, "TTP's");
162                     return false;
163                 }
164
165                 // Get PP port mapping
166                 if (!createPpPortMapping(nodeId, deviceInfo, portMapList)) {
167                     // return false if mapping creation for PP's failed
168                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, PortMappingUtils.CREATE, "PP's");
169                     return false;
170                 }
171                 // Get MC capabilities
172                 if (!createMcCapabilitiesList(nodeId, deviceInfo, mcCapabilities)) {
173                     // return false if MC capabilites failed
174                     LOG.warn(PortMappingUtils.UNABLE_MC_CAPA_LOGMSG, nodeId);
175                     return false;
176                 }
177                 break;
178             case Xpdr:
179                 if (!createXpdrPortMapping(nodeId, portMapList)) {
180                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, PortMappingUtils.CREATE, "Xponder");
181                     return false;
182                 }
183                 // In the case of 7.1 models, even XPDR advertizes mc-capabilities,
184                 // hence we need to populate this information into the port-mapping data
185                 // Get MC capabilities
186                 if (!createMcCapabilitiesList(nodeId, deviceInfo, mcCapabilities)) {
187                     // return false if MC capabilites failed
188                     LOG.warn(PortMappingUtils.UNABLE_MC_CAPA_LOGMSG, nodeId);
189                     return false;
190                 }
191                 break;
192             default:
193                 LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
194                     nodeId, PortMappingUtils.CREATE, deviceInfo.getNodeType() + " - unknown nodetype");
195                 break;
196
197         }
198         return postPortMapping(nodeId, nodeInfo, portMapList, null, null, mcCapabilities);
199     }
200
201     public boolean updateMapping(String nodeId, Mapping oldMapping) {
202         if (nodeId == null) {
203             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, "node id null" , PortMappingUtils.UPDATE, "a null value");
204             return false;
205         }
206         if (oldMapping == null) {
207             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, PortMappingUtils.UPDATE, "a null value");
208             return false;
209         }
210         InstanceIdentifier<Ports> portId = InstanceIdentifier.create(OrgOpenroadmDevice.class)
211             .child(CircuitPacks.class, new CircuitPacksKey(oldMapping.getSupportingCircuitPackName()))
212             .child(Ports.class, new PortsKey(oldMapping.getSupportingPort()));
213         try {
214             Ports port = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
215                 portId, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
216             Mapping newMapping = updateMappingObject(nodeId, port, oldMapping);
217             LOG.debug(PortMappingUtils.UPDATE_MAPPING_LOGMSG,
218                 nodeId, oldMapping, oldMapping.getLogicalConnectionPoint(), newMapping);
219             final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
220             InstanceIdentifier<Mapping> mapIID = InstanceIdentifier.create(Network.class)
221                 .child(Nodes.class, new NodesKey(nodeId))
222                 .child(Mapping.class, new MappingKey(oldMapping.getLogicalConnectionPoint()));
223             writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, mapIID, newMapping);
224             FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
225             commit.get();
226             return true;
227         } catch (InterruptedException | ExecutionException e) {
228             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
229                 nodeId, PortMappingUtils.UPDATE, oldMapping.getLogicalConnectionPoint(), e);
230             return false;
231         }
232     }
233
234     public boolean updatePortMappingWithOduSwitchingPools(String nodeId, InstanceIdentifier<OduSwitchingPools> ospIID,
235             Map<Uint16, List<InstanceIdentifier<PortList>>> nbliidMap) {
236
237         KeyedInstanceIdentifier<Nodes, NodesKey> portMappingNodeIID =
238             InstanceIdentifier.create(Network.class).child(Nodes.class, new NodesKey(nodeId));
239         Nodes portmappingNode = null;
240         try (ReadTransaction readTx = this.dataBroker.newReadOnlyTransaction()) {
241             portmappingNode = readTx.read(LogicalDatastoreType.CONFIGURATION, portMappingNodeIID).get().get();
242         } catch (InterruptedException | ExecutionException ex) {
243             LOG.error("Unable to read the port-mapping for nodeId {}", nodeId, ex);
244         }
245         if (portmappingNode == null) {
246             return false;
247         }
248
249         OduSwitchingPools osp = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
250             ospIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
251         Uint16 ospNumber = osp.getSwitchingPoolNumber();
252         Map<SwitchingPoolLcpKey, SwitchingPoolLcp> splMap =
253             new HashMap<SwitchingPoolLcpKey, SwitchingPoolLcp>(portmappingNode.nonnullSwitchingPoolLcp());
254         SwitchingPoolLcpBuilder splBldr = splMap.containsKey(new SwitchingPoolLcpKey(ospNumber))
255             ? new SwitchingPoolLcpBuilder(splMap.get(new SwitchingPoolLcpKey(ospNumber)))
256             : new SwitchingPoolLcpBuilder().setSwitchingPoolNumber(ospNumber)
257                 .setSwitchingPoolType(osp.getSwitchingPoolType());
258         Map<NonBlockingListKey, NonBlockingList> nblMap = new HashMap<>();
259         for (Entry<Uint16, List<InstanceIdentifier<PortList>>> entry : nbliidMap.entrySet()) {
260             NonBlockingList nbl = createNonBlockingList(
261                 splBldr,
262                 osp.getNonBlockingList()
263                     .get(new org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529
264                         .org.openroadm.device.container.org.openroadm.device.odu.switching.pools
265                         .NonBlockingListKey(entry.getKey()))
266                     .getInterconnectBandwidth(),
267                 entry,
268                 portmappingNode.nonnullMapping(),
269                 nodeId);
270             if (nbl == null) {
271                 return false;
272             }
273             nblMap.put(nbl.key(), nbl);
274         }
275         SwitchingPoolLcp switchingPoolLcp = splBldr.setNonBlockingList(nblMap).build();
276         splMap.put(switchingPoolLcp.key(), switchingPoolLcp);
277         postPortMapping(nodeId, null, null, null, new ArrayList<SwitchingPoolLcp>(splMap.values()), null);
278         return true;
279     }
280
281     private NonBlockingList createNonBlockingList(SwitchingPoolLcpBuilder splBldr, Uint32 interconnectBw,
282             Entry<Uint16, List<InstanceIdentifier<PortList>>> entry, Map<MappingKey, Mapping> mappings, String nodeId) {
283         NonBlockingListBuilder nblBldr = splBldr.getNonBlockingList() == null
284             || !splBldr.getNonBlockingList().containsKey(new NonBlockingListKey(entry.getKey()))
285                 ? new NonBlockingListBuilder().setNblNumber(entry.getKey()).setInterconnectBandwidth(interconnectBw)
286                 : new NonBlockingListBuilder(splBldr.getNonBlockingList().get(new NonBlockingListKey(entry.getKey())));
287         List<String> lcpList = nblBldr.getLcpList() != null ? nblBldr.getLcpList() : new ArrayList<>();
288         for (InstanceIdentifier<PortList> id : entry.getValue()) {
289             PortList portList = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
290                 id, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
291             String lcp = getLcpFromCpAndPort(mappings, portList.getCircuitPackName(), portList.getPortName());
292             if (lcp == null || lcpList.contains(lcp)) {
293                 return null;
294             }
295             lcpList.add(lcp);
296         }
297         return nblBldr.setLcpList(lcpList).build();
298     }
299
300     private boolean createXpdrPortMapping(String nodeId, List<Mapping> portMapList) {
301         // Creating for Xponder Line and Client Ports
302         OrgOpenroadmDevice device = getXpdrDevice(nodeId);
303         if (device == null) {
304             return false;
305         }
306         Map<String, String> lcpMap = new HashMap<>();
307         Map<String, Mapping> mappingMap = new HashMap<>();
308         getXpdrMaps(device, nodeId, lcpMap, mappingMap);
309         if (device.getConnectionMap() == null) {
310             LOG.warn(PortMappingUtils.NO_CONMAP_LOGMSG, nodeId);
311         } else {
312             for (ConnectionMap cm : device.nonnullConnectionMap().values()) {
313                 String skey = cm.getSource().getCircuitPackName() + "+" + cm.getSource().getPortName();
314                 Destination destination0 = cm.nonnullDestination().values().iterator().next();
315                 String dkey = destination0.getCircuitPackName() + "+" + destination0.getPortName();
316                 if (!lcpMap.containsKey(skey)) {
317                     LOG.error(PortMappingUtils.CONMAP_ISSUE_LOGMSG, nodeId, skey, dkey);
318                     continue;
319                 }
320                 String slcp = lcpMap.get(skey);
321                 Mapping mapping = mappingMap.get(slcp);
322                 mappingMap.remove(slcp);
323                 portMapList.add(createXpdrMappingObject(nodeId, null, null, null, null, mapping,
324                         //dlcp
325                         lcpMap.containsKey(dkey) ? lcpMap.get(dkey) : null,
326                         null));
327             }
328         }
329         if (device.getOduSwitchingPools() != null) {
330             postPortMapping(nodeId, null, null, null, getSwitchingPoolList(device, lcpMap, nodeId), null);
331         }
332         mappingMap.forEach((k,v) -> portMapList.add(v));
333         return true;
334     }
335
336     private OrgOpenroadmDevice getXpdrDevice(String nodeId) {
337         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
338         Optional<OrgOpenroadmDevice> deviceObject = deviceTransactionManager.getDataFromDevice(nodeId,
339             LogicalDatastoreType.OPERATIONAL, deviceIID,
340             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
341         if (deviceObject.isEmpty()) {
342             LOG.error(PortMappingUtils.CANNOT_GET_DEV_CONF_LOGMSG, nodeId);
343             return null;
344         }
345         OrgOpenroadmDevice device = deviceObject.get();
346         if (device.getCircuitPacks() == null) {
347             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, PortMappingUtils.FOUND);
348             return null;
349         }
350         return device;
351     }
352
353     private void getXpdrMaps(OrgOpenroadmDevice device, String nodeId,
354             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
355         List<CircuitPacks> circuitPackList = new ArrayList<>(device.nonnullCircuitPacks().values());
356         circuitPackList.sort(Comparator.comparing(CircuitPack::getCircuitPackName));
357         if (device.getXponder() == null) {
358             LOG.warn(PortMappingUtils.XPDR_LIST_IN_CONF_LOGMSG, nodeId, "not found");
359             // Variables to keep track of number of line ports and client ports
360             int line = 1;
361             int client = 1;
362             // TODO the treatment here inside the 2 nested for-loop is very similar to the one
363             //     when device.getXponder() != null. Some code mutualization must be considered.
364             for (CircuitPacks cp : circuitPackList) {
365                 String circuitPackName = cp.getCircuitPackName();
366                 if (cp.getPorts() == null) {
367                     LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, PortMappingUtils.FOUND, circuitPackName);
368                     continue;
369                 }
370                 List<Ports> portList = new ArrayList<>(cp.nonnullPorts().values());
371                 portList.sort(Comparator.comparing(Ports::getPortName));
372                 for (Ports port : portList) {
373                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
374                         1, null, circuitPackName, port,
375                         circuitPackList, lcpMap, mappingMap);
376                     line = counters[0];
377                     client = counters[1];
378                 }
379             }
380         } else {
381             LOG.info(PortMappingUtils.XPDR_LIST_IN_CONF_LOGMSG, nodeId, PortMappingUtils.FOUND);
382             for (Xponder xponder : device.nonnullXponder().values()) {
383                 // Variables to keep track of number of line ports and client ports
384                 int line = 1;
385                 int client = 1;
386                 Integer xponderNb = xponder.getXpdrNumber().toJava();
387                 XpdrNodeTypes xponderType = xponder.getXpdrType();
388                 for (XpdrPort xpdrPort : xponder.nonnullXpdrPort().values().stream()
389                         .sorted((xp1, xp2) -> xp1.getIndex().compareTo(xp2.getIndex())).collect(Collectors.toList())) {
390                     Ports port = getXpdrPorts(device, xpdrPort, nodeId);
391                     if (port == null) {
392                         continue;
393                     }
394                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
395                         xponderNb, xponderType, xpdrPort.getCircuitPackName(), port,
396                         circuitPackList, lcpMap, mappingMap);
397                     line = counters[0];
398                     client = counters[1];
399                 }
400             }
401         }
402     }
403
404     private Ports getXpdrPorts(OrgOpenroadmDevice device, XpdrPort xpdrPort, String nodeId) {
405         String circuitPackName = xpdrPort.getCircuitPackName();
406         String portName = xpdrPort.getPortName();
407         // If there xponder-subtree has missing circuit-packs or ports,
408         // This gives a null-pointer expection,
409         Optional<CircuitPacks> cpList = device.nonnullCircuitPacks().values().stream()
410                 .filter(cp -> cp.getCircuitPackName().equals(circuitPackName)).findFirst();
411         if (cpList.isEmpty()) {
412             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
413                 nodeId, circuitPackName);
414             return null;
415         }
416         Optional<Ports> portsList = cpList.get().nonnullPorts().values().stream()
417                 .filter(p -> p.getPortName().equals(portName)).findFirst();
418         if (portsList.isEmpty()) {
419             LOG.warn(PortMappingUtils.NO_ASSOC_FOUND_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
420                 nodeId, portName, circuitPackName, "in the device");
421             return null;
422         }
423         return portsList.get();
424     }
425
426     private List<SwitchingPoolLcp> getSwitchingPoolList(OrgOpenroadmDevice device,
427             Map<String, String> lcpMap, String nodeId) {
428         List<SwitchingPoolLcp> switchingPoolList = new ArrayList<>();
429         for (OduSwitchingPools odp : device.nonnullOduSwitchingPools().values()) {
430             Map<NonBlockingListKey,NonBlockingList> nbMap = new HashMap<>();
431             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org
432                 .openroadm.device.odu.switching.pools.NonBlockingList nbl : odp.nonnullNonBlockingList().values()) {
433                 if (nbl.getPortList() == null) {
434                     continue;
435                 }
436                 List<String> lcpList = new ArrayList<>();
437                 for (PortList item : nbl.nonnullPortList().values()) {
438                     String key = item.getCircuitPackName() + "+" + item.getPortName();
439                     if (!lcpMap.containsKey(key)) {
440                         LOG.error(PortMappingUtils.NO_ASSOC_FOUND_LOGMSG,
441                             nodeId, item.getPortName(), item.getCircuitPackName(), "to a logical connection point");
442                         continue;
443                     }
444                     lcpList.add(lcpMap.get(key));
445                 }
446                 NonBlockingList nonBlockingList = new NonBlockingListBuilder()
447                     .setNblNumber(nbl.getNblNumber())
448                     .setInterconnectBandwidth(nbl.getInterconnectBandwidth())
449                     .setInterconnectBandwidthUnit(nbl.getInterconnectBandwidthUnit())
450                     .setLcpList(lcpList)
451                     .build();
452                 nbMap.put(nonBlockingList.key(), nonBlockingList);
453             }
454             switchingPoolList.add(
455                 new SwitchingPoolLcpBuilder()
456                     .setSwitchingPoolNumber(odp.getSwitchingPoolNumber())
457                     .setSwitchingPoolType(odp.getSwitchingPoolType())
458                     //TODO differs from 2.2.1 SwitchingPoolTypes.forValue(odp.getSwitchingPoolType().getIntValue())
459                     .setNonBlockingList(nbMap)
460                     .build());
461         }
462         return switchingPoolList;
463     }
464
465     private boolean checkPartnerPortNotNull(Ports port) {
466         return (port.getPartnerPort() != null
467             && port.getPartnerPort().getCircuitPackName() != null
468             && port.getPartnerPort().getPortName() != null);
469     }
470
471     private boolean checkPartnerPortNoDir(String circuitPackName, Ports port1, Ports port2) {
472         return (checkPartnerPortNotNull(port2)
473             && port2.getPartnerPort().getCircuitPackName().equals(circuitPackName)
474             && port2.getPartnerPort().getPortName().equals(port1.getPortName()));
475     }
476
477     private boolean checkPartnerPort(String circuitPackName, Ports port1, Ports port2) {
478         return checkPartnerPortNoDir(circuitPackName, port1, port2)
479             && Set.of(port1.getPortDirection().getIntValue(), port2.getPortDirection().getIntValue())
480                 .equals(TXRX_SET);
481     }
482
483
484     private HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg
485             .CircuitPacks>> getSrgCps(String deviceId, Info ordmInfo) {
486         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg
487             .CircuitPacks>> cpPerSrg = new HashMap<>();
488         // Get value for max Srg from info subtree, required for iteration
489         // if not present assume to be 20 (temporary)
490         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
491         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
492             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks> srgCps
493                 = new ArrayList<>();
494             LOG.debug(PortMappingUtils.GETTING_CP_LOGMSG, deviceId, srgCounter);
495             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
496                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
497             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
498                 LogicalDatastoreType.OPERATIONAL, srgIID,
499                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
500             if (ordmSrgObject.isPresent()) {
501                 srgCps.addAll(ordmSrgObject.get().nonnullCircuitPacks().values());
502                 cpPerSrg.put(ordmSrgObject.get().getSrgNumber().toJava(), srgCps);
503             }
504         }
505         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG, deviceId, cpPerSrg.size(), "SRG");
506         return cpPerSrg;
507     }
508
509     private boolean createPpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
510         // Creating mapping data for SRG's PP
511         for (Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks>>
512                 srgCpEntry : getSrgCps(nodeId, deviceInfo).entrySet()) {
513             List<String> keys = new ArrayList<>();
514             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks
515                     cp : srgCpEntry.getValue()) {
516                 String circuitPackName = cp.getCircuitPackName();
517                 List<Ports> portList = getPortList(circuitPackName, nodeId);
518                 Collections.sort(portList, new SortPort710ByName());
519                 int portIndex = 1;
520                 for (Ports port : portList) {
521                     if (!checkPortQual(port, circuitPackName, nodeId)) {
522                         continue;
523                     }
524                     String currentKey = circuitPackName + "-" + port.getPortName();
525                     if (keys.contains(currentKey)) {
526                         LOG.debug(PortMappingUtils.PORT_ALREADY_HANDLED_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
527                             nodeId, port.getPortName(), circuitPackName);
528                         continue;
529                     }
530                     switch (port.getPortDirection()) {
531                         case Bidirectional:
532                             String lcp = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
533                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
534                                 nodeId, port.getPortName(), circuitPackName, lcp);
535                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp));
536                             portIndex++;
537                             keys.add(currentKey);
538                             break;
539                         case Rx:
540                         case Tx:
541                             Ports port2 = getPartnerPort(port, circuitPackName, nodeId);
542                             if (port2 == null) {
543                                 continue;
544                             }
545                             String lcp1 = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
546                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
547                                 nodeId, port.getPortName(), circuitPackName, lcp1);
548                             String lcp2 = createLogicalConnectionPort(port2, srgCpEntry.getKey(),portIndex);
549                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
550                                 nodeId, port2.getPortName(), circuitPackName, lcp2);
551                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp1));
552                             portMapList.add(
553                                 createMappingObject(nodeId ,port2, port.getPartnerPort().getCircuitPackName(), lcp2));
554                             portIndex++;
555                             keys.add(currentKey);
556                             keys.add(port.getPartnerPort().getCircuitPackName() + "-" + port2.getPortName());
557                             break;
558                         default:
559                             LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
560                                     nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
561                     }
562                 }
563             }
564         }
565         return true;
566     }
567
568     private Ports getPartnerPort(Ports port, String circuitPackName, String nodeId) {
569         if (!checkPartnerPortNotNull(port)) {
570             LOG.info(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
571                 nodeId, port.getPortName(), circuitPackName);
572             return null;
573         }
574         InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
575             .child(CircuitPacks.class, new CircuitPacksKey(port.getPartnerPort().getCircuitPackName()))
576             .child(Ports.class, new PortsKey(port.getPartnerPort().getPortName()));
577         Optional<Ports> port2Object = this.deviceTransactionManager
578             .getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, port2ID,
579                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
580         if (port2Object.isEmpty()
581                 || port2Object.get().getPortQual().getIntValue() != PortQual.RoadmExternal.getIntValue()) {
582             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG + PortMappingUtils.PARTNERPORT_GET_ERROR_LOGMSG,
583                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName(),
584                 port.getPortName(), circuitPackName);
585             return null;
586         }
587         Ports port2 = port2Object.get();
588         if (!checkPartnerPort(circuitPackName, port, port2)) {
589             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG + PortMappingUtils.PARTNERPORT_CONF_ERROR_LOGMSG,
590                 nodeId, port2.getPortName(), port.getPartnerPort().getCircuitPackName(),
591                 port.getPortName(), circuitPackName);
592             //TODO check if we really needed to increment portIndex in this condition
593             //     if yes this block should not be in getPartnerPort and must move back to createPpPortMapping
594             return null;
595         }
596         return port2;
597     }
598
599     private List<Ports> getPortList(String circuitPackName, String nodeId) {
600         InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
601             .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
602         Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
603              LogicalDatastoreType.OPERATIONAL, cpIID,
604              Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
605         if (circuitPackObject.isEmpty()) {
606             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
607                 nodeId, circuitPackName);
608             return new ArrayList<>();
609         }
610         if (circuitPackObject.get().getPorts() == null) {
611             LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, PortMappingUtils.FOUND, circuitPackName);
612             return new ArrayList<>();
613         }
614         return new ArrayList<>(circuitPackObject.get().nonnullPorts().values());
615     }
616
617     private String createLogicalConnectionPort(Ports port, int index, int portIndex) {
618         if (SUFFIX.containsKey(port.getPortDirection())) {
619             return String.join("-", "SRG" + index, "PP" + portIndex, SUFFIX.get(port.getPortDirection()));
620         }
621         LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
622             "createLogicalConnectionPort", port, "SRG" + index + "-PP" + portIndex, port.getPortDirection());
623         return null;
624     }
625
626     private Map<McCapabilityProfileKey, McCapabilityProfile> getMcCapabilityProfiles(String deviceId, Info ordmInfo) {
627         Map<McCapabilityProfileKey, McCapabilityProfile>  mcCapabilityProfiles = new HashMap<>();
628         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
629         Optional<OrgOpenroadmDevice> deviceObject = deviceTransactionManager.getDataFromDevice(deviceId,
630             LogicalDatastoreType.OPERATIONAL, deviceIID,
631             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
632         OrgOpenroadmDevice device = null;
633         if (deviceObject.isEmpty()) {
634             LOG.error(PortMappingUtils.CANNOT_GET_DEV_CONF_LOGMSG, deviceId);
635             LOG.warn("MC-capabilities profile will be empty for node {}", deviceId);
636             return mcCapabilityProfiles;
637         }
638         device = deviceObject.get();
639         mcCapabilityProfiles = device.getMcCapabilityProfile();
640         return mcCapabilityProfiles;
641     }
642
643     private Map<Integer, Degree> getDegreesMap(String deviceId, Info ordmInfo) {
644         Map<Integer, Degree> degrees = new HashMap<>();
645
646         // Get value for max degree from info subtree, required for iteration
647         // if not present assume to be 20 (temporary)
648         Integer maxDegree = ordmInfo.getMaxDegrees() == null ? 20 : ordmInfo.getMaxDegrees().toJava();
649
650         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
651             LOG.debug(PortMappingUtils.GETTING_CONPORT_LOGMSG, deviceId, degreeCounter);
652             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
653                 .child(Degree.class, new DegreeKey(Uint16.valueOf(degreeCounter)));
654             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
655                 LogicalDatastoreType.OPERATIONAL, deviceIID,
656                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
657             if (ordmDegreeObject.isPresent()) {
658                 degrees.put(degreeCounter, ordmDegreeObject.get());
659             }
660         }
661         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG,
662             deviceId, degrees.size(), degrees.size() <= 1 ? "degree" : "degrees");
663         return degrees;
664     }
665
666     private Map<Integer, List<ConnectionPorts>> getPerDegreePorts(String deviceId, Info ordmInfo) {
667         Map<Integer, List<ConnectionPorts>> conPortMap = new HashMap<>();
668         getDegreesMap(deviceId, ordmInfo).forEach(
669             (index, degree) -> conPortMap.put(index, new ArrayList<>(degree.nonnullConnectionPorts().values())));
670         return conPortMap;
671     }
672
673     private List<SharedRiskGroup> getSrgs(String deviceId, Info ordmInfo) {
674         List<SharedRiskGroup> srgs = new ArrayList<>();
675
676         // Get value for max Srg from info subtree, required for iteration
677         // if not present assume to be 20 (temporary)
678         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
679         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
680             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
681                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
682             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
683                 LogicalDatastoreType.OPERATIONAL, srgIID,
684                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
685             if (ordmSrgObject.isPresent()) {
686                 srgs.add(ordmSrgObject.get());
687
688             }
689         }
690         return srgs;
691     }
692
693     private Map<String, String> getEthInterfaceList(String nodeId) {
694         LOG.info(PortMappingUtils.GETTING_ETH_LIST_LOGMSG, nodeId);
695         InstanceIdentifier<Protocols> protocoliid = InstanceIdentifier.create(OrgOpenroadmDevice.class)
696             .child(Protocols.class);
697         Optional<Protocols> protocolObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
698             LogicalDatastoreType.OPERATIONAL, protocoliid, Timeouts.DEVICE_READ_TIMEOUT,
699             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
700         if (protocolObject.isEmpty() || protocolObject.get().augmentation(Protocols1.class).getLldp() == null) {
701             LOG.warn(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, PortMappingUtils.CANNOT_GET_LLDP_CONF_LOGMSG);
702             return new HashMap<>();
703         }
704         Map<String, String> cpToInterfaceMap = new HashMap<>();
705         Lldp lldp = protocolObject.get().augmentation(Protocols1.class).getLldp();
706         for (PortConfig portConfig : lldp.nonnullPortConfig().values()) {
707             if (!portConfig.getAdminStatus().equals(PortConfig.AdminStatus.Txandrx)) {
708                 continue;
709             }
710             InstanceIdentifier<Interface> interfaceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
711                 .child(Interface.class, new InterfaceKey(portConfig.getIfName()));
712             Optional<Interface> interfaceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
713                 LogicalDatastoreType.OPERATIONAL, interfaceIID, Timeouts.DEVICE_READ_TIMEOUT,
714                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
715             if (interfaceObject.isEmpty() || interfaceObject.get().getSupportingCircuitPackName() == null) {
716                 continue;
717             }
718             String supportingCircuitPackName = interfaceObject.get().getSupportingCircuitPackName();
719             cpToInterfaceMap.put(supportingCircuitPackName, portConfig.getIfName());
720             InstanceIdentifier<CircuitPacks> circuitPacksIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
721                 .child(CircuitPacks.class, new CircuitPacksKey(supportingCircuitPackName));
722             Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(
723                 nodeId, LogicalDatastoreType.OPERATIONAL, circuitPacksIID, Timeouts.DEVICE_READ_TIMEOUT,
724                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
725             if (circuitPackObject.isEmpty() || circuitPackObject.get().getParentCircuitPack() == null) {
726                 continue;
727             }
728             cpToInterfaceMap.put(circuitPackObject.get().getParentCircuitPack().getCircuitPackName(),
729                 portConfig.getIfName());
730         }
731         LOG.info(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, " - success");
732         return cpToInterfaceMap;
733     }
734
735     private List<CpToDegree> getCpToDegreeList(Map<Integer, Degree> degrees, Map<String, String> interfaceList) {
736         List<CpToDegree> cpToDegreeList = new ArrayList<>();
737         for (Degree degree : degrees.values()) {
738             cpToDegreeList.addAll(degree.nonnullCircuitPacks().values().stream()
739                 .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(),
740                     degree.getDegreeNumber().toString(), interfaceList))
741                 .collect(Collectors.toList()));
742         }
743         return cpToDegreeList;
744     }
745
746     private Map<McCapabilitiesKey, McCapabilities> getMcCapabilities(Map<Integer, Degree> degrees,
747             List<SharedRiskGroup> srgs, Info deviceInfo, String nodeId) {
748         //TODO some divergences with 2.2.1 here
749         LOG.info(PortMappingUtils.GETTING_MC_CAPA_LOGMSG , nodeId, "degrees");
750         //Get all the mc-capability profiles from the device
751         Map<McCapabilityProfileKey, McCapabilityProfile> mcCapabilityProfiles =
752             getMcCapabilityProfiles(nodeId, deviceInfo);
753         // Add the DEG mc-capabilities
754         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = createMcCapDegreeObject(degrees, mcCapabilityProfiles,
755             nodeId);
756         // Add the SRG mc-capabilities
757         LOG.info(PortMappingUtils.GETTING_MC_CAPA_LOGMSG , nodeId, "SRGs");
758         mcCapabilities.putAll(createMcCapSrgObject(srgs, mcCapabilityProfiles, nodeId));
759         return mcCapabilities;
760     }
761
762     private boolean postPortMapping(String nodeId, NodeInfo nodeInfo, List<Mapping> portMapList,
763             List<CpToDegree> cp2DegreeList, List<SwitchingPoolLcp> splList,
764             Map<McCapabilitiesKey, McCapabilities> mcCapMap) {
765         NodesBuilder nodesBldr = new NodesBuilder().withKey(new NodesKey(nodeId)).setNodeId(nodeId);
766         if (nodeInfo != null) {
767             nodesBldr.setNodeInfo(nodeInfo);
768         }
769         if (portMapList != null) {
770             Map<MappingKey, Mapping> mappingMap = new HashMap<>();
771             // No element in the list below should be null at this stage
772             for (Mapping mapping: portMapList) {
773                 mappingMap.put(mapping.key(), mapping);
774             }
775             nodesBldr.setMapping(mappingMap);
776         }
777         if (cp2DegreeList != null) {
778             Map<CpToDegreeKey, CpToDegree> cpToDegreeMap = new HashMap<>();
779             // No element in the list below should be null at this stage
780             for (CpToDegree cp2Degree: cp2DegreeList) {
781                 cpToDegreeMap.put(cp2Degree.key(), cp2Degree);
782             }
783             nodesBldr.setCpToDegree(cpToDegreeMap);
784         }
785
786         if (splList != null) {
787             Map<SwitchingPoolLcpKey,SwitchingPoolLcp> splMap = new HashMap<>();
788             // No element in the list below should be null at this stage
789             for (SwitchingPoolLcp spl: splList) {
790                 splMap.put(spl.key(), spl);
791             }
792             nodesBldr.setSwitchingPoolLcp(splMap);
793         }
794         if (mcCapMap != null) {
795             nodesBldr.setMcCapabilities(mcCapMap);
796         }
797         Map<NodesKey,Nodes> nodesList = new HashMap<>();
798         Nodes nodes = nodesBldr.build();
799         nodesList.put(nodes.key(),nodes);
800
801         Network network = new NetworkBuilder().setNodes(nodesList).build();
802
803         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
804         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
805         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
806         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
807         try {
808             commit.get();
809             return true;
810         } catch (InterruptedException | ExecutionException e) {
811             LOG.warn(PortMappingUtils.PORTMAPPING_POST_FAIL_LOGMSG, nodeId, network, e);
812             return false;
813         }
814     }
815
816     private CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber,
817             Map<String, String> interfaceList) {
818         return new CpToDegreeBuilder()
819             .withKey(new CpToDegreeKey(circuitPackName))
820             .setCircuitPackName(circuitPackName)
821             .setDegreeNumber(Uint32.valueOf(degreeNumber))
822             .setInterfaceName(interfaceList.get(circuitPackName)).build();
823     }
824
825     private Map<McCapabilitiesKey, McCapabilities> createMcCapDegreeObject(Map<Integer, Degree> degrees,
826             Map<McCapabilityProfileKey, McCapabilityProfile> mcCapabilityProfileMap, String nodeId) {
827         //TODO some divergences here with 2.2.1
828         Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap = new HashMap<>();
829         for (Degree degree : degrees.values()) {
830
831             if ((degree.getMcCapabilityProfileName() == null) || (degree.getMcCapabilityProfileName().isEmpty())) {
832                 String mcNodeName =
833                     PortMappingUtils.degreeTtpNodeName(degree.getDegreeNumber().toString(), "default-profile");
834                 LOG.warn(PortMappingUtils.NO_MC_LOGMSG, nodeId, "degree",
835                     degree.getDegreeNumber() +  " - using " + mcNodeName + " as default MC profile name");
836                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
837                     .withKey(new McCapabilitiesKey(mcNodeName))
838                     .setMcNodeName(mcNodeName);
839                 mcCapabilitiesBuilder
840                     .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
841                     .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
842                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
843                 continue;
844             }
845
846             for (String mcCapabilityProfileName : degree.getMcCapabilityProfileName()) {
847                 McCapabilityProfileKey mcKey = new McCapabilityProfileKey(mcCapabilityProfileName);
848                 McCapabilityProfile mcCapabilityProfile = mcCapabilityProfileMap.get(mcKey);
849                 String mcNodeName = PortMappingUtils.degreeTtpNodeName(degree.getDegreeNumber().toString(),
850                         mcCapabilityProfile.toString());
851                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
852                     .withKey(new McCapabilitiesKey(mcNodeName))
853                     .setMcNodeName(mcNodeName);
854                 mcCapabilitiesBuilder
855                     .setCenterFreqGranularity(mcCapabilityProfile.getCenterFreqGranularity())
856                     .setSlotWidthGranularity(mcCapabilityProfile.getSlotWidthGranularity());
857                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
858             }
859
860         }
861         return mcCapabilitiesMap;
862     }
863
864     private Map<McCapabilitiesKey, McCapabilities> createMcCapSrgObject(List<SharedRiskGroup> srgs,
865             Map<McCapabilityProfileKey, McCapabilityProfile> mcCapabilityProfileMap, String nodeId) {
866
867         Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap = new HashMap<>();
868         for (SharedRiskGroup srg : srgs) {
869
870             if ((srg.getMcCapabilityProfileName() == null) || (srg.getMcCapabilityProfileName().isEmpty())) {
871                 String mcNodeName = "SRG" + srg.getSrgNumber().toString() + "-PP-" + "default-profile";
872                 LOG.warn(PortMappingUtils.NO_MC_LOGMSG, nodeId, "SRG",
873                     srg.getSrgNumber() + " - using " + mcNodeName + " as default MC profile name");
874                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
875                     .withKey(new McCapabilitiesKey(mcNodeName))
876                     .setMcNodeName(mcNodeName);
877                 mcCapabilitiesBuilder
878                     .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
879                     .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
880                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
881                 continue;
882             }
883
884             for (String mcCapabilityProfileName : srg.getMcCapabilityProfileName()) {
885                 McCapabilityProfileKey mcKey = new McCapabilityProfileKey(mcCapabilityProfileName);
886                 McCapabilityProfile mcCapabilityProfile = mcCapabilityProfileMap.get(mcKey);
887                 String mcNodeName = "SRG" + srg.getSrgNumber().toString() + "-PP-" + mcCapabilityProfile;
888                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
889                     .withKey(new McCapabilitiesKey(mcNodeName))
890                     .setMcNodeName(mcNodeName);
891                 mcCapabilitiesBuilder
892                     .setCenterFreqGranularity(mcCapabilityProfile.getCenterFreqGranularity())
893                     .setSlotWidthGranularity(mcCapabilityProfile.getSlotWidthGranularity());
894                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
895             }
896         }
897         return mcCapabilitiesMap;
898     }
899
900     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
901             String logicalConnectionPoint) {
902         MappingBuilder mpBldr = new MappingBuilder()
903                 .withKey(new MappingKey(logicalConnectionPoint))
904                 .setLogicalConnectionPoint(logicalConnectionPoint)
905                 .setSupportingCircuitPackName(circuitPackName)
906                 .setSupportingPort(port.getPortName())
907                 .setPortDirection(port.getPortDirection().getName());
908         if (port.getAdministrativeState() != null) {
909             mpBldr.setPortAdminState(port.getAdministrativeState().name());
910         }
911         if (port.getOperationalState() != null) {
912             mpBldr.setPortOperState(port.getOperationalState().name());
913         }
914
915         if ((port.getInterfaces() == null)
916             || (!logicalConnectionPoint.contains(StringConstants.TTP_TOKEN)
917                 && !logicalConnectionPoint.contains(StringConstants.NETWORK_TOKEN))) {
918             return mpBldr.build();
919         }
920         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
921         return mpBldr.build();
922     }
923
924     private Mapping updateMappingObject(String nodeId, Ports port, Mapping oldmapping) {
925         MappingBuilder mpBldr = new MappingBuilder(oldmapping);
926         updateMappingStates(mpBldr, port, oldmapping);
927         if ((port.getInterfaces() == null)
928             || (!oldmapping.getLogicalConnectionPoint().contains(StringConstants.TTP_TOKEN)
929                 && !oldmapping.getLogicalConnectionPoint().contains(StringConstants.NETWORK_TOKEN))) {
930             return mpBldr.build();
931         }
932         // Get interfaces provisioned on the port
933         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
934         return mpBldr.build();
935     }
936
937     private MappingBuilder updateMappingStates(MappingBuilder mpBldr, Ports port, Mapping oldmapping) {
938         if (port.getAdministrativeState() != null
939             && !port.getAdministrativeState().getName().equals(oldmapping.getPortAdminState())) {
940             mpBldr.setPortAdminState(port.getAdministrativeState().name());
941         }
942         if (port.getOperationalState() != null
943             && !port.getOperationalState().getName().equals(oldmapping.getPortOperState())) {
944             mpBldr.setPortOperState(port.getOperationalState().name());
945         }
946         return mpBldr;
947     }
948
949     private MappingBuilder updateMappingInterfaces(String nodeId, MappingBuilder mpBldr, Ports port) {
950         for (Interfaces interfaces : port.getInterfaces()) {
951             try {
952                 Optional<Interface> openRoadmInterface = this.openRoadmInterfaces.getInterface(nodeId,
953                     interfaces.getInterfaceName());
954                 if (openRoadmInterface.isEmpty()) {
955                     LOG.warn(PortMappingUtils.INTF_ISSUE_LOGMSG,
956                         nodeId, interfaces.getInterfaceName() + "- empty interface");
957                     continue;
958                 }
959                 LOG.debug(PortMappingUtils.GOT_INTF_LOGMSG,
960                     nodeId, openRoadmInterface.get().getName(), openRoadmInterface.get().getType());
961                 Class<? extends InterfaceType> interfaceType
962                     = (Class<? extends InterfaceType>) openRoadmInterface.get().getType();
963                 // Check if interface type is OMS or OTS
964                 if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
965                     mpBldr.setSupportingOms(interfaces.getInterfaceName());
966                 }
967                 if (interfaceType.equals(OpticalTransport.class)) {
968                     mpBldr.setSupportingOts(interfaces.getInterfaceName());
969                 }
970                 String interfaceName = interfaces.getInterfaceName();
971                 if (interfaceType.equals(OtnOdu.class)
972                     && (interfaceName.substring(interfaceName.lastIndexOf("-") + 1)
973                     .equals("ODU"))) {
974                     mpBldr.setSupportingOdu4(interfaces.getInterfaceName());
975                 }
976                 if ((interfaceType.equals(OtnOdu.class))
977                     && (interfaceName.substring(interfaceName.lastIndexOf("-") + 1)
978                     .equals("ODUC4"))) {
979                     mpBldr.setSupportingOduc4(interfaces.getInterfaceName());
980                 }
981
982             } catch (OpenRoadmInterfaceException ex) {
983                 LOG.warn(PortMappingUtils.INTF_ISSUE_LOGMSG,
984                     nodeId, interfaces.getInterfaceName(), ex);
985             }
986         }
987         return mpBldr;
988     }
989
990     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
991             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String connectionMapLcp,
992             XpdrNodeTypes xpdrNodeType) {
993
994         //TODO some divergens here with 2.2.1
995         if (mapping != null && connectionMapLcp != null) {
996             // update existing mapping
997             return new MappingBuilder(mapping).setConnectionMapLcp(connectionMapLcp).build();
998         }
999         return createNewXpdrMapping(nodeId, port, circuitPackName, logicalConnectionPoint, partnerLcp, xpdrNodeType);
1000     }
1001
1002     private Mapping createNewXpdrMapping(String nodeId, Ports port, String circuitPackName,
1003             String logicalConnectionPoint, String partnerLcp, XpdrNodeTypes xpdrNodeType) {
1004         MappingBuilder mpBldr = new MappingBuilder()
1005                 .withKey(new MappingKey(logicalConnectionPoint))
1006                 .setLogicalConnectionPoint(logicalConnectionPoint)
1007                 .setSupportingCircuitPackName(circuitPackName)
1008                 .setSupportingPort(port.getPortName())
1009                 .setPortDirection(port.getPortDirection().getName())
1010                 .setLcpHashVal(PortMappingUtils.fnv1size64(nodeId + "-" + logicalConnectionPoint));
1011         if (port.getPortQual() != null) {
1012             mpBldr.setPortQual(port.getPortQual().getName());
1013         }
1014         if (xpdrNodeType != null) {
1015             mpBldr.setXponderType(xpdrNodeType);
1016         }
1017         if (partnerLcp != null) {
1018             mpBldr.setPartnerLcp(partnerLcp);
1019         }
1020         Collection<SupportedInterfaceCapability> supIntfCapaList = getSupIntfCapaList(port);
1021         if (supIntfCapaList != null) {
1022             List<Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
1023                 .SupportedIfCapability>> supportedIntf = new ArrayList<>();
1024             SupportedInterfaceCapability sic1 = null;
1025             for (SupportedInterfaceCapability sic : supIntfCapaList) {
1026                 supportedIntf.add(sic.getIfCapType());
1027                 sic1 = sic;
1028             }
1029             mpBldr.setSupportedInterfaceCapability(supportedIntf);
1030             if (port.getPortQual() == PortQual.SwitchClient
1031                 && !sic1.getOtnCapability().getMpdrClientRestriction().isEmpty()) {
1032                 // Here we assume all the supported-interfaces has the support same rates, and the
1033                 // trib-slot numbers are assumed to be the same
1034                 String mxpProfileName =
1035                     sic1.getOtnCapability().getMpdrClientRestriction().get(0).getMuxpProfileName().get(0);
1036                 // From this muxponder-profile get the min-trib-slot and the max-trib-slot
1037                 LOG.info("{}: Muxp-profile used for trib information {}", nodeId, mxpProfileName);
1038                 // This provides the tribSlot information from muxProfile
1039                 List<OpucnTribSlotDef> minMaxOpucnTribSlots = getOpucnTribSlots(nodeId, mxpProfileName);
1040                 mpBldr.setMpdrRestrictions(
1041                     new MpdrRestrictionsBuilder()
1042                         .setMinTribSlot(minMaxOpucnTribSlots.get(0))
1043                         .setMaxTribSlot(minMaxOpucnTribSlots.get(1))
1044                         .build());
1045             }
1046         }
1047         if (port.getAdministrativeState() != null) {
1048             mpBldr.setPortAdminState(port.getAdministrativeState().name());
1049         }
1050         if (port.getOperationalState() != null) {
1051             mpBldr.setPortOperState(port.getOperationalState().name());
1052         }
1053         return mpBldr.build();
1054     }
1055
1056     private Collection<SupportedInterfaceCapability> getSupIntfCapaList(Ports port) {
1057         return
1058             port.augmentation(Ports1.class) == null || port.augmentation(Ports1.class).getPortCapabilities() == null
1059                 ? null
1060                 : port.augmentation(Ports1.class).getPortCapabilities().nonnullSupportedInterfaceCapability().values();
1061     }
1062
1063     private ArrayList<OpucnTribSlotDef> getOpucnTribSlots(String deviceId, String mxpProfileName) {
1064         ArrayList<OpucnTribSlotDef> minMaxOpucnTribSlots = new ArrayList<>(2);
1065
1066         LOG.info("{} : Getting Min/Max Trib-slots from {}", deviceId, mxpProfileName);
1067         InstanceIdentifier<MuxpProfile> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1068             .child(MuxpProfile.class, new MuxpProfileKey(mxpProfileName));
1069
1070         Optional<MuxpProfile> muxpProfileObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
1071             LogicalDatastoreType.OPERATIONAL, deviceIID,
1072             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1073
1074         List<OpucnTribSlotDef> ntwHoOduOpucnTribSlots = muxpProfileObject.get().getNetworkHoOduOpucnTribSlots();
1075         // Sort the tib-slots in ascending order and pick min and max
1076         List<OpucnTribSlotDef> sortedNtwHoOduOpucnTribSlots = ntwHoOduOpucnTribSlots.stream().sorted(
1077             Comparator.comparingDouble(x -> Double.parseDouble(
1078                 x.getValue().substring(x.getValue().lastIndexOf('.') + 1))))
1079             .collect(Collectors.toList());
1080         minMaxOpucnTribSlots.add(sortedNtwHoOduOpucnTribSlots.get(0));
1081         minMaxOpucnTribSlots.add(sortedNtwHoOduOpucnTribSlots.get(sortedNtwHoOduOpucnTribSlots.size() - 1));
1082         LOG.debug("Min, Max trib slot list {}", minMaxOpucnTribSlots);
1083         return minMaxOpucnTribSlots;
1084     }
1085
1086     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
1087             //circuitPackName2 will be updated by reference contrary to circuitPackName
1088             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
1089         if (!checkPartnerPortNotNull(port)) {
1090             LOG.warn(PortMappingUtils.NO_VALID_PARTNERPORT_LOGMSG, nodeId, port.getPortName(), circuitPackName);
1091             return null;
1092         }
1093         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
1094             return null;
1095         }
1096         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
1097             .filter(
1098                 cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
1099             .findFirst();
1100         if (cpOpt.isEmpty()) {
1101             LOG.error(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, port.getPartnerPort().getCircuitPackName());
1102             return null;
1103         }
1104         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
1105             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName()))
1106             .findFirst();
1107         if (poOpt.isEmpty()) {
1108             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
1109                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
1110             return null;
1111         }
1112         Ports port2 = poOpt.get();
1113         circuitPackName2.append(cpOpt.get().getCircuitPackName());
1114         if (!checkPartnerPort(circuitPackName, port, port2)) {
1115             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
1116                 nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
1117             return null;
1118         }
1119         return port2;
1120     }
1121
1122
1123     private void putXpdrLcpsInMaps(int line, String nodeId,
1124             Integer xponderNb, XpdrNodeTypes xponderType,
1125             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
1126             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
1127         String lcp1 =
1128             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
1129         if (lcpMap.containsKey(lcp1)) {
1130             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp1 + " - already exist");
1131             return;
1132         }
1133         String lcp2 =
1134             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
1135         if (lcpMap.containsKey(lcp2)) {
1136             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp2 + " - already exist");
1137             return;
1138         }
1139         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
1140         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
1141         mappingMap.put(lcp1,
1142                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null, xponderType));
1143         mappingMap.put(lcp2,
1144                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null, xponderType));
1145         return;
1146     }
1147
1148     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
1149             Integer xponderNb, XpdrNodeTypes xponderType,
1150             String circuitPackName,  Ports port,
1151             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
1152
1153         if (port.getPortQual() == null) {
1154             LOG.warn(PortMappingUtils.PORTQUAL_LOGMSG, nodeId, port.getPortName(), circuitPackName, "not found");
1155             return new int[] {line, client};
1156         }
1157
1158         switch (port.getPortQual()) {
1159
1160             case XpdrClient:
1161             case SwitchClient:
1162                 String lcp0 =
1163                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
1164                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
1165                 mappingMap.put(lcp0,
1166                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null, xponderType));
1167                 client++;
1168                 break;
1169
1170             case XpdrNetwork:
1171             case SwitchNetwork:
1172                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
1173                         xponderNb, xponderType,
1174                         circuitPackName,  port,
1175                         circuitPackList,  lcpMap, mappingMap);
1176                 break;
1177
1178             default:
1179                 LOG.error(PortMappingUtils.PORTQUAL_LOGMSG,
1180                     nodeId, port.getPortName(), circuitPackName, port.getPortQual() + " not supported");
1181         }
1182         return new int[] {line, client};
1183     }
1184
1185     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
1186             Integer xponderNb, XpdrNodeTypes xponderType,
1187             String circuitPackName,  Ports port,
1188             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
1189
1190         switch (port.getPortDirection()) {
1191
1192             case Bidirectional:
1193                 String lcp =
1194                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
1195                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
1196                 mappingMap.put(lcp,
1197                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null, xponderType));
1198                 line++;
1199                 break;
1200
1201             case Rx:
1202             case Tx:
1203                 StringBuilder circuitPackName2 = new StringBuilder();
1204                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
1205                         circuitPackList, lcpMap);
1206
1207                 if (port2 == null) {
1208                      //key already present or an error occured and was logged
1209                     return line;
1210                 }
1211
1212                 putXpdrLcpsInMaps(line, nodeId, xponderNb, xponderType,
1213                         circuitPackName, circuitPackName2.toString(), port, port2,
1214                         lcpMap, mappingMap);
1215                 line += 2;
1216                 break;
1217
1218             default:
1219                 LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
1220                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
1221         }
1222
1223         return line;
1224     }
1225
1226     private boolean createMcCapabilitiesList(String nodeId, Info deviceInfo,
1227             Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap) {
1228         if (deviceInfo.getNodeType() == NodeTypes.Rdm) {
1229             Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1230             List<SharedRiskGroup> srgs = getSrgs(nodeId, deviceInfo);
1231             mcCapabilitiesMap.putAll(getMcCapabilities(degrees, srgs, deviceInfo, nodeId));
1232         } else if ((deviceInfo.getNodeType() == NodeTypes.Xpdr)) {
1233             Map<McCapabilityProfileKey, McCapabilityProfile> mcProfileXpdr = getMcCapabilityProfiles(nodeId,
1234                 deviceInfo);
1235             if (mcProfileXpdr.size() > 1) {
1236                 LOG.warn("Re-check the mc-capability-profiles for XPDR port-mapping");
1237             }
1238             // Typically for a XPDR there will be only one mc-capability-profile
1239             for (Map.Entry<McCapabilityProfileKey, McCapabilityProfile> mcCapProfile : mcProfileXpdr.entrySet()) {
1240                 String mcNodeName = "XPDR" + "-" + "mcprofile";
1241                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
1242                     .withKey(new McCapabilitiesKey(mcNodeName))
1243                     .setMcNodeName(mcNodeName);
1244                 mcCapabilitiesBuilder
1245                     .setCenterFreqGranularity(mcCapProfile.getValue().getCenterFreqGranularity())
1246                     .setSlotWidthGranularity(mcCapProfile.getValue().getSlotWidthGranularity());
1247                 // Build and add to the Map
1248                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
1249                 LOG.info("Finished building mc-capability profile for XPDR {}", nodeId);
1250                 // Since we only have one mc-profile for XPDR, we can break the for-loop
1251                 break;
1252             }
1253
1254         }
1255         return true;
1256     }
1257
1258     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
1259         // Creating mapping data for degree TTP's
1260         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1261         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
1262         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
1263         LOG.info(PortMappingUtils.MAP_LOOKS_LOGMSG, nodeId, interfaceList);
1264         postPortMapping(nodeId, null, null, cpToDegreeList, null, null);
1265
1266         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : getPerDegreePorts(nodeId, deviceInfo).entrySet()) {
1267             List<ConnectionPorts> cpMapValue = cpMapEntry.getValue();
1268             ConnectionPorts cp1 = cpMapValue.get(0);
1269             String cp1Name = cp1.getCircuitPackName();
1270             switch (cpMapValue.size()) {
1271                 case 1:
1272                     // port is bidirectional
1273                     Ports port = getTtpPort(cp1, cp1Name, nodeId);
1274                     if (port == null) {
1275                         return false;
1276                     }
1277                     if (!checkTtpPort(port, cp1Name, nodeId, true)) {
1278                         continue;
1279                     }
1280                     String logicalConnectionPoint =
1281                             PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(), "TXRX");
1282                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
1283                         nodeId, port.getPortName(), cp1Name, logicalConnectionPoint);
1284                     portMapList.add(createMappingObject(nodeId, port, cp1Name, logicalConnectionPoint));
1285                     break;
1286                 case 2:
1287                     // ports are unidirectionals
1288                     Ports port1 = getTtpPort(cp1, cp1Name, nodeId);
1289                     if (port1 == null) {
1290                         return false;
1291                     }
1292                     ConnectionPorts cp2 = cpMapValue.get(1);
1293                     String cp2Name = cp2.getCircuitPackName();
1294                     Ports port2 = getTtpPort(cp2, cp2Name, nodeId);
1295                     if (port2 == null) {
1296                         return false;
1297                     }
1298                     if (!checkTtpPortsUnidir(port1, port2, cp1Name, cp2Name, nodeId)) {
1299                         continue;
1300                     }
1301                     String logicalConnectionPoint1 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
1302                             port1.getPortDirection().getName().toUpperCase(Locale.getDefault()));
1303                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
1304                         nodeId, port1.getPortName(), cp1Name, logicalConnectionPoint1);
1305                     portMapList.add(createMappingObject(nodeId, port1, cp1Name, logicalConnectionPoint1));
1306                     String logicalConnectionPoint2 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
1307                             port2.getPortDirection().getName().toUpperCase(Locale.getDefault()));
1308                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
1309                         nodeId, port2.getPortName(), cp2Name, logicalConnectionPoint2);
1310                     portMapList.add(createMappingObject(nodeId, port2, cp2Name, logicalConnectionPoint2));
1311                     break;
1312                 default:
1313                     LOG.error(PortMappingUtils.NOT_CORRECT_CONPORT_LOGMSG, nodeId, cpMapEntry.getKey());
1314                     continue;
1315                     //TODO should it be continue or return false ?
1316             }
1317         }
1318         return true;
1319     }
1320
1321     private Ports getTtpPort(ConnectionPorts cp, String cpName, String nodeId) {
1322         InstanceIdentifier<Ports> portID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1323             .child(CircuitPacks.class, new CircuitPacksKey(cpName))
1324             .child(Ports.class, new PortsKey(cp.getPortName()));
1325         LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG, nodeId, cp.getPortName(), cpName);
1326         Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
1327             LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
1328             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1329         if (portObject.isEmpty()) {
1330             LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, cp.getPortName(), cpName);
1331             return null;
1332         }
1333         return portObject.get();
1334     }
1335
1336     private boolean checkPortQual(Ports port, String cpName, String nodeId) {
1337         if (port.getPortQual() == null) {
1338             return false;
1339         }
1340         if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
1341             //used to be LOG.error when called from createTtpPortMapping
1342             LOG.debug(PortMappingUtils.PORT_NOT_RDMEXT_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
1343                 nodeId, port.getPortName(), cpName);
1344             return false;
1345         }
1346         return true;
1347     }
1348
1349     private boolean checkTtpPort(Ports port, String cpName, String nodeId, boolean bidirectional) {
1350         if (!checkPortQual(port, cpName, nodeId)) {
1351             return false;
1352         }
1353         if (Direction.Bidirectional.getIntValue() == port.getPortDirection().getIntValue() ^ bidirectional) {
1354         // (a ^ b) makes more sense than (!a && b) here since it can also work for unidirectional links
1355             LOG.error(PortMappingUtils.PORTDIR_ERROR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
1356                 nodeId, port.getPortName(), cpName);
1357             return false;
1358         }
1359         return true;
1360     }
1361
1362     private boolean checkTtpPortsUnidir(Ports port1, Ports port2, String cp1Name, String cp2Name, String nodeId) {
1363         if (!checkTtpPort(port1, cp1Name, nodeId, false)) {
1364             return false;
1365         }
1366         if (!checkTtpPort(port2, cp2Name, nodeId, false)) {
1367             return false;
1368         }
1369         if (!checkPartnerPort(cp1Name, port1, port2)) {
1370             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
1371                 nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
1372             return false;
1373         }
1374         // Directions checks are the same for cp1 and cp2, no need to check them twice.
1375         if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
1376             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
1377                 nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
1378             return false;
1379         }
1380         return true;
1381     }
1382
1383     private NodeInfo createNodeInfo(Info deviceInfo) {
1384         if (deviceInfo.getNodeType() == null) {
1385             // TODO make mandatory in yang
1386             LOG.error(PortMappingUtils.NODE_TYPE_LOGMSG, deviceInfo.getNodeId(), "field missing");
1387             return null;
1388         }
1389         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
1390                 .setOpenroadmVersion(OpenroadmNodeVersion._71)
1391                 .setNodeClli(
1392                     deviceInfo.getClli() == null || deviceInfo.getClli().isEmpty()
1393                         ? "defaultCLLI"
1394                         : deviceInfo.getClli())
1395                 .setNodeType(deviceInfo.getNodeType());
1396         // TODO: 221 versions expects an int value - need to check whether it is bug or an evolution here
1397         if (deviceInfo.getModel() != null) {
1398             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
1399         }
1400         if (deviceInfo.getVendor() != null) {
1401             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
1402         }
1403         if (deviceInfo.getIpAddress() != null) {
1404             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
1405         }
1406         return nodeInfoBldr.build();
1407     }
1408
1409     private String getLcpFromCpAndPort(Map<MappingKey, Mapping> mappings, String cpName, String portName) {
1410         for (Mapping mapping : mappings.values()) {
1411             if (cpName.equals(mapping.getSupportingCircuitPackName())
1412                 && portName.equals(mapping.getSupportingPort())) {
1413                 return mapping.getLogicalConnectionPoint();
1414             }
1415         }
1416         return null;
1417     }
1418
1419 }