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