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