Update path description with OpucnTribSlots
[transportpce.git] / renderer / src / main / java / org / opendaylight / transportpce / renderer / provisiondevice / RendererServiceOperationsImpl.java
1 /*
2  * Copyright © 2017 AT&T 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.renderer.provisiondevice;
9
10 import com.google.common.util.concurrent.Futures;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import com.google.common.util.concurrent.ListeningExecutorService;
13 import com.google.common.util.concurrent.MoreExecutors;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Optional;
17 import java.util.concurrent.Callable;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Executors;
20 import java.util.concurrent.Future;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
23 import org.opendaylight.mdsal.binding.api.DataBroker;
24 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
25 import org.opendaylight.mdsal.binding.api.ReadTransaction;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.transportpce.common.ResponseCodes;
28 import org.opendaylight.transportpce.common.StringConstants;
29 import org.opendaylight.transportpce.common.Timeouts;
30 import org.opendaylight.transportpce.renderer.ModelMappingUtils;
31 import org.opendaylight.transportpce.renderer.ServicePathInputData;
32 import org.opendaylight.transportpce.renderer.provisiondevice.servicepath.ServicePathDirection;
33 import org.opendaylight.transportpce.renderer.provisiondevice.tasks.DeviceRenderingRollbackTask;
34 import org.opendaylight.transportpce.renderer.provisiondevice.tasks.DeviceRenderingTask;
35 import org.opendaylight.transportpce.renderer.provisiondevice.tasks.OlmPowerSetupRollbackTask;
36 import org.opendaylight.transportpce.renderer.provisiondevice.tasks.OlmPowerSetupTask;
37 import org.opendaylight.transportpce.renderer.provisiondevice.tasks.OtnDeviceRenderingTask;
38 import org.opendaylight.transportpce.renderer.provisiondevice.tasks.RollbackProcessor;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev200128.OtnServicePathInput;
40 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev200128.OtnServicePathOutput;
41 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.GetPmInputBuilder;
42 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.GetPmOutput;
43 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.ServicePowerSetupInput;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.ServicePowerTurndownInputBuilder;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.ServicePowerTurndownOutput;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.TransportpceOlmService;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.get.pm.output.Measurements;
48 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.RendererRpcResultSp;
49 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.RendererRpcResultSpBuilder;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.ServiceDeleteInput;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.ServiceDeleteOutput;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.ServiceImplementationRequestInput;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.renderer.rev201125.ServiceImplementationRequestOutput;
54 import org.opendaylight.yang.gen.v1.http.org.openroadm.otn.common.types.rev200327.ODU4;
55 import org.opendaylight.yang.gen.v1.http.org.openroadm.otn.common.types.rev200327.ODUCn;
56 import org.opendaylight.yang.gen.v1.http.org.openroadm.otn.common.types.rev200327.OTU4;
57 import org.opendaylight.yang.gen.v1.http.org.openroadm.otn.common.types.rev200327.OTUCn;
58 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.types.rev161014.PmGranularity;
59 import org.opendaylight.yang.gen.v1.http.org.openroadm.resource.types.rev161014.ResourceTypeEnum;
60 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.format.rev190531.ServiceFormat;
61 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev190531.service.list.Services;
62 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.PathDescription;
63 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128.RpcStatusEx;
64 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128.ServicePathNotificationTypes;
65 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.ServicePathList;
66 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.service.path.list.ServicePaths;
67 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.service.path.list.ServicePathsKey;
68 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev201211.olm.get.pm.input.ResourceIdentifierBuilder;
69 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev201211.olm.renderer.input.Nodes;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
71 import org.opendaylight.yangtools.yang.binding.Notification;
72 import org.opendaylight.yangtools.yang.common.RpcResult;
73 import org.opendaylight.yangtools.yang.common.Uint32;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77
78 public class RendererServiceOperationsImpl implements RendererServiceOperations {
79
80     private static final String DEVICE_RENDERING_ROLL_BACK_MSG =
81             "Device rendering was not successful! Rendering will be rolled back.";
82     private static final String OLM_ROLL_BACK_MSG =
83             "OLM power setup was not successful! Rendering and OLM will be rolled back.";
84     private static final String RENDERING_DEVICES_A_Z_MSG = "Rendering devices A-Z";
85     private static final String RENDERING_DEVICES_Z_A_MSG = "Rendering device Z-A";
86     private static final String TURNING_DOWN_POWER_ON_A_TO_Z_PATH_MSG = "Turning down power on A-to-Z path";
87     private static final Logger LOG = LoggerFactory.getLogger(RendererServiceOperationsImpl.class);
88     private static final String FAILED = "Failed";
89     private static final String OPERATION_FAILED = "Operation Failed";
90     private static final String OPERATION_SUCCESSFUL = "Operation Successful";
91     private static final int NUMBER_OF_THREADS = 4;
92
93     private final DeviceRendererService deviceRenderer;
94     private final OtnDeviceRendererService otnDeviceRenderer;
95     private final TransportpceOlmService olmService;
96     private final DataBroker dataBroker;
97     private final NotificationPublishService notificationPublishService;
98     private ListeningExecutorService executor;
99
100     public RendererServiceOperationsImpl(DeviceRendererService deviceRenderer,
101             OtnDeviceRendererService otnDeviceRenderer, TransportpceOlmService olmService,
102             DataBroker dataBroker, NotificationPublishService notificationPublishService) {
103         this.deviceRenderer = deviceRenderer;
104         this.otnDeviceRenderer = otnDeviceRenderer;
105         this.olmService = olmService;
106         this.dataBroker = dataBroker;
107         this.notificationPublishService = notificationPublishService;
108         this.executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(NUMBER_OF_THREADS));
109     }
110
111     @Override
112     public ListenableFuture<ServiceImplementationRequestOutput>
113             serviceImplementation(ServiceImplementationRequestInput input) {
114         LOG.info("Calling service impl request {}", input.getServiceName());
115         return executor.submit(new Callable<ServiceImplementationRequestOutput>() {
116
117             @Override
118             public ServiceImplementationRequestOutput call() throws Exception {
119                 sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest, input.getServiceName(),
120                         RpcStatusEx.Pending, "Service compliant, submitting service implementation Request ...");
121                 // Here is the switch statement that distinguishes on the connection-type
122                 LOG.info("Connection-type is {} for {}", input.getConnectionType(), input.getServiceName());
123                 switch (input.getConnectionType()) {
124                     case Service: case RoadmLine: // This takes into account of Ethernet 100G, 1G, 10G and ODU4
125                         LOG.info("RPC implementation for {}", input.getConnectionType());
126                         if (((input.getServiceAEnd().getServiceRate() != null)
127                             && ((input.getServiceAEnd().getServiceRate().intValue() == 100))
128                             || (input.getServiceAEnd().getServiceRate().intValue() == 400))
129                             && ((input.getServiceAEnd().getServiceFormat().getName().equals("Ethernet"))
130                                 || (input.getServiceAEnd().getServiceFormat().getName().equals("OC")))) {
131                             LOG.info("Service format for {} is {} and rate is {}", input.getServiceName(),
132                                 input.getServiceAEnd().getServiceFormat(), input.getServiceAEnd().getServiceRate());
133                             if (!createServicepathInput(input)) {
134                                 return ModelMappingUtils.createServiceImplResponse(ResponseCodes.RESPONSE_FAILED,
135                                     OPERATION_FAILED);
136                             }
137                         } else { // This implies, service-rate is 1 or 10G
138                             // This includes the lower-order odu (1G, 10G, 100G) and this is A-Z side
139                             LOG.info("RPC implementation for LO-ODU");
140                             String serviceRate = ""; // Assuming service at A-side and Z-side has same service rate
141                             if (input.getServiceAEnd().getServiceRate() != null) {
142                                 serviceRate = input.getServiceAEnd().getServiceRate().toString() + "G";
143                             }
144                             LOG.info("Start rendering for {} service with {} rate and {} format",
145                                 input.getServiceName(), serviceRate,
146                                 input.getServiceAEnd().getServiceFormat());
147                             // This is A-Z side
148                             OtnServicePathInput otnServicePathInputAtoZ = ModelMappingUtils
149                                 .rendererCreateOtnServiceInput(input.getServiceName(),
150                                     input.getServiceAEnd().getServiceFormat().getName(),
151                                     serviceRate, (PathDescription) input.getPathDescription(), true);
152                             // Rollback should be same for all conditions, so creating a new one
153                             RollbackProcessor rollbackProcessor = new RollbackProcessor();
154                             List<OtnDeviceRenderingResult> otnRenderingResults = otnDeviceRendering(rollbackProcessor,
155                                 otnServicePathInputAtoZ, null);
156                             if (rollbackProcessor.rollbackAllIfNecessary() > 0) {
157                                 sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
158                                     input.getServiceName(), RpcStatusEx.Failed, DEVICE_RENDERING_ROLL_BACK_MSG);
159                                 return ModelMappingUtils.createServiceImplResponse(ResponseCodes.RESPONSE_FAILED,
160                                     OPERATION_FAILED);
161                             }
162                             LOG.info("OTN rendering result size {}", otnRenderingResults.size());
163                         }
164                         break;
165                     case Infrastructure:
166                         LOG.info("RPC implementation for {}", input.getConnectionType());
167                         if (input.getServiceAEnd().getOtuServiceRate() != null) {
168                             if ((input.getServiceAEnd().getOtuServiceRate().equals(OTU4.class))
169                                 || (input.getServiceAEnd().getOtuServiceRate().equals(OTUCn.class))) {
170                                 // For the service of OTU4 or OTUCn infrastructure
171                                 // Create the OCH and OTU interfaces for OTU4 class
172                                 // Create OTSi, OTSi-group and OTUCn interface
173                                 if (!createServicepathInput(input)) {
174                                     return ModelMappingUtils.createServiceImplResponse(ResponseCodes.RESPONSE_FAILED,
175                                         OPERATION_FAILED);
176                                 }
177                             }
178                         }
179                         if (input.getServiceAEnd().getOduServiceRate() != null) {
180                             String serviceRate = null;
181                             if (input.getServiceAEnd().getOduServiceRate().equals(ODU4.class)) {
182                                 // For the service of OTU4 infrastructure
183                                 serviceRate = "100G"; // For OtnDeviceRendererServiceImpl
184                             }
185                             else if (input.getServiceAEnd().getOduServiceRate().equals(ODUCn.class)) {
186                                 // For the service of OTUCn infrastructure
187                                 // TODO: what happens if split-lambda where to be used? We will have ODUC2 rate,
188                                 // TODO: which case service-rate would be 200
189                                 // TODO: in that case it would be 200G?? Need to understand more
190                                 serviceRate = "400G"; // For OtnDeviceRendererServiceImpl
191                             }
192                             LOG.info("Service format for {} is {} and rate is {}", input.getServiceName(),
193                                 input.getServiceAEnd().getOduServiceRate(), serviceRate);
194                             // Now start rendering ODU4 or ODUC4 interface
195                             // This is A-Z side
196                             OtnServicePathInput otnServicePathInputAtoZ = ModelMappingUtils
197                                 .rendererCreateOtnServiceInput(input.getServiceName(),
198                                     input.getServiceAEnd().getServiceFormat().getName(),
199                                     serviceRate,
200                                     input.getPathDescription(), true);
201                             // This is Z-A side
202                             OtnServicePathInput otnServicePathInputZtoA = ModelMappingUtils
203                                 .rendererCreateOtnServiceInput(input.getServiceName(),
204                                     input.getServiceZEnd().getServiceFormat().getName(),
205                                     serviceRate,
206                                     input.getPathDescription(), false);
207                             // Rollback should be same for all conditions, so creating a new one
208                             RollbackProcessor rollbackProcessor = new RollbackProcessor();
209                             List<OtnDeviceRenderingResult> otnRenderingResults = otnDeviceRendering(rollbackProcessor,
210                                 otnServicePathInputAtoZ, otnServicePathInputZtoA);
211                             if (rollbackProcessor.rollbackAllIfNecessary() > 0) {
212                                 sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
213                                     input.getServiceName(), RpcStatusEx.Failed, DEVICE_RENDERING_ROLL_BACK_MSG);
214                                 return ModelMappingUtils.createServiceImplResponse(ResponseCodes.RESPONSE_FAILED,
215                                     OPERATION_FAILED);
216                             }
217                             LOG.info("OTN rendering result size {}", otnRenderingResults.size());
218                         }
219                         break;
220                     default:
221                         LOG.warn("Unsupported connection type {}", input.getConnectionType());
222                 }
223                 sendNotificationsWithPathDescription(
224                         ServicePathNotificationTypes.ServiceImplementationRequest,
225                         input.getServiceName(), RpcStatusEx.Successful, OPERATION_SUCCESSFUL,
226                         input.getPathDescription());
227                 return ModelMappingUtils.createServiceImplResponse(ResponseCodes.RESPONSE_OK,
228                     OPERATION_SUCCESSFUL);
229             }
230         });
231     }
232
233     @Override
234     public ListenableFuture<ServiceDeleteOutput> serviceDelete(ServiceDeleteInput input, Services service) {
235         String serviceName = input.getServiceName();
236         LOG.info("Calling service delete request {}", serviceName);
237         return executor.submit(new Callable<ServiceDeleteOutput>() {
238
239             @Override
240             public ServiceDeleteOutput call() throws Exception {
241                 sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName,
242                         RpcStatusEx.Pending, "Service compliant, submitting service delete Request ...");
243                 // Obtain path description
244                 Optional<
245                     org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128.service
246                     .path.PathDescription> pathDescriptionOpt = getPathDescriptionFromDatastore(serviceName);
247                 PathDescription pathDescription;
248                 if (pathDescriptionOpt.isPresent()) {
249                     pathDescription = pathDescriptionOpt.get();
250                 } else {
251                     LOG.error("Unable to get path description for service {}!", serviceName);
252                     sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName,
253                             RpcStatusEx.Failed, "Unable to get path description for service");
254                     return ModelMappingUtils.createServiceDeleteResponse(ResponseCodes.RESPONSE_FAILED,
255                             OPERATION_FAILED);
256                 }
257                 switch (service.getConnectionType()) {
258                     case RoadmLine:
259                     case Service:
260                         if ((ServiceFormat.Ethernet.equals(service.getServiceAEnd().getServiceFormat())
261                                 || ServiceFormat.OC.equals(service.getServiceAEnd().getServiceFormat()))
262                             && (Uint32.valueOf("100").equals(service.getServiceAEnd().getServiceRate())
263                                 || Uint32.valueOf("400").equals(service.getServiceAEnd().getServiceRate()))) {
264                             if (!manageServicePathDeletion(serviceName, pathDescription)) {
265                                 return ModelMappingUtils.createServiceDeleteResponse(ResponseCodes.RESPONSE_FAILED,
266                                     OPERATION_FAILED);
267                             }
268                         }
269                         if (ServiceFormat.Ethernet.equals(service.getServiceAEnd().getServiceFormat())
270                             && (Uint32.valueOf("10").equals(service.getServiceAEnd().getServiceRate())
271                                 || Uint32.valueOf("1").equals(service.getServiceAEnd().getServiceRate()))) {
272                             if (!manageOtnServicePathDeletion(serviceName, pathDescription, service)) {
273                                 return ModelMappingUtils.createServiceDeleteResponse(ResponseCodes.RESPONSE_FAILED,
274                                     OPERATION_FAILED);
275                             }
276                         }
277                         break;
278                     case Infrastructure:
279                         if (ServiceFormat.OTU.equals(service.getServiceAEnd().getServiceFormat())) {
280                             if (!manageServicePathDeletion(serviceName, pathDescription)) {
281                                 return ModelMappingUtils.createServiceDeleteResponse(ResponseCodes.RESPONSE_FAILED,
282                                     OPERATION_FAILED);
283                             }
284                         } else if (ServiceFormat.ODU.equals(service.getServiceAEnd().getServiceFormat())) {
285                             if (!manageOtnServicePathDeletion(serviceName, pathDescription, service)) {
286                                 return ModelMappingUtils.createServiceDeleteResponse(ResponseCodes.RESPONSE_FAILED,
287                                     OPERATION_FAILED);
288                             }
289                         }
290                         break;
291                     default:
292                         LOG.error("Unmanaged connection-type for deletion of service {}", serviceName);
293                         break;
294                     }
295                 return ModelMappingUtils.createServiceDeleteResponse(ResponseCodes.RESPONSE_OK, OPERATION_SUCCESSFUL);
296             }
297         });
298     }
299
300     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
301             value = "UPM_UNCALLED_PRIVATE_METHOD",
302             justification = "call in call() method")
303     private ServicePowerTurndownOutput olmPowerTurndown(ServicePathInputData servicePathInputData)
304             throws InterruptedException, ExecutionException, TimeoutException {
305         LOG.debug(TURNING_DOWN_POWER_ON_A_TO_Z_PATH_MSG);
306         Future<RpcResult<ServicePowerTurndownOutput>> powerTurndownFuture = this.olmService.servicePowerTurndown(
307                 new ServicePowerTurndownInputBuilder(servicePathInputData.getServicePathInput()).build());
308         return powerTurndownFuture.get(Timeouts.DATASTORE_READ, TimeUnit.MILLISECONDS).getResult();
309     }
310
311     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
312             value = "UPM_UNCALLED_PRIVATE_METHOD",
313             justification = "call in call() method")
314     private Optional<org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128
315         .service.path.PathDescription> getPathDescriptionFromDatastore(String serviceName) {
316         InstanceIdentifier<org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128
317             .service.path.PathDescription> pathDescriptionIID = InstanceIdentifier.create(ServicePathList.class)
318                 .child(ServicePaths.class, new ServicePathsKey(serviceName))
319                 .child(org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev200128
320                     .service.path.PathDescription.class);
321         ReadTransaction pathDescReadTx = this.dataBroker.newReadOnlyTransaction();
322         try {
323             LOG.debug("Getting path description for service {}", serviceName);
324             return pathDescReadTx.read(LogicalDatastoreType.OPERATIONAL, pathDescriptionIID)
325                     .get(Timeouts.DATASTORE_READ, TimeUnit.MILLISECONDS);
326         } catch (InterruptedException | ExecutionException | TimeoutException e) {
327             LOG.warn("Exception while getting path description from datastore {} for service {}!", pathDescriptionIID,
328                     serviceName, e);
329             return Optional.empty();
330         }
331     }
332
333     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
334             value = "UPM_UNCALLED_PRIVATE_METHOD",
335             justification = "call in call() method")
336     private List<DeviceRenderingResult> deviceRendering(RollbackProcessor rollbackProcessor,
337             ServicePathInputData servicePathDataAtoZ, ServicePathInputData servicePathDataZtoA) {
338         LOG.info(RENDERING_DEVICES_A_Z_MSG);
339         sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
340                 servicePathDataAtoZ.getServicePathInput().getServiceName(), RpcStatusEx.Pending,
341                 RENDERING_DEVICES_A_Z_MSG);
342         ListenableFuture<DeviceRenderingResult> atozrenderingFuture =
343                 this.executor.submit(new DeviceRenderingTask(this.deviceRenderer, servicePathDataAtoZ,
344                         ServicePathDirection.A_TO_Z));
345
346         LOG.info("Rendering devices Z-A");
347         sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
348                 servicePathDataZtoA.getServicePathInput().getServiceName(), RpcStatusEx.Pending,
349                 RENDERING_DEVICES_Z_A_MSG);
350         ListenableFuture<DeviceRenderingResult> ztoarenderingFuture =
351                 this.executor.submit(new DeviceRenderingTask(this.deviceRenderer, servicePathDataZtoA,
352                         ServicePathDirection.Z_TO_A));
353         ListenableFuture<List<DeviceRenderingResult>> renderingCombinedFuture =
354                 Futures.allAsList(atozrenderingFuture, ztoarenderingFuture);
355
356         List<DeviceRenderingResult> renderingResults = new ArrayList<>(2);
357         try {
358             LOG.info("Waiting for A-Z and Z-A device renderers ...");
359             renderingResults = renderingCombinedFuture.get(Timeouts.RENDERING_TIMEOUT, TimeUnit.MILLISECONDS);
360         } catch (InterruptedException | ExecutionException | TimeoutException e) {
361             LOG.warn(DEVICE_RENDERING_ROLL_BACK_MSG, e);
362             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
363                     servicePathDataAtoZ.getServicePathInput().getServiceName(), RpcStatusEx.Pending,
364                     DEVICE_RENDERING_ROLL_BACK_MSG);
365             //FIXME we can't do rollback here, because we don't have rendering results.
366             return renderingResults;
367         }
368
369         rollbackProcessor.addTask(new DeviceRenderingRollbackTask("AtoZDeviceTask",
370                 ! renderingResults.get(0).isSuccess(), renderingResults.get(0).getRenderedNodeInterfaces(),
371                 this.deviceRenderer));
372         rollbackProcessor.addTask(new DeviceRenderingRollbackTask("ZtoADeviceTask",
373                 ! renderingResults.get(1).isSuccess(), renderingResults.get(1).getRenderedNodeInterfaces(),
374                 this.deviceRenderer));
375         return renderingResults;
376     }
377
378     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
379         value = "UPM_UNCALLED_PRIVATE_METHOD",
380         justification = "call in call() method")
381     private List<OtnDeviceRenderingResult> otnDeviceRendering(RollbackProcessor rollbackProcessor,
382         OtnServicePathInput otnServicePathAtoZ, OtnServicePathInput otnServicePathZtoA) {
383         LOG.info(RENDERING_DEVICES_A_Z_MSG);
384         sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
385             otnServicePathAtoZ.getServiceName(), RpcStatusEx.Pending,
386             RENDERING_DEVICES_A_Z_MSG);
387         ListenableFuture<OtnDeviceRenderingResult> atozrenderingFuture =
388             this.executor.submit(new OtnDeviceRenderingTask(this.otnDeviceRenderer, otnServicePathAtoZ));
389         ListenableFuture<List<OtnDeviceRenderingResult>> renderingCombinedFuture;
390         if (otnServicePathZtoA != null) {
391             LOG.info("Rendering devices Z-A");
392             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
393                 otnServicePathZtoA.getServiceName(), RpcStatusEx.Pending,
394                 RENDERING_DEVICES_Z_A_MSG);
395             ListenableFuture<OtnDeviceRenderingResult> ztoarenderingFuture =
396                 this.executor.submit(new OtnDeviceRenderingTask(this.otnDeviceRenderer, otnServicePathZtoA));
397             renderingCombinedFuture = Futures.allAsList(atozrenderingFuture, ztoarenderingFuture);
398         } else {
399             renderingCombinedFuture = Futures.allAsList(atozrenderingFuture);
400         }
401         List<OtnDeviceRenderingResult> otnRenderingResults = new ArrayList<>(2);
402         try {
403             LOG.info("Waiting for A-Z and Z-A device renderers ...");
404             otnRenderingResults = renderingCombinedFuture.get(Timeouts.RENDERING_TIMEOUT, TimeUnit.MILLISECONDS);
405         } catch (InterruptedException | ExecutionException | TimeoutException e) {
406             LOG.warn(DEVICE_RENDERING_ROLL_BACK_MSG, e);
407             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
408                 otnServicePathAtoZ.getServiceName(), RpcStatusEx.Pending,
409                 DEVICE_RENDERING_ROLL_BACK_MSG);
410             //FIXME we can't do rollback here, because we don't have rendering results.
411             return otnRenderingResults;
412         }
413         for (int i = 0; i < otnRenderingResults.size(); i++) {
414             rollbackProcessor.addTask(new DeviceRenderingRollbackTask("DeviceTask n° " + i + 1,
415                 ! otnRenderingResults.get(i).isSuccess(), otnRenderingResults.get(i).getRenderedNodeInterfaces(),
416                 this.deviceRenderer));
417         }
418         return otnRenderingResults;
419     }
420
421     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
422             value = "UPM_UNCALLED_PRIVATE_METHOD",
423             justification = "call in call() method")
424     private void olmPowerSetup(RollbackProcessor rollbackProcessor, ServicePowerSetupInput powerSetupInputAtoZ,
425             ServicePowerSetupInput powerSetupInputZtoA) {
426         LOG.info("Olm power setup A-Z");
427         sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
428                 powerSetupInputAtoZ.getServiceName(), RpcStatusEx.Pending, "Olm power setup A-Z");
429         ListenableFuture<OLMRenderingResult> olmPowerSetupFutureAtoZ
430                 = this.executor.submit(new OlmPowerSetupTask(this.olmService, powerSetupInputAtoZ));
431
432         LOG.info("OLM power setup Z-A");
433         sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
434                 powerSetupInputAtoZ.getServiceName(), RpcStatusEx.Pending, "Olm power setup Z-A");
435         ListenableFuture<OLMRenderingResult> olmPowerSetupFutureZtoA
436                 = this.executor.submit(new OlmPowerSetupTask(this.olmService, powerSetupInputZtoA));
437         ListenableFuture<List<OLMRenderingResult>> olmFutures =
438                 Futures.allAsList(olmPowerSetupFutureAtoZ, olmPowerSetupFutureZtoA);
439
440         List<OLMRenderingResult> olmResults;
441         try {
442             LOG.info("Waiting for A-Z and Z-A OLM power setup ...");
443             olmResults = olmFutures.get(Timeouts.OLM_TIMEOUT, TimeUnit.MILLISECONDS);
444         } catch (InterruptedException | ExecutionException | TimeoutException e) {
445             LOG.warn(OLM_ROLL_BACK_MSG, e);
446             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
447                     powerSetupInputAtoZ.getServiceName(), RpcStatusEx.Pending,
448                     OLM_ROLL_BACK_MSG);
449             rollbackProcessor.addTask(new OlmPowerSetupRollbackTask("AtoZOLMTask", true,
450                     this.olmService, powerSetupInputAtoZ));
451             rollbackProcessor.addTask(new OlmPowerSetupRollbackTask("ZtoAOLMTask", true,
452                     this.olmService, powerSetupInputZtoA));
453             return;
454         }
455
456         rollbackProcessor.addTask(new OlmPowerSetupRollbackTask("AtoZOLMTask", ! olmResults.get(0).isSuccess(),
457                 this.olmService, powerSetupInputAtoZ));
458         rollbackProcessor.addTask(new OlmPowerSetupRollbackTask("ZtoAOLMTask", ! olmResults.get(1).isSuccess(),
459                 this.olmService, powerSetupInputZtoA));
460     }
461
462     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
463             value = "UPM_UNCALLED_PRIVATE_METHOD",
464             justification = "call in call() method")
465     private boolean isServiceActivated(String nodeId, String tpId) {
466         LOG.info("Starting service activation test on node {} and tp {}", nodeId, tpId);
467         for (int i = 0; i < 3; i++) {
468             List<Measurements> measurements = getMeasurements(nodeId, tpId);
469             if ((measurements != null) && verifyPreFecBer(measurements)) {
470                 return true;
471             } else if (measurements == null) {
472                 LOG.warn("Device {} is not reporting PreFEC on TP: {}", nodeId, tpId);
473                 return true;
474             } else {
475                 try {
476                     Thread.sleep(Timeouts.SERVICE_ACTIVATION_TEST_RETRY_TIME);
477                 } catch (InterruptedException ex) {
478                     Thread.currentThread().interrupt();
479                 }
480             }
481         }
482         LOG.error("Service activation test failed on node {} and termination point {}!", nodeId, tpId);
483         return false;
484     }
485
486     private List<Measurements> getMeasurements(String nodeId, String tp) {
487         GetPmInputBuilder getPmIpBldr = new GetPmInputBuilder();
488         getPmIpBldr.setNodeId(nodeId);
489         getPmIpBldr.setGranularity(PmGranularity._15min);
490         ResourceIdentifierBuilder rsrcBldr = new ResourceIdentifierBuilder();
491         rsrcBldr.setResourceName(tp + "-OTU");
492         getPmIpBldr.setResourceIdentifier(rsrcBldr.build());
493         getPmIpBldr.setResourceType(ResourceTypeEnum.Interface);
494
495         try {
496             Future<RpcResult<GetPmOutput>> getPmFuture = this.olmService.getPm(getPmIpBldr.build());
497             RpcResult<GetPmOutput> getPmRpcResult = getPmFuture.get();
498             GetPmOutput getPmOutput = getPmRpcResult.getResult();
499             if ((getPmOutput != null) && (getPmOutput.getNodeId() != null)) {
500                 LOG.info("successfully finished calling OLM's get PM");
501                 return getPmOutput.getMeasurements();
502                 // may return null
503             } else {
504                 LOG.warn("OLM's get PM failed for node {} and tp {}", nodeId, tp);
505             }
506
507         } catch (ExecutionException | InterruptedException e) {
508             LOG.warn("Error occurred while getting PM for node {} and tp {}", nodeId, tp, e);
509         }
510         return null;
511     }
512
513     private boolean verifyPreFecBer(List<Measurements> measurements) {
514         double preFecCorrectedErrors = Double.MIN_VALUE;
515         double fecUncorrectableBlocks = Double.MIN_VALUE;
516
517         for (Measurements measurement : measurements) {
518             if (measurement.getPmparameterName().equals("preFECCorrectedErrors")) {
519                 preFecCorrectedErrors = Double.parseDouble(measurement.getPmparameterValue());
520             }
521             if (measurement.getPmparameterName().equals("FECUncorrectableBlocks")) {
522                 fecUncorrectableBlocks = Double.parseDouble(measurement.getPmparameterValue());
523             }
524         }
525
526         LOG.info("Measurements: preFECCorrectedErrors = {}; FECUncorrectableBlocks = {}", preFecCorrectedErrors,
527                 fecUncorrectableBlocks);
528
529         if (fecUncorrectableBlocks > Double.MIN_VALUE) {
530             LOG.error("Data has uncorrectable errors, BER test failed");
531             return false;
532         } else {
533             double numOfBitsPerSecond = 112000000000d;
534             double threshold = 0.00002d;
535             double result = preFecCorrectedErrors / numOfBitsPerSecond;
536             LOG.info("PreFEC value is {}", Double.toString(result));
537             return result <= threshold;
538         }
539     }
540
541     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
542         value = "UPM_UNCALLED_PRIVATE_METHOD",
543         justification = "call in call() method")
544     private boolean createServicepathInput(ServiceImplementationRequestInput input) {
545         ServicePathInputData servicePathInputDataAtoZ = ModelMappingUtils
546             .rendererCreateServiceInputAToZ(input.getServiceName(), input.getPathDescription());
547         ServicePathInputData servicePathInputDataZtoA = ModelMappingUtils
548             .rendererCreateServiceInputZToA(input.getServiceName(), input.getPathDescription());
549         // Rollback should be same for all conditions, so creating a new one
550         RollbackProcessor rollbackProcessor = new RollbackProcessor();
551         List<DeviceRenderingResult> renderingResults =
552             deviceRendering(rollbackProcessor, servicePathInputDataAtoZ, servicePathInputDataZtoA);
553         if (rollbackProcessor.rollbackAllIfNecessary() > 0) {
554             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
555                 input.getServiceName(), RpcStatusEx.Failed, DEVICE_RENDERING_ROLL_BACK_MSG);
556             return false;
557         }
558         ServicePowerSetupInput olmPowerSetupInputAtoZ =
559             ModelMappingUtils.createServicePowerSetupInput(renderingResults.get(0).getOlmList(), input);
560         ServicePowerSetupInput olmPowerSetupInputZtoA =
561             ModelMappingUtils.createServicePowerSetupInput(renderingResults.get(1).getOlmList(), input);
562         olmPowerSetup(rollbackProcessor, olmPowerSetupInputAtoZ, olmPowerSetupInputZtoA);
563         if (rollbackProcessor.rollbackAllIfNecessary() > 0) {
564             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
565                 input.getServiceName(), RpcStatusEx.Failed, OLM_ROLL_BACK_MSG);
566             return false;
567         }
568         // run service activation test twice - once on source node and once on
569         // destination node
570         List<Nodes> nodes = servicePathInputDataAtoZ.getServicePathInput().getNodes();
571         if ((nodes == null) || (nodes.isEmpty())) {
572             return false;
573         }
574
575         Nodes sourceNode = nodes.get(0);
576         Nodes destNode = nodes.get(nodes.size() - 1);
577         String srcNetworkTp;
578         String dstNetowrkTp;
579         if (sourceNode.getDestTp().contains(StringConstants.NETWORK_TOKEN)) {
580             srcNetworkTp = sourceNode.getDestTp();
581         } else {
582             srcNetworkTp = sourceNode.getSrcTp();
583         }
584         if (destNode.getDestTp().contains(StringConstants.NETWORK_TOKEN)) {
585             dstNetowrkTp = destNode.getDestTp();
586         } else {
587             dstNetowrkTp = destNode.getSrcTp();
588         }
589         if (!isServiceActivated(sourceNode.getNodeId(), srcNetworkTp)
590             || !isServiceActivated(destNode.getNodeId(), dstNetowrkTp)) {
591             rollbackProcessor.rollbackAll();
592             sendNotifications(ServicePathNotificationTypes.ServiceImplementationRequest,
593                 input.getServiceName(), RpcStatusEx.Failed,
594                 "Service activation test failed.");
595             return false;
596         }
597         sendNotificationsWithPathDescription(ServicePathNotificationTypes.ServiceImplementationRequest,
598             input.getServiceName(), RpcStatusEx.Successful, OPERATION_SUCCESSFUL, input.getPathDescription());
599         return true;
600     }
601
602     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
603         value = "UPM_UNCALLED_PRIVATE_METHOD",
604         justification = "call in call() method")
605     private boolean manageServicePathDeletion(String serviceName, PathDescription pathDescription) {
606         ServicePathInputData servicePathInputDataAtoZ =
607             ModelMappingUtils.rendererCreateServiceInputAToZ(serviceName, pathDescription);
608         ServicePathInputData servicePathInputDataZtoA =
609             ModelMappingUtils.rendererCreateServiceInputZToA(serviceName, pathDescription);
610         // OLM turn down power
611         try {
612             LOG.debug(TURNING_DOWN_POWER_ON_A_TO_Z_PATH_MSG);
613             sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName,
614                 RpcStatusEx.Pending, TURNING_DOWN_POWER_ON_A_TO_Z_PATH_MSG);
615             ServicePowerTurndownOutput atozPowerTurndownOutput = olmPowerTurndown(servicePathInputDataAtoZ);
616             // TODO add some flag rather than string
617             if (FAILED.equals(atozPowerTurndownOutput.getResult())) {
618                 LOG.error("Service power turndown failed on A-to-Z path for service {}!", serviceName);
619                 sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName, RpcStatusEx.Failed,
620                         "Service power turndown failed on A-to-Z path for service");
621                 return false;
622             }
623             LOG.debug("Turning down power on Z-to-A path");
624             sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName, RpcStatusEx.Pending,
625                     "Turning down power on Z-to-A path");
626             ServicePowerTurndownOutput ztoaPowerTurndownOutput = olmPowerTurndown(servicePathInputDataZtoA);
627             // TODO add some flag rather than string
628             if (FAILED.equals(ztoaPowerTurndownOutput.getResult())) {
629                 LOG.error("Service power turndown failed on Z-to-A path for service {}!", serviceName);
630                 sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName, RpcStatusEx.Failed,
631                         "Service power turndown failed on Z-to-A path for service");
632                 return false;
633             }
634         } catch (InterruptedException | ExecutionException | TimeoutException e) {
635             LOG.error("Error while turning down power!", e);
636             return false;
637         }
638         // delete service path with renderer
639         LOG.info("Deleting service path via renderer");
640         sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName, RpcStatusEx.Pending,
641                 "Deleting service path via renderer");
642         deviceRenderer.deleteServicePath(servicePathInputDataAtoZ.getServicePathInput());
643         deviceRenderer.deleteServicePath(servicePathInputDataZtoA.getServicePathInput());
644         sendNotificationsWithPathDescription(ServicePathNotificationTypes.ServiceDelete,
645                 serviceName, RpcStatusEx.Successful, OPERATION_SUCCESSFUL,pathDescription);
646         return true;
647     }
648
649     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
650         value = "UPM_UNCALLED_PRIVATE_METHOD",
651         justification = "call in call() method")
652     private boolean manageOtnServicePathDeletion(String serviceName, PathDescription pathDescription,
653         Services service) {
654         OtnServicePathInput ospi = null;
655         ospi = ModelMappingUtils.rendererCreateOtnServiceInput(serviceName,
656                 service.getServiceAEnd().getServiceFormat().getName(),
657                 service.getServiceAEnd().getServiceRate().toString() + "G", pathDescription, true);
658         LOG.info("Deleting otn-service path {} via renderer", serviceName);
659         sendNotifications(ServicePathNotificationTypes.ServiceDelete, serviceName, RpcStatusEx.Pending,
660                 "Deleting otn-service path via renderer");
661         OtnServicePathOutput result = otnDeviceRenderer.deleteOtnServicePath(ospi);
662         if (result.getSuccess()) {
663             sendNotificationsWithPathDescription(ServicePathNotificationTypes.ServiceDelete,
664                     serviceName, RpcStatusEx.Successful, OPERATION_SUCCESSFUL, pathDescription);
665             return true;
666         } else {
667             return false;
668         }
669     }
670
671     /**
672      * Send renderer notification.
673      * @param servicePathNotificationTypes ServicePathNotificationTypes
674      * @param serviceName String
675      * @param rpcStatusEx RpcStatusEx
676      * @param message String
677      */
678     private void sendNotifications(ServicePathNotificationTypes servicePathNotificationTypes, String serviceName,
679             RpcStatusEx rpcStatusEx, String message) {
680         Notification notification = buildNotification(servicePathNotificationTypes, serviceName, rpcStatusEx, message,
681                 null);
682         send(notification);
683     }
684
685     /**
686      * Send renderer notification with path description information.
687      * @param servicePathNotificationTypes ServicePathNotificationTypes
688      * @param serviceName String
689      * @param rpcStatusEx RpcStatusEx
690      * @param message String
691      * @param pathDescription PathDescription
692      */
693     private void sendNotificationsWithPathDescription(ServicePathNotificationTypes servicePathNotificationTypes,
694             String serviceName, RpcStatusEx rpcStatusEx, String message, PathDescription pathDescription) {
695         Notification notification = buildNotification(servicePathNotificationTypes, serviceName, rpcStatusEx, message,
696                 pathDescription);
697         send(notification);
698     }
699
700     /**
701      * Build notification containing path description information.
702      * @param servicePathNotificationTypes ServicePathNotificationTypes
703      * @param serviceName String
704      * @param rpcStatusEx RpcStatusEx
705      * @param message String
706      * @param pathDescription PathDescription
707      * @return notification with RendererRpcResultSp type.
708      */
709     private RendererRpcResultSp buildNotification(ServicePathNotificationTypes servicePathNotificationTypes,
710             String serviceName, RpcStatusEx rpcStatusEx, String message, PathDescription pathDescription) {
711         RendererRpcResultSpBuilder builder = new RendererRpcResultSpBuilder()
712                 .setNotificationType(servicePathNotificationTypes).setServiceName(serviceName).setStatus(rpcStatusEx)
713                 .setStatusMessage(message);
714         if (pathDescription != null) {
715             builder.setAToZDirection(pathDescription.getAToZDirection())
716                     .setZToADirection(pathDescription.getZToADirection());
717         }
718         return builder.build();
719     }
720
721     /**
722      * Send renderer notification.
723      * @param notification Notification
724      */
725     private void send(Notification notification) {
726         try {
727             LOG.info("Sending notification {}", notification);
728             notificationPublishService.putNotification(notification);
729         } catch (InterruptedException e) {
730             LOG.info("notification offer rejected: ", e);
731             Thread.currentThread().interrupt();
732         }
733     }
734
735 }