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