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