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