Fix ConvertORToTapiTopology Upper/Lower Freq bug
[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.rev230728.PublishNotificationProcessService;
39 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230728.PublishNotificationProcessServiceBuilder;
40 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230728.notification.process.service.ServiceAEndBuilder;
41 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230728.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.rev230728.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.rev230728.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(
268             RendererRpcResultSp notification, ServiceNotificationTypes type) {
269         try {
270             ServiceRpcResultSh serviceHandlerNotification = new ServiceRpcResultShBuilder()
271                     .setAToZDirection(notification.getAToZDirection())
272                     .setZToADirection(notification.getZToADirection())
273                     .setServiceName(notification.getServiceName())
274                     .setStatus(notification.getStatus())
275                     .setStatusMessage(notification.getStatusMessage())
276                     .setNotificationType(type)
277                     .build();
278             LOG.debug("Service update in datastore OK, sending notification {}", serviceHandlerNotification);
279             notificationPublishService.putNotification(serviceHandlerNotification);
280         } catch (InterruptedException e) {
281             LOG.warn("Something went wrong while sending notification for service {}",
282                     serviceRpcResultSp.getServiceName(), e);
283             Thread.currentThread().interrupt();
284         }
285     }
286
287     private ServiceRpcResult sendServiceRpcResultNotification(
288             RendererRpcResultSp notification, ServiceNotificationTypes type) {
289         try {
290             ServiceRpcResult serviceRpcResult = new ServiceRpcResultBuilder()
291                     .setServiceName(notification.getServiceName())
292                     .setNotificationType(type)
293                     .setStatusMessage(notification.getStatusMessage())
294                     .setCommonId(notification.getCommonId())
295                     .setPathComputationResult(new PathComputationResultBuilder()
296                             .setAToZ(new AToZBuilder()
297                                             .setFrequency(notification
298                                                             .getAToZDirection()
299                                                             .getCentralFrequency())
300                                             .setWidth(notification
301                                                             .getAToZDirection()
302                                                             .getWidth())
303                                             // TODO: here the optical operational mode should be set
304                                             // A default value is set here
305                                             .setOpticalOperationalMode("OR-W-400G-oFEC-63.1Gbd")
306                                             // TODO: also set the GNSR, OSNR, power values
307                                             .build())
308                             .setZToA(new ZToABuilder()
309                                             .setFrequency(notification
310                                                             .getZToADirection()
311                                                             .getCentralFrequency())
312                                             .setWidth(notification
313                                                             .getZToADirection()
314                                                             .getWidth())
315                                             // TODO: here the optical operational mode should be set
316                                             // A default value is set here
317                                             .setOpticalOperationalMode("OR-W-400G-oFEC-63.1Gbd")
318                                             // TODO: also set the GNSR, OSNR, power values
319                                             .build())
320                             .build())
321                     .build();
322             LOG.info("Sending the notification for service-rpc-result {}", serviceRpcResult);
323             notificationPublishService.putNotification(serviceRpcResult);
324             return serviceRpcResult;
325         } catch (InterruptedException e) {
326             LOG.warn("Something went wrong while sending notification for service {}",
327                     serviceRpcResultSp.getServiceName(), e);
328             Thread.currentThread().interrupt();
329         }
330         return null;
331     }
332
333
334
335     /**
336      * Process failed service implementation for serviceName.
337      * @param serviceName String
338      */
339     private void onFailedServiceImplementation(String serviceName) {
340         LOG.error("Renderer implementation failed !");
341         Services service = serviceDataStoreOperations.getService(input.getServiceName()).orElseThrow();
342         sendNbiNotification(new PublishNotificationProcessServiceBuilder()
343                 .setServiceName(service.getServiceName())
344                 .setServiceAEnd(new ServiceAEndBuilder(service.getServiceAEnd()).build())
345                 .setServiceZEnd(new ServiceZEndBuilder(service.getServiceZEnd()).build())
346                 .setCommonId(service.getCommonId())
347                 .setConnectionType(service.getConnectionType())
348                 .setIsTempService(false)
349                 .setResponseFailed("Renderer implementation failed !")
350                 .setMessage("ServiceCreate request failed ...")
351                 .setOperationalState(service.getOperationalState())
352                 .setPublisherName(PUBLISHER)
353                 .build());
354         OperationResult deleteServicePathOperationResult =
355                 this.serviceDataStoreOperations.deleteServicePath(serviceName);
356         if (!deleteServicePathOperationResult.isSuccess()) {
357             LOG.warn("Service path was not removed from datastore!");
358         }
359         OperationResult deleteServiceOperationResult;
360         String serviceType = "";
361         if (tempService) {
362             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteTempService(serviceName);
363             serviceType = "Temp ";
364         } else {
365             deleteServiceOperationResult = this.serviceDataStoreOperations.deleteService(serviceName);
366         }
367         if (deleteServiceOperationResult.isSuccess()) {
368             LOG.warn("{}Service was not removed from datastore!", serviceType);
369         }
370     }
371
372     @SuppressFBWarnings(
373         value = "ES_COMPARING_STRINGS_WITH_EQ",
374         justification = "false positives, not strings but real object references comparisons")
375     private Boolean compareServiceRpcResultSp(RendererRpcResultSp notification) {
376         if (serviceRpcResultSp == null
377                 || serviceRpcResultSp.getNotificationType() != notification.getNotificationType()
378                 || serviceRpcResultSp.getServiceName() != notification.getServiceName()
379                 || serviceRpcResultSp.getStatus() != notification.getStatus()
380                 || serviceRpcResultSp.getStatusMessage() != notification.getStatusMessage()) {
381             return false;
382         }
383         return true;
384     }
385
386     @Override
387     public void setServiceInput(ServiceInput serviceInput) {
388         this.input = serviceInput;
389     }
390
391     @Override
392     public void setserviceDataStoreOperations(ServiceDataStoreOperations serviceData) {
393         this.serviceDataStoreOperations = serviceData;
394     }
395
396     @Override
397     public void setTempService(Boolean tempService) {
398         this.tempService = tempService;
399     }
400
401     /**
402      * Send notification to NBI notification in order to publish message.
403      * @param service PublishNotificationService
404      */
405     private void sendNbiNotification(PublishNotificationProcessService service) {
406         try {
407             notificationPublishService.putNotification(service);
408         } catch (InterruptedException e) {
409             LOG.warn("Cannot send notification to nbi", e);
410             Thread.currentThread().interrupt();
411         }
412     }
413
414
415     private void updateOtnTopology(RendererRpcResultSp notification, boolean isDeletion) {
416         Link link = notification.getLink();
417         if (link == null && notification.getLinkId() == null) {
418             return;
419         }
420         List<String> supportedLinkIds = null;
421         if (notification.getLinkId() != null) {
422             supportedLinkIds = new ArrayList<>(notification.getLinkId());
423         }
424         String serviceType = notification.getServiceType();
425         switch (serviceType) {
426             case StringConstants.SERVICE_TYPE_OTU4:
427             case StringConstants.SERVICE_TYPE_OTUC2:
428             case StringConstants.SERVICE_TYPE_OTUC3:
429             case StringConstants.SERVICE_TYPE_OTUC4:
430             case StringConstants.SERVICE_TYPE_ODU4:
431             case StringConstants.SERVICE_TYPE_ODUC2:
432             case StringConstants.SERVICE_TYPE_ODUC3:
433             case StringConstants.SERVICE_TYPE_ODUC4:
434                 Map<String, OtnLinkType> otnLinkTypeMap = Map.of(
435                     StringConstants.SERVICE_TYPE_OTU4, OtnLinkType.OTU4,
436                     // TODO: need to change it when OtnLinkType is updated with enum
437                     StringConstants.SERVICE_TYPE_OTUC2, OtnLinkType.OTUC4,
438                     StringConstants.SERVICE_TYPE_OTUC3, OtnLinkType.OTUC4,
439                     StringConstants.SERVICE_TYPE_OTUC4, OtnLinkType.OTUC4,
440                     StringConstants.SERVICE_TYPE_ODU4, OtnLinkType.ODTU4,
441                     // TODO: need to change it when OtnLinkType is updated with enum
442                     StringConstants.SERVICE_TYPE_ODUC2, OtnLinkType.ODUC4,
443                     StringConstants.SERVICE_TYPE_ODUC3, OtnLinkType.ODUC4,
444                     StringConstants.SERVICE_TYPE_ODUC4, OtnLinkType.ODUC4);
445                 if (isDeletion) {
446                     LOG.info("updating otn-topology removing links");
447                     this.networkModelService.deleteOtnLinks(link, supportedLinkIds, otnLinkTypeMap.get(serviceType));
448                 } else {
449                     LOG.info("updating otn-topology adding links");
450                     this.networkModelService.createOtnLinks(link, supportedLinkIds, otnLinkTypeMap.get(serviceType));
451                 }
452                 break;
453             case StringConstants.SERVICE_TYPE_1GE:
454             case StringConstants.SERVICE_TYPE_10GE:
455             case StringConstants.SERVICE_TYPE_100GE_M:
456                 Short tribPort = Short.valueOf(notification.getAToZDirection().getMinTribSlot().getValue()
457                     .split("\\.")[0]);
458                 Short minTribSlot = Short.valueOf(notification.getAToZDirection().getMinTribSlot().getValue()
459                     .split("\\.")[1]);
460                 Short maxTribSlot = Short.valueOf(notification.getAToZDirection().getMaxTribSlot().getValue()
461                     .split("\\.")[1]);
462                 LOG.info("updating otn-topology node tps -tps and tpn pools");
463                 this.networkModelService.updateOtnLinks(link, supportedLinkIds,
464                     notification.getAToZDirection().getRate(), tribPort, minTribSlot, maxTribSlot, isDeletion);
465                 break;
466             case StringConstants.SERVICE_TYPE_100GE_S:
467                 this.networkModelService.updateOtnLinks(supportedLinkIds, isDeletion);
468                 break;
469             default:
470                 LOG.warn("service-type {} not managed yet", serviceType);
471                 break;
472         }
473     }
474
475 }