Refactor NBINotifications and serviceHandlerImpl
[transportpce.git] / servicehandler / src / main / java / org / opendaylight / transportpce / servicehandler / listeners / PceListenerImpl.java
1 /*
2  * Copyright © 2017 Orange, 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.servicehandler.listeners;
9
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
12 import org.opendaylight.transportpce.common.OperationResult;
13 import org.opendaylight.transportpce.pce.service.PathComputationService;
14 import org.opendaylight.transportpce.renderer.provisiondevice.RendererServiceOperations;
15 import org.opendaylight.transportpce.servicehandler.ModelMappingUtils;
16 import org.opendaylight.transportpce.servicehandler.ServiceInput;
17 import org.opendaylight.transportpce.servicehandler.service.PCEServiceWrapper;
18 import org.opendaylight.transportpce.servicehandler.service.ServiceDataStoreOperations;
19 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev210701.PathComputationRequestOutput;
20 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev210701.PathComputationRequestOutputBuilder;
21 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev210701.ServicePathRpcResult;
22 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev210701.TransportpcePceListener;
23 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev210701.service.path.rpc.result.PathDescription;
24 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev210701.service.path.rpc.result.PathDescriptionBuilder;
25 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev210618.ServiceImplementationRequestInput;
26 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev181130.State;
27 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev190531.service.list.Services;
28 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128.RpcStatusEx;
29 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128.response.parameters.sp.ResponseParameters;
30 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128.response.parameters.sp.ResponseParametersBuilder;
31 import org.opendaylight.yang.gen.v1.nbi.notifications.rev210813.PublishNotificationProcessService;
32 import org.opendaylight.yang.gen.v1.nbi.notifications.rev210813.PublishNotificationProcessServiceBuilder;
33 import org.opendaylight.yang.gen.v1.nbi.notifications.rev210813.notification.process.service.ServiceAEndBuilder;
34 import org.opendaylight.yang.gen.v1.nbi.notifications.rev210813.notification.process.service.ServiceZEndBuilder;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 public class PceListenerImpl implements TransportpcePceListener {
39
40     private static final Logger LOG = LoggerFactory.getLogger(PceListenerImpl.class);
41     private static final String PUBLISHER = "PceListener";
42
43     private ServicePathRpcResult servicePathRpcResult;
44     private RendererServiceOperations rendererServiceOperations;
45     private ServiceDataStoreOperations serviceDataStoreOperations;
46     private PCEServiceWrapper pceServiceWrapper;
47     private ServiceInput input;
48     private Boolean serviceReconfigure;
49     private Boolean tempService;
50     private Boolean serviceFeasiblity;
51     private NotificationPublishService notificationPublishService;
52
53     public PceListenerImpl(RendererServiceOperations rendererServiceOperations,
54             PathComputationService pathComputationService, NotificationPublishService notificationPublishService,
55             ServiceDataStoreOperations serviceDataStoreOperations) {
56         this.rendererServiceOperations = rendererServiceOperations;
57         this.pceServiceWrapper = new PCEServiceWrapper(pathComputationService, notificationPublishService);
58         this.serviceDataStoreOperations = serviceDataStoreOperations;
59         setServiceReconfigure(false);
60         setInput(null);
61         setTempService(false);
62         setServiceFeasiblity(false);
63         this.notificationPublishService = notificationPublishService;
64     }
65
66     @Override
67     public void onServicePathRpcResult(ServicePathRpcResult notification) {
68         if (compareServicePathRpcResult(notification)) {
69             LOG.warn("ServicePathRpcResult already wired !");
70             return;
71         }
72         servicePathRpcResult = notification;
73         switch (servicePathRpcResult.getNotificationType().getIntValue()) {
74             /* path-computation-request. */
75             case 1:
76                 onPathComputationResult(notification);
77                 break;
78             /* cancel-resource-reserve. */
79             case 2:
80                 onCancelResourceResult();
81                 break;
82             default:
83                 break;
84         }
85     }
86
87     /**
88      * Process path computation request result.
89      * @param notification the result notification.
90      */
91     private void onPathComputationResult(ServicePathRpcResult notification) {
92         LOG.info("PCE '{}' Notification received : {}", servicePathRpcResult.getNotificationType().getName(),
93                 notification);
94         if (!checkStatus(notification)) {
95             return;
96         }
97         if (servicePathRpcResult.getPathDescription() == null) {
98             LOG.error("'PathDescription' parameter is null ");
99             return;
100         }
101         PathDescription pathDescription = new PathDescriptionBuilder()
102                 .setAToZDirection(servicePathRpcResult.getPathDescription().getAToZDirection())
103                 .setZToADirection(servicePathRpcResult.getPathDescription().getZToADirection())
104                 .build();
105         LOG.info("PathDescription gets : {}", pathDescription);
106         if (serviceFeasiblity) {
107             LOG.warn("service-feasibility-check RPC ");
108             return;
109         }
110         if (input == null) {
111             LOG.error("Input is null !");
112             return;
113         }
114         OperationResult operationResult = null;
115         if (tempService) {
116             operationResult = this.serviceDataStoreOperations.createTempService(input.getTempServiceCreateInput());
117             if (!operationResult.isSuccess()) {
118                 LOG.error("Temp Service not created in datastore !");
119             }
120         } else {
121             operationResult = this.serviceDataStoreOperations.createService(input.getServiceCreateInput());
122             if (!operationResult.isSuccess()) {
123                 LOG.error("Service not created in datastore !");
124             }
125         }
126         ResponseParameters responseParameters = new ResponseParametersBuilder()
127                 .setPathDescription(new org.opendaylight.yang.gen.v1.http
128                         .org.transportpce.b.c._interface.service.types.rev200128
129                         .response.parameters.sp.response.parameters.PathDescriptionBuilder(pathDescription).build())
130                 .build();
131         PathComputationRequestOutput pceResponse = new PathComputationRequestOutputBuilder()
132                 .setResponseParameters(responseParameters).build();
133         OperationResult operationServicePathSaveResult = this.serviceDataStoreOperations
134                 .createServicePath(input, pceResponse);
135         if (!operationServicePathSaveResult.isSuccess()) {
136             LOG.error("Service Path not created in datastore !");
137         }
138         ServiceImplementationRequestInput serviceImplementationRequest = ModelMappingUtils
139                 .createServiceImplementationRequest(input, pathDescription);
140         LOG.info("Sending serviceImplementation request : {}", serviceImplementationRequest);
141         this.rendererServiceOperations.serviceImplementation(serviceImplementationRequest);
142     }
143
144     /**
145      * Check status of notification and send nbi notification.
146      * @param notification ServicePathRpcResult the notification to check.
147      * @return true is status is Successful, false otherwise.
148      */
149     private boolean checkStatus(ServicePathRpcResult notification) {
150         PublishNotificationProcessService nbiNotification = getPublishNotificationProcessService(notification);
151         PublishNotificationProcessServiceBuilder publishNotificationProcessServiceBuilder =
152                 new PublishNotificationProcessServiceBuilder(nbiNotification);
153         switch (servicePathRpcResult.getStatus()) {
154             case Failed:
155                 LOG.error("PCE path computation failed !");
156                 nbiNotification = publishNotificationProcessServiceBuilder
157                         .setMessage("ServiceCreate request failed ...")
158                         .setResponseFailed("PCE path computation failed !")
159                         .setOperationalState(State.Degraded).build();
160                 sendNbiNotification(nbiNotification);
161                 return false;
162             case Pending:
163                 LOG.warn("PCE path computation returned a Pending RpcStatusEx code!");
164                 return false;
165             case Successful:
166                 LOG.info("PCE calculation done OK !");
167                 return true;
168             default:
169                 LOG.error("PCE path computation returned an unknown RpcStatusEx code {}",
170                         servicePathRpcResult.getStatus());
171                 nbiNotification = publishNotificationProcessServiceBuilder
172                         .setMessage("ServiceCreate request failed ...")
173                         .setResponseFailed("PCE path computation returned an unknown RpcStatusEx code!")
174                         .setOperationalState(State.Degraded).build();
175                 sendNbiNotification(nbiNotification);
176                 return false;
177         }
178     }
179
180     private PublishNotificationProcessService getPublishNotificationProcessService(ServicePathRpcResult notification) {
181         PublishNotificationProcessServiceBuilder nbiNotificationBuilder =
182                 new PublishNotificationProcessServiceBuilder();
183         if (input != null) {
184             nbiNotificationBuilder.setServiceName(input.getServiceName())
185                     .setServiceAEnd(new ServiceAEndBuilder(input.getServiceAEnd()).build())
186                     .setServiceZEnd(new ServiceZEndBuilder(input.getServiceZEnd()).build())
187                     .setCommonId(input.getCommonId())
188                     .setConnectionType(input.getConnectionType());
189         } else {
190             nbiNotificationBuilder.setServiceName(notification.getServiceName());
191         }
192         nbiNotificationBuilder.setPublisherName(PUBLISHER);
193         return nbiNotificationBuilder.build();
194     }
195
196     /**
197      * Process cancel resource result.
198      */
199     private void onCancelResourceResult() {
200         if (servicePathRpcResult.getStatus() == RpcStatusEx.Pending) {
201             LOG.warn("PCE cancel returned a Pending RpcStatusEx code !");
202             return;
203         } else if (servicePathRpcResult.getStatus() != RpcStatusEx.Successful
204                 && servicePathRpcResult.getStatus() != RpcStatusEx.Failed) {
205             LOG.error("PCE cancel returned an unknown RpcStatusEx code !");
206             return;
207         }
208         Services service = serviceDataStoreOperations.getService(input.getServiceName()).get();
209         PublishNotificationProcessServiceBuilder nbiNotificationBuilder = new PublishNotificationProcessServiceBuilder()
210                 .setServiceName(service.getServiceName())
211                 .setServiceAEnd(new ServiceAEndBuilder(service.getServiceAEnd()).build())
212                 .setServiceZEnd(new ServiceZEndBuilder(service.getServiceZEnd()).build())
213                 .setCommonId(service.getCommonId())
214                 .setConnectionType(service.getConnectionType())
215                 .setPublisherName(PUBLISHER);
216         if (servicePathRpcResult.getStatus() == RpcStatusEx.Failed) {
217             LOG.info("PCE cancel resource failed !");
218             sendNbiNotification(nbiNotificationBuilder
219                     .setResponseFailed("PCE cancel resource failed !")
220                     .setMessage("ServiceDelete request failed ...")
221                     .setOperationalState(service.getOperationalState())
222                     .build());
223             return;
224         }
225         LOG.info("PCE cancel resource done OK !");
226         OperationResult deleteServicePathOperationResult =
227                 this.serviceDataStoreOperations.deleteServicePath(input.getServiceName());
228         if (!deleteServicePathOperationResult.isSuccess()) {
229             LOG.warn("Service path was not removed from datastore !");
230         }
231         OperationResult deleteServiceOperationResult;
232         String serviceType = "";
233         if (tempService) {
234             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteTempService(input.getServiceName());
235             serviceType = "Temp ";
236         } else {
237             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteService(input.getServiceName());
238         }
239         if (deleteServiceOperationResult.isSuccess()) {
240             sendNbiNotification(nbiNotificationBuilder
241                     .setResponseFailed("")
242                     .setMessage("Service deleted !")
243                     .setOperationalState(State.Degraded)
244                     .build());
245         } else {
246             LOG.warn("{}Service was not removed from datastore !", serviceType);
247             sendNbiNotification(nbiNotificationBuilder
248                     .setResponseFailed(serviceType + "Service was not removed from datastore !")
249                     .setMessage("ServiceDelete request failed ...")
250                     .setOperationalState(service.getOperationalState())
251                     .build());
252         }
253         /**
254          * if it was an RPC serviceReconfigure, re-launch PCR.
255          */
256         if (this.serviceReconfigure) {
257             LOG.info("cancel resource reserve done, relaunching PCE path computation ...");
258             this.pceServiceWrapper.performPCE(input.getServiceCreateInput(), true);
259             this.serviceReconfigure = false;
260         }
261     }
262
263     @SuppressFBWarnings(
264         value = "ES_COMPARING_STRINGS_WITH_EQ",
265         justification = "false positives, not strings but real object references comparisons")
266     private Boolean compareServicePathRpcResult(ServicePathRpcResult notification) {
267         if (servicePathRpcResult == null) {
268             return false;
269         }
270         if (servicePathRpcResult.getNotificationType() != notification.getNotificationType()) {
271             return false;
272         }
273         if (servicePathRpcResult.getServiceName() != notification.getServiceName()) {
274             return false;
275         }
276         if (servicePathRpcResult.getStatus() != notification.getStatus()) {
277             return false;
278         }
279         if (servicePathRpcResult.getStatusMessage() != notification.getStatusMessage()) {
280             return false;
281         }
282         return true;
283     }
284
285     public void setInput(ServiceInput serviceInput) {
286         this.input = serviceInput;
287     }
288
289     public void setServiceReconfigure(Boolean serv) {
290         this.serviceReconfigure = serv;
291     }
292
293     public void setserviceDataStoreOperations(ServiceDataStoreOperations serviceData) {
294         this.serviceDataStoreOperations = serviceData;
295     }
296
297     public void setTempService(Boolean tempService) {
298         this.tempService = tempService;
299     }
300
301     public void setServiceFeasiblity(Boolean serviceFeasiblity) {
302         this.serviceFeasiblity = serviceFeasiblity;
303     }
304
305     /**
306      * Send notification to NBI notification in order to publish message.
307      * @param service PublishNotificationService
308      */
309     private void sendNbiNotification(PublishNotificationProcessService service) {
310         try {
311             notificationPublishService.putNotification(service);
312         } catch (InterruptedException e) {
313             LOG.warn("Cannot send notification to nbi", e);
314             Thread.currentThread().interrupt();
315         }
316     }
317 }