8b7dad5a08b73586303099fda45b8b0b82eb54d7
[transportpce.git] / olm / src / main / java / org / opendaylight / transportpce / olm / service / OlmPowerServiceImpl.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.olm.service;
10
11 import com.google.common.base.Strings;
12 import java.math.BigDecimal;
13 import java.math.RoundingMode;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25 import java.util.stream.Collectors;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.binding.api.DataBroker;
28 import org.opendaylight.mdsal.binding.api.ReadTransaction;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.transportpce.common.InstanceIdentifiers;
31 import org.opendaylight.transportpce.common.NetworkUtils;
32 import org.opendaylight.transportpce.common.ResponseCodes;
33 import org.opendaylight.transportpce.common.StringConstants;
34 import org.opendaylight.transportpce.common.Timeouts;
35 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
36 import org.opendaylight.transportpce.common.mapping.MappingUtils;
37 import org.opendaylight.transportpce.common.mapping.PortMapping;
38 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
39 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
40 import org.opendaylight.transportpce.olm.power.PowerMgmt;
41 import org.opendaylight.transportpce.olm.util.OlmUtils;
42 import org.opendaylight.transportpce.olm.util.OtsPmHolder;
43 import org.opendaylight.transportpce.olm.util.RoadmLinks;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.CalculateSpanlossBaseInput;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.CalculateSpanlossBaseOutput;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.CalculateSpanlossBaseOutputBuilder;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.CalculateSpanlossCurrentInput;
48 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.CalculateSpanlossCurrentOutput;
49 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.CalculateSpanlossCurrentOutputBuilder;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.GetPmInput;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.GetPmInputBuilder;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.GetPmOutput;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.GetPmOutputBuilder;
54 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerResetInput;
55 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerResetOutput;
56 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerSetupInput;
57 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerSetupOutput;
58 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerSetupOutputBuilder;
59 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerTurndownInput;
60 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerTurndownOutput;
61 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.ServicePowerTurndownOutputBuilder;
62 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.calculate.spanloss.base.output.Spans;
63 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.calculate.spanloss.base.output.SpansBuilder;
64 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev210618.get.pm.output.Measurements;
65 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.OpenroadmNodeVersion;
66 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.mapping.Mapping;
67 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev211210.Link1;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.RatioDB;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.Interface;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.InterfaceBuilder;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev211210.OpenroadmLinkType;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.Interface1;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.Interface1Builder;
74 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.ots.container.Ots;
75 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.ots.container.OtsBuilder;
76 import org.opendaylight.yang.gen.v1.http.org.openroadm.resource.types.rev161014.ResourceTypeEnum;
77 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev220926.PmGranularity;
78 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev220926.PmNamesEnum;
79 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev220926.olm.get.pm.input.ResourceIdentifierBuilder;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NetworkId;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.Networks;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.Network;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.NetworkKey;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.Node;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.NodeKey;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.node.SupportingNode;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.LinkId;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.Network1;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network.Link;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network.LinkKey;
92 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
93 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
94 import org.opendaylight.yangtools.yang.common.Decimal64;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97
98 public class OlmPowerServiceImpl implements OlmPowerService {
99     private static final Logger LOG = LoggerFactory.getLogger(OlmPowerServiceImpl.class);
100     private final MappingUtils mappingUtils;
101     private final OpenRoadmInterfaces openRoadmInterfaces;
102     private final DataBroker dataBroker;
103     private final PowerMgmt powerMgmt;
104     private final DeviceTransactionManager deviceTransactionManager;
105     private final PortMapping portMapping;
106
107     public OlmPowerServiceImpl(DataBroker dataBroker, PowerMgmt powerMgmt,
108                                DeviceTransactionManager deviceTransactionManager, PortMapping portMapping,
109                                MappingUtils mappingUtils, OpenRoadmInterfaces openRoadmInterfaces) {
110         this.dataBroker = dataBroker;
111         this.powerMgmt = powerMgmt;
112         this.portMapping = portMapping;
113         this.deviceTransactionManager = deviceTransactionManager;
114         this.mappingUtils = mappingUtils;
115         this.openRoadmInterfaces = openRoadmInterfaces;
116     }
117
118     public void init() {
119         LOG.info("init ...");
120     }
121
122     public void close() {
123         LOG.info("close ...");
124     }
125
126
127     @Override
128     public GetPmOutput getPm(GetPmInput pmInput) {
129         GetPmOutputBuilder pmOutputBuilder = new GetPmOutputBuilder();
130         if (mappingUtils.getOpenRoadmVersion(pmInput.getNodeId()) == null) {
131             return pmOutputBuilder.build();
132         }
133         OpenroadmNodeVersion nodeVersion;
134         switch (mappingUtils.getOpenRoadmVersion(pmInput.getNodeId())) {
135             case StringConstants.OPENROADM_DEVICE_VERSION_1_2_1:
136                 nodeVersion = OpenroadmNodeVersion._121;
137                 break;
138             case StringConstants.OPENROADM_DEVICE_VERSION_2_2_1:
139                 nodeVersion = OpenroadmNodeVersion._221;
140                 break;
141             case StringConstants.OPENROADM_DEVICE_VERSION_7_1:
142                 nodeVersion = OpenroadmNodeVersion._71;
143                 break;
144             default:
145                 LOG.error("Unknown device version");
146                 return pmOutputBuilder.build();
147         }
148         LOG.info("Now calling get pm data");
149         pmOutputBuilder = OlmUtils.pmFetch(pmInput, deviceTransactionManager,
150             nodeVersion);
151         return pmOutputBuilder.build();
152     }
153
154     @Override
155     public ServicePowerSetupOutput servicePowerSetup(ServicePowerSetupInput powerSetupInput) {
156         ServicePowerSetupOutputBuilder powerSetupOutput = new ServicePowerSetupOutputBuilder();
157         boolean successValPowerCalculation = powerMgmt.setPower(powerSetupInput);
158         if (successValPowerCalculation) {
159             powerSetupOutput.setResult(ResponseCodes.SUCCESS_RESULT);
160         } else {
161             powerSetupOutput.setResult(ResponseCodes.FAILED_RESULT);
162         }
163         return powerSetupOutput.build();
164     }
165
166     @Override
167     public ServicePowerTurndownOutput servicePowerTurndown(
168         ServicePowerTurndownInput powerTurndownInput) {
169
170         ServicePowerTurndownOutputBuilder powerTurnDownOutput = new ServicePowerTurndownOutputBuilder();
171         // TODO add flag or return failure instead of string
172         if (powerMgmt.powerTurnDown(powerTurndownInput)) {
173             powerTurnDownOutput.setResult(ResponseCodes.SUCCESS_RESULT);
174         } else {
175             powerTurnDownOutput.setResult(ResponseCodes.FAILED_RESULT);
176         }
177         return powerTurnDownOutput.build();
178     }
179
180     @Override
181     public CalculateSpanlossBaseOutput calculateSpanlossBase(CalculateSpanlossBaseInput spanlossBaseInput) {
182         LOG.info("CalculateSpanlossBase Request received for source type {}", spanlossBaseInput.getSrcType());
183         List<RoadmLinks> roadmLinks = new ArrayList<>();
184         CalculateSpanlossBaseOutputBuilder spanLossBaseBuilder = new CalculateSpanlossBaseOutputBuilder();
185         Map<LinkId, BigDecimal> spanLossResult = null;
186         //Depending on the source type do the calculation
187         switch (spanlossBaseInput.getSrcType()) {
188             case Link:
189                 LOG.debug("Calculate SpanLossBase for a linkId: {}",spanlossBaseInput.getLinkId());
190                 Link inputLink = getNetworkLinkById(spanlossBaseInput.getLinkId());
191                 if (inputLink != null) {
192                     RoadmLinks roadmLink = new RoadmLinks();
193                     roadmLink.setSrcNodeId(inputLink.getSource().getSourceNode().getValue());
194                     roadmLink.setSrcTpId(inputLink.getSource().getSourceTp().getValue());
195                     roadmLink.setDestNodeId(inputLink.getDestination().getDestNode().getValue());
196                     roadmLink.setDestTpid(inputLink.getDestination().getDestTp().getValue());
197                     roadmLink.setLinkId(inputLink.getLinkId());
198                     roadmLinks.add(roadmLink);
199                     spanLossResult = getLinkSpanloss(roadmLinks);
200                 }
201                 break;
202             case All:
203                 LOG.info("Do something for all");
204                 List<Link> networkLinks = getNetworkLinks();
205                 if (networkLinks.isEmpty()) {
206                     LOG.warn("Failed to get links form {} topology.", NetworkUtils.OVERLAY_NETWORK_ID);
207                     return new CalculateSpanlossBaseOutputBuilder().setResult(ResponseCodes.FAILED_RESULT).build();
208                 }
209                 //else for all other links
210                 for (Link link : networkLinks) {
211                     Link1 roadmLinkAugmentation = link.augmentation(Link1.class);
212                     if (roadmLinkAugmentation == null) {
213                         LOG.debug("Missing OpenRoadm link augmentation in link {} from {} topology.",
214                             link.getLinkId().getValue(), NetworkUtils.OVERLAY_NETWORK_ID);
215                         continue;
216                     }
217                     if (OpenroadmLinkType.ROADMTOROADM.equals(roadmLinkAugmentation.getLinkType())) {
218                         // Only calculate spanloss for Roadm-to-Roadm links
219                         RoadmLinks roadmLink = new RoadmLinks();
220                         roadmLink.setSrcNodeId(link.getSource().getSourceNode().getValue());
221                         roadmLink.setSrcTpId(link.getSource().getSourceTp().getValue());
222                         roadmLink.setDestNodeId(link.getDestination().getDestNode().getValue());
223                         roadmLink.setDestTpid(link.getDestination().getDestTp().getValue());
224                         roadmLink.setLinkId(link.getLinkId());
225                         roadmLinks.add(roadmLink);
226                     }
227                 }
228                 if (roadmLinks.isEmpty()) {
229                     LOG.warn("Topology {} does not have any Roadm-to-Roadm links.", NetworkUtils.OVERLAY_NETWORK_ID);
230                     return new CalculateSpanlossBaseOutputBuilder().setResult(ResponseCodes.FAILED_RESULT).build();
231                 }
232                 spanLossResult = getLinkSpanloss(roadmLinks);
233                 break;
234             default:
235                 LOG.info("Invalid input in request");
236         }
237
238         if (spanLossResult != null && !spanLossResult.isEmpty()) {
239             spanLossBaseBuilder.setResult(ResponseCodes.SUCCESS_RESULT);
240             List<Spans> listSpans = new ArrayList<>();
241             Set<Entry<LinkId, BigDecimal>> spanLossResultSet = spanLossResult.entrySet();
242             for (Entry<LinkId, BigDecimal> entry : spanLossResultSet) {
243                 Spans span = new SpansBuilder().setLinkId(entry.getKey()).setSpanloss(entry.getValue().toString())
244                     .build();
245                 listSpans.add(span);
246             }
247             spanLossBaseBuilder.setSpans(listSpans);
248             return spanLossBaseBuilder.build();
249         } else {
250             LOG.warn("Spanloss calculation failed");
251             spanLossBaseBuilder.setResult(ResponseCodes.FAILED_RESULT);
252             return spanLossBaseBuilder.build();
253         }
254
255     }
256
257
258     @Override
259     public CalculateSpanlossCurrentOutput calculateSpanlossCurrent(CalculateSpanlossCurrentInput input) {
260         LOG.info("calculateSpanlossCurrent Request received for all links in network model.");
261         List<Link> networkLinks = getNetworkLinks();
262         if (networkLinks.isEmpty()) {
263             LOG.warn("Failed to get links form {} topology.", NetworkUtils.OVERLAY_NETWORK_ID);
264             return null;
265         }
266         List<RoadmLinks> roadmLinks = new ArrayList<>();
267         for (Link link : networkLinks) {
268             Link1 roadmLinkAugmentation = link.augmentation(Link1.class);
269             if (roadmLinkAugmentation == null) {
270                 LOG.debug("Missing OpenRoadm link augmentation in link {} from {} topology.",
271                     link.getLinkId().getValue(), NetworkUtils.OVERLAY_NETWORK_ID);
272                 continue;
273             }
274             if (OpenroadmLinkType.ROADMTOROADM.equals(roadmLinkAugmentation.getLinkType())) {
275                 // Only calculate spanloss for Roadm-to-Roadm links
276                 RoadmLinks roadmLink = new RoadmLinks();
277                 roadmLink.setSrcNodeId(link.getSource().getSourceNode().getValue());
278                 roadmLink.setSrcTpId(link.getSource().getSourceTp().getValue());
279                 roadmLink.setDestNodeId(link.getDestination().getDestNode().getValue());
280                 roadmLink.setDestTpid(link.getDestination().getDestTp().getValue());
281                 roadmLinks.add(roadmLink);
282             }
283         }
284
285         if (roadmLinks.isEmpty()) {
286             LOG.warn("Topology {} does not have any Roadm-to-Roadm links.", NetworkUtils.OVERLAY_NETWORK_ID);
287             return null;
288         }
289
290         Map<LinkId, BigDecimal> spanLossResult = getLinkSpanloss(roadmLinks);
291         CalculateSpanlossCurrentOutputBuilder spanLossCurrentBuilder = new CalculateSpanlossCurrentOutputBuilder();
292         if (spanLossResult != null && !spanLossResult.isEmpty()) {
293             spanLossCurrentBuilder.setResult(ResponseCodes.SUCCESS_RESULT);
294             return spanLossCurrentBuilder.build();
295         } else {
296             LOG.error("Spanloss Current calculation failed");
297             spanLossCurrentBuilder.setResult(ResponseCodes.FAILED_RESULT);
298             return spanLossCurrentBuilder.build();
299         }
300     }
301
302     @Override
303     public ServicePowerResetOutput servicePowerReset(ServicePowerResetInput input) {
304         // TODO
305         return null;
306     }
307
308     private List<Link> getNetworkLinks() {
309         NetworkKey overlayTopologyKey = new NetworkKey(new NetworkId(NetworkUtils.OVERLAY_NETWORK_ID));
310
311         InstanceIdentifier<Network1> networkIID = InstanceIdentifier.builder(Networks.class)
312             .child(Network.class, overlayTopologyKey)
313                 .augmentation(Network1.class)
314                 .build();
315         Optional<Network1> networkOptional;
316         try (ReadTransaction rtx = this.dataBroker.newReadOnlyTransaction()) {
317             //TODO change to constant from Timeouts class when it will be merged.
318             networkOptional = rtx.read(LogicalDatastoreType.CONFIGURATION, networkIID).get(Timeouts.DATASTORE_READ,
319                 TimeUnit.MILLISECONDS);
320
321         } catch (InterruptedException | ExecutionException | TimeoutException e) {
322             LOG.warn("Read of {} topology failed", NetworkUtils.OVERLAY_NETWORK_ID);
323             return Collections.emptyList();
324         }
325
326         if (! networkOptional.isPresent()) {
327             LOG.warn("Network augmentation with links data is not present in {} topology.",
328                 NetworkUtils.OVERLAY_NETWORK_ID);
329
330             return Collections.emptyList();
331         }
332
333         @Nullable Map<LinkKey, Link> networkLinks = networkOptional.get().getLink();
334         if ((networkLinks == null) || networkLinks.isEmpty()) {
335             LOG.warn("Links are not present in {} topology.", NetworkUtils.OVERLAY_NETWORK_ID);
336             return Collections.emptyList();
337         }
338         return new ArrayList<>(networkLinks.values());
339     }
340
341     /**
342      * This method retrieves OTS PM from current PM list by nodeId and TPId: Steps:
343      *
344      * <p>
345      * 1. Get OTS interface name from port mapping by TPId 2. Call getPm RPC to get OTS PM
346      *
347      * <p>
348      *
349      * @param nodeId Node-id of the NE.
350      * @param tpID Termination point Name.
351      * @param pmName PM name which need to be retrieved
352      * @return reference to OtsPmHolder
353      */
354     private OtsPmHolder getPmMeasurements(String nodeId, String tpID, String pmName) {
355         String realNodeId = getRealNodeId(nodeId);
356         Mapping mapping = portMapping.getMapping(realNodeId, tpID);
357         if (mapping == null) {
358             return null;
359         }
360         GetPmInput getPmInput = new GetPmInputBuilder().setNodeId(realNodeId)
361             .setResourceType(ResourceTypeEnum.Interface)
362             .setResourceIdentifier(
363                 new ResourceIdentifierBuilder().setResourceName(mapping.getSupportingOts()).build())
364             .setPmNameType(PmNamesEnum.valueOf(pmName))
365             .setGranularity(PmGranularity._15min)
366             .build();
367         GetPmOutput otsPmOutput = getPm(getPmInput);
368
369         if (otsPmOutput == null || otsPmOutput.getMeasurements() == null) {
370             LOG.info("OTS PM not found for NodeId: {} TP Id:{} PMName:{}", realNodeId, tpID, pmName);
371             return null;
372         }
373         try {
374             for (Measurements measurement : otsPmOutput.getMeasurements()) {
375                 if (pmName.equalsIgnoreCase(measurement.getPmparameterName())) {
376                     return new OtsPmHolder(pmName, Double.parseDouble(measurement.getPmparameterValue()),
377                         mapping.getSupportingOts());
378                 }
379             }
380         } catch (NumberFormatException e) {
381             LOG.warn("Unable to get PM for NodeId: {} TP Id:{} PMName:{}", realNodeId, tpID, pmName, e);
382         }
383         return null;
384     }
385
386     /**
387      * This method Sets Spanloss on A-End and Z-End OTS interface: Steps:
388      *
389      * <p>
390      * 1. Read existing interface details
391      *
392      * <p>
393      * 2. Set spanloss
394      *
395      * @param nodeId nodeId of NE on which spanloss need to be updated
396      * @param interfaceName OTS interface for NE on which spanloss is cacluated
397      * @param spanLoss calculated spanloss value
398      * @param direction for which spanloss is calculated.It can be either Tx or Rx
399      * @return true/false
400      */
401     private boolean setSpanLoss(String nodeId, String interfaceName, BigDecimal spanLoss, String direction) {
402         String realNodeId = getRealNodeId(nodeId);
403         try {
404             LOG.info("Setting Spanloss in device for {}, InterfaceName: {}", realNodeId, interfaceName);
405             if (mappingUtils.getOpenRoadmVersion(realNodeId)
406                 .equals(StringConstants.OPENROADM_DEVICE_VERSION_1_2_1)) {
407                 RatioDB spanLossRx;
408                 RatioDB spanLossTx;
409
410                 Optional<Interface> interfaceObject;
411                 interfaceObject = openRoadmInterfaces.getInterface(realNodeId, interfaceName);
412                 if (interfaceObject.isPresent()) {
413                     InterfaceBuilder interfaceBuilder = new InterfaceBuilder(interfaceObject.get());
414                     OtsBuilder otsBuilder = new OtsBuilder();
415                     Interface intf = interfaceObject.get();
416                     if (intf.augmentation(Interface1.class) != null
417                         && intf.augmentation(Interface1.class).getOts() != null) {
418                         Ots ots = intf.augmentation(Interface1.class).getOts();
419                         otsBuilder.setFiberType(ots.getFiberType());
420                         spanLossRx = ots.getSpanLossReceive();
421                         spanLossTx = ots.getSpanLossTransmit();
422                     } else {
423                         spanLossRx = new RatioDB(Decimal64.valueOf(spanLoss));
424                         spanLossTx = new RatioDB(Decimal64.valueOf(spanLoss));
425                     }
426                     Interface1Builder intf1Builder = new Interface1Builder();
427                     if (direction.equals("TX")) {
428                         otsBuilder.setSpanLossTransmit(new RatioDB(Decimal64.valueOf(spanLoss)));
429                         otsBuilder.setSpanLossReceive(spanLossRx);
430                     } else {
431                         otsBuilder
432                             .setSpanLossTransmit(spanLossTx)
433                             .setSpanLossReceive(new RatioDB(Decimal64.valueOf(spanLoss)));
434                     }
435                     interfaceBuilder.addAugmentation(intf1Builder.setOts(otsBuilder.build()).build());
436                     openRoadmInterfaces.postInterface(realNodeId,interfaceBuilder);
437                     LOG.info("Spanloss Value update completed successfully");
438                     return true;
439                 } else {
440                     LOG.error("Interface not found for nodeId: {} and interfaceName: {}", nodeId, interfaceName);
441                     return false;
442                 }
443             } else if (mappingUtils.getOpenRoadmVersion(realNodeId)
444                 .equals(StringConstants.OPENROADM_DEVICE_VERSION_2_2_1)) {
445
446                 org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.RatioDB spanLossRx;
447                 org.opendaylight.yang.gen.v1.http.org.openroadm.common.types
448                     .rev181019.RatioDB spanLossTx;
449                 Optional<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019
450                     .interfaces.grp.Interface> interfaceObject =
451                         openRoadmInterfaces.getInterface(realNodeId, interfaceName);
452                 if (interfaceObject.isPresent()) {
453                     org.opendaylight.yang.gen.v1.http.org.openroadm.device
454                         .rev181019.interfaces.grp.InterfaceBuilder interfaceBuilder =
455                         new org.opendaylight.yang.gen.v1.http.org.openroadm.device
456                             .rev181019.interfaces.grp.InterfaceBuilder(interfaceObject.get());
457                     org.opendaylight.yang.gen.v1.http.org.openroadm.optical
458                         .transport.interfaces.rev181019.ots.container.OtsBuilder otsBuilder =
459                         new org.opendaylight.yang.gen.v1.http.org.openroadm
460                             .optical.transport.interfaces.rev181019.ots.container.OtsBuilder();
461                     org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.interfaces.grp.Interface intf =
462                         interfaceObject.get();
463                     if (intf.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.optical
464                         .transport.interfaces.rev181019.Interface1.class) != null
465                             && intf.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport
466                                 .interfaces.rev181019.Interface1.class).getOts() != null) {
467                         org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces
468                             .rev181019.ots.container.Ots ots =
469                                 intf.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.optical
470                                     .transport.interfaces.rev181019.Interface1.class).getOts();
471
472                         otsBuilder.setFiberType(ots.getFiberType());
473                         spanLossRx = ots.getSpanLossReceive();
474                         spanLossTx = ots.getSpanLossTransmit();
475                     } else {
476                         spanLossRx = new org.opendaylight.yang.gen.v1.http.org
477                             .openroadm.common.types.rev181019.RatioDB(Decimal64.valueOf(spanLoss));
478                         spanLossTx = new org.opendaylight.yang.gen.v1.http.org
479                             .openroadm.common.types.rev181019.RatioDB(Decimal64.valueOf(spanLoss));
480                     }
481                     org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces
482                         .rev181019.Interface1Builder intf1Builder =
483                             new org.opendaylight.yang.gen.v1.http.org.openroadm.optical
484                             .transport.interfaces.rev181019.Interface1Builder();
485                     if (direction.equals("TX")) {
486                         otsBuilder.setSpanLossTransmit(new org.opendaylight.yang.gen.v1.http.org
487                             .openroadm.common.types.rev181019.RatioDB(Decimal64.valueOf(spanLoss)));
488                         otsBuilder.setSpanLossReceive(spanLossRx);
489                     } else {
490                         otsBuilder
491                             .setSpanLossTransmit(spanLossTx)
492                             .setSpanLossReceive(
493                                 new org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.RatioDB(
494                                     Decimal64.valueOf(spanLoss)));
495                     }
496                     interfaceBuilder.addAugmentation(intf1Builder.setOts(otsBuilder.build()).build());
497                     openRoadmInterfaces.postInterface(realNodeId,interfaceBuilder);
498                     LOG.info("Spanloss Value update completed successfully");
499                     return true;
500                 } else {
501                     LOG.error("Interface not found for nodeId: {} and interfaceName: {}", nodeId,interfaceName);
502                     return false;
503                 }
504             }
505         } catch (OpenRoadmInterfaceException e) {
506             // TODO Auto-generated catch block
507             LOG.error("OpenRoadmInterfaceException occured: ",e);
508         } /**catch (InterruptedException e) {
509          // TODO Auto-generated catch block
510          } catch (ExecutionException e) {
511          // TODO Auto-generated catch block
512          }**/
513         return false;
514     }
515
516     /**
517      * This method calculates Spanloss by TranmistPower - Receive Power Steps:
518      *
519      * <p>
520      * 1. Read PM measurement
521      *
522      * <p>
523      * 2. Set Spanloss value for interface
524      *
525      * @param roadmLinks
526      *            reference to list of RoadmLinks
527      * @return map with list of spans with their spanloss value
528      */
529     private Map<LinkId, BigDecimal> getLinkSpanloss(List<RoadmLinks> roadmLinks) {
530         Map<LinkId, BigDecimal> map = new HashMap<>();
531         LOG.info("Executing GetLinkSpanLoss");
532         BigDecimal spanLoss;
533         for (RoadmLinks link : roadmLinks) {
534             String sourceNodeId = link.getSrcNodeId();
535             String sourceTpId = link.getSrcTpId();
536             String destNodeId = link.getDestNodeId();
537             String destTpId = link.getDestTpid();
538             OtsPmHolder srcOtsPmHolder = getPmMeasurements(sourceNodeId, sourceTpId, "OpticalPowerOutput");
539             if (srcOtsPmHolder == null) {
540                 srcOtsPmHolder = getPmMeasurements(sourceNodeId, sourceTpId, "OpticalPowerOutputOSC");
541                 if (srcOtsPmHolder == null) {
542                     LOG.warn("OTS configuration issue at {} - {}", sourceNodeId, sourceTpId);
543                     continue;
544                 }
545             }
546             OtsPmHolder destOtsPmHolder = getPmMeasurements(destNodeId, destTpId, "OpticalPowerInput");
547             if (destOtsPmHolder == null) {
548                 destOtsPmHolder = getPmMeasurements(destNodeId, destTpId, "OpticalPowerInputOSC");
549                 if (destOtsPmHolder == null) {
550                     LOG.warn("OTS configuration issue at {} - {}", destNodeId, destTpId);
551                     continue;
552                 }
553             }
554             spanLoss = BigDecimal.valueOf(srcOtsPmHolder.getOtsParameterVal() - destOtsPmHolder.getOtsParameterVal())
555                 .setScale(1, RoundingMode.HALF_UP);
556             LOG.info("Spanloss Calculated as :{}={}-{}",
557                 spanLoss, srcOtsPmHolder.getOtsParameterVal(), destOtsPmHolder.getOtsParameterVal());
558             if (spanLoss.doubleValue() > 28) {
559                 LOG.warn("Span Loss is out of range of OpenROADM specifications");
560             }
561             if (spanLoss.intValue() <= 0) {
562                 spanLoss = BigDecimal.valueOf(0);
563             }
564             if (!setSpanLoss(sourceNodeId, srcOtsPmHolder.getOtsInterfaceName(), spanLoss, "TX")) {
565                 LOG.info("Setting spanLoss failed for {}", sourceNodeId);
566                 return null;
567             }
568             if (!setSpanLoss(destNodeId, destOtsPmHolder.getOtsInterfaceName(), spanLoss, "RX")) {
569                 LOG.info("Setting spanLoss failed for {}", destNodeId);
570                 return null;
571             }
572             map.put(link.getLinkId(), spanLoss);
573         }
574         return map;
575     }
576
577     private String getRealNodeId(String mappedNodeId) {
578         KeyedInstanceIdentifier<Node, NodeKey> mappedNodeII =
579             InstanceIdentifiers.OVERLAY_NETWORK_II.child(Node.class, new NodeKey(new NodeId(mappedNodeId)));
580         Optional<Node> realNode;
581         try (ReadTransaction readOnlyTransaction = this.dataBroker.newReadOnlyTransaction()) {
582             realNode = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, mappedNodeII).get();
583         } catch (InterruptedException | ExecutionException e) {
584             LOG.error("Error on getRealNodeId {} :", mappedNodeId, e);
585             throw new IllegalStateException(e);
586         }
587         if (!realNode.isPresent() || (realNode.get().getSupportingNode() == null)) {
588             LOG.error("supporting node is null");
589             throw new IllegalArgumentException(
590                 String.format("Could not find node %s, or supporting node is not present", mappedNodeId));
591         }
592         List<SupportingNode> collect = realNode.get().nonnullSupportingNode().values().stream()
593             .filter(node -> (node.getNetworkRef() != null)
594                 && NetworkUtils.UNDERLAY_NETWORK_ID.equals(node.getNetworkRef().getValue())
595                 && (node.getNodeRef() != null) && !Strings.isNullOrEmpty(node.getNodeRef().getValue()))
596             .collect(Collectors.toList());
597         if (collect.isEmpty() || (collect.size() > 1)) {
598             throw new IllegalArgumentException(String.format("Invalid support node count [%d] was found for node %s",
599                 collect.size(), mappedNodeId));
600
601         }
602         LOG.info("getRealNodeId - return {}", collect.iterator().next().getNodeRef().getValue());
603         return collect.iterator().next().getNodeRef().getValue();
604     }
605
606     private Link getNetworkLinkById(LinkId linkId) {
607         NetworkKey overlayTopologyKey = new NetworkKey(new NetworkId(NetworkUtils.OVERLAY_NETWORK_ID));
608         InstanceIdentifier<Link> linkIID = InstanceIdentifier.builder(Networks.class)
609             .child(Network.class, overlayTopologyKey)
610             .augmentation(Network1.class).child(Link.class, new LinkKey(linkId))
611             .build();
612         Optional<Link> linkOptional;
613         try (ReadTransaction rtx = dataBroker.newReadOnlyTransaction()) {
614             //TODO change to constant from Timeouts class when it will be merged.
615             linkOptional = rtx.read(LogicalDatastoreType.CONFIGURATION, linkIID).get(Timeouts.DATASTORE_READ,
616                 TimeUnit.MILLISECONDS);
617             return linkOptional.get();
618         } catch (InterruptedException | ExecutionException | TimeoutException e) {
619             LOG.warn("Read of {} topology failed", NetworkUtils.OVERLAY_NETWORK_ID);
620             return null;
621         }
622     }
623
624 }