Merge "Add SO Same deployment id on deployed custom workflows"
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / bpmn / servicedecomposition / tasks / ExecuteBuildingBlockRainyDay.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2018 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.servicedecomposition.tasks;
24
25 import java.util.Map;
26 import org.camunda.bpm.engine.delegate.BpmnError;
27 import org.camunda.bpm.engine.delegate.DelegateExecution;
28 import org.onap.so.bpmn.core.WorkflowException;
29 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
30 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
31 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
32 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
33 import org.onap.so.constants.Status;
34 import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus;
35 import org.onap.so.db.catalog.client.CatalogDbClient;
36 import org.onap.so.db.request.beans.InfraActiveRequests;
37 import org.onap.so.db.request.client.RequestsDbClient;
38 import org.onap.so.utils.TargetEntities;
39 import org.onap.so.utils.TargetEntity;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.core.env.Environment;
44 import org.springframework.stereotype.Component;
45
46 @Component
47 public class ExecuteBuildingBlockRainyDay {
48
49     private static final Logger logger = LoggerFactory.getLogger(ExecuteBuildingBlockRainyDay.class);
50     public static final String HANDLING_CODE = "handlingCode";
51     public static final String ROLLBACK_TARGET_STATE = "rollbackTargetState";
52
53     @Autowired
54     private CatalogDbClient catalogDbClient;
55     @Autowired
56     private RequestsDbClient requestDbclient;
57     private static final String ASTERISK = "*";
58
59     @Autowired
60     private Environment environment;
61     protected String retryDurationPath = "mso.rainyDay.retryDurationMultiplier";
62     protected String defaultCode = "mso.rainyDay.defaultCode";
63     protected String maxRetries = "mso.rainyDay.maxRetries";
64
65     public void setRetryTimer(DelegateExecution execution) {
66         try {
67             int retryDurationMult = Integer.parseInt(this.environment.getProperty(retryDurationPath));
68             int retryCount = (int) execution.getVariable("retryCount");
69             int retryTimeToWait = (int) Math.pow(retryDurationMult, retryCount) * 10;
70             String RetryDuration = "PT" + retryTimeToWait + "S";
71             execution.setVariable("RetryDuration", RetryDuration);
72         } catch (Exception e) {
73             logger.error("Exception occurred", e);
74             throw new BpmnError("Unknown error incrementing retry counter");
75         }
76     }
77
78     public void queryRainyDayTable(DelegateExecution execution, boolean primaryPolicy) {
79         try {
80             ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
81             String bbName = ebb.getBuildingBlock().getBpmnFlowName();
82             GeneralBuildingBlock gBBInput = (GeneralBuildingBlock) execution.getVariable("gBBInput");
83             String requestId = (String) execution.getVariable("mso-request-id");
84             Map<ResourceKey, String> lookupKeyMap = (Map<ResourceKey, String>) execution.getVariable("lookupKeyMap");
85             String serviceType = ASTERISK;
86             boolean aLaCarte = (boolean) execution.getVariable("aLaCarte");
87             boolean suppressRollback = (boolean) execution.getVariable("suppressRollback");
88             WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
89             if (workflowException != null) {
90                 execution.setVariable("WorkflowExceptionErrorMessage", workflowException.getErrorMessage());
91             } else {
92                 logger.debug("WorkflowException is null, unable to set WorkflowExceptionErrorMessage");
93             }
94             String handlingCode = "";
95
96             if (suppressRollback) {
97                 handlingCode = "Abort";
98             } else {
99                 try {
100                     serviceType = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
101                             .getModelInfoServiceInstance().getServiceType();
102                     if (serviceType == null || serviceType.isEmpty()) {
103                         serviceType = ASTERISK;
104                     }
105                 } catch (Exception ex) {
106                     // keep default serviceType value
107                     logger.error("Exception in serviceType retrivel", ex);
108                 }
109                 String vnfType = ASTERISK;
110                 try {
111                     for (GenericVnf vnf : gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
112                             .getVnfs()) {
113                         if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
114                             vnfType = vnf.getVnfType();
115                         }
116                     }
117                 } catch (Exception ex) {
118                     // keep default vnfType value
119                     logger.error("Exception in vnfType retrivel", ex);
120                 }
121
122                 String errorCode = ASTERISK;
123                 try {
124                     errorCode = "" + workflowException.getErrorCode();
125                 } catch (Exception ex) {
126                     // keep default errorCode value
127                     logger.error("Exception in errorCode retrivel", ex);
128                 }
129
130                 try {
131                     errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode");
132                 } catch (Exception ex) {
133                     // keep default errorCode value
134                     logger.error("Exception in errorCode retrivel", ex);
135                 }
136
137                 String workStep = ASTERISK;
138                 try {
139                     workStep = workflowException.getWorkStep();
140                 } catch (Exception ex) {
141                     // keep default workStep value
142                     logger.error("Exception in workStep retrivel", ex);
143                 }
144
145                 String errorMessage = ASTERISK;
146                 try {
147                     errorMessage = workflowException.getErrorMessage();
148                 } catch (Exception ex) {
149                     // keep default workStep value
150                     logger.error("Exception in errorMessage retrivel", ex);
151                 }
152
153                 String serviceRole = ASTERISK;
154                 try {
155                     serviceRole = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
156                             .getModelInfoServiceInstance().getServiceRole();
157                     if (serviceRole == null || serviceRole.isEmpty()) {
158                         serviceRole = ASTERISK;
159                     }
160                 } catch (Exception ex) {
161                     // keep default serviceRole value
162                 }
163
164                 RainyDayHandlerStatus rainyDayHandlerStatus;
165                 rainyDayHandlerStatus = catalogDbClient.getRainyDayHandlerStatus(bbName, serviceType, vnfType,
166                         errorCode, workStep, errorMessage, serviceRole);
167
168                 if (rainyDayHandlerStatus == null) {
169                     handlingCode = "Abort";
170                 } else {
171                     if (primaryPolicy) {
172                         handlingCode = rainyDayHandlerStatus.getPolicy();
173                     } else {
174                         handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
175                     }
176                 }
177                 if (!primaryPolicy) {
178                     try {
179                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
180                         request.setRetryStatusMessage("Retries have been exhausted.");
181                         requestDbclient.updateInfraActiveRequests(request);
182                     } catch (Exception ex) {
183                         logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex);
184                     }
185                 }
186                 if ("RollbackToAssigned".equals(handlingCode) && !aLaCarte) {
187                     handlingCode = "Rollback";
188                 }
189                 if (handlingCode.startsWith("Rollback")) {
190                     String targetState = "";
191                     if ("RollbackToAssigned".equalsIgnoreCase(handlingCode)) {
192                         targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString();
193                     } else if ("RollbackToCreated".equalsIgnoreCase(handlingCode)) {
194                         targetState = Status.ROLLED_BACK_TO_CREATED.toString();
195                     } else {
196                         targetState = Status.ROLLED_BACK.toString();
197                     }
198                     execution.setVariable(ROLLBACK_TARGET_STATE, targetState);
199                     logger.debug("Rollback target state is: {}", targetState);
200                 }
201             }
202             logger.debug("RainyDayHandler Status Code is: {}", handlingCode);
203             execution.setVariable(HANDLING_CODE, handlingCode);
204         } catch (Exception e) {
205             String code = this.environment.getProperty(defaultCode);
206             logger.error("Failed to determine RainyDayHandler Status. Seting handlingCode = {}", code, e);
207             execution.setVariable(HANDLING_CODE, code);
208         }
209         try {
210             int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
211             execution.setVariable("maxRetries", envMaxRetries);
212         } catch (Exception ex) {
213             logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
214             execution.setVariable("maxRetries", 5);
215         }
216     }
217
218     public void setHandlingStatusSuccess(DelegateExecution execution) {
219         execution.setVariable(HANDLING_CODE, "Success");
220     }
221
222     public void updateExtSystemErrorSource(DelegateExecution execution) {
223         try {
224             String requestId = (String) execution.getVariable("mso-request-id");
225             WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
226             TargetEntities extSystemErrorSource = exception.getExtSystemErrorSource();
227             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
228             Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
229             if (isRollbackFailure == null) {
230                 isRollbackFailure = false;
231             }
232
233             if (extSystemErrorSource != null) {
234                 String extSystemErrorSourceString = extSystemErrorSource.toString();
235                 if (isRollbackFailure) {
236                     logger.debug("Updating extSystemErrorSource for isRollbackFailure to {} for request: {}",
237                             extSystemErrorSourceString, requestId);
238                     request.setRollbackExtSystemErrorSource(extSystemErrorSourceString);
239                 } else {
240                     logger.debug("Updating extSystemErrorSource to {} for request: {}", extSystemErrorSourceString,
241                             requestId);
242                     request.setExtSystemErrorSource(extSystemErrorSourceString);
243                 }
244             } else if (isRollbackFailure) {
245                 logger.debug(
246                         "rollbackExtSystemErrorSource is null for isRollbackFailure. Setting rollbackExtSystemErrorSource to UNKNOWN");
247                 request.setRollbackExtSystemErrorSource(TargetEntity.UNKNOWN.toString());
248             } else {
249                 logger.debug("extSystemErrorSource is null. Setting extSystemErrorSource to UNKNOWN");
250                 request.setExtSystemErrorSource(TargetEntity.UNKNOWN.toString());
251             }
252
253             request.setLastModifiedBy("CamundaBPMN");
254             requestDbclient.updateInfraActiveRequests(request);
255         } catch (Exception e) {
256             logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: ", e);
257         }
258     }
259
260 }