Add portmapping methods to fill XpdR LCPs maps
[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.rev201012.Network;
35 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.NetworkBuilder;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.Nodes;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.NodesBuilder;
38 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.NodesKey;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.CpToDegree;
40 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.CpToDegreeBuilder;
41 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.CpToDegreeKey;
42 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.Mapping;
43 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.MappingBuilder;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.MappingKey;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.McCapabilities;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.McCapabilitiesBuilder;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.McCapabilitiesKey;
48 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.NodeInfo;
49 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.NodeInfo.OpenroadmVersion;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.NodeInfoBuilder;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.SwitchingPoolLcp;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.SwitchingPoolLcpBuilder;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.SwitchingPoolLcpKey;
54 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.switching.pool.lcp.NonBlockingList;
55 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.switching.pool.lcp.NonBlockingListBuilder;
56 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev201012.network.nodes.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         InstanceIdentifier<Ports> portIId = InstanceIdentifier.create(OrgOpenroadmDevice.class)
181             .child(CircuitPacks.class, new CircuitPacksKey(oldMapping.getSupportingCircuitPackName()))
182             .child(Ports.class, new PortsKey(oldMapping.getSupportingPort()));
183         if ((oldMapping == null) || (nodeId == null)) {
184             LOG.error("Impossible to update mapping");
185             return false;
186         }
187         try {
188             Optional<Ports> portObject = deviceTransactionManager.getDataFromDevice(nodeId,
189                 LogicalDatastoreType.OPERATIONAL, portIId, Timeouts.DEVICE_READ_TIMEOUT,
190                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
191             if (!portObject.isPresent()) {
192                 return false;
193             }
194             Ports port = portObject.get();
195             Mapping newMapping = createMappingObject(nodeId, port, oldMapping.getSupportingCircuitPackName(),
196                 oldMapping.getLogicalConnectionPoint());
197             LOG.debug("{} : Updating old mapping Data {} for {} by new mapping data {}",
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("{} : exception when updating Mapping {} - ",
209                     nodeId, 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("{} : Impossible to get device configuration", nodeId);
222             return false;
223         }
224         OrgOpenroadmDevice device = deviceObject.get();
225         if (device.getCircuitPacks() == null) {
226             LOG.warn("{} : Circuit Packs not present", nodeId);
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("{} : configuration does not contain a list of Xponders", nodeId);
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("{} : Ports were not found for circuit pack {}", nodeId, 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("{} : configuration contains a list of xponders", nodeId);
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()) {
266                     String circuitPackName = xpdrPort.getCircuitPackName();
267                     String portName = xpdrPort.getPortName().toString();
268                     // If there xponder-subtree has missing circuit-packs or ports,
269                     // This gives a null-pointer expection,
270                     if (device.nonnullCircuitPacks().values().stream()
271                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
272                             .findFirst().isEmpty()) {
273                         LOG.warn("{} : Circuit-pack {} is missing in the device - ignoring it in port-mapping",
274                                 nodeId, circuitPackName);
275                         continue;
276                     }
277                     if (device.nonnullCircuitPacks().values().stream()
278                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
279                             .findFirst().get().nonnullPorts().values().stream()
280                             .filter(p -> p.getPortName().equals(portName))
281                             .findFirst().isEmpty()) {
282                         LOG.warn("{} : port {} on {} - association missing in the device - ignoring it in port-mapping",
283                                 nodeId, portName, circuitPackName);
284                         continue;
285                     }
286                     Ports port = device.nonnullCircuitPacks().values().stream()
287                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
288                             .findFirst().get().nonnullPorts().values().stream()
289                             .filter(p -> p.getPortName().equals(portName))
290                             .findFirst().get();
291                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
292                         xponderNb, xponderType, circuitPackName, port,
293                         circuitPackList, lcpMap, mappingMap);
294                     line = counters[0];
295                     client = counters[1];
296                 }
297             }
298         }
299
300         if (device.getConnectionMap() == null) {
301             LOG.warn("{} : No connection-map inside device configuration", nodeId);
302         } else {
303             Collection<ConnectionMap> connectionMap = deviceObject.get().nonnullConnectionMap().values();
304             for (ConnectionMap cm : connectionMap) {
305                 String skey = cm.getSource().getCircuitPackName() + "+" + cm.getSource().getPortName();
306                 String slcp = lcpMap.containsKey(skey) ? lcpMap.get(skey) : null;
307                 Destination destination0 = cm.nonnullDestination().values().iterator().next();
308                 String dkey = destination0.getCircuitPackName() + "+" + destination0.getPortName();
309                 if (slcp == null) {
310                     LOG.error("{} : Error in connection-map analysis for source {} and destination (CP+port) {}",
311                         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("{} : port {} on {} is not associated to a logical connection point",
336                                 nodeId, item.getPortName(), item.getCircuitPackName());
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         if (port.getPartnerPort() == null
367             || port.getPartnerPort().getCircuitPackName() == null
368             || port.getPartnerPort().getPortName() == null) {
369             return false;
370         }
371         return true;
372     }
373
374     private boolean checkPartnerPortNoDir(String circuitPackName, Ports port1, Ports port2) {
375         if (!checkPartnerPortNotNull(port2)
376             || !port2.getPartnerPort().getCircuitPackName().equals(circuitPackName)
377             || !port2.getPartnerPort().getPortName().equals(port1.getPortName())) {
378             return false;
379         }
380         return true;
381     }
382
383     private boolean checkPartnerPort(String circuitPackName, Ports port1, Ports port2) {
384         if (!checkPartnerPortNoDir(circuitPackName, port1, port2)
385             || ((Direction.Rx.getIntValue() != port1.getPortDirection().getIntValue()
386                     || Direction.Tx.getIntValue() != port2.getPortDirection().getIntValue())
387                 &&
388                 (Direction.Tx.getIntValue() != port1.getPortDirection().getIntValue()
389                     || Direction.Rx.getIntValue() != port2.getPortDirection().getIntValue()))) {
390             return false;
391         }
392         return true;
393     }
394
395
396     private HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg
397             .CircuitPacks>> getSrgCps(String deviceId, Info ordmInfo) {
398         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg
399             .CircuitPacks>> cpPerSrg = new HashMap<>();
400         // Get value for max Srg from info subtree, required for iteration
401         // if not present assume to be 20 (temporary)
402         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
403         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
404             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks> srgCps
405                 = new ArrayList<>();
406             LOG.debug("{} : Getting Circuitpacks for Srg Number {}", deviceId, srgCounter);
407             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
408                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
409             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
410                 LogicalDatastoreType.OPERATIONAL, srgIID,
411                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
412             if (ordmSrgObject.isPresent()) {
413                 srgCps.addAll(ordmSrgObject.get().nonnullCircuitPacks().values());
414                 cpPerSrg.put(ordmSrgObject.get().getSrgNumber().toJava(), srgCps);
415             }
416         }
417         LOG.info("{} : Device has {} Srg", deviceId, cpPerSrg.size());
418         return cpPerSrg;
419     }
420
421     private boolean createPpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
422         // Creating mapping data for SRG's PP
423         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks>> srgCps
424             = getSrgCps(nodeId, deviceInfo);
425         for (Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks>>
426                 srgCpEntry : srgCps.entrySet()) {
427             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks> cpList =
428                 srgCps.get(srgCpEntry.getKey());
429             List<String> keys = new ArrayList<>();
430             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.srg.CircuitPacks cp : cpList) {
431                 String circuitPackName = cp.getCircuitPackName();
432                 InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
433                     .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
434                 Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
435                     LogicalDatastoreType.OPERATIONAL, cpIID,
436                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
437
438                 if (!circuitPackObject.isPresent() || (circuitPackObject.get().getPorts() == null)) {
439                     LOG.warn("{} : Circuit pack {} not found or without ports.", nodeId, circuitPackName);
440                     continue;
441                 }
442                 List<Ports> portList = new ArrayList<>(circuitPackObject.get().nonnullPorts().values());
443                 Collections.sort(portList, new SortPort221ByName());
444                 int portIndex = 1;
445                 for (Ports port : portList) {
446                     String currentKey = circuitPackName + "-" + port.getPortName();
447                     if (port.getPortQual() == null) {
448                         continue;
449                     }
450
451                     if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
452                         LOG.debug("{} : port {} on {} is not roadm-external - cannot assign logicalConnectionPoint.",
453                                 nodeId, port.getPortName(), circuitPackName);
454                         continue;
455                     }
456
457                     if (keys.contains(currentKey)) {
458                         LOG.debug("{} : port {} on {} has already been handled - cannot assign logicalConnectionPoint.",
459                                 nodeId, port.getPortName(), circuitPackName);
460                         continue;
461                     }
462
463                     switch (port.getPortDirection()) {
464
465                         case Bidirectional:
466                             String lcp = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
467                             LOG.info("{} : port {} on {} - associated Logical Connection Point is {}",
468                                     nodeId, port.getPortName(), circuitPackName, lcp);
469                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp));
470                             portIndex++;
471                             keys.add(currentKey);
472                             break;
473
474                         case Rx:
475                         case Tx:
476                             if (!checkPartnerPortNotNull(port)) {
477                                 LOG.info("{} : port {} on {} is unidirectional but has no valid partnerPort"
478                                         + " - cannot assign  logicalConnectionPoint.",
479                                         nodeId, port.getPortName(), circuitPackName);
480                                 continue;
481                             }
482
483                             String lcp1 = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
484                             LOG.info("{} :  port {} on {} - associated Logical Connection Point is {}",
485                                     nodeId, port.getPortName(), circuitPackName, lcp1);
486                             InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
487                                 .child(CircuitPacks.class,
488                                     new CircuitPacksKey(port.getPartnerPort().getCircuitPackName()))
489                                 .child(Ports.class, new PortsKey(port.getPartnerPort().getPortName().toString()));
490                             Optional<Ports> port2Object = this.deviceTransactionManager
491                                 .getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, port2ID,
492                                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
493                             if (!port2Object.isPresent()
494                                 || port2Object.get().getPortQual().getIntValue()
495                                     != PortQual.RoadmExternal.getIntValue()) {
496                                 LOG.error("{} : port {} on {} - error getting partner",
497                                         nodeId, port.getPartnerPort().getPortName().toString(),
498                                         port.getPartnerPort().getCircuitPackName());
499                                 continue;
500                             }
501
502                             Ports port2 = port2Object.get();
503                             if (!checkPartnerPort(circuitPackName, port, port2)) {
504                                 LOG.error("{} : port {} on {} - Error with partner port configuration",
505                                         nodeId, port.getPortName(), circuitPackName);
506                                 portIndex++;
507                                 continue;
508                             }
509                             String lcp2 = createLogicalConnectionPort(port2, srgCpEntry.getKey(),portIndex);
510                             LOG.info("{} : port {} on {} - associated Logical Connection Point is {}",
511                                     nodeId, port2.getPortName(), circuitPackName, lcp2);
512                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp1));
513                             portMapList.add(
514                                 createMappingObject(nodeId ,port2, port.getPartnerPort().getCircuitPackName(), lcp2));
515                             portIndex++;
516                             keys.add(currentKey);
517                             keys.add(port.getPartnerPort().getCircuitPackName() + "-" + port2.getPortName());
518                             break;
519
520                         default:
521                             LOG.error("{} : port {} on {} - unsupported Direction {}"
522                                     + " - cannot assign  logicalConnectionPoint.",
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("port {} : Unsupported port direction {}", port, port.getPortDirection());
537         return null;
538     }
539
540     private String createXpdrLogicalConnectionPort(int xponderNb, int lcpNb, String token) {
541         return new StringBuilder("XPDR").append(xponderNb)
542                 .append("-")
543                 .append(token).append(lcpNb)
544                 .toString();
545     }
546
547
548     private Map<Integer, Degree> getDegreesMap(String deviceId, Info ordmInfo) {
549         Map<Integer, Degree> degrees = new HashMap<>();
550
551         // Get value for max degree from info subtree, required for iteration
552         // if not present assume to be 20 (temporary)
553         Integer maxDegree = ordmInfo.getMaxDegrees() == null ? 20 : ordmInfo.getMaxDegrees().toJava();
554
555         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
556             LOG.debug("{} : Getting Connection ports for Degree Number {}", deviceId, degreeCounter);
557             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
558                 .child(Degree.class, new DegreeKey(Uint16.valueOf(degreeCounter)));
559             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
560                 LogicalDatastoreType.OPERATIONAL, deviceIID,
561                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
562             if (ordmDegreeObject.isPresent()) {
563                 degrees.put(degreeCounter, ordmDegreeObject.get());
564             }
565         }
566         LOG.info("{} : Device has {} degree(s)", deviceId, degrees.size());
567         return degrees;
568     }
569
570     private Map<Integer, List<ConnectionPorts>> getPerDegreePorts(String deviceId, Info ordmInfo) {
571         Map<Integer, List<ConnectionPorts>> conPortMap = new HashMap<>();
572         getDegreesMap(deviceId, ordmInfo).forEach(
573             (index, degree) -> conPortMap.put(index, new ArrayList<>(degree.nonnullConnectionPorts().values())));
574         return conPortMap;
575     }
576
577     private List<SharedRiskGroup> getSrgs(String deviceId, Info ordmInfo) {
578         List<SharedRiskGroup> srgs = new ArrayList<>();
579
580         // Get value for max Srg from info subtree, required for iteration
581         // if not present assume to be 20 (temporary)
582         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
583         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
584             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
585                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
586             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
587                 LogicalDatastoreType.OPERATIONAL, srgIID,
588                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
589             if (ordmSrgObject.isPresent()) {
590                 srgs.add(ordmSrgObject.get());
591
592             }
593         }
594         return srgs;
595     }
596
597     private Map<String, String> getEthInterfaceList(String nodeId) {
598         LOG.info("{} : It is calling get ethernet interface", nodeId);
599         InstanceIdentifier<Protocols> protocoliid = InstanceIdentifier.create(OrgOpenroadmDevice.class)
600             .child(Protocols.class);
601         Optional<Protocols> protocolObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
602             LogicalDatastoreType.OPERATIONAL, protocoliid, Timeouts.DEVICE_READ_TIMEOUT,
603             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
604         if (!protocolObject.isPresent() || protocolObject.get().augmentation(Protocols1.class).getLldp() == null) {
605             LOG.warn("{} : Couldnt find port config under LLDP - Processiong is done.. now returning..", nodeId);
606             return new HashMap<>();
607         }
608         Map<String, String> cpToInterfaceMap = new HashMap<>();
609         Lldp lldp = protocolObject.get().augmentation(Protocols1.class).getLldp();
610         for (PortConfig portConfig : lldp.nonnullPortConfig().values()) {
611             if (!portConfig.getAdminStatus().equals(PortConfig.AdminStatus.Txandrx)) {
612                 continue;
613             }
614             InstanceIdentifier<Interface> interfaceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
615                 .child(Interface.class, new InterfaceKey(portConfig.getIfName()));
616             Optional<Interface> interfaceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
617                 LogicalDatastoreType.OPERATIONAL, interfaceIID, Timeouts.DEVICE_READ_TIMEOUT,
618                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
619             if (!interfaceObject.isPresent() || (interfaceObject.get().getSupportingCircuitPackName() == null)) {
620                 continue;
621             }
622             String supportingCircuitPackName = interfaceObject.get().getSupportingCircuitPackName();
623             cpToInterfaceMap.put(supportingCircuitPackName, portConfig.getIfName());
624             InstanceIdentifier<CircuitPacks> circuitPacksIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
625                 .child(CircuitPacks.class, new CircuitPacksKey(supportingCircuitPackName));
626             Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(
627                 nodeId, LogicalDatastoreType.OPERATIONAL, circuitPacksIID, Timeouts.DEVICE_READ_TIMEOUT,
628                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
629             if (!circuitPackObject.isPresent() || (circuitPackObject.get().getParentCircuitPack() == null)) {
630                 continue;
631             }
632             cpToInterfaceMap.put(circuitPackObject.get().getParentCircuitPack().getCircuitPackName(),
633                 portConfig.getIfName());
634         }
635         LOG.info("{} : Processiong is done.. now returning..", nodeId);
636         return cpToInterfaceMap;
637     }
638
639     private List<CpToDegree> getCpToDegreeList(Map<Integer, Degree> degrees, Map<String, String> interfaceList) {
640         List<CpToDegree> cpToDegreeList = new ArrayList<>();
641         for (Degree degree : degrees.values()) {
642             LOG.debug("Inside CP to degree list");
643             cpToDegreeList.addAll(degree.nonnullCircuitPacks().values().stream()
644                 .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(),
645                     degree.getDegreeNumber().toString(), interfaceList))
646                 .collect(Collectors.toList()));
647         }
648         return cpToDegreeList;
649     }
650
651     private Map<McCapabilitiesKey, McCapabilities> getMcCapabilities(Map<Integer, Degree> degrees,
652             List<SharedRiskGroup> srgs, String nodeId) {
653         LOG.info("{} : Getting the MC capabilities for degrees", nodeId);
654         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = degrees.values().stream()
655             .map(degree -> createMcCapDegreeObject(degree, nodeId))
656             .collect(Collectors.toMap(McCapabilities::key, mcc -> mcc));
657         // Add the SRG mc-capabilities
658         LOG.info("{} : Getting the MC capabilities for SRGs", nodeId);
659         mcCapabilities.putAll(srgs.stream().map(srg -> createMcCapSrgObject(srg, nodeId))
660             .collect(Collectors.toMap(McCapabilities::key, mcCapabilities2 -> mcCapabilities2)));
661         return mcCapabilities;
662     }
663
664     private boolean postPortMapping(String nodeId, NodeInfo nodeInfo, List<Mapping> portMapList,
665             List<CpToDegree> cp2DegreeList, List<SwitchingPoolLcp> splList,
666             Map<McCapabilitiesKey, McCapabilities> mcCapabilities) {
667         NodesBuilder nodesBldr = new NodesBuilder().withKey(new NodesKey(nodeId)).setNodeId(nodeId);
668         if (nodeInfo != null) {
669             nodesBldr.setNodeInfo(nodeInfo);
670         }
671         if (portMapList != null) {
672             Map<MappingKey, Mapping> mappingMap = new HashMap<>();
673             // No element in the list below should be null at this stage
674             for (Mapping mapping: portMapList) {
675                 mappingMap.put(mapping.key(), mapping);
676             }
677             nodesBldr.setMapping(mappingMap);
678         }
679         if (cp2DegreeList != null) {
680             Map<CpToDegreeKey, CpToDegree> cpToDegreeMap = new HashMap<>();
681             // No element in the list below should be null at this stage
682             for (CpToDegree cp2Degree: cp2DegreeList) {
683                 cpToDegreeMap.put(cp2Degree.key(), cp2Degree);
684             }
685             nodesBldr.setCpToDegree(cpToDegreeMap);
686         }
687
688         if (splList != null) {
689             Map<SwitchingPoolLcpKey,SwitchingPoolLcp> splMap = new HashMap<>();
690             // No element in the list below should be null at this stage
691             for (SwitchingPoolLcp spl: splList) {
692                 splMap.put(spl.key(), spl);
693             }
694             nodesBldr.setSwitchingPoolLcp(splMap);
695         }
696         if (mcCapabilities != null) {
697             nodesBldr.setMcCapabilities(mcCapabilities);
698         }
699         Map<NodesKey,Nodes> nodesList = new HashMap<>();
700         Nodes nodes = nodesBldr.build();
701         nodesList.put(nodes.key(),nodes);
702
703         Network network = new NetworkBuilder().setNodes(nodesList).build();
704
705         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
706         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
707         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
708         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
709         try {
710             commit.get();
711             return true;
712         } catch (InterruptedException | ExecutionException e) {
713             LOG.warn("{} : Failed to post {}", nodeId, network, e);
714             return false;
715         }
716     }
717
718     private CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber,
719             Map<String, String> interfaceList) {
720         return new CpToDegreeBuilder()
721             .withKey(new CpToDegreeKey(circuitPackName))
722             .setCircuitPackName(circuitPackName)
723             .setDegreeNumber(Uint32.valueOf(degreeNumber))
724             .setInterfaceName(interfaceList.get(circuitPackName)).build();
725     }
726
727     private McCapabilities createMcCapDegreeObject(Degree degree, String nodeId) {
728         String mcNodeName = "DEG" + degree.getDegreeNumber().toString() + "-TTP";
729         McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
730             .withKey(new McCapabilitiesKey(mcNodeName))
731             .setMcNodeName(mcNodeName);
732         if (degree.getMcCapabilities() == null) {
733             LOG.warn("{} : Media channel capabilities are not advertised for degree {} - assuming fixed grid",
734                     nodeId, degree.getDegreeNumber());
735             mcCapabilitiesBuilder
736                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
737                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
738         } else {
739             mcCapabilitiesBuilder
740                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance(degree.getMcCapabilities()
741                     .getCenterFreqGranularity().getValue().toString()))
742                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance(degree.getMcCapabilities()
743                     .getSlotWidthGranularity().getValue().toString()));
744         }
745         return mcCapabilitiesBuilder.build();
746     }
747
748     private McCapabilities createMcCapSrgObject(SharedRiskGroup srg, String nodeId) {
749         String mcNodeName = "SRG" + srg.getSrgNumber().toString() + "-PP";
750         McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
751             .withKey(new McCapabilitiesKey(mcNodeName))
752             .setMcNodeName(mcNodeName);
753         if (srg.getMcCapabilities() == null) {
754             LOG.warn("{} : Media channel capabilities are not advertised for SRG {} - assuming fixed grid",
755                     nodeId, srg.getSrgNumber());
756             mcCapabilitiesBuilder
757                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
758                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
759         } else {
760             mcCapabilitiesBuilder
761                 .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance(srg.getMcCapabilities()
762                     .getCenterFreqGranularity().getValue().toString()))
763                 .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance(srg.getMcCapabilities()
764                     .getSlotWidthGranularity().getValue().toString()));
765         }
766         return mcCapabilitiesBuilder.build();
767     }
768
769     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
770             String logicalConnectionPoint) {
771         MappingBuilder mpBldr = new MappingBuilder()
772                 .withKey(new MappingKey(logicalConnectionPoint))
773                 .setLogicalConnectionPoint(logicalConnectionPoint)
774                 .setSupportingCircuitPackName(circuitPackName)
775                 .setSupportingPort(port.getPortName())
776                 .setPortDirection(port.getPortDirection().getName());
777
778         if ((port.getInterfaces() == null)
779             || (!logicalConnectionPoint.contains(StringConstants.TTP_TOKEN)
780                 && !logicalConnectionPoint.contains(StringConstants.NETWORK_TOKEN))) {
781             return mpBldr.build();
782         }
783         // Get OMS and OTS interface provisioned on the TTP's
784         for (Interfaces interfaces : port.getInterfaces()) {
785             try {
786                 Optional<Interface> openRoadmInterface = this.openRoadmInterfaces.getInterface(nodeId,
787                     interfaces.getInterfaceName());
788                 if (!openRoadmInterface.isPresent()) {
789                     LOG.warn("{} : Interface {} was null!", nodeId, interfaces.getInterfaceName());
790                     continue;
791                 }
792                 LOG.debug("{} : interface get from device is {} and of type {}",
793                     nodeId, openRoadmInterface.get().getName(), openRoadmInterface.get().getType());
794                 Class<? extends InterfaceType> interfaceType
795                     = (Class<? extends InterfaceType>) openRoadmInterface.get().getType();
796                 // Check if interface type is OMS or OTS
797                 if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
798                     mpBldr.setSupportingOms(interfaces.getInterfaceName());
799                 }
800                 if (interfaceType.equals(OpticalTransport.class)) {
801                     mpBldr.setSupportingOts(interfaces.getInterfaceName());
802                 }
803                 if (interfaceType.equals(OtnOdu.class)) {
804                     mpBldr.setSupportingOdu4(interfaces.getInterfaceName());
805                 }
806             } catch (OpenRoadmInterfaceException ex) {
807                 LOG.warn("{} : Error while getting interface {} - ",
808                     nodeId, interfaces.getInterfaceName(), ex);
809             }
810         }
811         return mpBldr.build();
812     }
813
814     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
815             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String connectionMapLcp,
816             XpdrNodeTypes xpdrNodeType) {
817
818         if (mapping != null && connectionMapLcp != null) {
819             // update existing mapping
820             return new MappingBuilder(mapping).setConnectionMapLcp(connectionMapLcp).build();
821         }
822
823         // create a new mapping
824         String nodeIdLcp = nodeId + "-" + logicalConnectionPoint;
825         MappingBuilder mpBldr = new MappingBuilder()
826                 .withKey(new MappingKey(logicalConnectionPoint))
827                 .setLogicalConnectionPoint(logicalConnectionPoint)
828                 .setSupportingCircuitPackName(circuitPackName)
829                 .setSupportingPort(port.getPortName())
830                 .setPortDirection(port.getPortDirection().getName())
831                 .setLcpHashVal(FnvUtils.fnv1_64(nodeIdLcp));
832         if (port.getPortQual() != null) {
833             mpBldr.setPortQual(port.getPortQual().getName());
834         }
835         if (xpdrNodeType != null) {
836             mpBldr.setXponderType(
837                 org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.XpdrNodeTypes.forValue(
838                     xpdrNodeType.getIntValue()));
839         }
840         if (partnerLcp != null) {
841             mpBldr.setPartnerLcp(partnerLcp);
842         }
843         if (port.getSupportedInterfaceCapability() != null) {
844             List<Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
845                 .SupportedIfCapability>> supportedIntf = new ArrayList<>();
846             for (Class<? extends SupportedIfCapability> sup: port.getSupportedInterfaceCapability()) {
847                 @SuppressWarnings("unchecked") Class<? extends
848                     org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327.SupportedIfCapability> sup1 =
849                     (Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
850                         .SupportedIfCapability>) sup;
851                 supportedIntf.add(sup1);
852             }
853             mpBldr.setSupportedInterfaceCapability(supportedIntf);
854         }
855         return mpBldr.build();
856     }
857
858     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
859             //circuitPackName2 will be updated by reference contrary to circuitPackName
860             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
861         if (!checkPartnerPortNotNull(port)) {
862             LOG.warn("{} : port {} on {} - Error in the configuration ",
863                     nodeId, port.getPortName(), circuitPackName);
864             return null;
865         }
866         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
867             return null;
868         }
869         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
870             .filter(
871                 cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
872             .findFirst();
873         if (!cpOpt.isPresent()) {
874             LOG.error("{} : Error fetching circuit-pack {}",
875                     nodeId, port.getPartnerPort().getCircuitPackName());
876             return null;
877         }
878         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
879             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName().toString()))
880             .findFirst();
881         if (!poOpt.isPresent()) {
882             LOG.error("{} : Error fetching port {} on {}",
883                     nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
884             return null;
885         }
886         Ports port2 = poOpt.get();
887         circuitPackName2.append(cpOpt.get().getCircuitPackName());
888         if (!checkPartnerPort(circuitPackName, port, port2)) {
889             LOG.error("{} : port {} on {} is not a correct partner port of {} on  {}",
890                     nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
891             return null;
892         }
893         return port2;
894     }
895
896
897     private void putXpdrLcpsInMaps(int line, String nodeId,
898             Integer xponderNb, XpdrNodeTypes xponderType,
899             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
900             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
901         String lcp1 = createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
902         String lcp2 = createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
903         if (lcpMap.containsKey(lcp1) || lcpMap.containsKey(lcp2)) {
904             LOG.warn("{} : mapping already exists for {} or {}", nodeId, lcp1, lcp2);
905             return;
906         }
907         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
908         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
909         mappingMap.put(lcp1,
910                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null, xponderType));
911         mappingMap.put(lcp2,
912                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null, xponderType));
913         return;
914     }
915
916     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
917             Integer xponderNb, XpdrNodeTypes xponderType,
918             String circuitPackName,  Ports port,
919             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
920         if (port.getPortQual() == null) {
921             LOG.warn("{} : port {} on {} - PortQual was not found",
922                     nodeId, port.getPortName(), circuitPackName);
923             return new int[] {line, client};
924         }
925
926         switch (port.getPortQual()) {
927
928             case XpdrClient:
929             case SwitchClient:
930                 String lcp0 = createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
931                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
932                 mappingMap.put(lcp0,
933                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null, null));
934                 client++;
935                 break;
936
937             case XpdrNetwork:
938             case SwitchNetwork:
939                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
940                         xponderNb, xponderType,
941                         circuitPackName,  port,
942                         circuitPackList,  lcpMap, mappingMap);
943                 break;
944
945             default:
946                 LOG.error("{} : port {} on {} - unsupported PortQual {}",
947                         nodeId, port.getPortName(), circuitPackName, port.getPortQual());
948         }
949         return new int[] {line, client};
950     }
951
952     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
953             Integer xponderNb, XpdrNodeTypes xponderType,
954             String circuitPackName,  Ports port,
955             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
956
957         switch (port.getPortDirection()) {
958
959             case Bidirectional:
960                 String lcp = createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
961                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
962                 mappingMap.put(lcp,
963                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null, xponderType));
964                 line++;
965                 break;
966
967             case Rx:
968             case Tx:
969                 StringBuilder circuitPackName2 = new StringBuilder();
970                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
971                         circuitPackList, lcpMap);
972
973                 if (port2 == null) {
974                      //key already present or an error occured and was logged
975                     return line;
976                 }
977
978                 putXpdrLcpsInMaps(line, nodeId, xponderNb, xponderType,
979                         circuitPackName, circuitPackName2.toString(), port, port2,
980                         lcpMap, mappingMap);
981                 line += 2;
982                 break;
983
984             default:
985                 LOG.error("{} : port {} on {} - unsupported Direction {}",
986                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
987         }
988
989         return line;
990     }
991
992     private boolean createMcCapabilitiesList(String nodeId, Info deviceInfo,
993             Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap) {
994         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
995         List<SharedRiskGroup> srgs = getSrgs(nodeId, deviceInfo);
996         mcCapabilitiesMap.putAll(getMcCapabilities(degrees, srgs, nodeId));
997         return true;
998     }
999
1000     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
1001         // Creating mapping data for degree TTP's
1002         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1003         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
1004         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
1005         LOG.info("{} : Map looks like this {}", nodeId, interfaceList);
1006         postPortMapping(nodeId, null, null, cpToDegreeList, null, null);
1007
1008         Map<Integer, List<ConnectionPorts>> connectionPortMap = getPerDegreePorts(nodeId, deviceInfo);
1009         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : connectionPortMap.entrySet()) {
1010             switch (connectionPortMap.get(cpMapEntry.getKey()).size()) {
1011                 case 1:
1012                     // port is bidirectional
1013                     InstanceIdentifier<Ports> portID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1014                         .child(CircuitPacks.class,
1015                             new CircuitPacksKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName()))
1016                         .child(Ports.class,
1017                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName().toString()));
1018                     LOG.debug("{} : Fetching connection-port {} at circuit pack {}",
1019                             nodeId,
1020                             connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(),
1021                             connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1022                     Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
1023                         LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
1024                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1025                     if (!portObject.isPresent()) {
1026                         LOG.error("{} : No port {} on circuit pack {}",
1027                                 nodeId,
1028                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(),
1029                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1030                         return false;
1031                     }
1032                     Ports port = portObject.get();
1033                     if (port.getPortQual() == null) {
1034                         continue;
1035                     }
1036                     if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()
1037                         || Direction.Bidirectional.getIntValue() != port.getPortDirection().getIntValue()) {
1038                         LOG.error("{} : port {} on {} - Impossible to create logical connection point"
1039                                 + " - Error in configuration with port-qual or port-direction",
1040                                 nodeId, port.getPortName(),
1041                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1042                         continue;
1043                     }
1044                     String logicalConnectionPoint = new StringBuilder("DEG")
1045                         .append(cpMapEntry.getKey())
1046                         .append("-TTP-TXRX")
1047                         .toString();
1048                     LOG.info("{} : Logical Connection Point for {} on {} is {}",
1049                             nodeId,
1050                             port.getPortName(), connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1051                             logicalConnectionPoint);
1052                     portMapList.add(createMappingObject(nodeId, port,
1053                         connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1054                         logicalConnectionPoint));
1055                     break;
1056                 case 2:
1057                     // ports are unidirectionals
1058                     String cp1Name = connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName();
1059                     String cp2Name = connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName();
1060                     InstanceIdentifier<Ports> port1ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1061                         .child(CircuitPacks.class, new CircuitPacksKey(cp1Name))
1062                         .child(Ports.class,
1063                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName().toString()));
1064                     LOG.debug("{} : Fetching connection-port {} at circuit pack {}",
1065                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(), cp1Name);
1066                     Optional<Ports> port1Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
1067                         LogicalDatastoreType.OPERATIONAL, port1ID, Timeouts.DEVICE_READ_TIMEOUT,
1068                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1069                     InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1070                         .child(CircuitPacks.class, new CircuitPacksKey(cp2Name))
1071                         .child(Ports.class,
1072                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName().toString()));
1073                     LOG.debug("{} : Fetching connection-port {} at circuit pack {}",
1074                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName(), cp2Name);
1075                     Optional<Ports> port2Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
1076                         LogicalDatastoreType.OPERATIONAL, port2ID, Timeouts.DEVICE_READ_TIMEOUT,
1077                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1078                     if (!port1Object.isPresent() || !port2Object.isPresent()) {
1079                         LOG.error("{} : No port {} on circuit pack {}",
1080                                 nodeId,
1081                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(),
1082                                 connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName());
1083                         return false;
1084                     }
1085
1086                     Ports port1 = port1Object.get();
1087                     Ports port2 = port2Object.get();
1088                     if (port1.getPortQual() == null || port2.getPortQual() == null) {
1089                         continue;
1090                     }
1091                     if (PortQual.RoadmExternal.getIntValue() != port1.getPortQual().getIntValue()
1092                         || PortQual.RoadmExternal.getIntValue() != port2.getPortQual().getIntValue()) {
1093                         LOG.error("{} : Impossible to create logical connection point for port {} or port {}"
1094                                 + " - Error in configuration with port-qual",
1095                                 nodeId, port1.getPortName(), port2.getPortName());
1096                         continue;
1097                     }
1098                     if (!checkPartnerPort(cp1Name, port1, port2)) {
1099                         LOG.error("{} : port {} on {} is not a correct partner port of {} on  {}",
1100                                 nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
1101                         continue;
1102                     }
1103                     // Directions checks are the same for cp1 and cp2, no need to check them twice.
1104                     if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
1105                         LOG.error("{} : port {} on {} is not a correct partner port of {} on  {}",
1106                                 nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
1107                         continue;
1108                     }
1109
1110                     String logicalConnectionPoint1 = new StringBuilder("DEG")
1111                         .append(cpMapEntry.getKey())
1112                         .append("-TTP-")
1113                         .append(port1.getPortDirection().getName().toUpperCase(Locale.getDefault()))
1114                         .toString();
1115                     LOG.info("{} : Logical Connection Point for {} {} is {}", nodeId,
1116                         connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1117                         port1.getPortName(), logicalConnectionPoint1);
1118                     portMapList.add(createMappingObject(nodeId, port1,
1119                             connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName(),
1120                             logicalConnectionPoint1));
1121                     String logicalConnectionPoint2 = new StringBuilder("DEG")
1122                         .append(cpMapEntry.getKey())
1123                         .append("-TTP-")
1124                         .append(port2.getPortDirection().getName().toUpperCase(Locale.getDefault()))
1125                         .toString();
1126                     LOG.info("{} : Logical Connection Point for {} {} is {}",
1127                             nodeId,
1128                             connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName(),
1129                             port2.getPortName(), logicalConnectionPoint2);
1130                     portMapList.add(createMappingObject(nodeId, port2,
1131                             connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName(),
1132                             logicalConnectionPoint2));
1133                     break;
1134                 default:
1135                     LOG.error("{} : Number of connection port for DEG{} is incorrect", nodeId, cpMapEntry.getKey());
1136                     continue;
1137             }
1138         }
1139         return true;
1140     }
1141
1142     private NodeInfo createNodeInfo(Info deviceInfo) {
1143
1144         if (deviceInfo.getNodeType() == null) {
1145             // TODO make mandatory in yang
1146             LOG.error("Node type field is missing");
1147             return null;
1148         }
1149
1150         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
1151                 .setOpenroadmVersion(OpenroadmVersion._221)
1152                 .setNodeType(NodeTypes.forValue(deviceInfo.getNodeType().getIntValue()));
1153         if (deviceInfo.getClli() != null && !deviceInfo.getClli().isEmpty()) {
1154             nodeInfoBldr.setNodeClli(deviceInfo.getClli());
1155         } else {
1156             nodeInfoBldr.setNodeClli("defaultCLLI");
1157         }
1158         if (deviceInfo.getModel() != null) {
1159             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
1160         }
1161         if (deviceInfo.getVendor() != null) {
1162             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
1163         }
1164         if (deviceInfo.getIpAddress() != null) {
1165             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
1166         }
1167
1168         return nodeInfoBldr.build();
1169     }
1170
1171 }