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