Migrate Optional.get() callers
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / crossconnect / CrossConnectImpl121.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 package org.opendaylight.transportpce.common.crossconnect;
9
10 import com.google.common.util.concurrent.FluentFuture;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.Optional;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.opendaylight.mdsal.binding.api.MountPoint;
19 import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
20 import org.opendaylight.mdsal.common.api.CommitInfo;
21 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
22 import org.opendaylight.transportpce.common.Timeouts;
23 import org.opendaylight.transportpce.common.device.DeviceTransaction;
24 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
25 import org.opendaylight.transportpce.common.fixedflex.GridConstant;
26 import org.opendaylight.transportpce.common.fixedflex.SpectrumInformation;
27 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
28 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.OpticalControlMode;
29 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.PowerDBm;
30 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.GetConnectionPortTrailInputBuilder;
31 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.GetConnectionPortTrailOutput;
32 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.OrgOpenroadmDeviceData;
33 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.OrgOpenroadmDeviceService;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.connection.DestinationBuilder;
35 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.connection.SourceBuilder;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.get.connection.port.trail.output.Ports;
37 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
38 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.RoadmConnections;
39 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.RoadmConnectionsBuilder;
40 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.RoadmConnectionsKey;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.opendaylight.yangtools.yang.common.Decimal64;
43 import org.opendaylight.yangtools.yang.common.RpcResult;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class CrossConnectImpl121 {
48     private static final Logger LOG = LoggerFactory.getLogger(CrossConnectImpl121.class);
49
50     private final DeviceTransactionManager deviceTransactionManager;
51
52     public CrossConnectImpl121(DeviceTransactionManager deviceTransactionManager) {
53         this.deviceTransactionManager = deviceTransactionManager;
54     }
55
56     public Optional<RoadmConnections> getCrossConnect(String deviceId, String connectionNumber) {
57         return deviceTransactionManager.getDataFromDevice(deviceId, LogicalDatastoreType.OPERATIONAL,
58                 generateRdmConnectionIID(connectionNumber), Timeouts.DEVICE_READ_TIMEOUT,
59                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
60     }
61
62     public Optional<String> postCrossConnect(String deviceId, String srcTp, String destTp,
63             SpectrumInformation spectrumInformation) {
64         RoadmConnectionsBuilder rdmConnBldr = new RoadmConnectionsBuilder();
65         String connectionNumber = spectrumInformation.getIdentifierFromParams(srcTp, destTp);
66         rdmConnBldr.setConnectionNumber(connectionNumber);
67         rdmConnBldr.setWavelengthNumber(spectrumInformation.getWaveLength());
68         rdmConnBldr.setOpticalControlMode(OpticalControlMode.Off);
69         rdmConnBldr.setSource(new SourceBuilder().setSrcIf(spectrumInformation.getIdentifierFromParams(srcTp))
70                 .build());
71         rdmConnBldr.setDestination(new DestinationBuilder()
72                 .setDstIf(spectrumInformation.getIdentifierFromParams(destTp))
73                 .build());
74         InstanceIdentifier<RoadmConnections> rdmConnectionIID = InstanceIdentifier
75             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
76             .child(RoadmConnections.class, new RoadmConnectionsKey(rdmConnBldr.getConnectionNumber()))
77             .build();
78
79         Future<Optional<DeviceTransaction>> deviceTxFuture = deviceTransactionManager.getDeviceTransaction(deviceId);
80         DeviceTransaction deviceTx;
81         try {
82             Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
83             if (deviceTxOpt.isPresent()) {
84                 deviceTx = deviceTxOpt.orElseThrow();
85             } else {
86                 LOG.error("Device transaction for device {} was not found!", deviceId);
87                 return Optional.empty();
88             }
89         } catch (InterruptedException | ExecutionException e) {
90             LOG.error("Unable to obtain device transaction for device {}!", deviceId, e);
91             return Optional.empty();
92         }
93
94         // post the cross connect on the device
95         deviceTx.merge(LogicalDatastoreType.CONFIGURATION, rdmConnectionIID, rdmConnBldr.build());
96         FluentFuture<? extends @NonNull CommitInfo> commit =
97                 deviceTx.commit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
98         try {
99             commit.get();
100             LOG.info("Roadm-connection successfully created: {}-{}-{}-{}", srcTp, destTp,
101                     spectrumInformation.getLowerSpectralSlotNumber(),
102                     spectrumInformation.getHigherSpectralSlotNumber());
103             return Optional.of(connectionNumber);
104         } catch (InterruptedException | ExecutionException e) {
105             LOG.warn("Failed to post {}. Exception: ", rdmConnBldr.build(), e);
106         }
107         return Optional.empty();
108     }
109
110     public List<String> deleteCrossConnect(String deviceId, String connectionNumber) {
111         List<String> interfList = new ArrayList<>();
112         Optional<RoadmConnections> xc = getCrossConnect(deviceId, connectionNumber);
113         //Check if cross connect exists before delete
114         if (xc.isPresent()) {
115             interfList.add(xc.orElseThrow().getSource().getSrcIf());
116             interfList.add(xc.orElseThrow().getDestination().getDstIf());
117         } else {
118             LOG.warn("Cross connect does not exist, halting delete");
119             return null;
120         }
121         Future<Optional<DeviceTransaction>> deviceTxFuture = deviceTransactionManager.getDeviceTransaction(deviceId);
122         DeviceTransaction deviceTx;
123         try {
124             Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
125             if (deviceTxOpt.isPresent()) {
126                 deviceTx = deviceTxOpt.orElseThrow();
127             } else {
128                 LOG.error("Device transaction for device {} was not found!", deviceId);
129                 return null;
130             }
131         } catch (InterruptedException | ExecutionException e) {
132             LOG.error("Unable to obtain device transaction for device {}!", deviceId, e);
133             return null;
134         }
135
136         // post the cross connect on the device
137         deviceTx.delete(LogicalDatastoreType.CONFIGURATION, generateRdmConnectionIID(connectionNumber));
138         FluentFuture<? extends @NonNull CommitInfo> commit =
139                 deviceTx.commit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
140         try {
141             commit.get();
142             LOG.info("Roadm connection successfully deleted ");
143             return interfList;
144         } catch (InterruptedException | ExecutionException e) {
145             LOG.warn("Failed to delete {}", connectionNumber, e);
146         }
147         return null;
148     }
149
150
151     public List<Ports> getConnectionPortTrail(String nodeId, String srcTp, String destTp,
152             int lowerSpectralSlotNumber, int higherSpectralSlotNumber) throws OpenRoadmInterfaceException {
153         String spectralSlotName = String.join(GridConstant.SPECTRAL_SLOT_SEPARATOR,
154                 String.valueOf(lowerSpectralSlotNumber), String.valueOf(higherSpectralSlotNumber));
155         String connectionName = generateConnectionNumber(srcTp, destTp, spectralSlotName);
156         Optional<MountPoint> mountPointOpt = deviceTransactionManager.getDeviceMountPoint(nodeId);
157         List<Ports> ports = null;
158         MountPoint mountPoint;
159         if (mountPointOpt.isPresent()) {
160             mountPoint = mountPointOpt.orElseThrow();
161         } else {
162             LOG.error("Failed to obtain mount point for device {}!", nodeId);
163             return Collections.emptyList();
164         }
165         final Optional<RpcConsumerRegistry> service = mountPoint.getService(RpcConsumerRegistry.class);
166         if (!service.isPresent()) {
167             LOG.error("Failed to get RpcService for node {}", nodeId);
168         }
169         final OrgOpenroadmDeviceService rpcService = service.orElseThrow()
170             .getRpcService(OrgOpenroadmDeviceService.class);
171         final GetConnectionPortTrailInputBuilder portTrainInputBuilder = new GetConnectionPortTrailInputBuilder();
172         portTrainInputBuilder.setConnectionNumber(connectionName);
173         final Future<RpcResult<GetConnectionPortTrailOutput>> portTrailOutput = rpcService.getConnectionPortTrail(
174                 portTrainInputBuilder.build());
175         if (portTrailOutput != null) {
176             try {
177                 RpcResult<GetConnectionPortTrailOutput> connectionPortTrailOutputRpcResult = portTrailOutput.get();
178                 GetConnectionPortTrailOutput connectionPortTrailOutput = connectionPortTrailOutputRpcResult.getResult();
179                 if (connectionPortTrailOutput == null) {
180                     throw new OpenRoadmInterfaceException(String.format("RPC get connection port trail called on"
181                             + " node %s returned null!", nodeId));
182                 }
183                 LOG.info("Getting port trail for node {}'s connection number {}", nodeId, connectionName);
184                 ports = connectionPortTrailOutput.getPorts();
185                 for (Ports port : ports) {
186                     LOG.info("{} - Circuit pack {} - Port {}", nodeId, port.getCircuitPackName(), port.getPortName());
187                 }
188             } catch (InterruptedException | ExecutionException e) {
189                 LOG.warn("Exception caught", e);
190             }
191         } else {
192             LOG.warn("Port trail is null in getConnectionPortTrail for nodeId {}", nodeId);
193         }
194         return ports != null ? ports : Collections.emptyList();
195     }
196
197     private InstanceIdentifier<RoadmConnections> generateRdmConnectionIID(String connectionNumber) {
198         return InstanceIdentifier.builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
199             .child(RoadmConnections.class, new RoadmConnectionsKey(connectionNumber))
200             .build();
201     }
202
203     private String generateConnectionNumber(String srcTp, String destTp, String spectralSlotName) {
204         return String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, destTp, spectralSlotName);
205     }
206
207     public boolean setPowerLevel(String deviceId, OpticalControlMode mode, Decimal64 powerValue, String ctNumber) {
208
209         Optional<RoadmConnections> rdmConnOpt = getCrossConnect(deviceId, ctNumber);
210         if (rdmConnOpt.isPresent()) {
211             RoadmConnectionsBuilder rdmConnBldr = new RoadmConnectionsBuilder(rdmConnOpt.orElseThrow())
212                     .setOpticalControlMode(mode);
213             if (powerValue != null) {
214                 rdmConnBldr.setTargetOutputPower(new PowerDBm(powerValue));
215             }
216             RoadmConnections newRdmConn = rdmConnBldr.build();
217
218             Future<Optional<DeviceTransaction>> deviceTxFuture =
219                     deviceTransactionManager.getDeviceTransaction(deviceId);
220             DeviceTransaction deviceTx;
221             try {
222                 Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
223                 if (deviceTxOpt.isPresent()) {
224                     deviceTx = deviceTxOpt.orElseThrow();
225                 } else {
226                     LOG.error("Transaction for device {} was not found!", deviceId);
227                     return false;
228                 }
229             } catch (InterruptedException | ExecutionException e) {
230                 LOG.error("Unable to get transaction for device {}!", deviceId, e);
231                 return false;
232             }
233
234             // post the cross connect on the device
235             InstanceIdentifier<RoadmConnections> roadmConnIID = InstanceIdentifier
236                 .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
237                 .child(RoadmConnections.class, new RoadmConnectionsKey(ctNumber))
238                 .build();
239             deviceTx.merge(LogicalDatastoreType.CONFIGURATION, roadmConnIID, newRdmConn);
240             FluentFuture<? extends @NonNull CommitInfo> commit =
241                 deviceTx.commit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
242             try {
243                 commit.get();
244                 LOG.info("Roadm connection power level successfully set ");
245                 return true;
246             } catch (InterruptedException | ExecutionException ex) {
247                 LOG.warn("Failed to post {}", newRdmConn, ex);
248             }
249
250         } else {
251             LOG.warn("Roadm-Connection is null in set power level ({})", ctNumber);
252         }
253         return false;
254     }
255
256 }