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