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