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