Turn PortMappingImpl into a component
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / openroadminterfaces / OpenRoadmInterfacesImpl710.java
1 /*
2  * Copyright © 2020 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.openroadminterfaces;
10
11 import com.google.common.util.concurrent.FluentFuture;
12 import java.util.Optional;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.Future;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.mdsal.common.api.CommitInfo;
17 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
18 import org.opendaylight.transportpce.common.StringConstants;
19 import org.opendaylight.transportpce.common.Timeouts;
20 import org.opendaylight.transportpce.common.device.DeviceTransaction;
21 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
22 import org.opendaylight.transportpce.common.mapping.PortMapping;
23 import org.opendaylight.transportpce.common.mapping.PortMappingVersion710;
24 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.mapping.Mapping;
25 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.OrgOpenroadmDeviceData;
26 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.pack.Ports;
27 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.pack.PortsKey;
28 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacks;
29 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacksBuilder;
30 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacksKey;
31 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.Interface;
32 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.InterfaceBuilder;
33 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.InterfaceKey;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.OrgOpenroadmDevice;
35 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.port.Interfaces;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.equipment.states.types.rev191129.AdminStates;
37 import org.opendaylight.yang.gen.v1.http.org.openroadm.equipment.states.types.rev191129.States;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class OpenRoadmInterfacesImpl710 {
43
44     private static final Logger LOG = LoggerFactory.getLogger(OpenRoadmInterfacesImpl710.class);
45
46     private final DeviceTransactionManager deviceTransactionManager;
47     private final PortMapping portMapping;
48     private final PortMappingVersion710 portMapping710;
49
50     public OpenRoadmInterfacesImpl710(DeviceTransactionManager deviceTransactionManager, PortMapping portMapping) {
51         this.deviceTransactionManager = deviceTransactionManager;
52         this.portMapping = portMapping;
53         this.portMapping710 = portMapping.getPortMappingVersion710();
54     }
55
56     public void postInterface(String nodeId, InterfaceBuilder ifBuilder) throws OpenRoadmInterfaceException {
57         Future<Optional<DeviceTransaction>> deviceTxFuture = deviceTransactionManager.getDeviceTransaction(nodeId);
58         DeviceTransaction deviceTx;
59         try {
60             Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
61             if (deviceTxOpt.isPresent()) {
62                 deviceTx = deviceTxOpt.get();
63             } else {
64                 throw new OpenRoadmInterfaceException(String.format("Device transaction was not found for node %s!",
65                     nodeId));
66             }
67         } catch (InterruptedException | ExecutionException e) {
68             throw new OpenRoadmInterfaceException(String.format("Failed to obtain device transaction for node %s!",
69                 nodeId), e);
70         }
71
72         InstanceIdentifier<Interface> interfacesIID = InstanceIdentifier
73             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
74             .child(Interface.class, new InterfaceKey(ifBuilder.getName()))
75             .build();
76         LOG.info("POST INTERF for {} : InterfaceBuilder : name = {} \t type = {}", nodeId, ifBuilder.getName(),
77             ifBuilder.getType().toString());
78         deviceTx.merge(LogicalDatastoreType.CONFIGURATION, interfacesIID, ifBuilder.build());
79         FluentFuture<? extends @NonNull CommitInfo> txSubmitFuture =
80             deviceTx.commit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
81         // TODO: instead of using this infinite loop coupled with this timeout,
82         // it would be better to use a notification mechanism from the device to be advertised
83         // that the new created interface is present in the device circuit-pack/port
84         final Thread current = Thread.currentThread();
85         Thread timer = new Thread() {
86             public void run() {
87                 try {
88                     Thread.sleep(3000);
89                     current.interrupt();
90                 } catch (InterruptedException e) {
91                     LOG.error("Timeout before the new created interface appears on the deivce circuit-pack port", e);
92                 }
93             }
94         };
95         try {
96             txSubmitFuture.get();
97             LOG.info("Successfully posted/deleted interface {} on node {}", ifBuilder.getName(), nodeId);
98             // this check is not needed during the delete operation
99             // during the delete operation, ifBuilder does not contain supporting-cp and supporting-port
100             if (ifBuilder.getSupportingCircuitPackName() != null && ifBuilder.getSupportingPort() != null) {
101                 boolean devicePortIsUptodated = false;
102                 while (!devicePortIsUptodated) {
103                     devicePortIsUptodated = checkIfDevicePortIsUpdatedWithInterface(nodeId, ifBuilder);
104                 }
105                 LOG.info("{} - {} - interface {} updated on port {}", nodeId, ifBuilder.getSupportingCircuitPackName(),
106                     ifBuilder.getName(), ifBuilder.getSupportingPort());
107             }
108             timer.interrupt();
109         } catch (InterruptedException | ExecutionException e) {
110             throw new OpenRoadmInterfaceException(String.format("Failed to post interface %s on node %s!", ifBuilder
111                 .getName(), nodeId), e);
112         }
113     }
114
115
116     public Optional<Interface> getInterface(String nodeId, String interfaceName) throws OpenRoadmInterfaceException {
117         InstanceIdentifier<Interface> interfacesIID = InstanceIdentifier
118             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
119             .child(Interface.class, new InterfaceKey(interfaceName))
120             .build();
121         return deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.CONFIGURATION,
122             interfacesIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
123     }
124
125
126     public synchronized void deleteInterface(String nodeId, String interfaceName) throws OpenRoadmInterfaceException {
127         LOG.info("deleting interface {} on device71 {}", interfaceName, nodeId);
128         Optional<Interface> intf2DeleteOpt;
129         try {
130             intf2DeleteOpt = getInterface(nodeId, interfaceName);
131         } catch (OpenRoadmInterfaceException e) {
132             throw new OpenRoadmInterfaceException(String.format("Failed to check if interface %s exists on node %s!",
133                 interfaceName, nodeId), e);
134         }
135         if (intf2DeleteOpt.isPresent()) {
136             Interface intf2Delete = intf2DeleteOpt.get();
137             // set the name and set the type. Having these two lines will post the interface with just
138             // name, type and admin-state, without all the default values such as maint-testsignal
139             //  delete the interfaces successfully
140             // just build a new Interface builder without the arguments for inter2Delete
141             InterfaceBuilder ifBuilder = new InterfaceBuilder()
142                 .setAdministrativeState(AdminStates.OutOfService)
143                 // Though these could be redundant, but 'when' statements are causing problem,
144                 // when deleting the interfaces trying to be deleted
145                 .setName(intf2Delete.getName())
146                 .setType(intf2Delete.getType());
147
148             // post interface with updated admin state
149             try {
150                 postInterface(nodeId, ifBuilder);
151             } catch (OpenRoadmInterfaceException ex) {
152                 throw new OpenRoadmInterfaceException(String.format("Failed to set state of interface %s to %s while"
153                     + " deleting it!", interfaceName, AdminStates.OutOfService), ex);
154             }
155
156             InstanceIdentifier<Interface> interfacesIID = InstanceIdentifier
157                 .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
158                 .child(Interface.class, new InterfaceKey(interfaceName))
159                 .build();
160             Future<Optional<DeviceTransaction>> deviceTxFuture = this.deviceTransactionManager.getDeviceTransaction(
161                 nodeId);
162             DeviceTransaction deviceTx;
163             try {
164                 Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
165                 if (deviceTxOpt.isPresent()) {
166                     deviceTx = deviceTxOpt.get();
167                 } else {
168                     throw new OpenRoadmInterfaceException(String.format("Device transaction was not found for node %s!",
169                         nodeId));
170                 }
171             } catch (InterruptedException | ExecutionException e) {
172                 throw new OpenRoadmInterfaceException(String.format("Failed to obtain device transaction for node %s!",
173                     nodeId), e);
174             }
175
176             deviceTx.delete(LogicalDatastoreType.CONFIGURATION, interfacesIID);
177             FluentFuture<? extends @NonNull CommitInfo> commit =
178                 deviceTx.commit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
179
180             try {
181                 commit.get();
182                 LOG.info("Successfully deleted {} on node {}", interfaceName, nodeId);
183             } catch (InterruptedException | ExecutionException e) {
184                 throw new OpenRoadmInterfaceException(String.format("Failed to delete interface %s on " + "node %s",
185                     interfaceName, nodeId), e);
186             }
187             // change the equipment state on circuit pack if xpdr node
188             if (intf2Delete.getName().contains(StringConstants.CLIENT_TOKEN) || intf2Delete.getName().contains(
189                 StringConstants.NETWORK_TOKEN)) {
190                 postEquipmentState(nodeId, intf2Delete.getSupportingCircuitPackName(), false);
191                 // Here we update the port-mapping data after the interface delete
192                 Mapping oldMapping = this.portMapping.getMapping(
193                     nodeId, intf2Delete.getSupportingCircuitPackName(), intf2Delete.getSupportingPort());
194                 this.portMapping.deleteMapping(nodeId, oldMapping.getLogicalConnectionPoint());
195                 this.portMapping710.updateMapping(nodeId, oldMapping);
196             }
197
198         } else {
199             LOG.info("Interface does not exist, cannot delete on node {}", nodeId);
200         }
201     }
202
203     public void postEquipmentState(String nodeId, String circuitPackName, boolean activate)
204         throws OpenRoadmInterfaceException {
205         InstanceIdentifier<CircuitPacks> circuitPackIID = InstanceIdentifier
206             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
207             .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName))
208             .build();
209         Optional<CircuitPacks> cpOpt = this.deviceTransactionManager.getDataFromDevice(nodeId,
210             LogicalDatastoreType.CONFIGURATION, circuitPackIID, Timeouts.DEVICE_READ_TIMEOUT,
211             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
212         CircuitPacks cp = null;
213         if (cpOpt.isPresent()) {
214             cp = cpOpt.get();
215         } else {
216             throw new OpenRoadmInterfaceException(String.format(
217                 "Could not find CircuitPack %s in equipment config datastore for node %s", circuitPackName, nodeId));
218         }
219         CircuitPacksBuilder cpBldr = new CircuitPacksBuilder(cp);
220         boolean change = false;
221         if (activate) {
222             if (cpBldr.getEquipmentState() != null
223                 && !States.NotReservedInuse.equals(cpBldr.getEquipmentState())) {
224                 cpBldr.setEquipmentState(States.NotReservedInuse);
225                 change = true;
226             }
227         } else if ((cpBldr.getEquipmentState() != null
228             && !States.NotReservedAvailable.equals(cpBldr.getEquipmentState()))) {
229             cpBldr.setEquipmentState(States.NotReservedAvailable);
230             change = true;
231         }
232         if (change) {
233             Future<Optional<DeviceTransaction>> deviceTxFuture = this.deviceTransactionManager.getDeviceTransaction(
234                 nodeId);
235             DeviceTransaction deviceTx;
236             try {
237                 Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
238                 if (deviceTxOpt.isPresent()) {
239                     deviceTx = deviceTxOpt.get();
240                 } else {
241                     throw new OpenRoadmInterfaceException(String.format("Device transaction was not found for node %s!",
242                         nodeId));
243                 }
244             } catch (InterruptedException | ExecutionException e) {
245                 throw new OpenRoadmInterfaceException(String.format("Failed to obtain device transaction for node %s!",
246                     nodeId), e);
247             }
248             deviceTx.merge(LogicalDatastoreType.CONFIGURATION, circuitPackIID, cpBldr.build());
249             FluentFuture<? extends @NonNull CommitInfo> txSubmitFuture =
250                 deviceTx.commit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
251             try {
252                 txSubmitFuture.get();
253                 LOG.info("Successfully posted equipment state change on node {}", nodeId);
254             } catch (InterruptedException | ExecutionException e) {
255                 throw new OpenRoadmInterfaceException(String.format("Failed to post equipment state on node %s!",
256                     nodeId), e);
257             }
258         }
259     }
260
261     public String getSupportedInterface(String nodeId, String interf) {
262         Optional<Interface> supInterfOpt;
263         try {
264             supInterfOpt = getInterface(nodeId, interf);
265             if (supInterfOpt.isPresent()) {
266                 return supInterfOpt.get().getSupportingInterfaceList().stream().findFirst().get();
267             } else {
268                 return null;
269             }
270         } catch (OpenRoadmInterfaceException e) {
271             LOG.error("error getting Supported Interface of {} - {}", interf, nodeId, e);
272             return null;
273         }
274     }
275
276     private boolean checkIfDevicePortIsUpdatedWithInterface(String nodeId, InterfaceBuilder ifBuilder) {
277         InstanceIdentifier<Ports> portIID = InstanceIdentifier
278             .builderOfInherited(OrgOpenroadmDeviceData.class, OrgOpenroadmDevice.class)
279             .child(CircuitPacks.class, new CircuitPacksKey(ifBuilder.getSupportingCircuitPackName()))
280             .child(Ports.class, new PortsKey(ifBuilder.getSupportingPort()))
281             .build();
282         Ports port = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
283             portIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
284         if (port.getInterfaces() == null) {
285             return false;
286         }
287         for (Interfaces interf : port.getInterfaces()) {
288             if (interf.getInterfaceName().equals(ifBuilder.getName())) {
289                 return true;
290             }
291         }
292         return false;
293     }
294 }