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