Fix the misplacements of service notifications
[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.rev200128.PathComputationRequestOutput;
20 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.PathComputationRequestOutputBuilder;
21 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.ServicePathRpcResult;
22 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.TransportpcePceListener;
23 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.service.path.rpc.result.PathDescription;
24 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.service.path.rpc.result.PathDescriptionBuilder;
25 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.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.rev201130.PublishNotificationService;
32 import org.opendaylight.yang.gen.v1.nbi.notifications.rev201130.PublishNotificationServiceBuilder;
33 import org.opendaylight.yang.gen.v1.nbi.notifications.rev201130.notification.service.ServiceAEndBuilder;
34 import org.opendaylight.yang.gen.v1.nbi.notifications.rev201130.notification.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 TOPIC = "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         PublishNotificationService nbiNotification = getPublishNotificationService(notification);
151         PublishNotificationServiceBuilder publishNotificationServiceBuilder = new PublishNotificationServiceBuilder(
152                 nbiNotification);
153         switch (servicePathRpcResult.getStatus()) {
154             case Failed:
155                 LOG.error("PCE path computation failed !");
156                 nbiNotification = publishNotificationServiceBuilder.setMessage("ServiceCreate request failed ...")
157                         .setResponseFailed("PCE path computation failed !")
158                         .setOperationalState(State.Degraded).build();
159                 sendNbiNotification(nbiNotification);
160                 return false;
161             case Pending:
162                 LOG.warn("PCE path computation returned a Pending RpcStatusEx code!");
163                 return false;
164             case Successful:
165                 LOG.info("PCE calculation done OK !");
166                 nbiNotification = publishNotificationServiceBuilder.setMessage("PCE calculation done OK !")
167                         .setResponseFailed("").setOperationalState(State.OutOfService).build();
168                 sendNbiNotification(nbiNotification);
169                 return true;
170             default:
171                 LOG.error("PCE path computation returned an unknown RpcStatusEx code {}",
172                         servicePathRpcResult.getStatus());
173                 nbiNotification = publishNotificationServiceBuilder.setMessage("ServiceCreate request failed ...")
174                         .setResponseFailed("PCE path computation returned an unknown RpcStatusEx code!")
175                         .setOperationalState(State.Degraded).build();
176                 sendNbiNotification(nbiNotification);
177                 return false;
178         }
179     }
180
181     private PublishNotificationService getPublishNotificationService(ServicePathRpcResult notification) {
182         PublishNotificationServiceBuilder nbiNotificationBuilder = new PublishNotificationServiceBuilder();
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()).setConnectionType(input.getConnectionType());
188         } else {
189             nbiNotificationBuilder.setServiceName(notification.getServiceName());
190         }
191         nbiNotificationBuilder.setTopic(TOPIC);
192         return nbiNotificationBuilder.build();
193     }
194
195     /**
196      * Process cancel resource result.
197      */
198     private void onCancelResourceResult() {
199         if (servicePathRpcResult.getStatus() == RpcStatusEx.Pending) {
200             LOG.warn("PCE cancel returned a Pending RpcStatusEx code !");
201             return;
202         } else if (servicePathRpcResult.getStatus() != RpcStatusEx.Successful
203                 && servicePathRpcResult.getStatus() != RpcStatusEx.Failed) {
204             LOG.error("PCE cancel returned an unknown RpcStatusEx code !");
205             return;
206         }
207         Services service = serviceDataStoreOperations.getService(input.getServiceName()).get();
208         PublishNotificationServiceBuilder nbiNotificationBuilder = new PublishNotificationServiceBuilder()
209                 .setServiceName(service.getServiceName())
210                 .setServiceAEnd(new ServiceAEndBuilder(service.getServiceAEnd()).build())
211                 .setServiceZEnd(new ServiceZEndBuilder(service.getServiceZEnd()).build())
212                 .setCommonId(service.getCommonId())
213                 .setConnectionType(service.getConnectionType())
214                 .setTopic(TOPIC);
215         if (servicePathRpcResult.getStatus() == RpcStatusEx.Failed) {
216             LOG.info("PCE cancel resource failed !");
217             sendNbiNotification(nbiNotificationBuilder
218                     .setResponseFailed("PCE cancel resource failed !")
219                     .setMessage("ServiceDelete request failed ...")
220                     .setOperationalState(service.getOperationalState())
221                     .build());
222             return;
223         }
224         LOG.info("PCE cancel resource done OK !");
225         OperationResult deleteServicePathOperationResult =
226                 this.serviceDataStoreOperations.deleteServicePath(input.getServiceName());
227         if (!deleteServicePathOperationResult.isSuccess()) {
228             LOG.warn("Service path was not removed from datastore !");
229         }
230         OperationResult deleteServiceOperationResult;
231         String serviceType = "";
232         if (tempService) {
233             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteTempService(input.getServiceName());
234             serviceType = "Temp ";
235         } else {
236             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteService(input.getServiceName());
237         }
238         if (deleteServiceOperationResult.isSuccess()) {
239             sendNbiNotification(nbiNotificationBuilder
240                     .setResponseFailed("")
241                     .setMessage("Service deleted !")
242                     .setOperationalState(State.Degraded)
243                     .build());
244         } else {
245             LOG.warn("{}Service was not removed from datastore !", serviceType);
246             sendNbiNotification(nbiNotificationBuilder
247                     .setResponseFailed(serviceType + "Service was not removed from datastore !")
248                     .setMessage("ServiceDelete request failed ...")
249                     .setOperationalState(service.getOperationalState())
250                     .build());
251         }
252         /**
253          * if it was an RPC serviceReconfigure, re-launch PCR.
254          */
255         if (this.serviceReconfigure) {
256             LOG.info("cancel resource reserve done, relaunching PCE path computation ...");
257             this.pceServiceWrapper.performPCE(input.getServiceCreateInput(), true);
258             this.serviceReconfigure = false;
259         }
260     }
261
262     @SuppressFBWarnings(
263         value = "ES_COMPARING_STRINGS_WITH_EQ",
264         justification = "false positives, not strings but real object references comparisons")
265     private Boolean compareServicePathRpcResult(ServicePathRpcResult notification) {
266         if (servicePathRpcResult == null) {
267             return false;
268         }
269         if (servicePathRpcResult.getNotificationType() != notification.getNotificationType()) {
270             return false;
271         }
272         if (servicePathRpcResult.getServiceName() != notification.getServiceName()) {
273             return false;
274         }
275         if (servicePathRpcResult.getStatus() != notification.getStatus()) {
276             return false;
277         }
278         if (servicePathRpcResult.getStatusMessage() != notification.getStatusMessage()) {
279             return false;
280         }
281         return true;
282     }
283
284     public void setInput(ServiceInput serviceInput) {
285         this.input = serviceInput;
286     }
287
288     public void setServiceReconfigure(Boolean serv) {
289         this.serviceReconfigure = serv;
290     }
291
292     public void setserviceDataStoreOperations(ServiceDataStoreOperations serviceData) {
293         this.serviceDataStoreOperations = serviceData;
294     }
295
296     public void setTempService(Boolean tempService) {
297         this.tempService = tempService;
298     }
299
300     public void setServiceFeasiblity(Boolean serviceFeasiblity) {
301         this.serviceFeasiblity = serviceFeasiblity;
302     }
303
304     /**
305      * Send notification to NBI notification in order to publish message.
306      * @param service PublishNotificationService
307      */
308     private void sendNbiNotification(PublishNotificationService service) {
309         try {
310             notificationPublishService.putNotification(service);
311         } catch (InterruptedException e) {
312             LOG.warn("Cannot send notification to nbi", e);
313             Thread.currentThread().interrupt();
314         }
315     }
316 }