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