Update xponder portmapping
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / mapping / PortMappingImpl.java
1 /*
2  * Copyright © 2017 AT&T 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.CheckedFuture;
12 import java.util.ArrayList;
13 import java.util.Comparator;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Optional;
19 import java.util.Set;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
23 import java.util.stream.Collectors;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
26 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
29 import org.opendaylight.transportpce.common.Timeouts;
30 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
31 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
32 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
33 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfacesImpl;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.NodeTypes;
35 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.CircuitPack;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.Port;
37 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.pack.Ports;
38 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.pack.PortsKey;
39 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.packs.CircuitPacks;
40 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.circuit.packs.CircuitPacksKey;
41 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.degree.ConnectionPorts;
42 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.Interface;
43 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
44 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Degree;
45 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.DegreeKey;
46 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.Info;
47 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.SharedRiskGroup;
48 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.SharedRiskGroupKey;
49 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.port.Interfaces;
50 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.InterfaceType;
51 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.OpenROADMOpticalMultiplex;
52 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev161014.OpticalTransport;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.Network;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.NetworkBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.Nodes;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.NodesBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.NodesKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.nodes.CpToDegree;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.nodes.CpToDegreeBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.nodes.CpToDegreeKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.nodes.Mapping;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.nodes.MappingBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.portmapping.rev170228.network.nodes.MappingKey;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public class PortMappingImpl implements PortMapping {
69
70     private static final Logger LOG = LoggerFactory.getLogger(PortMappingImpl.class);
71
72     private final DataBroker dataBroker;
73     private final DeviceTransactionManager deviceTransactionManager;
74     private final OpenRoadmInterfaces openRoadmInterfaces;
75
76     public PortMappingImpl(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager,
77         OpenRoadmInterfaces openRoadmInterfaces) {
78         this.dataBroker = dataBroker;
79         this.deviceTransactionManager = deviceTransactionManager;
80         this.openRoadmInterfaces = openRoadmInterfaces;
81     }
82
83     @Override
84     public boolean createMappingData(String nodeId) {
85
86         LOG.info("Create Mapping Data for node {}", nodeId);
87         List<Mapping> portMapList = new ArrayList<>();
88         InstanceIdentifier<Info> infoIID = InstanceIdentifier.create(OrgOpenroadmDevice.class).child(Info.class);
89         Optional<Info> deviceInfoOptional = this.deviceTransactionManager.getDataFromDevice(nodeId,
90             LogicalDatastoreType.OPERATIONAL, infoIID,
91             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
92
93         Info deviceInfo;
94         if (deviceInfoOptional.isPresent()) {
95             deviceInfo = deviceInfoOptional.get();
96         } else {
97             LOG.warn("Device info subtree is absent for {}", nodeId);
98             return false;
99         }
100         if (deviceInfo.getNodeType() == null) {
101             LOG.error("Node type field is missing"); // TODO make mandatory in yang
102             return false;
103         }
104         switch (deviceInfo.getNodeType()) {
105
106             case Rdm:
107                 // Get TTP port mapping
108                 if (!createTtpPortMapping(nodeId, deviceInfo, portMapList)) {
109                     // return false if mapping creation for TTP's failed
110                     LOG.warn("Unable to create mapping for TTP's on node {}", nodeId);
111                     return false;
112                 }
113
114                 // Get PP port mapping
115                 if (!createPpPortMapping(nodeId, deviceInfo, portMapList)) {
116                     // return false if mapping creation for PP's failed
117                     LOG.warn("Unable to create mapping for PP's on node {}", nodeId);
118                     return false;
119                 }
120                 break;
121             case Xpdr:
122                 if (!createXpdrPortMapping(nodeId, portMapList)) {
123                     LOG.warn("Unable to create mapping for Xponder on node {}", nodeId);
124                     return false;
125                 }
126                 break;
127             default:
128                 LOG.error("Unable to create mapping for node {} : unknown nodetype ", nodeId);
129                 break;
130
131         }
132         return postPortMapping(deviceInfo, portMapList, deviceInfo.getNodeType().getIntValue(), null);
133     }
134
135     /**
136      * This private method gets the list of external ports on a degree. For each
137      * port in the degree, it does a get on port subtree with
138      * circuit-pack-name/port-name as key in order to get the logical connection
139      * point name corresponding to it.
140      *
141      * @param deviceInfo
142      *            Info subtree read from the device
143      * @param portMapList
144      *            Reference to the list containing the mapping to be pushed to
145      *            MD-SAL
146      *
147      * @return true/false based on status of operation
148      */
149     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
150         // Creating mapping data for degree TTP's
151
152         List<Degree> degrees = getDegrees(nodeId, deviceInfo);
153         List<ConnectionPorts> degreeConPorts = getDegreePorts(degrees);
154         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees);
155
156         postPortMapping(deviceInfo, null, deviceInfo.getNodeType().getIntValue(), cpToDegreeList);
157
158         // Getting circuit-pack-name/port-name corresponding to TTP's
159         for (ConnectionPorts cp : degreeConPorts) {
160             String circuitPackName = cp.getCircuitPackName();
161             String portName = cp.getPortName().toString();
162             InstanceIdentifier<Ports> portIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
163                 .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName))
164                 .child(Ports.class, new PortsKey(portName));
165
166             LOG.info("Fetching logical Connection Point value for port {} at circuit pack {}", portName,
167                 circuitPackName);
168             Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
169                 LogicalDatastoreType.OPERATIONAL, portIID,
170                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
171             if (portObject.isPresent()) {
172                 Ports port = portObject.get();
173                 if (port.getLogicalConnectionPoint() != null) {
174                     LOG.info("Logical Connection Point for {} {} is {}", circuitPackName, portName,
175                         port.getLogicalConnectionPoint());
176                     portMapList.add(createMappingObject(nodeId, port, circuitPackName,
177                         port.getLogicalConnectionPoint()));
178                 } else {
179                     LOG.warn("Logical Connection Point value is missing for {} {}", circuitPackName,
180                         port.getPortName());
181                 }
182             } else {
183                 LOG.warn("Port {} is not present in node {} in circuit pack {}!", portName, nodeId, circuitPackName);
184                 continue; // TODO continue or return true?
185             }
186         }
187         return true;
188     }
189
190     private List<Degree> getDegrees(String deviceId, Info ordmInfo) {
191         List<Degree> degrees = new ArrayList<>();
192         Integer maxDegree;
193
194         // Get value for max degree from info subtree, required for iteration
195         // if not present assume to be 20 (temporary)
196         if (ordmInfo.getMaxDegrees() != null) {
197             maxDegree = ordmInfo.getMaxDegrees();
198         } else {
199             maxDegree = 20;
200         }
201
202         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
203             LOG.info("Getting Connection ports for Degree Number {}", degreeCounter);
204             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
205                 .child(Degree.class, new DegreeKey(degreeCounter));
206             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
207                 LogicalDatastoreType.CONFIGURATION,
208                 deviceIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
209             if (ordmDegreeObject.isPresent()) {
210                 degrees.add(ordmDegreeObject.get());
211             } else {
212                 LOG.info("Device has {} degree", degreeCounter - 1);
213                 break;
214             }
215         }
216         return degrees;
217     }
218
219     /**
220      * This private method gets the list of circuit packs on an Srg. For each
221      * circuit pack on an Srg, it does a get on circuit-pack subtree with
222      * circuit-pack-name as key in order to get the list of ports. It then
223      * iterates over the list of ports to get ports with port-qual as
224      * roadm-external. It appends a TX,RX,TXRX to the logical connection point
225      * name based on the direction of the port.
226      *
227      * @param nodeId
228      *            Id of device
229      * @param deviceInfo
230      *            Info subtree read from the device
231      * @param portMapList
232      *            Reference to the list containing the mapping to be pushed to
233      *            MD-SAL
234      *
235      * @return true/false based on status of operation
236      */
237
238     private boolean createPpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
239         // Creating mapping data for SRG's PP
240         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg
241             .CircuitPacks>> srgCps = getSrgCps(nodeId, deviceInfo);
242         Set<Map.Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206
243             .srg.CircuitPacks>>> circuitPacks = srgCps.entrySet();
244         for (Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg
245                 .CircuitPacks>> entry : circuitPacks) {
246             Integer srgIndex = entry.getKey();
247             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg.CircuitPacks cp : entry
248                 .getValue()) {
249                 String circuitPackName = cp.getCircuitPackName();
250                 InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
251                     .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
252                 Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
253                     LogicalDatastoreType.OPERATIONAL, cpIID,
254                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
255
256                 if (!circuitPackObject.isPresent() || (circuitPackObject.get().getPorts() == null)) {
257                     LOG.warn("{} : Circuit pack {} not found or without ports.", nodeId, circuitPackName);
258                     continue; // TODO continue or return false?
259                 }
260                 CircuitPacks circuitPack = circuitPackObject.get();
261                 for (Ports port : circuitPack.getPorts()) {
262                     if (port.getLogicalConnectionPoint() != null) {
263                         String logicalConnectionPoint = getLogicalConnectionPort(port, srgIndex);
264                         LOG.info("{} : Logical Connection Point for {} {} is {}", nodeId, circuitPackName, port
265                             .getPortName(),
266                             logicalConnectionPoint);
267                         portMapList.add(createMappingObject(nodeId, port, circuitPackName, logicalConnectionPoint));
268                     } else if (Port.PortQual.RoadmInternal.equals(port.getPortQual())) {
269                         LOG.info("Port is internal, skipping Logical Connection Point missing for {} {}",
270                             circuitPackName,
271                             port.getPortName());
272                     } else if (port.getLogicalConnectionPoint() == null) {
273                         LOG.info("Value missing, Skipping Logical Connection Point missing for {} {}", circuitPackName,
274                             port.getPortName());
275                     }
276                 }
277             }
278         }
279         return true;
280     }
281
282     /**
283      * This method does a get operation on shared risk group subtree of the
284      * netconf device's config datastore and returns a list of all circuit packs
285      * objects that are part of srgs. It is required to do a selective get on
286      * all the circuit packs that contain add/drop ports of interest.
287      *
288      * @param deviceId
289      *            Device id
290      * @param ordmInfo
291      *            Info subtree from the device
292      * @return List of circuit packs object belonging to- shared risk group
293      *         subtree
294      */
295     private HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg
296         .CircuitPacks>> getSrgCps(String deviceId, Info ordmInfo) {
297         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg
298             .CircuitPacks>> cpPerSrg = new HashMap<>();
299         Integer maxSrg;
300         // Get value for max Srg from info subtree, required for iteration
301         // if not present assume to be 20 (temporary)
302         if (ordmInfo.getMaxSrgs() != null) {
303             maxSrg = ordmInfo.getMaxSrgs();
304         } else {
305             maxSrg = 20;
306         }
307         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
308             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.srg.CircuitPacks> srgCps =
309                 new ArrayList<>();
310             LOG.info("Getting Circuitpacks for Srg Number {}", srgCounter);
311             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
312                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(srgCounter));
313             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
314                 LogicalDatastoreType.CONFIGURATION,
315                 srgIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
316             if (ordmSrgObject.isPresent()) {
317                 srgCps.addAll(ordmSrgObject.get().getCircuitPacks());
318                 cpPerSrg.put(ordmSrgObject.get().getSrgNumber(), srgCps);
319             }
320         }
321         LOG.info("Device {} has {} Srg", deviceId, cpPerSrg.size());
322         return cpPerSrg;
323     }
324
325     /**
326      * This private method gets the list of circuit packs on a xponder. For each
327      * circuit pack on a Xponder, it does a get on circuit-pack subtree with
328      * circuit-pack-name as key in order to get the list of ports. It then
329      * iterates over the list of ports to get ports with port-qual as
330      * xpdr-network/xpdr-client. The line and client ports are saved as:
331      *
332      * <p>
333      * 1. LINEn
334      *
335      * <p>
336      * 2. CLNTn
337      *
338      * @param nodeId
339      *            Id of device
340      * @param portMapList
341      *            Reference to the list containing the mapping to be pushed to
342      *            MD-SAL
343      *
344      * @return true/false based on status of operation
345      */
346     private boolean createXpdrPortMapping(String nodeId, List<Mapping> portMapList) {
347         // Creating for Xponder Line and Client Ports
348         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
349         Optional<OrgOpenroadmDevice> deviceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
350             LogicalDatastoreType.OPERATIONAL, deviceIID,
351             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
352
353         // Variable to keep track of number of line ports
354         int line = 1;
355         // Variable to keep track of number of client ports
356         int client = 1;
357         if (!deviceObject.isPresent() || (deviceObject.get().getCircuitPacks() == null)) {
358             LOG.warn("Circuit Packs are not present for {}", nodeId);
359             return false; // TODO return false or continue?
360         }
361
362         List<CircuitPacks> circuitPackList = deviceObject.get().getCircuitPacks();
363         circuitPackList.sort(Comparator.comparing(CircuitPack::getCircuitPackName));
364
365         for (CircuitPacks cp : circuitPackList) {
366             String circuitPackName = cp.getCircuitPackName();
367             if (cp.getPorts() == null) {
368                 LOG.warn("Ports were not found for circuit pack: {}", circuitPackName);
369                 continue;
370             }
371             for (Ports port : cp.getPorts()) {
372                 if (Port.PortQual.XpdrNetwork.equals(port.getPortQual())) {
373                     portMapList.add(createMappingObject(nodeId, port, circuitPackName,
374                         "XPDR1-"+OpenRoadmInterfacesImpl.NETWORK_TOKEN + line));
375                     line++;
376                 } else if (Port.PortQual.XpdrClient.equals(port.getPortQual())) {
377                     portMapList.add(createMappingObject(nodeId, port, circuitPackName,
378                         "XPDR1-"+OpenRoadmInterfacesImpl.CLIENT_TOKEN + client));
379                     client++;
380                 } else {
381                     LOG.warn("Not supported type of port! Port type: {}", port.getPortQual());
382                 }
383             }
384         }
385         return true;
386     }
387
388     /**
389      * This private method builds the mapping object to be pushed in MD-SAL in
390      * order to save port mapping. In case of TTP ports, it also saves the
391      * OTS,OMS interfaces provisioned on the port.
392      *
393      * @param port
394      *            Reference to device's port subtree object.
395      * @param circuitPackName
396      *            Name of cp where port exists.
397      * @param logicalConnectionPoint
398      *            logical name of the port.
399      *
400      * @return true/false based on status of operation
401      */
402
403     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
404         String logicalConnectionPoint) {
405         MappingBuilder mpBldr = new MappingBuilder();
406         mpBldr.withKey(new MappingKey(logicalConnectionPoint)).setLogicalConnectionPoint(logicalConnectionPoint)
407             .setSupportingCircuitPackName(circuitPackName).setSupportingPort(port.getPortName());
408
409         // Get OMS and OTS interface provisioned on the TTP's
410         if (logicalConnectionPoint.contains(OpenRoadmInterfacesImpl.TTP_TOKEN) && (port.getInterfaces() != null)) {
411             for (Interfaces interfaces : port.getInterfaces()) {
412                 try {
413                     Optional<Interface> openRoadmInterface = this.openRoadmInterfaces.getInterface(nodeId,
414                         interfaces.getInterfaceName());
415                     if (openRoadmInterface.isPresent()) {
416                         Class<? extends InterfaceType> interfaceType = openRoadmInterface.get().getType();
417                         // Check if interface type is OMS or OTS
418                         if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
419                             mpBldr.setSupportingOms(interfaces.getInterfaceName());
420                         }
421                         if (interfaceType.equals(OpticalTransport.class)) {
422                             mpBldr.setSupportingOts(interfaces.getInterfaceName());
423                         }
424                     } else {
425                         LOG.warn("Interface {} from node {} was null!", interfaces.getInterfaceName(), nodeId);
426                     }
427                 } catch (OpenRoadmInterfaceException ex) {
428                     LOG.warn("Error while getting interface {} from node {}!", interfaces.getInterfaceName(), nodeId,
429                         ex);
430                 }
431             }
432         }
433         return mpBldr.build();
434     }
435
436     private static CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber) {
437         return new CpToDegreeBuilder().withKey(new CpToDegreeKey(circuitPackName)).setCircuitPackName(circuitPackName)
438             .setDegreeNumber(new Long(degreeNumber)).build();
439     }
440
441     private static List<ConnectionPorts> getDegreePorts(List<Degree> degrees) {
442         return degrees.stream().filter(degree -> degree.getConnectionPorts() != null)
443             .flatMap(degree -> degree.getConnectionPorts().stream()).collect(Collectors.toList());
444     }
445
446     private List<CpToDegree> getCpToDegreeList(List<Degree> degrees) {
447         List<CpToDegree> cpToDegreeList = new ArrayList<>();
448         for (Degree degree : degrees) {
449             if (degree.getCircuitPacks() != null) {
450                 cpToDegreeList.addAll(degree.getCircuitPacks().stream()
451                     .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(), degree.getDegreeNumber().toString()))
452                     .collect(Collectors.toList()));
453             }
454         }
455         return cpToDegreeList;
456     }
457
458     /**
459      * This method for ports the portMapping corresponding to the
460      * portmapping.yang file to the MD-SAL datastore.
461      *
462      * <p>
463      * 1. Supporting circuit pack 2. Supporting port 3. Supporting OMS interface
464      * (if port on ROADM)
465      *
466      * @param deviceInfo
467      *            Info subtree from the device.
468      * @param portMapList
469      *            Reference to the list containing the mapping to be pushed to
470      *            MD-SAL.
471      *
472      * @return Result true/false based on status of operation.
473      */
474     private boolean postPortMapping(Info deviceInfo, List<Mapping> portMapList, Integer nodeType,
475         List<CpToDegree> cp2DegreeList) {
476         NodesBuilder nodesBldr = new NodesBuilder();
477         nodesBldr.withKey(new NodesKey(deviceInfo.getNodeId())).setNodeId(deviceInfo.getNodeId());
478         nodesBldr.setNodeType(NodeTypes.forValue(nodeType));
479
480         if (portMapList != null) {
481             nodesBldr.setMapping(portMapList);
482         }
483         if (cp2DegreeList != null) {
484             nodesBldr.setCpToDegree(cp2DegreeList);
485         }
486
487         List<Nodes> nodesList = new ArrayList<>();
488         nodesList.add(nodesBldr.build());
489
490         NetworkBuilder nwBldr = new NetworkBuilder();
491         nwBldr.setNodes(nodesList);
492
493         final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
494         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
495         Network network = nwBldr.build();
496         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
497         CheckedFuture<Void, TransactionCommitFailedException> submit = writeTransaction.submit();
498         try {
499             submit.checkedGet();
500             return true;
501
502         } catch (TransactionCommitFailedException e) {
503             LOG.warn("Failed to post {}", network, e);
504             return false;
505         }
506     }
507
508     @Override
509     public Mapping getMapping(String nodeId, String logicalConnPoint) {
510
511         /*
512          * Getting physical mapping corresponding to logical connection point
513          */
514         InstanceIdentifier<Mapping> portMappingIID = InstanceIdentifier.builder(Network.class).child(Nodes.class,
515             new NodesKey(nodeId)).child(Mapping.class, new MappingKey(logicalConnPoint)).build();
516         try (ReadOnlyTransaction readTx = this.dataBroker.newReadOnlyTransaction()) {
517             Optional<Mapping> mapObject = readTx.read(LogicalDatastoreType.CONFIGURATION, portMappingIID).get()
518                 .toJavaUtil();
519             if (mapObject.isPresent()) {
520                 Mapping mapping = mapObject.get();
521                 LOG.info("Found mapping for the logical port {}. Mapping: {}", logicalConnPoint, mapping.toString());
522                 return mapping;
523             } else {
524                 LOG.warn("Could not find mapping for logical connection point {} for nodeId {}", logicalConnPoint,
525                     nodeId);
526             }
527         } catch (InterruptedException | ExecutionException ex) {
528             LOG.error("Unable to read mapping for logical connection point : {} for nodeId {}", logicalConnPoint,
529                 nodeId, ex);
530         }
531         return null;
532     }
533
534     private static String getLogicalConnectionPort(Ports port, int srgCounter) {
535         String logicalConnectionPoint = null;
536         if (port.getLogicalConnectionPoint() != null) {
537             switch (port.getPortDirection()) {
538                 case Tx:
539                     // Port direction is transmit
540                     if (!port.getLogicalConnectionPoint().contains("SRG")) {
541                         logicalConnectionPoint = "SRG" + srgCounter + "-" + port.getLogicalConnectionPoint() + "-TX";
542                     } else {
543                         logicalConnectionPoint = port.getLogicalConnectionPoint() + "-TX";
544                     }
545                     break;
546                 case Rx:
547                     // Port direction is receive
548                     if (!port.getLogicalConnectionPoint().contains("SRG")) {
549                         logicalConnectionPoint = "SRG" + srgCounter + "-" + port.getLogicalConnectionPoint() + "-RX";
550                     } else {
551                         logicalConnectionPoint = port.getLogicalConnectionPoint() + "-RX";
552                     }
553                     break;
554                 case Bidirectional:
555                     // port is bidirectional
556                     if (!port.getLogicalConnectionPoint().contains("SRG")) {
557                         logicalConnectionPoint = "SRG" + srgCounter + "-" + port.getLogicalConnectionPoint();
558                     } else {
559                         logicalConnectionPoint = port.getLogicalConnectionPoint();
560                     }
561                     if (!port.getLogicalConnectionPoint().endsWith("-TXRX")) {
562                         logicalConnectionPoint = logicalConnectionPoint.concat("-TXRX");
563                     }
564                     break;
565                 default:
566                     // Unsupported Port direction
567                     LOG.error("Unsupported port direction for port {}  {}", port, port.getPortDirection());
568                     return null; // TODO return false or continue?
569             }
570             return logicalConnectionPoint;
571         }
572         LOG.warn("Unsupported port direction for port {} - {} - LogicalConnectionPoint is null",
573             port, port.getPortDirection());
574         return null; // TODO return false or continue?
575     }
576
577     @Override
578     public void deleteMappingData(String nodeId) {
579         LOG.info("Deleting Mapping Data corresponding at node '{}'", nodeId);
580         WriteTransaction rw = this.dataBroker.newWriteOnlyTransaction();
581         InstanceIdentifier<Nodes> nodesIID = InstanceIdentifier.create(Network.class)
582             .child(Nodes.class, new NodesKey(nodeId));
583         rw.delete(LogicalDatastoreType.CONFIGURATION, nodesIID);
584         try {
585             rw.submit().get(1, TimeUnit.SECONDS);
586             LOG.info("Port mapping removal for node '{}'", nodeId);
587         } catch (InterruptedException | ExecutionException | TimeoutException e) {
588             LOG.error("Error for removing port mapping infos for node '{}'", nodeId);
589         }
590
591     }
592
593     @Override
594     public boolean updateMapping(String nodeId, Mapping oldMapping) {
595         InstanceIdentifier<Ports> portIId = InstanceIdentifier.create(OrgOpenroadmDevice.class).child(
596             CircuitPacks.class, new CircuitPacksKey(oldMapping.getSupportingCircuitPackName())).child(Ports.class,
597                 new PortsKey(oldMapping.getSupportingPort()));
598         if (oldMapping != null && nodeId != null) {
599             try {
600                 Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
601                     LogicalDatastoreType.OPERATIONAL, portIId, Timeouts.DEVICE_READ_TIMEOUT,
602                     Timeouts.DEVICE_READ_TIMEOUT_UNIT);
603                 if (portObject.isPresent()) {
604                     Ports port = portObject.get();
605                     Mapping newMapping = createMappingObject(nodeId, port, oldMapping.getSupportingCircuitPackName(),
606                         oldMapping.getLogicalConnectionPoint());
607
608                     final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
609                     InstanceIdentifier<Mapping> mapIID = InstanceIdentifier.create(Network.class).child(Nodes.class,
610                         new NodesKey(nodeId)).child(Mapping.class, new MappingKey(oldMapping
611                             .getLogicalConnectionPoint()));
612                     writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, mapIID, newMapping);
613                     CheckedFuture<Void, TransactionCommitFailedException> submit = writeTransaction.submit();
614                     submit.checkedGet();
615                     return true;
616                 }
617                 return false;
618             } catch (TransactionCommitFailedException e) {
619                 LOG.error("Transaction Commit Error updating Mapping {} for node {}", oldMapping
620                     .getLogicalConnectionPoint(), nodeId, e);
621                 return false;
622             }
623         } else {
624             LOG.error("Impossible to update mapping");
625             return false;
626         }
627
628     }
629
630 }