2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
23 import java.sql.Timestamp;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.UUID;
29 import javax.persistence.EntityNotFoundException;
31 import org.camunda.bpm.engine.delegate.DelegateExecution;
32 import org.onap.aai.domain.yang.Vnfc;
33 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
34 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
35 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
36 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
37 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
38 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
39 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
40 import org.onap.so.client.aai.AAIObjectType;
41 import org.onap.so.client.aai.entities.AAIResultWrapper;
42 import org.onap.so.client.aai.entities.Relationships;
43 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
44 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
45 import org.onap.so.client.exception.ExceptionBuilder;
46 import org.onap.so.db.catalog.beans.CvnfcCustomization;
47 import org.onap.so.db.catalog.beans.VnfVfmoduleCvnfcConfigurationCustomization;
48 import org.onap.so.db.catalog.client.CatalogDbClient;
49 import org.onap.so.db.request.beans.InfraActiveRequests;
50 import org.onap.so.db.request.client.RequestsDbClient;
51 import org.onap.so.serviceinstancebeans.RequestReferences;
52 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.core.env.Environment;
57 import org.springframework.stereotype.Component;
59 import com.fasterxml.jackson.core.JsonProcessingException;
60 import com.fasterxml.jackson.databind.ObjectMapper;
63 public class WorkflowActionBBTasks {
65 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
66 private static final String G_REQUEST_ID = "mso-request-id";
67 private static final String G_ALACARTE = "aLaCarte";
68 private static final String G_ACTION = "requestAction";
69 private static final String RETRY_COUNT = "retryCount";
70 private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
71 private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
72 private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
73 protected String maxRetries = "mso.rainyDay.maxRetries";
74 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
77 private RequestsDbClient requestDbclient;
79 private WorkflowAction workflowAction;
81 private WorkflowActionBBFailure workflowActionBBFailure;
83 private Environment environment;
85 private BBInputSetupUtils bbInputSetupUtils;
87 private CatalogDbClient catalogDbClient;
89 public void selectBB(DelegateExecution execution) {
90 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
91 .getVariable("flowsToExecute");
92 execution.setVariable("MacroRollback", false);
93 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
94 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
95 boolean homing = (boolean) execution.getVariable("homing");
96 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
97 if (homing && !calledHoming) {
98 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
100 execution.setVariable("calledHoming", true);
103 ebb.setHoming(false);
105 execution.setVariable("buildingBlock", ebb);
107 if (currentSequence >= flowsToExecute.size()) {
108 execution.setVariable("completed", true);
110 execution.setVariable("completed", false);
112 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
115 public void updateFlowStatistics(DelegateExecution execution) {
117 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
118 if(currentSequence > 1) {
119 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
120 requestDbclient.updateInfraActiveRequests(request);
122 }catch (Exception ex){
123 logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
127 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
128 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
129 .getVariable("flowsToExecute");
130 String requestId = (String) execution.getVariable(G_REQUEST_ID);
131 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
132 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
133 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
134 int completedBBs = currentSequence - 1;
135 int totalBBs = flowsToExecute.size();
136 int remainingBBs = totalBBs - completedBBs;
137 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
138 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
139 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
140 request.setFlowStatus(statusMessage);
141 request.setProgress(percentProgress);
142 request.setLastModifiedBy("CamundaBPMN");
146 protected Long getPercentProgress(int completedBBs, int totalBBs) {
147 double ratio = (completedBBs / (totalBBs * 1.0));
148 int percentProgress = (int) (ratio * 95);
149 return new Long(percentProgress + 5);
152 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
153 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
154 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
158 public void sendSyncAck(DelegateExecution execution) {
159 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
160 final String resourceId = (String) execution.getVariable("resourceId");
161 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
162 RequestReferences requestRef = new RequestReferences();
163 requestRef.setInstanceId(resourceId);
164 requestRef.setRequestId(requestId);
165 serviceInstancesResponse.setRequestReferences(requestRef);
166 ObjectMapper mapper = new ObjectMapper();
167 String jsonRequest = "";
169 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
170 } catch (JsonProcessingException e) {
171 workflowAction.buildAndThrowException(execution,
172 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
174 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
175 callbackResponse.setStatusCode(200);
176 callbackResponse.setMessage("Success");
177 callbackResponse.setResponse(jsonRequest);
178 String processKey = execution.getProcessEngineServices().getRepositoryService()
179 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
180 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
182 logger.info("Successfully sent sync ack.");
183 updateInstanceId(execution);
186 public void sendErrorSyncAck(DelegateExecution execution) {
187 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
189 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
190 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
191 if (errorMsg == null) {
192 errorMsg = "WorkflowAction failed unexpectedly.";
194 String processKey = exceptionBuilder.getProcessKey(execution);
195 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
197 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
198 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
199 callbackResponse.setStatusCode(500);
200 callbackResponse.setMessage("Fail");
201 callbackResponse.setResponse(buildworkflowException);
202 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
204 execution.setVariable("sentSyncResponse", true);
205 } catch (Exception ex) {
206 logger.error(" Sending Sync Error Activity Failed. {}" , ex.getMessage(), ex);
210 public void updateRequestStatusToComplete(DelegateExecution execution) {
212 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
213 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
214 final String action = (String) execution.getVariable(G_ACTION);
215 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
216 final String resourceName = (String) execution.getVariable("resourceName");
217 String macroAction = "";
219 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
221 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
223 execution.setVariable("finalStatusMessage", macroAction);
224 Timestamp endTime = new Timestamp(System.currentTimeMillis());
225 request.setEndTime(endTime);
226 request.setFlowStatus("Successfully completed all Building Blocks");
227 request.setStatusMessage(macroAction);
228 request.setProgress(Long.valueOf(100));
229 request.setRequestStatus("COMPLETE");
230 request.setLastModifiedBy("CamundaBPMN");
231 requestDbclient.updateInfraActiveRequests(request);
232 }catch (Exception ex) {
233 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
237 public void checkRetryStatus(DelegateExecution execution) {
238 String handlingCode = (String) execution.getVariable("handlingCode");
239 String requestId = (String) execution.getVariable(G_REQUEST_ID);
240 String retryDuration = (String) execution.getVariable("RetryDuration");
241 int retryCount = (int) execution.getVariable(RETRY_COUNT);
244 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
245 } catch (Exception ex) {
246 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
249 int nextCount = retryCount +1;
250 if (handlingCode.equals("Retry")){
251 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
253 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
254 request.setRetryStatusMessage("Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
255 requestDbclient.updateInfraActiveRequests(request);
256 } catch(Exception ex){
257 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
259 if(retryCount<envMaxRetries){
260 int currSequence = (int) execution.getVariable("gCurrentSequence");
261 execution.setVariable("gCurrentSequence", currSequence-1);
262 execution.setVariable(RETRY_COUNT, nextCount);
264 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
267 execution.setVariable(RETRY_COUNT, 0);
272 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
273 * layer will rollback the flow its currently working on.
275 public void rollbackExecutionPath(DelegateExecution execution) {
276 if(!(boolean)execution.getVariable("isRollback")){
277 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
278 .getVariable("flowsToExecute");
279 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
280 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
281 int listSize = flowsToExecute.size();
282 for (int i = listSize - 1; i >= 0; i--) {
283 if (i > currentSequence - 1) {
284 flowsToExecute.remove(i);
286 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
287 if (flowName.contains("Assign")) {
288 flowName = "Unassign" + flowName.substring(6, flowName.length());
289 } else if (flowName.contains("Create")) {
290 flowName = "Delete" + flowName.substring(6, flowName.length());
291 } else if (flowName.contains("Activate")) {
292 flowName = "Deactivate" + flowName.substring(8, flowName.length());
296 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
297 rollbackFlows.add(flowsToExecute.get(i));
301 String handlingCode = (String) execution.getVariable("handlingCode");
302 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
303 rollbackFlowsFiltered.addAll(rollbackFlows);
304 if(handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")){
305 for(int i = 0; i<rollbackFlows.size(); i++){
306 if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
307 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
308 } else if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete") && handlingCode.equals("RollbackToCreated")) {
309 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
314 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
316 if (rollbackFlows.isEmpty())
317 execution.setVariable("isRollbackNeeded", false);
319 execution.setVariable("isRollbackNeeded", true);
320 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
321 execution.setVariable("handlingCode", "PreformingRollback");
322 execution.setVariable("isRollback", true);
323 execution.setVariable("gCurrentSequence", 0);
324 execution.setVariable(RETRY_COUNT, 0);
326 workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
330 protected void updateInstanceId(DelegateExecution execution){
332 String requestId = (String) execution.getVariable(G_REQUEST_ID);
333 String resourceId = (String) execution.getVariable("resourceId");
334 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
335 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
336 if(resourceType == WorkflowType.SERVICE){
337 request.setServiceInstanceId(resourceId);
338 }else if(resourceType == WorkflowType.VNF){
339 request.setVnfId(resourceId);
340 }else if(resourceType == WorkflowType.VFMODULE){
341 request.setVfModuleId(resourceId);
342 }else if(resourceType == WorkflowType.VOLUMEGROUP){
343 request.setVolumeGroupId(resourceId);
344 }else if(resourceType == WorkflowType.NETWORK){
345 request.setNetworkId(resourceId);
346 }else if(resourceType == WorkflowType.CONFIGURATION){
347 request.setConfigurationId(resourceId);
348 }else if(resourceType == WorkflowType.INSTANCE_GROUP){
349 request.setInstanceGroupId(resourceId);
351 requestDbclient.updateInfraActiveRequests(request);
352 }catch(Exception ex){
353 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
357 public void postProcessingExecuteBB(DelegateExecution execution) {
358 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
359 .getVariable("flowsToExecute");
360 String handlingCode = (String) execution.getVariable("handlingCode");
361 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
362 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
363 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
364 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
365 if(bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
366 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
370 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution,
371 ExecuteBuildingBlock ebb, List<ExecuteBuildingBlock> flowsToExecute) {
373 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
374 String vfModuleId = ebb.getResourceId();
375 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
376 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
377 String vfModuleCustomizationUUID = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
378 List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
379 for(Vnfc vnfc : vnfcs) {
380 String modelCustomizationId = vnfc.getModelCustomizationId();
381 VnfVfmoduleCvnfcConfigurationCustomization fabricConfig =
382 catalogDbClient.getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid(vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
383 if(fabricConfig != null && fabricConfig.getConfigurationResource() != null
384 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
385 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
386 String configurationId = UUID.randomUUID().toString();
387 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
388 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
389 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
390 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
391 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
392 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
393 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
394 flowsToExecute.add(assignConfigBB);
395 flowsToExecute.add(activateConfigBB);
396 execution.setVariable("flowsToExecute", flowsToExecute);
397 execution.setVariable("completed", false);
399 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
402 } catch (EntityNotFoundException e) {
403 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
404 } catch (Exception e) {
405 String errorMessage = "Error occurred in post processing of Vf Module create";
406 execution.setVariable("handlingCode", "RollbackToCreated");
407 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
408 logger.error(errorMessage, e);
412 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb, String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
413 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
414 BuildingBlock buildingBlock = new BuildingBlock();
415 buildingBlock.setBpmnFlowName(bbName);
416 buildingBlock.setMsoId(UUID.randomUUID().toString());
417 configBB.setaLaCarte(ebb.isaLaCarte());
418 configBB.setApiVersion(ebb.getApiVersion());
419 configBB.setRequestAction(ebb.getRequestAction());
420 configBB.setVnfType(ebb.getVnfType());
421 configBB.setRequestId(ebb.getRequestId());
422 configBB.setRequestDetails(ebb.getRequestDetails());
423 configBB.setBuildingBlock(buildingBlock);
424 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
425 workflowResourceIds.setConfigurationId(configurationId);
426 configBB.setWorkflowResourceIds(workflowResourceIds);
427 configBB.setConfigurationResourceKeys(configurationResourceKeys);