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