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