Refactor: update transportpce yang models
[transportpce.git] / tapi / src / main / java / org / opendaylight / transportpce / tapi / listeners / TapiRendererListenerImpl.java
1 /*
2  * Copyright © 2021 Nokia, Inc. 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.tapi.listeners;
9
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import java.nio.charset.Charset;
12 import java.util.Optional;
13 import java.util.UUID;
14 import java.util.concurrent.ExecutionException;
15 import org.opendaylight.mdsal.binding.api.DataBroker;
16 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
17 import org.opendaylight.transportpce.common.network.NetworkTransactionImpl;
18 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
19 import org.opendaylight.transportpce.common.network.RequestProcessor;
20 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev210618.RendererRpcResultSp;
21 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev210618.TransportpceRendererListener;
22 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.AdministrativeState;
23 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Context;
24 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.LifecycleState;
25 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.OperationalState;
26 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Uuid;
27 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1;
28 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionBuilder;
29 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionKey;
30 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityService;
31 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceBuilder;
32 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceKey;
33 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.service.Connection;
34 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 public class TapiRendererListenerImpl implements TransportpceRendererListener {
39
40     private static final Logger LOG = LoggerFactory.getLogger(TapiRendererListenerImpl.class);
41     private final DataBroker dataBroker;
42     private Uuid serviceUuid;
43     private RendererRpcResultSp serviceRpcResultSp;
44     private final NetworkTransactionService networkTransactionService;
45
46     public TapiRendererListenerImpl(DataBroker dataBroker) {
47         this.dataBroker = dataBroker;
48         this.networkTransactionService = new NetworkTransactionImpl(new RequestProcessor(this.dataBroker));
49     }
50
51     @Override
52     public void onRendererRpcResultSp(RendererRpcResultSp notification) {
53         if (compareServiceRpcResultSp(notification)) {
54             LOG.warn("ServiceRpcResultSp already wired !");
55             return;
56         }
57         serviceRpcResultSp = notification;
58         int notifType = serviceRpcResultSp.getNotificationType().getIntValue();
59         LOG.info("Renderer '{}' Notification received : {}", serviceRpcResultSp.getNotificationType().getName(),
60                 notification);
61         /* service-implementation-request. */
62         if (notifType == 3) {
63             onServiceImplementationResult(notification);
64         }
65     }
66
67     /**
68      * Process service implementation result for serviceName.
69      * @param notification RendererRpcResultSp
70      */
71     private void onServiceImplementationResult(RendererRpcResultSp notification) {
72         switch (serviceRpcResultSp.getStatus()) {
73             case Successful:
74                 onSuccededServiceImplementation();
75                 break;
76             case Failed:
77                 onFailedServiceImplementation(notification.getServiceName());
78                 break;
79             case  Pending:
80                 LOG.warn("Service Implementation still pending according to RpcStatusEx");
81                 break;
82             default:
83                 LOG.warn("Service Implementation has an unknown RpcStatusEx code");
84                 break;
85         }
86     }
87
88     /**
89      * Process succeeded service implementation for service.
90      */
91     private void onSuccededServiceImplementation() {
92         LOG.info("Service implemented !");
93         // TODO: update Connections and Connectivity Service states
94         ConnectivityService connectivityService = getConnectivityService(this.serviceUuid);
95         if (connectivityService == null) {
96             LOG.error("Couldnt retrieve service from datastore");
97             return;
98         }
99         LOG.info("Connectivity service = {}", connectivityService.toString());
100         // TODO --> this throws error because the renderer goes really fast. Is this normal??
101         ConnectivityService updtConnServ = new ConnectivityServiceBuilder(connectivityService)
102             .setAdministrativeState(AdministrativeState.UNLOCKED)
103             .setLifecycleState(LifecycleState.INSTALLED)
104             .setOperationalState(OperationalState.ENABLED)
105             .build();
106         for (Connection connection:updtConnServ.getConnection().values()) {
107             updateConnectionState(connection.getConnectionUuid());
108         }
109         updateConnectivityService(updtConnServ);
110     }
111
112     /**
113      * Process failed service implementation for serviceName.
114      * @param serviceName String
115      */
116     private void onFailedServiceImplementation(String serviceName) {
117         LOG.error("Renderer implementation failed !");
118         LOG.info("PCE cancel resource done OK !");
119         Uuid suuid = new Uuid(UUID.nameUUIDFromBytes(serviceName.getBytes(Charset.forName("UTF-8")))
120                 .toString());
121         // get connections of connectivity service and remove them from tapi context and then remove
122         //  service from context. The CEPs are maintained as they could be reused by another service
123         ConnectivityService connService = getConnectivityService(suuid);
124         if (connService == null) {
125             LOG.error("Service doesnt exist in tapi context");
126             return;
127         }
128         for (Connection connection:connService.getConnection().values()) {
129             deleteConnection(connection.getConnectionUuid());
130         }
131         deleteConnectivityService(suuid);
132     }
133
134     @SuppressFBWarnings(
135             value = "ES_COMPARING_STRINGS_WITH_EQ",
136             justification = "false positives, not strings but real object references comparisons")
137     private Boolean compareServiceRpcResultSp(RendererRpcResultSp notification) {
138         if (serviceRpcResultSp == null) {
139             return false;
140         }
141         if (serviceRpcResultSp.getNotificationType() != notification.getNotificationType()) {
142             return false;
143         }
144         if (serviceRpcResultSp.getServiceName() != notification.getServiceName()) {
145             return false;
146         }
147         if (serviceRpcResultSp.getStatus() != notification.getStatus()) {
148             return false;
149         }
150         if (serviceRpcResultSp.getStatusMessage() != notification.getStatusMessage()) {
151             return false;
152         }
153         return true;
154     }
155
156     private ConnectivityService getConnectivityService(Uuid suuid) {
157         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
158         try {
159             // First read connectivity service with service uuid and update info
160             InstanceIdentifier<ConnectivityService> connectivityServIID =
161                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
162                     .child(org.opendaylight.yang.gen.v1.urn
163                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
164                     .child(ConnectivityService.class, new ConnectivityServiceKey(suuid))
165                     .build();
166
167             Optional<ConnectivityService> optConnServ =
168                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityServIID).get();
169             if (!optConnServ.isPresent()) {
170                 LOG.error("Connectivity service not found in tapi context");
171                 return null;
172             }
173             return optConnServ.get();
174         } catch (InterruptedException | ExecutionException e) {
175             LOG.error("Failed to merge TAPI connectivity", e);
176             return null;
177         }
178     }
179
180     private void updateConnectionState(Uuid connectionUuid) {
181         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
182         try {
183             // First read connection with connection uuid and update info
184             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn
185                 .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection> connectionIID =
186                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
187                     .child(org.opendaylight.yang.gen.v1.urn
188                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
189                     .child(org.opendaylight.yang.gen.v1.urn
190                             .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection.class,
191                         new ConnectionKey(connectionUuid))
192                     .build();
193
194             Optional<org.opendaylight.yang.gen.v1.urn
195                 .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection> optConn =
196                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectionIID).get();
197             if (!optConn.isPresent()) {
198                 LOG.error("Connection not found in tapi context");
199                 return;
200             }
201             org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection
202                 newConnection = new ConnectionBuilder(optConn.get()).setLifecycleState(LifecycleState.INSTALLED)
203                     .setOperationalState(OperationalState.ENABLED).build();
204             // merge in datastore
205             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connectionIID,
206                     newConnection);
207             this.networkTransactionService.commit().get();
208             LOG.info("TAPI connection merged successfully.");
209         } catch (InterruptedException | ExecutionException e) {
210             LOG.error("Failed to merge TAPI connection", e);
211         }
212     }
213
214     private void updateConnectivityService(ConnectivityService updtConnServ) {
215         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
216         try {
217             // First read connectivity service with connectivity service uuid and update info
218             InstanceIdentifier<ConnectivityService> connServIID =
219                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
220                     .child(org.opendaylight.yang.gen.v1.urn
221                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
222                     .child(ConnectivityService.class, new ConnectivityServiceKey(updtConnServ.getUuid()))
223                     .build();
224
225             Optional<ConnectivityService> optConnServ =
226                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connServIID).get();
227             if (!optConnServ.isPresent()) {
228                 LOG.error("Connection not found in tapi context");
229                 return;
230             }
231             ConnectivityService newConnServ = new ConnectivityServiceBuilder(updtConnServ).build();
232             // merge in datastore
233             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connServIID,
234                     newConnServ);
235             this.networkTransactionService.commit().get();
236             LOG.info("TAPI connectivity service merged successfully.");
237         } catch (InterruptedException | ExecutionException e) {
238             LOG.error("Failed to merge TAPI connectivity service", e);
239         }
240     }
241
242     private void deleteConnectivityService(Uuid suuid) {
243         // First read connectivity service with service uuid and update info
244         InstanceIdentifier<ConnectivityService> connectivityServIID =
245             InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
246                 .child(org.opendaylight.yang.gen.v1.urn
247                     .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
248                 .child(ConnectivityService.class, new ConnectivityServiceKey(suuid))
249                 .build();
250         try {
251             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, connectivityServIID);
252             this.networkTransactionService.commit().get();
253         } catch (InterruptedException | ExecutionException e) {
254             LOG.error("Failed to delete TAPI connectivity service", e);
255         }
256     }
257
258     private void deleteConnection(Uuid connectionUuid) {
259         // First read connectivity service with service uuid and update info
260         InstanceIdentifier<org.opendaylight.yang.gen.v1
261             .urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection> connectionIID =
262             InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
263                 .child(org.opendaylight.yang.gen.v1.urn
264                     .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
265                 .child(org.opendaylight.yang.gen.v1.urn
266                         .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection.class,
267                     new org.opendaylight.yang.gen.v1.urn
268                         .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionKey(
269                             connectionUuid))
270                 .build();
271         try {
272             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, connectionIID);
273             this.networkTransactionService.commit().get();
274         } catch (InterruptedException | ExecutionException e) {
275             LOG.error("Failed to delete TAPI connection", e);
276         }
277     }
278
279     public void setServiceUuid(Uuid serviceUuid) {
280         this.serviceUuid = serviceUuid;
281     }
282 }