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