Enable CreateChildServiceBB for Service-Macro-Create
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / workflow / tasks / WorkflowActionBBFailure.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.workflow.tasks;
24
25 import java.sql.Timestamp;
26 import java.util.Optional;
27 import org.camunda.bpm.engine.delegate.BpmnError;
28 import org.camunda.bpm.engine.delegate.DelegateExecution;
29 import org.onap.so.bpmn.core.WorkflowException;
30 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
31 import org.onap.so.constants.Status;
32 import org.onap.so.db.request.beans.InfraActiveRequests;
33 import org.onap.so.db.request.client.RequestsDbClient;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.stereotype.Component;
38 import static org.onap.so.bpmn.infrastructure.service.composition.ServiceCompositionConstants.CHILD_SVC_REQ_CORRELATION_ID;
39 import static org.onap.so.bpmn.infrastructure.service.composition.ServiceCompositionConstants.CHILD_SVC_REQ_ERROR;
40 import static org.onap.so.bpmn.infrastructure.service.composition.ServiceCompositionConstants.CHILD_SVC_REQ_MESSAGE_NAME;
41 import static org.onap.so.bpmn.infrastructure.service.composition.ServiceCompositionConstants.CHILD_SVC_REQ_STATUS;
42 import static org.onap.so.bpmn.infrastructure.service.composition.ServiceCompositionConstants.IS_CHILD_PROCESS;
43 import static org.onap.so.bpmn.infrastructure.service.composition.ServiceCompositionConstants.PARENT_CORRELATION_ID;
44
45 @Component
46 public class WorkflowActionBBFailure {
47
48     private static final String DEACTIVATE_FABRIC_CONFIGURATION_FLOW = "DeactivateFabricConfigurationBB";
49     private static final String UNASSIGN_FABRIC_CONFIGURATION_FLOW = "UnassignFabricConfigurationBB";
50     private static final String DELETE_FABRIC_CONFIGURATION_FLOW = "DeleteFabricConfigurationBB";
51     private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBFailure.class);
52     public static final String ROLLBACK_TARGET_STATE = "rollbackTargetState";
53
54     @Autowired
55     private RequestsDbClient requestDbclient;
56     @Autowired
57     private WorkflowAction workflowAction;
58
59     protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
60         try {
61             String requestId = (String) execution.getVariable("mso-request-id");
62             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
63             String errorMsg = "";
64             Optional<String> errorMsgOp = retrieveErrorMessage(execution);
65             if (errorMsgOp.isPresent()) {
66                 errorMsg = errorMsgOp.get();
67             } else {
68                 errorMsg = "Failed to determine error message";
69             }
70             Boolean isRollback = (Boolean) execution.getVariable("isRollback");
71             if (!Boolean.TRUE.equals(isRollback)) {
72                 request.setStatusMessage(errorMsg);
73             } else {
74                 request.setRollbackStatusMessage(errorMsg);
75             }
76             request.setProgress(Long.valueOf(100));
77             request.setLastModifiedBy("CamundaBPMN");
78             request.setEndTime(new Timestamp(System.currentTimeMillis()));
79             requestDbclient.updateInfraActiveRequests(request);
80         } catch (Exception e) {
81             logger.error(
82                     "Failed to update Request db with the status message after retry or rollback has been initialized.",
83                     e);
84         }
85     }
86
87     public void updateRequestStatusToFailed(DelegateExecution execution) {
88         try {
89             String requestId = (String) execution.getVariable("mso-request-id");
90             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
91             String rollbackErrorMsg = "";
92             String errorMsg = "";
93             String childErrorMessage = "";
94             Boolean rollbackCompletedSuccessfully = (Boolean) execution.getVariable("isRollbackComplete");
95             Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
96             ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
97             if (rollbackCompletedSuccessfully == null)
98                 rollbackCompletedSuccessfully = false;
99
100             if (isRollbackFailure == null)
101                 isRollbackFailure = false;
102
103             if (rollbackCompletedSuccessfully) {
104                 rollbackErrorMsg = "Rollback has been completed successfully.";
105                 childErrorMessage = rollbackErrorMsg;
106                 request.setRollbackStatusMessage(rollbackErrorMsg);
107                 execution.setVariable("RollbackErrorMessage", rollbackErrorMsg);
108                 String rollbackTargetState = (String) execution.getVariable(ROLLBACK_TARGET_STATE);
109                 request.setRequestStatus(rollbackTargetState);
110             } else if (isRollbackFailure) {
111                 if (ebb != null && ebb.getBuildingBlock() != null && ebb.getBuildingBlock().getBpmnFlowName() != null) {
112                     String flowName = ebb.getBuildingBlock().getBpmnFlowName();
113                     if (DEACTIVATE_FABRIC_CONFIGURATION_FLOW.equalsIgnoreCase(flowName)
114                             || UNASSIGN_FABRIC_CONFIGURATION_FLOW.equalsIgnoreCase(flowName)
115                             || DELETE_FABRIC_CONFIGURATION_FLOW.equalsIgnoreCase(flowName)) {
116                         String statusMessage = String.format(
117                                 "%s Warning: The vf-module is active but configuration was not removed completely for one or more VMs.",
118                                 request.getStatusMessage());
119                         request.setStatusMessage(statusMessage);
120                     }
121                 }
122                 Optional<String> rollbackErrorMsgOp = retrieveErrorMessage(execution);
123                 if (rollbackErrorMsgOp.isPresent()) {
124                     rollbackErrorMsg = rollbackErrorMsgOp.get();
125                 } else {
126                     rollbackErrorMsg = "Failed to determine rollback error message.";
127                 }
128                 childErrorMessage = rollbackErrorMsg;
129                 request.setRollbackStatusMessage(rollbackErrorMsg);
130                 execution.setVariable("RollbackErrorMessage", rollbackErrorMsg);
131                 request.setRequestStatus(Status.FAILED.toString());
132             } else {
133                 Optional<String> errorMsgOp = retrieveErrorMessage(execution);
134                 if (errorMsgOp.isPresent()) {
135                     errorMsg = errorMsgOp.get();
136                 } else {
137                     errorMsg = "Failed to determine error message";
138                 }
139                 childErrorMessage = errorMsg;
140                 request.setStatusMessage(errorMsg);
141                 execution.setVariable("ErrorMessage", errorMsg);
142                 String handlingCode = (String) execution.getVariable("handlingCode");
143                 if ("Abort".equalsIgnoreCase(handlingCode)) {
144                     request.setRequestStatus(Status.ABORTED.toString());
145                 } else {
146                     request.setRequestStatus(Status.FAILED.toString());
147                 }
148             }
149             if (ebb != null && ebb.getBuildingBlock() != null) {
150                 String flowStatus = "";
151                 if (rollbackCompletedSuccessfully) {
152                     flowStatus = "All Rollback flows have completed successfully";
153                 } else {
154                     flowStatus = ebb.getBuildingBlock().getBpmnFlowName() + " has failed.";
155                 }
156                 request.setFlowStatus(flowStatus);
157                 execution.setVariable("flowStatus", flowStatus);
158             }
159
160             if (Boolean.TRUE.equals(execution.getVariable(IS_CHILD_PROCESS))) {
161                 String parentCorrelationId = (String) execution.getVariable(PARENT_CORRELATION_ID);
162                 logger.info("Child service creation failed. Sending message to parent with correlationId: "
163                         + parentCorrelationId);
164                 execution.getProcessEngineServices().getRuntimeService()
165                         .createMessageCorrelation(CHILD_SVC_REQ_MESSAGE_NAME)
166                         .setVariable(CHILD_SVC_REQ_STATUS, "FAILED").setVariable(CHILD_SVC_REQ_ERROR, childErrorMessage)
167                         .processInstanceVariableEquals(CHILD_SVC_REQ_CORRELATION_ID, parentCorrelationId).correlate();
168             }
169
170             request.setProgress(Long.valueOf(100));
171             request.setLastModifiedBy("CamundaBPMN");
172             request.setEndTime(new Timestamp(System.currentTimeMillis()));
173             requestDbclient.updateInfraActiveRequests(request);
174         } catch (Exception e) {
175             workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
176         }
177     }
178
179     private Optional<String> retrieveErrorMessage(DelegateExecution execution) {
180         String errorMsg = null;
181         try {
182             WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
183             if (exception != null && (exception.getErrorMessage() != null || !"".equals(exception.getErrorMessage()))) {
184                 errorMsg = exception.getErrorMessage();
185             }
186             if (errorMsg == null || "".equals(errorMsg)) {
187                 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
188             }
189             if (errorMsg == null) {
190                 throw new IllegalStateException(
191                         "could not find WorkflowException or WorkflowExceptionErrorMessage in execution");
192             }
193             return Optional.of(errorMsg);
194         } catch (Exception ex) {
195             logger.error("Failed to extract workflow exception from execution.", ex);
196         }
197         return Optional.empty();
198     }
199
200     public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
201         execution.setVariable("isRollbackComplete", true);
202         updateRequestStatusToFailed(execution);
203     }
204
205     public void abortCallErrorHandling() {
206         String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
207         logger.error(msg);
208         throw new BpmnError(msg);
209     }
210 }