Merge "added in fix to use old volume group name for"
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / workflow / tasks / WorkflowActionBBTasks.java
index a17556f..343b25e 100644 (file)
 
 package org.onap.so.bpmn.infrastructure.workflow.tasks;
 
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-import javax.persistence.EntityNotFoundException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import org.camunda.bpm.engine.delegate.DelegateExecution;
-import org.onap.aai.domain.yang.Vnfc;
+import org.onap.aai.domain.yang.*;
+import org.onap.aaiclient.client.aai.AAIObjectType;
+import org.onap.aaiclient.client.aai.entities.Configuration;
 import org.onap.so.bpmn.common.DelegateExecutionImpl;
+import org.onap.so.bpmn.common.listener.db.RequestsDbListenerRunner;
 import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner;
 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
@@ -36,10 +36,8 @@ import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
-import org.onap.so.client.aai.AAIObjectType;
 import org.onap.so.client.exception.ExceptionBuilder;
 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
-import org.onap.so.db.catalog.beans.VnfResourceCustomization;
 import org.onap.so.db.catalog.client.CatalogDbClient;
 import org.onap.so.db.request.beans.InfraActiveRequests;
 import org.onap.so.db.request.client.RequestsDbClient;
@@ -50,8 +48,13 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.stereotype.Component;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import javax.persistence.EntityNotFoundException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
 
 @Component
 public class WorkflowActionBBTasks {
@@ -62,8 +65,12 @@ public class WorkflowActionBBTasks {
     private static final String G_ACTION = "requestAction";
     private static final String RETRY_COUNT = "retryCount";
     private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
-    private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
-    private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
+    private static final String ADD_FABRIC_CONFIGURATION_BB = "AddFabricConfigurationBB";
+    private static final String COMPLETED = "completed";
+    private static final String HANDLINGCODE = "handlingCode";
+    private static final String ROLLBACKTOCREATED = "RollbackToCreated";
+    private static final String REPLACEINSTANCE = "replaceInstance";
+    private static final String VFMODULE = "VfModule";
     protected String maxRetries = "mso.rainyDay.maxRetries";
     private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
 
@@ -81,6 +88,8 @@ public class WorkflowActionBBTasks {
     private CatalogDbClient catalogDbClient;
     @Autowired
     private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
+    @Autowired
+    private RequestsDbListenerRunner requestsDbListener;
 
     public void selectBB(DelegateExecution execution) {
         List<ExecuteBuildingBlock> flowsToExecute =
@@ -94,11 +103,7 @@ public class WorkflowActionBBTasks {
 
         execution.setVariable("buildingBlock", ebb);
         currentSequence++;
-        if (currentSequence >= flowsToExecute.size()) {
-            execution.setVariable("completed", true);
-        } else {
-            execution.setVariable("completed", false);
-        }
+        execution.setVariable(COMPLETED, currentSequence >= flowsToExecute.size());
         execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
     }
 
@@ -111,7 +116,8 @@ public class WorkflowActionBBTasks {
             }
         } catch (Exception ex) {
             logger.warn(
-                    "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
+                    "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.",
+                    ex);
         }
     }
 
@@ -137,7 +143,7 @@ public class WorkflowActionBBTasks {
     protected Long getPercentProgress(int completedBBs, int totalBBs) {
         double ratio = (completedBBs / (totalBBs * 1.0));
         int percentProgress = (int) (ratio * 95);
-        return new Long(percentProgress + 5);
+        return (long) (percentProgress + 5);
     }
 
     protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
@@ -207,7 +213,7 @@ public class WorkflowActionBBTasks {
             final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
             final String resourceName = (String) execution.getVariable("resourceName");
             String statusMessage = (String) execution.getVariable("StatusMessage");
-            String macroAction = "";
+            String macroAction;
             if (statusMessage == null) {
                 if (aLaCarte) {
                     macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
@@ -222,9 +228,10 @@ public class WorkflowActionBBTasks {
             request.setEndTime(endTime);
             request.setFlowStatus("Successfully completed all Building Blocks");
             request.setStatusMessage(macroAction);
-            request.setProgress(Long.valueOf(100));
+            request.setProgress(100L);
             request.setRequestStatus("COMPLETE");
             request.setLastModifiedBy("CamundaBPMN");
+            requestsDbListener.post(request, new DelegateExecutionImpl(execution));
             requestDbclient.updateInfraActiveRequests(request);
         } catch (Exception ex) {
             workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
@@ -232,7 +239,7 @@ public class WorkflowActionBBTasks {
     }
 
     public void checkRetryStatus(DelegateExecution execution) {
-        String handlingCode = (String) execution.getVariable("handlingCode");
+        String handlingCode = (String) execution.getVariable(HANDLINGCODE);
         String requestId = (String) execution.getVariable(G_REQUEST_ID);
         String retryDuration = (String) execution.getVariable("RetryDuration");
         int retryCount = (int) execution.getVariable(RETRY_COUNT);
@@ -240,11 +247,11 @@ public class WorkflowActionBBTasks {
         try {
             envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
         } catch (Exception ex) {
-            logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
+            logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
             envMaxRetries = 5;
         }
         int nextCount = retryCount + 1;
-        if (handlingCode.equals("Retry")) {
+        if ("Retry".equals(handlingCode)) {
             workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
             try {
                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
@@ -255,8 +262,8 @@ public class WorkflowActionBBTasks {
                 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
             }
             if (retryCount < envMaxRetries) {
-                int currSequence = (int) execution.getVariable("gCurrentSequence");
-                execution.setVariable("gCurrentSequence", currSequence - 1);
+                int currSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
+                execution.setVariable(G_CURRENT_SEQUENCE, currSequence - 1);
                 execution.setVariable(RETRY_COUNT, nextCount);
             } else {
                 workflowAction.buildAndThrowException(execution,
@@ -272,23 +279,45 @@ public class WorkflowActionBBTasks {
      * working on.
      */
     public void rollbackExecutionPath(DelegateExecution execution) {
+        final String action = (String) execution.getVariable(G_ACTION);
+        final String resourceName = (String) execution.getVariable("resourceName");
         if (!(boolean) execution.getVariable("isRollback")) {
             List<ExecuteBuildingBlock> flowsToExecute =
                     (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
-            List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
+
+            List<ExecuteBuildingBlock> flowsToExecuteChangeBBs = flowsToExecute.stream()
+                    .filter(buildingBlock -> buildingBlock.getBuildingBlock().getBpmnFlowName().startsWith("Change"))
+                    .collect(Collectors.toList());
+
+            List<ExecuteBuildingBlock> rollbackFlows = new ArrayList<>();
             int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
             int listSize = flowsToExecute.size();
+
             for (int i = listSize - 1; i >= 0; i--) {
                 if (i > currentSequence - 1) {
                     flowsToExecute.remove(i);
                 } else {
                     String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
-                    if (flowName.contains("Assign")) {
-                        flowName = "Unassign" + flowName.substring(6, flowName.length());
-                    } else if (flowName.contains("Create")) {
-                        flowName = "Delete" + flowName.substring(6, flowName.length());
-                    } else if (flowName.contains("Activate")) {
-                        flowName = "Deactivate" + flowName.substring(8, flowName.length());
+                    if (flowName.startsWith("Assign")) {
+                        flowName = flowName.replaceFirst("Assign", "Unassign");
+                    } else if (flowName.startsWith("Create")) {
+                        flowName = flowName.replaceFirst("Create", "Delete");
+                    } else if (flowName.startsWith("Activate")) {
+                        flowName = flowName.replaceFirst("Activate", "Deactivate");
+                    } else if (flowName.startsWith("Add")) {
+                        flowName = flowName.replaceFirst("Add", "Delete");
+                    } else if (flowName.startsWith("VNF")) {
+                        if (flowName.startsWith("VNFSet")) {
+                            flowName = flowName.replaceFirst("VNFSet", "VNFUnset");
+                        } else if (flowName.startsWith("VNFLock")) {
+                            flowName = flowName.replaceFirst("VNFLock", "VNFUnlock");
+                        } else if (flowName.startsWith("VNFStop")) {
+                            flowName = flowName.replaceFirst("VNFStop", "VNFStart");
+                        } else if (flowName.startsWith("VNFQuiesce")) {
+                            flowName = flowName.replaceFirst("VNFQuiesce", "VNFResume");
+                        } else {
+                            continue;
+                        }
                     } else {
                         continue;
                     }
@@ -297,29 +326,38 @@ public class WorkflowActionBBTasks {
                 }
             }
 
-            String handlingCode = (String) execution.getVariable("handlingCode");
-            List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
-            rollbackFlowsFiltered.addAll(rollbackFlows);
-            if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
-                for (int i = 0; i < rollbackFlows.size(); i++) {
-                    if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
-                        rollbackFlowsFiltered.remove(rollbackFlows.get(i));
-                    } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
-                            && handlingCode.equals("RollbackToCreated")) {
-                        rollbackFlowsFiltered.remove(rollbackFlows.get(i));
+            String handlingCode = (String) execution.getVariable(HANDLINGCODE);
+            List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>(rollbackFlows);
+            if ("RollbackToAssigned".equals(handlingCode) || ROLLBACKTOCREATED.equals(handlingCode)) {
+                for (ExecuteBuildingBlock rollbackFlow : rollbackFlows) {
+                    if (rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("Unassign")
+                            && !rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("FabricConfiguration")) {
+                        rollbackFlowsFiltered.remove(rollbackFlow);
+                    } else if (rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("Delete")
+                            && ROLLBACKTOCREATED.equals(handlingCode)) {
+                        rollbackFlowsFiltered.remove(rollbackFlow);
                     }
                 }
             }
 
+            List<ExecuteBuildingBlock> rollbackFlowsFilteredNonChangeBBs = new ArrayList<>();
+            if (action.equals(REPLACEINSTANCE) && resourceName.equals(VFMODULE)) {
+                for (ExecuteBuildingBlock executeBuildingBlock : rollbackFlowsFiltered) {
+                    if (!executeBuildingBlock.getBuildingBlock().getBpmnFlowName().startsWith("Change")) {
+                        rollbackFlowsFilteredNonChangeBBs.add(executeBuildingBlock);
+                    }
+                }
+                rollbackFlowsFiltered.clear();
+                rollbackFlowsFiltered.addAll(flowsToExecuteChangeBBs);
+                rollbackFlowsFiltered.addAll(rollbackFlowsFilteredNonChangeBBs);
+            }
+
             workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
-            if (rollbackFlows.isEmpty())
-                execution.setVariable("isRollbackNeeded", false);
-            else
-                execution.setVariable("isRollbackNeeded", true);
+            execution.setVariable("isRollbackNeeded", !rollbackFlows.isEmpty());
             execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
-            execution.setVariable("handlingCode", "PreformingRollback");
+            execution.setVariable(HANDLINGCODE, "PreformingRollback");
             execution.setVariable("isRollback", true);
-            execution.setVariable("gCurrentSequence", 0);
+            execution.setVariable(G_CURRENT_SEQUENCE, 0);
             execution.setVariable(RETRY_COUNT, 0);
         } else {
             workflowAction.buildAndThrowException(execution,
@@ -348,8 +386,11 @@ public class WorkflowActionBBTasks {
             } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
                 request.setInstanceGroupId(resourceId);
             }
+            setInstanceName(resourceId, resourceType, request);
+            request.setLastModifiedBy("CamundaBPMN");
             requestDbclient.updateInfraActiveRequests(request);
         } catch (Exception ex) {
+            logger.error("Exception in updateInstanceId", ex);
             workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
         }
     }
@@ -357,12 +398,12 @@ public class WorkflowActionBBTasks {
     public void postProcessingExecuteBB(DelegateExecution execution) {
         List<ExecuteBuildingBlock> flowsToExecute =
                 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
-        String handlingCode = (String) execution.getVariable("handlingCode");
+        String handlingCode = (String) execution.getVariable(HANDLINGCODE);
         final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
         ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
         String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
-        if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
+        if ("ActivateVfModuleBB".equalsIgnoreCase(bbFlowName) && aLaCarte && "Success".equalsIgnoreCase(handlingCode)) {
             postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
         }
     }
@@ -390,54 +431,98 @@ public class WorkflowActionBBTasks {
                 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
                         && fabricConfig.getConfigurationResource().getToscaNodeType() != null
                         && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
-                    String configurationId = UUID.randomUUID().toString();
+                    String configurationId = getConfigurationId(vnfc);
                     ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
                     configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
                     configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
                     configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
                     configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
-                    ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
+                    ExecuteBuildingBlock addConfigBB = getExecuteBBForConfig(ADD_FABRIC_CONFIGURATION_BB, ebb,
                             configurationId, configurationResourceKeys);
-                    ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
-                            configurationId, configurationResourceKeys);
-                    flowsToExecute.add(assignConfigBB);
-                    flowsToExecute.add(activateConfigBB);
-                    flowsToExecute.stream()
-                            .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
-                                    executeBB.getBuildingBlock().getBpmnFlowName()));
+                    flowsToExecute.add(addConfigBB);
+                    flowsToExecute.forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
+                            executeBB.getBuildingBlock().getBpmnFlowName()));
                     execution.setVariable("flowsToExecute", flowsToExecute);
-                    execution.setVariable("completed", false);
+                    execution.setVariable(COMPLETED, false);
                 } else {
-                    logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
+                    logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
                 }
             }
         } catch (EntityNotFoundException e) {
-            logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
+            logger.debug("Will not be running Fabric Config Building Blocks", e);
         } catch (Exception e) {
             String errorMessage = "Error occurred in post processing of Vf Module create";
-            execution.setVariable("handlingCode", "RollbackToCreated");
+            execution.setVariable(HANDLINGCODE, ROLLBACKTOCREATED);
             execution.setVariable("WorkflowActionErrorMessage", errorMessage);
             logger.error(errorMessage, e);
         }
     }
 
+    protected String getConfigurationId(Vnfc vnfc) {
+        List<Configuration> configurations =
+                workflowAction.getRelatedResourcesInVnfc(vnfc, Configuration.class, AAIObjectType.CONFIGURATION);
+        if (!configurations.isEmpty()) {
+            Configuration configuration = configurations.get(0);
+            return configuration.getConfigurationId();
+        } else {
+            return UUID.randomUUID().toString();
+        }
+    }
+
     protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
             String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
-        ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
-        BuildingBlock buildingBlock = new BuildingBlock();
-        buildingBlock.setBpmnFlowName(bbName);
-        buildingBlock.setMsoId(UUID.randomUUID().toString());
-        configBB.setaLaCarte(ebb.isaLaCarte());
-        configBB.setApiVersion(ebb.getApiVersion());
-        configBB.setRequestAction(ebb.getRequestAction());
-        configBB.setVnfType(ebb.getVnfType());
-        configBB.setRequestId(ebb.getRequestId());
-        configBB.setRequestDetails(ebb.getRequestDetails());
-        configBB.setBuildingBlock(buildingBlock);
-        WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
+        BuildingBlock buildingBlock =
+                new BuildingBlock().setBpmnFlowName(bbName).setMsoId(UUID.randomUUID().toString());
+
+        WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(ebb.getWorkflowResourceIds());
         workflowResourceIds.setConfigurationId(configurationId);
-        configBB.setWorkflowResourceIds(workflowResourceIds);
-        configBB.setConfigurationResourceKeys(configurationResourceKeys);
-        return configBB;
+        return new ExecuteBuildingBlock().setaLaCarte(ebb.isaLaCarte()).setApiVersion(ebb.getApiVersion())
+                .setRequestAction(ebb.getRequestAction()).setVnfType(ebb.getVnfType()).setRequestId(ebb.getRequestId())
+                .setRequestDetails(ebb.getRequestDetails()).setBuildingBlock(buildingBlock)
+                .setWorkflowResourceIds(workflowResourceIds).setConfigurationResourceKeys(configurationResourceKeys);
+    }
+
+    protected void setInstanceName(String resourceId, WorkflowType resourceType, InfraActiveRequests request) {
+        logger.debug("Setting instanceName in infraActiveRequest");
+        try {
+            if (resourceType == WorkflowType.SERVICE && request.getServiceInstanceName() == null) {
+                ServiceInstance service = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
+                if (service != null) {
+                    request.setServiceInstanceName(service.getServiceInstanceName());
+                }
+            } else if (resourceType == WorkflowType.VNF && request.getVnfName() == null) {
+                GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(resourceId);
+                if (vnf != null) {
+                    request.setVnfName(vnf.getVnfName());
+                }
+            } else if (resourceType == WorkflowType.VFMODULE && request.getVfModuleName() == null) {
+                VfModule vfModule = bbInputSetupUtils.getAAIVfModule(request.getVnfId(), resourceId);
+                if (vfModule != null) {
+                    request.setVfModuleName(vfModule.getVfModuleName());
+                }
+            } else if (resourceType == WorkflowType.VOLUMEGROUP && request.getVolumeGroupName() == null) {
+                Optional<VolumeGroup> volumeGroup =
+                        bbInputSetupUtils.getRelatedVolumeGroupByIdFromVnf(request.getVnfId(), resourceId);
+                volumeGroup.ifPresent(group -> request.setVolumeGroupName(group.getVolumeGroupName()));
+            } else if (resourceType == WorkflowType.NETWORK && request.getNetworkName() == null) {
+                L3Network network = bbInputSetupUtils.getAAIL3Network(resourceId);
+                if (network != null) {
+                    request.setNetworkName(network.getNetworkName());
+                }
+            } else if (resourceType == WorkflowType.CONFIGURATION && request.getConfigurationName() == null) {
+                org.onap.aai.domain.yang.Configuration configuration =
+                        bbInputSetupUtils.getAAIConfiguration(resourceId);
+                if (configuration != null) {
+                    request.setConfigurationName(configuration.getConfigurationName());
+                }
+            } else if (resourceType == WorkflowType.INSTANCE_GROUP && request.getInstanceGroupName() == null) {
+                InstanceGroup instanceGroup = bbInputSetupUtils.getAAIInstanceGroup(resourceId);
+                if (instanceGroup != null) {
+                    request.setInstanceGroupName(instanceGroup.getInstanceGroupName());
+                }
+            }
+        } catch (Exception ex) {
+            logger.error("Exception in setInstanceName", ex);
+        }
     }
 }