4bf6d11dd5672da281c3d2534e6c93017f125a8f
[transportpce.git] / servicehandler / src / main / java / org / opendaylight / transportpce / servicehandler / listeners / RendererNotificationHandler.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 java.util.ArrayList;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Set;
15 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
16 import org.opendaylight.mdsal.binding.api.NotificationService.CompositeListener;
17 import org.opendaylight.transportpce.common.OperationResult;
18 import org.opendaylight.transportpce.common.StringConstants;
19 import org.opendaylight.transportpce.networkmodel.service.NetworkModelService;
20 import org.opendaylight.transportpce.pce.service.PathComputationService;
21 import org.opendaylight.transportpce.servicehandler.ServiceInput;
22 import org.opendaylight.transportpce.servicehandler.service.PCEServiceWrapper;
23 import org.opendaylight.transportpce.servicehandler.service.ServiceDataStoreOperations;
24 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.networkutils.rev220630.OtnLinkType;
25 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev210915.RendererRpcResultSp;
26 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev210915.renderer.rpc.result.sp.Link;
27 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.servicehandler.rev201125.ServiceRpcResultSh;
28 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.servicehandler.rev201125.ServiceRpcResultShBuilder;
29 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.service.types.rev230526.ServiceNotificationTypes;
30 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev191129.State;
31 import org.opendaylight.yang.gen.v1.http.org.openroadm.equipment.states.types.rev191129.AdminStates;
32 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev230526.ServiceRpcResult;
33 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev230526.ServiceRpcResultBuilder;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev230526.service.list.Services;
35 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev230526.service.rpc.result.PathComputationResultBuilder;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev230526.service.rpc.result.path.computation.result.AToZBuilder;
37 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev230526.service.rpc.result.path.computation.result.ZToABuilder;
38 import org.opendaylight.yang.gen.v1.nbi.notifications.rev211013.PublishNotificationProcessService;
39 import org.opendaylight.yang.gen.v1.nbi.notifications.rev211013.PublishNotificationProcessServiceBuilder;
40 import org.opendaylight.yang.gen.v1.nbi.notifications.rev211013.notification.process.service.ServiceAEndBuilder;
41 import org.opendaylight.yang.gen.v1.nbi.notifications.rev211013.notification.process.service.ServiceZEndBuilder;
42 import org.osgi.service.component.annotations.Activate;
43 import org.osgi.service.component.annotations.Component;
44 import org.osgi.service.component.annotations.Reference;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Calls to listen to Renderer notifications.
50  *
51  * @author Martial Coulibaly ( martial.coulibaly@gfi.com ) on behalf of Orange
52  *
53  */
54 @Component(service = {RendererNotificationHandler.class, RendererListener.class})
55 public class RendererNotificationHandler implements RendererListener {
56
57     private static final String PUBLISHER = "RendererListener";
58     private static final Logger LOG = LoggerFactory.getLogger(RendererNotificationHandler.class);
59     private RendererRpcResultSp serviceRpcResultSp;
60     private ServiceDataStoreOperations serviceDataStoreOperations;
61     private ServiceInput input;
62     private PCEServiceWrapper pceServiceWrapper;
63     private Boolean tempService;
64     private NotificationPublishService notificationPublishService;
65     private final NetworkModelService networkModelService;
66
67     @Activate
68     public RendererNotificationHandler(@Reference PathComputationService pathComputationService,
69             @Reference NotificationPublishService notificationPublishService,
70             @Reference NetworkModelService networkModelService) {
71         this.pceServiceWrapper = new PCEServiceWrapper(pathComputationService, notificationPublishService);
72         setServiceInput(null);
73         setTempService(false);
74         this.notificationPublishService = notificationPublishService;
75         this.networkModelService = networkModelService;
76     }
77
78     public CompositeListener getCompositeListener() {
79         return new CompositeListener(Set.of(
80             new CompositeListener.Component<>(RendererRpcResultSp.class, this::onRendererRpcResultSp)));
81     }
82
83     private void onRendererRpcResultSp(RendererRpcResultSp notification) {
84         if (compareServiceRpcResultSp(notification)) {
85             LOG.warn("ServiceRpcResultSp already wired !");
86             return;
87         }
88         serviceRpcResultSp = notification;
89         int notifType = serviceRpcResultSp.getNotificationType().getIntValue();
90         LOG.info("Renderer '{}' Notification received : {}", serviceRpcResultSp.getNotificationType().getName(),
91                 notification);
92         switch (notifType) {
93             /* service-implementation-request. */
94             case 3:
95                 onServiceImplementationResult(notification);
96                 break;
97             /* service-delete. */
98             case 4:
99                 onServiceDeleteResult(notification);
100                 break;
101             default:
102                 break;
103         }
104     }
105
106     /**
107      * Process service delete result for serviceName.
108      * @param notification RendererRpcResultSp
109      */
110     private void onServiceDeleteResult(RendererRpcResultSp notification) {
111         switch (serviceRpcResultSp.getStatus()) {
112             case Successful:
113                 updateOtnTopology(notification, true);
114                 break;
115             case Failed:
116                 LOG.error("Renderer service delete failed !");
117                 Services service = serviceDataStoreOperations.getService(input.getServiceName()).orElseThrow();
118                 sendNbiNotification(new PublishNotificationProcessServiceBuilder()
119                         .setServiceName(service.getServiceName())
120                         .setServiceAEnd(new ServiceAEndBuilder(service.getServiceAEnd()).build())
121                         .setServiceZEnd(new ServiceZEndBuilder(service.getServiceZEnd()).build())
122                         .setCommonId(service.getCommonId())
123                         .setConnectionType(service.getConnectionType())
124                         .setResponseFailed("Renderer service delete failed !")
125                         .setMessage("ServiceDelete request failed ...")
126                         .setOperationalState(service.getOperationalState())
127                         .setPublisherName(PUBLISHER)
128                         .build());
129                 return;
130             case Pending:
131                 LOG.warn("Renderer service delete returned a Pending RpcStatusEx code!");
132                 return;
133             default:
134                 LOG.error("Renderer service delete returned an unknown RpcStatusEx code!");
135                 return;
136         }
137         LOG.info("Service '{}' deleted !", notification.getServiceName());
138         if (this.input == null) {
139             LOG.error("ServiceInput parameter is null !");
140             return;
141         }
142         LOG.info("sending PCE cancel resource reserve for '{}'", this.input.getServiceName());
143         this.pceServiceWrapper.cancelPCEResource(this.input.getServiceName(),
144                 ServiceNotificationTypes.ServiceDeleteResult);
145         sendServiceHandlerNotification(notification, ServiceNotificationTypes.ServiceDeleteResult);
146     }
147
148     /**
149      * Process service implementation result for serviceName.
150      * @param notification RendererRpcResultSp
151      */
152     private void onServiceImplementationResult(RendererRpcResultSp notification) {
153         switch (serviceRpcResultSp.getStatus()) {
154             case Successful:
155                 onSuccededServiceImplementation(notification);
156                 break;
157             case Failed:
158                 onFailedServiceImplementation(notification.getServiceName());
159                 break;
160             case Pending:
161                 LOG.warn("Service Implementation still pending according to RpcStatusEx");
162                 break;
163             default:
164                 LOG.warn("Service Implementation has an unknown RpcStatusEx code");
165                 break;
166         }
167     }
168
169     /**
170      * Process succeeded service implementation for service.
171      * @param notification RendererRpcResultSp
172      */
173     private void onSuccededServiceImplementation(RendererRpcResultSp notification) {
174         LOG.info("Service implemented !");
175         if (serviceDataStoreOperations == null) {
176             LOG.debug("serviceDataStoreOperations is null");
177             return;
178         }
179         updateOtnTopology(notification, false);
180         PublishNotificationProcessServiceBuilder nbiNotificationBuilder =
181             new PublishNotificationProcessServiceBuilder()
182                 .setServiceName(input.getServiceName())
183                 .setServiceAEnd(new ServiceAEndBuilder(input.getServiceAEnd()).build())
184                 .setServiceZEnd(new ServiceZEndBuilder(input.getServiceZEnd()).build())
185                 .setCommonId(input.getCommonId()).setConnectionType(input.getConnectionType())
186                 .setPublisherName(PUBLISHER);
187         String serviceTemp = "";
188         if (tempService) {
189             OperationResult operationResult = this.serviceDataStoreOperations.modifyTempService(
190                     serviceRpcResultSp.getServiceName(), State.InService, AdminStates.InService);
191             serviceTemp = "Temp ";
192             if (operationResult.isSuccess()) {
193                 sendNbiNotification(nbiNotificationBuilder
194                     .setResponseFailed("")
195                     .setMessage("Temp Service implemented !")
196                     .setOperationalState(State.InService)
197                     .build());
198                 LOG.debug("For the Temp service, sending notification on service-result-rpc");
199                 sendServiceRpcResultNotification(notification, ServiceNotificationTypes.ServiceCreateResult);
200                 return;
201             }
202         } else {
203             OperationResult operationResult = this.serviceDataStoreOperations.modifyService(
204                     serviceRpcResultSp.getServiceName(), State.InService, AdminStates.InService);
205             // Here the service is implemented and the tempService has to be deleted if present
206             String commonId = input.getCommonId();
207             if (commonId != null) {
208                 if (this.serviceDataStoreOperations.getTempService(commonId).isPresent()) {
209                     LOG.info("Temp-service exists with the common-Id {}", commonId);
210                     // Delete the common-id from this temp-service-list here
211                     OperationResult tempServiceListDelete = serviceDataStoreOperations.deleteTempService(commonId);
212                     //TODO: Also need to delete the service-path from the transportpce-service-path list
213                     this.serviceDataStoreOperations.deleteServicePath(commonId);
214                     LOG.info("Result for temp-service-list with {} is {}", commonId, tempServiceListDelete);
215                 }
216             }
217
218             if (operationResult.isSuccess()) {
219                 sendNbiNotification(nbiNotificationBuilder
220                     .setResponseFailed("")
221                     .setMessage("Service implemented !")
222                     .setOperationalState(State.InService)
223                     .build());
224                 sendServiceHandlerNotification(notification, ServiceNotificationTypes.ServiceCreateResult);
225                 return;
226             }
227         }
228         LOG.warn("{}Service status not updated in datastore !", serviceTemp);
229         sendNbiNotification(nbiNotificationBuilder
230             .setResponseFailed(serviceTemp + "Service status not updated in datastore !")
231             .setMessage("ServiceCreate request failed ...")
232             .setOperationalState(State.OutOfService)
233             .build());
234     }
235
236     /**
237      * Create and send service handler notification.
238      * @param notification RendererRpcResultSp
239      * @param type ServiceNotificationTypes
240      */
241     private void sendServiceHandlerNotification(RendererRpcResultSp notification, ServiceNotificationTypes type) {
242         try {
243             ServiceRpcResultSh serviceHandlerNotification = new ServiceRpcResultShBuilder()
244                     .setAToZDirection(notification.getAToZDirection())
245                     .setZToADirection(notification.getZToADirection())
246                     .setServiceName(notification.getServiceName())
247                     .setStatus(notification.getStatus())
248                     .setStatusMessage(notification.getStatusMessage())
249                     .setNotificationType(type)
250                     .build();
251             LOG.debug("Service update in datastore OK, sending notification {}", serviceHandlerNotification);
252             notificationPublishService.putNotification(
253                     serviceHandlerNotification);
254         } catch (InterruptedException e) {
255             LOG.warn("Something went wrong while sending notification for service {}",
256                     serviceRpcResultSp.getServiceName(), e);
257             Thread.currentThread().interrupt();
258         }
259     }
260
261     private void sendServiceRpcResultNotification(RendererRpcResultSp notification, ServiceNotificationTypes type) {
262         try {
263             ServiceRpcResult serviceRpcResult = new ServiceRpcResultBuilder()
264                     .setServiceName(notification.getServiceName())
265                     .setNotificationType(type)
266                     .setStatusMessage(notification.getStatusMessage())
267                     .setCommonId(notification.getCommonId())
268                     .setPathComputationResult(new PathComputationResultBuilder()
269                             .setAToZ(new AToZBuilder()
270                                             .setFrequency(notification
271                                                             .getAToZDirection()
272                                                             .getCentralFrequency())
273                                             .setWidth(notification
274                                                             .getAToZDirection()
275                                                             .getWidth())
276                                             // TODO: here the optical operational mode should be set
277                                             // TODO: also set the GNSR, OSNR, power values
278                                             .setOpticalOperationalMode("test")
279                                             .build())
280                             .setZToA(new ZToABuilder()
281                                             .setFrequency(notification
282                                                             .getZToADirection()
283                                                             .getCentralFrequency())
284                                             .setWidth(notification
285                                                             .getZToADirection()
286                                                             .getWidth())
287                                             // TODO: here the optical operational mode should be set
288                                             // TODO: also set the GNSR, OSNR, power values
289                                             .setOpticalOperationalMode("test")
290                                             .build())
291                             .build())
292                     .build();
293             LOG.info("Sending the notification for service-rpc-result {}", serviceRpcResult);
294             notificationPublishService.putNotification(
295                     serviceRpcResult);
296         } catch (InterruptedException e) {
297             LOG.warn("Something went wrong while sending notification for service {}",
298                     serviceRpcResultSp.getServiceName(), e);
299             Thread.currentThread().interrupt();
300         }
301     }
302
303
304
305     /**
306      * Process failed service implementation for serviceName.
307      * @param serviceName String
308      */
309     private void onFailedServiceImplementation(String serviceName) {
310         LOG.error("Renderer implementation failed !");
311         Services service = serviceDataStoreOperations.getService(input.getServiceName()).orElseThrow();
312         sendNbiNotification(new PublishNotificationProcessServiceBuilder()
313                 .setServiceName(service.getServiceName())
314                 .setServiceAEnd(new ServiceAEndBuilder(service.getServiceAEnd()).build())
315                 .setServiceZEnd(new ServiceZEndBuilder(service.getServiceZEnd()).build())
316                 .setCommonId(service.getCommonId())
317                 .setConnectionType(service.getConnectionType())
318                 .setResponseFailed("Renderer implementation failed !")
319                 .setMessage("ServiceCreate request failed ...")
320                 .setOperationalState(service.getOperationalState())
321                 .setPublisherName(PUBLISHER)
322                 .build());
323         OperationResult deleteServicePathOperationResult =
324                 this.serviceDataStoreOperations.deleteServicePath(serviceName);
325         if (!deleteServicePathOperationResult.isSuccess()) {
326             LOG.warn("Service path was not removed from datastore!");
327         }
328         OperationResult deleteServiceOperationResult;
329         String serviceType = "";
330         if (tempService) {
331             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteTempService(serviceName);
332             serviceType = "Temp ";
333         } else {
334             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteService(serviceName);
335         }
336         if (deleteServiceOperationResult.isSuccess()) {
337             LOG.warn("{}Service was not removed from datastore!", serviceType);
338         }
339     }
340
341     @SuppressFBWarnings(
342         value = "ES_COMPARING_STRINGS_WITH_EQ",
343         justification = "false positives, not strings but real object references comparisons")
344     private Boolean compareServiceRpcResultSp(RendererRpcResultSp notification) {
345         if (serviceRpcResultSp == null
346                 || serviceRpcResultSp.getNotificationType() != notification.getNotificationType()
347                 || serviceRpcResultSp.getServiceName() != notification.getServiceName()
348                 || serviceRpcResultSp.getStatus() != notification.getStatus()
349                 || serviceRpcResultSp.getStatusMessage() != notification.getStatusMessage()) {
350             return false;
351         }
352         return true;
353     }
354
355     @Override
356     public void setServiceInput(ServiceInput serviceInput) {
357         this.input = serviceInput;
358     }
359
360     @Override
361     public void setserviceDataStoreOperations(ServiceDataStoreOperations serviceData) {
362         this.serviceDataStoreOperations = serviceData;
363     }
364
365     @Override
366     public void setTempService(Boolean tempService) {
367         this.tempService = tempService;
368     }
369
370     /**
371      * Send notification to NBI notification in order to publish message.
372      * @param service PublishNotificationService
373      */
374     private void sendNbiNotification(PublishNotificationProcessService service) {
375         try {
376             notificationPublishService.putNotification(service);
377         } catch (InterruptedException e) {
378             LOG.warn("Cannot send notification to nbi", e);
379             Thread.currentThread().interrupt();
380         }
381     }
382
383
384     private void updateOtnTopology(RendererRpcResultSp notification, boolean isDeletion) {
385         Link link = notification.getLink();
386         if (link == null && notification.getLinkId() == null) {
387             return;
388         }
389         List<String> supportedLinkIds = null;
390         if (notification.getLinkId() != null) {
391             supportedLinkIds = new ArrayList<>(notification.getLinkId());
392         }
393         String serviceType = notification.getServiceType();
394         switch (serviceType) {
395             case StringConstants.SERVICE_TYPE_OTU4:
396             case StringConstants.SERVICE_TYPE_OTUC2:
397             case StringConstants.SERVICE_TYPE_OTUC3:
398             case StringConstants.SERVICE_TYPE_OTUC4:
399             case StringConstants.SERVICE_TYPE_ODU4:
400             case StringConstants.SERVICE_TYPE_ODUC2:
401             case StringConstants.SERVICE_TYPE_ODUC3:
402             case StringConstants.SERVICE_TYPE_ODUC4:
403                 Map<String, OtnLinkType> otnLinkTypeMap = Map.of(
404                     StringConstants.SERVICE_TYPE_OTU4, OtnLinkType.OTU4,
405                     // TODO: need to change it when OtnLinkType is updated with enum
406                     StringConstants.SERVICE_TYPE_OTUC2, OtnLinkType.OTUC4,
407                     StringConstants.SERVICE_TYPE_OTUC3, OtnLinkType.OTUC4,
408                     StringConstants.SERVICE_TYPE_OTUC4, OtnLinkType.OTUC4,
409                     StringConstants.SERVICE_TYPE_ODU4, OtnLinkType.ODTU4,
410                     // TODO: need to change it when OtnLinkType is updated with enum
411                     StringConstants.SERVICE_TYPE_ODUC2, OtnLinkType.ODUC4,
412                     StringConstants.SERVICE_TYPE_ODUC3, OtnLinkType.ODUC4,
413                     StringConstants.SERVICE_TYPE_ODUC4, OtnLinkType.ODUC4);
414                 if (isDeletion) {
415                     LOG.info("updating otn-topology removing links");
416                     this.networkModelService.deleteOtnLinks(link, supportedLinkIds, otnLinkTypeMap.get(serviceType));
417                 } else {
418                     LOG.info("updating otn-topology adding links");
419                     this.networkModelService.createOtnLinks(link, supportedLinkIds, otnLinkTypeMap.get(serviceType));
420                 }
421                 break;
422             case StringConstants.SERVICE_TYPE_1GE:
423             case StringConstants.SERVICE_TYPE_10GE:
424             case StringConstants.SERVICE_TYPE_100GE_M:
425                 Short tribPort = Short.valueOf(notification.getAToZDirection().getMinTribSlot().getValue()
426                     .split("\\.")[0]);
427                 Short minTribSlot = Short.valueOf(notification.getAToZDirection().getMinTribSlot().getValue()
428                     .split("\\.")[1]);
429                 Short maxTribSlot = Short.valueOf(notification.getAToZDirection().getMaxTribSlot().getValue()
430                     .split("\\.")[1]);
431                 LOG.info("updating otn-topology node tps -tps and tpn pools");
432                 this.networkModelService.updateOtnLinks(link, supportedLinkIds,
433                     notification.getAToZDirection().getRate(), tribPort, minTribSlot, maxTribSlot, isDeletion);
434                 break;
435             case StringConstants.SERVICE_TYPE_100GE_S:
436                 this.networkModelService.updateOtnLinks(supportedLinkIds, isDeletion);
437                 break;
438             default:
439                 LOG.warn("service-type {} not managed yet", serviceType);
440                 break;
441         }
442     }
443
444 }