2359412db3533f7db799f7613addc7930dcb37fc
[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.rev230726.PublishNotificationProcessService;
39 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230726.PublishNotificationProcessServiceBuilder;
40 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230726.notification.process.service.ServiceAEndBuilder;
41 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230726.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                         .setIsTempService(false)
124                         .setConnectionType(service.getConnectionType())
125                         .setResponseFailed("Renderer service delete failed !")
126                         .setMessage("ServiceDelete request failed ...")
127                         .setOperationalState(service.getOperationalState())
128                         .setPublisherName(PUBLISHER)
129                         .build());
130                 return;
131             case Pending:
132                 LOG.warn("Renderer service delete returned a Pending RpcStatusEx code!");
133                 return;
134             default:
135                 LOG.error("Renderer service delete returned an unknown RpcStatusEx code!");
136                 return;
137         }
138         LOG.info("Service '{}' deleted !", notification.getServiceName());
139         if (this.input == null) {
140             LOG.error("ServiceInput parameter is null !");
141             return;
142         }
143         LOG.info("sending PCE cancel resource reserve for '{}'", this.input.getServiceName());
144         this.pceServiceWrapper.cancelPCEResource(this.input.getServiceName(),
145                 ServiceNotificationTypes.ServiceDeleteResult);
146         sendServiceHandlerNotification(notification, ServiceNotificationTypes.ServiceDeleteResult);
147     }
148
149     /**
150      * Process service implementation result for serviceName.
151      * @param notification RendererRpcResultSp
152      */
153     private void onServiceImplementationResult(RendererRpcResultSp notification) {
154         switch (serviceRpcResultSp.getStatus()) {
155             case Successful:
156                 onSuccededServiceImplementation(notification);
157                 break;
158             case Failed:
159                 onFailedServiceImplementation(notification.getServiceName());
160                 break;
161             case Pending:
162                 LOG.warn("Service Implementation still pending according to RpcStatusEx");
163                 break;
164             default:
165                 LOG.warn("Service Implementation has an unknown RpcStatusEx code");
166                 break;
167         }
168     }
169
170     /**
171      * Process succeeded service implementation for service.
172      * @param notification RendererRpcResultSp
173      */
174     private void onSuccededServiceImplementation(RendererRpcResultSp notification) {
175         LOG.info("Service implemented !");
176         if (serviceDataStoreOperations == null) {
177             LOG.debug("serviceDataStoreOperations is null");
178             return;
179         }
180         updateOtnTopology(notification, false);
181         PublishNotificationProcessServiceBuilder nbiNotificationBuilder =
182             new PublishNotificationProcessServiceBuilder()
183                 .setServiceAEnd(new ServiceAEndBuilder(input.getServiceAEnd()).build())
184                 .setServiceZEnd(new ServiceZEndBuilder(input.getServiceZEnd()).build())
185                 .setPublisherName(PUBLISHER);
186         String serviceTemp = "";
187         if (tempService) {
188             nbiNotificationBuilder.setCommonId(input.getCommonId()).setConnectionType(input.getConnectionType());
189             nbiNotificationBuilder.setIsTempService(true);
190             if (input.getServiceName() != null) {
191                 nbiNotificationBuilder.setServiceName(input.getServiceName());
192             }
193             OperationResult operationResult = this.serviceDataStoreOperations.modifyTempService(
194                     serviceRpcResultSp.getServiceName(), State.InService, AdminStates.InService);
195             serviceTemp = "Temp ";
196             if (operationResult.isSuccess()) {
197                 ServiceRpcResult serviceRpcResult =
198                     sendServiceRpcResultNotification(notification, ServiceNotificationTypes.ServiceCreateResult);
199                 sendNbiNotification(nbiNotificationBuilder
200                     .setResponseFailed("")
201                     .setMessage("Temp Service implemented")
202                     .setAToZ(
203                         new org.opendaylight.yang.gen.v1.nbi.notifications.rev230726.notification.process.service
204                                 .AToZBuilder()
205                             .setFrequency(serviceRpcResult.getPathComputationResult().getAToZ().getFrequency())
206                             .setWidth(serviceRpcResult.getPathComputationResult().getAToZ().getWidth())
207                             .setOpticalOperationalMode(serviceRpcResult.getPathComputationResult()
208                                         .getAToZ().getOpticalOperationalMode())
209                             // TODO: add GNSR, OSNR, min/max output powers
210                             .build())
211                     .setZToA(
212                         new org.opendaylight.yang.gen.v1.nbi.notifications.rev230726.notification.process.service
213                                 .ZToABuilder()
214                             .setFrequency(serviceRpcResult.getPathComputationResult().getZToA().getFrequency())
215                             .setWidth(serviceRpcResult.getPathComputationResult().getZToA().getWidth())
216                             .setOpticalOperationalMode(serviceRpcResult.getPathComputationResult()
217                                         .getZToA().getOpticalOperationalMode())
218                             // TODO: add GNSR, OSNR, min/max output powers
219                             .build())
220                     .setOperationalState(State.InService)
221                     .build());
222                 LOG.debug("For the Temp service, sending notification on service-result-rpc");
223                 return;
224             }
225         } else {
226             // Here the service is implemented and the tempService has to be deleted if present
227             nbiNotificationBuilder.setServiceName(input.getServiceName()).setConnectionType(input.getConnectionType());
228             // Make sure temp-service is false
229             nbiNotificationBuilder.setIsTempService(false);
230             String commonId = input.getCommonId();
231             if (commonId != null) {
232                 nbiNotificationBuilder.setCommonId(commonId);
233                 if (this.serviceDataStoreOperations.getTempService(commonId).isPresent()) {
234                     LOG.info("Temp-service exists with the common-Id {}", commonId);
235                     // Delete the common-id from this temp-service-list here
236                     OperationResult tempServiceListDelete = serviceDataStoreOperations.deleteTempService(commonId);
237                     //TODO: Also need to delete the service-path from the transportpce-service-path list
238                     this.serviceDataStoreOperations.deleteServicePath(commonId);
239                     LOG.info("Result for temp-service-list with {} is {}", commonId, tempServiceListDelete);
240                 }
241             }
242             OperationResult operationResult = this.serviceDataStoreOperations.modifyService(
243                     serviceRpcResultSp.getServiceName(), State.InService, AdminStates.InService);
244             if (operationResult.isSuccess()) {
245                 sendNbiNotification(nbiNotificationBuilder
246                     .setResponseFailed("")
247                     .setMessage("Service implemented !")
248                     .setOperationalState(State.InService)
249                     .build());
250                 sendServiceHandlerNotification(notification, ServiceNotificationTypes.ServiceCreateResult);
251                 return;
252             }
253         }
254         LOG.warn("{}Service status not updated in datastore !", serviceTemp);
255         sendNbiNotification(nbiNotificationBuilder
256             .setResponseFailed(serviceTemp + "Service status not updated in datastore !")
257             .setMessage("ServiceCreate request failed ...")
258             .setOperationalState(State.OutOfService)
259             .build());
260     }
261
262     /**
263      * Create and send service handler notification.
264      * @param notification RendererRpcResultSp
265      * @param type ServiceNotificationTypes
266      */
267     private void sendServiceHandlerNotification(RendererRpcResultSp notification, ServiceNotificationTypes type) {
268         try {
269             ServiceRpcResultSh serviceHandlerNotification = new ServiceRpcResultShBuilder()
270                     .setAToZDirection(notification.getAToZDirection())
271                     .setZToADirection(notification.getZToADirection())
272                     .setServiceName(notification.getServiceName())
273                     .setStatus(notification.getStatus())
274                     .setStatusMessage(notification.getStatusMessage())
275                     .setNotificationType(type)
276                     .build();
277             LOG.debug("Service update in datastore OK, sending notification {}", serviceHandlerNotification);
278             notificationPublishService.putNotification(serviceHandlerNotification);
279         } catch (InterruptedException e) {
280             LOG.warn("Something went wrong while sending notification for service {}",
281                     serviceRpcResultSp.getServiceName(), e);
282             Thread.currentThread().interrupt();
283         }
284     }
285
286     private ServiceRpcResult sendServiceRpcResultNotification(
287             RendererRpcResultSp notification, ServiceNotificationTypes type) {
288         try {
289             ServiceRpcResult serviceRpcResult = new ServiceRpcResultBuilder()
290                     .setServiceName(notification.getServiceName())
291                     .setNotificationType(type)
292                     .setStatusMessage(notification.getStatusMessage())
293                     .setCommonId(notification.getCommonId())
294                     .setPathComputationResult(new PathComputationResultBuilder()
295                             .setAToZ(new AToZBuilder()
296                                             .setFrequency(notification
297                                                             .getAToZDirection()
298                                                             .getCentralFrequency())
299                                             .setWidth(notification
300                                                             .getAToZDirection()
301                                                             .getWidth())
302                                             // TODO: here the optical operational mode should be set
303                                             // A default value is set here
304                                             .setOpticalOperationalMode("OR-W-400G-oFEC-63.1Gbd")
305                                             // TODO: also set the GNSR, OSNR, power values
306                                             .build())
307                             .setZToA(new ZToABuilder()
308                                             .setFrequency(notification
309                                                             .getZToADirection()
310                                                             .getCentralFrequency())
311                                             .setWidth(notification
312                                                             .getZToADirection()
313                                                             .getWidth())
314                                             // TODO: here the optical operational mode should be set
315                                             // A default value is set here
316                                             .setOpticalOperationalMode("OR-W-400G-oFEC-63.1Gbd")
317                                             // TODO: also set the GNSR, OSNR, power values
318                                             .build())
319                             .build())
320                     .build();
321             LOG.info("Sending the notification for service-rpc-result {}", serviceRpcResult);
322             notificationPublishService.putNotification(serviceRpcResult);
323             return serviceRpcResult;
324         } catch (InterruptedException e) {
325             LOG.warn("Something went wrong while sending notification for service {}",
326                     serviceRpcResultSp.getServiceName(), e);
327             Thread.currentThread().interrupt();
328         }
329         return null;
330     }
331
332
333
334     /**
335      * Process failed service implementation for serviceName.
336      * @param serviceName String
337      */
338     private void onFailedServiceImplementation(String serviceName) {
339         LOG.error("Renderer implementation failed !");
340         Services service = serviceDataStoreOperations.getService(input.getServiceName()).orElseThrow();
341         sendNbiNotification(new PublishNotificationProcessServiceBuilder()
342                 .setServiceName(service.getServiceName())
343                 .setServiceAEnd(new ServiceAEndBuilder(service.getServiceAEnd()).build())
344                 .setServiceZEnd(new ServiceZEndBuilder(service.getServiceZEnd()).build())
345                 .setCommonId(service.getCommonId())
346                 .setConnectionType(service.getConnectionType())
347                 .setIsTempService(false)
348                 .setResponseFailed("Renderer implementation failed !")
349                 .setMessage("ServiceCreate request failed ...")
350                 .setOperationalState(service.getOperationalState())
351                 .setPublisherName(PUBLISHER)
352                 .build());
353         OperationResult deleteServicePathOperationResult =
354                 this.serviceDataStoreOperations.deleteServicePath(serviceName);
355         if (!deleteServicePathOperationResult.isSuccess()) {
356             LOG.warn("Service path was not removed from datastore!");
357         }
358         OperationResult deleteServiceOperationResult;
359         String serviceType = "";
360         if (tempService) {
361             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteTempService(serviceName);
362             serviceType = "Temp ";
363         } else {
364             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteService(serviceName);
365         }
366         if (deleteServiceOperationResult.isSuccess()) {
367             LOG.warn("{}Service was not removed from datastore!", serviceType);
368         }
369     }
370
371     @SuppressFBWarnings(
372         value = "ES_COMPARING_STRINGS_WITH_EQ",
373         justification = "false positives, not strings but real object references comparisons")
374     private Boolean compareServiceRpcResultSp(RendererRpcResultSp notification) {
375         if (serviceRpcResultSp == null
376                 || serviceRpcResultSp.getNotificationType() != notification.getNotificationType()
377                 || serviceRpcResultSp.getServiceName() != notification.getServiceName()
378                 || serviceRpcResultSp.getStatus() != notification.getStatus()
379                 || serviceRpcResultSp.getStatusMessage() != notification.getStatusMessage()) {
380             return false;
381         }
382         return true;
383     }
384
385     @Override
386     public void setServiceInput(ServiceInput serviceInput) {
387         this.input = serviceInput;
388     }
389
390     @Override
391     public void setserviceDataStoreOperations(ServiceDataStoreOperations serviceData) {
392         this.serviceDataStoreOperations = serviceData;
393     }
394
395     @Override
396     public void setTempService(Boolean tempService) {
397         this.tempService = tempService;
398     }
399
400     /**
401      * Send notification to NBI notification in order to publish message.
402      * @param service PublishNotificationService
403      */
404     private void sendNbiNotification(PublishNotificationProcessService service) {
405         try {
406             notificationPublishService.putNotification(service);
407         } catch (InterruptedException e) {
408             LOG.warn("Cannot send notification to nbi", e);
409             Thread.currentThread().interrupt();
410         }
411     }
412
413
414     private void updateOtnTopology(RendererRpcResultSp notification, boolean isDeletion) {
415         Link link = notification.getLink();
416         if (link == null && notification.getLinkId() == null) {
417             return;
418         }
419         List<String> supportedLinkIds = null;
420         if (notification.getLinkId() != null) {
421             supportedLinkIds = new ArrayList<>(notification.getLinkId());
422         }
423         String serviceType = notification.getServiceType();
424         switch (serviceType) {
425             case StringConstants.SERVICE_TYPE_OTU4:
426             case StringConstants.SERVICE_TYPE_OTUC2:
427             case StringConstants.SERVICE_TYPE_OTUC3:
428             case StringConstants.SERVICE_TYPE_OTUC4:
429             case StringConstants.SERVICE_TYPE_ODU4:
430             case StringConstants.SERVICE_TYPE_ODUC2:
431             case StringConstants.SERVICE_TYPE_ODUC3:
432             case StringConstants.SERVICE_TYPE_ODUC4:
433                 Map<String, OtnLinkType> otnLinkTypeMap = Map.of(
434                     StringConstants.SERVICE_TYPE_OTU4, OtnLinkType.OTU4,
435                     // TODO: need to change it when OtnLinkType is updated with enum
436                     StringConstants.SERVICE_TYPE_OTUC2, OtnLinkType.OTUC4,
437                     StringConstants.SERVICE_TYPE_OTUC3, OtnLinkType.OTUC4,
438                     StringConstants.SERVICE_TYPE_OTUC4, OtnLinkType.OTUC4,
439                     StringConstants.SERVICE_TYPE_ODU4, OtnLinkType.ODTU4,
440                     // TODO: need to change it when OtnLinkType is updated with enum
441                     StringConstants.SERVICE_TYPE_ODUC2, OtnLinkType.ODUC4,
442                     StringConstants.SERVICE_TYPE_ODUC3, OtnLinkType.ODUC4,
443                     StringConstants.SERVICE_TYPE_ODUC4, OtnLinkType.ODUC4);
444                 if (isDeletion) {
445                     LOG.info("updating otn-topology removing links");
446                     this.networkModelService.deleteOtnLinks(link, supportedLinkIds, otnLinkTypeMap.get(serviceType));
447                 } else {
448                     LOG.info("updating otn-topology adding links");
449                     this.networkModelService.createOtnLinks(link, supportedLinkIds, otnLinkTypeMap.get(serviceType));
450                 }
451                 break;
452             case StringConstants.SERVICE_TYPE_1GE:
453             case StringConstants.SERVICE_TYPE_10GE:
454             case StringConstants.SERVICE_TYPE_100GE_M:
455                 Short tribPort = Short.valueOf(notification.getAToZDirection().getMinTribSlot().getValue()
456                     .split("\\.")[0]);
457                 Short minTribSlot = Short.valueOf(notification.getAToZDirection().getMinTribSlot().getValue()
458                     .split("\\.")[1]);
459                 Short maxTribSlot = Short.valueOf(notification.getAToZDirection().getMaxTribSlot().getValue()
460                     .split("\\.")[1]);
461                 LOG.info("updating otn-topology node tps -tps and tpn pools");
462                 this.networkModelService.updateOtnLinks(link, supportedLinkIds,
463                     notification.getAToZDirection().getRate(), tribPort, minTribSlot, maxTribSlot, isDeletion);
464                 break;
465             case StringConstants.SERVICE_TYPE_100GE_S:
466                 this.networkModelService.updateOtnLinks(supportedLinkIds, isDeletion);
467                 break;
468             default:
469                 LOG.warn("service-type {} not managed yet", serviceType);
470                 break;
471         }
472     }
473
474 }