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