Merge "Sonar fix in mso-adapter-utils"
[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                 }
108                 String vnfType = ASTERISK;
109                 try {
110                     for (GenericVnf vnf : gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
111                             .getVnfs()) {
112                         if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
113                             vnfType = vnf.getVnfType();
114                         }
115                     }
116                 } catch (Exception ex) {
117                     // keep default vnfType value
118                 }
119
120                 String errorCode = ASTERISK;
121                 try {
122                     errorCode = "" + workflowException.getErrorCode();
123                 } catch (Exception ex) {
124                     // keep default errorCode value
125                 }
126
127                 try {
128                     errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode");
129                 } catch (Exception ex) {
130                     // keep default errorCode value
131                 }
132
133                 String workStep = ASTERISK;
134                 try {
135                     workStep = workflowException.getWorkStep();
136                 } catch (Exception ex) {
137                     // keep default workStep value
138                 }
139
140                 String errorMessage = ASTERISK;
141                 try {
142                     errorMessage = workflowException.getErrorMessage();
143                 } catch (Exception ex) {
144                     // keep default workStep value
145                 }
146
147                 String serviceRole = ASTERISK;
148                 try {
149                     serviceRole = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
150                             .getModelInfoServiceInstance().getServiceRole();
151                     if (serviceRole == null || serviceRole.isEmpty()) {
152                         serviceRole = ASTERISK;
153                     }
154                 } catch (Exception ex) {
155                     // keep default serviceRole value
156                 }
157
158                 RainyDayHandlerStatus rainyDayHandlerStatus;
159                 rainyDayHandlerStatus = catalogDbClient.getRainyDayHandlerStatus(bbName, serviceType, vnfType,
160                         errorCode, workStep, errorMessage, serviceRole);
161
162                 if (rainyDayHandlerStatus == null) {
163                     handlingCode = "Abort";
164                 } else {
165                     if (primaryPolicy) {
166                         handlingCode = rainyDayHandlerStatus.getPolicy();
167                     } else {
168                         handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
169                     }
170                 }
171                 if (!primaryPolicy) {
172                     try {
173                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
174                         request.setRetryStatusMessage("Retries have been exhausted.");
175                         requestDbclient.updateInfraActiveRequests(request);
176                     } catch (Exception ex) {
177                         logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex);
178                     }
179                 }
180                 if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) {
181                     handlingCode = "Rollback";
182                 }
183                 if (handlingCode.startsWith("Rollback")) {
184                     String targetState = "";
185                     if (handlingCode.equalsIgnoreCase("RollbackToAssigned")) {
186                         targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString();
187                     } else if (handlingCode.equalsIgnoreCase("RollbackToCreated")) {
188                         targetState = Status.ROLLED_BACK_TO_CREATED.toString();
189                     } else {
190                         targetState = Status.ROLLED_BACK.toString();
191                     }
192                     execution.setVariable(ROLLBACK_TARGET_STATE, targetState);
193                     logger.debug("Rollback target state is: {}", targetState);
194                 }
195             }
196             logger.debug("RainyDayHandler Status Code is: {}", handlingCode);
197             execution.setVariable(HANDLING_CODE, handlingCode);
198         } catch (Exception e) {
199             String code = this.environment.getProperty(defaultCode);
200             logger.error("Failed to determine RainyDayHandler Status. Seting handlingCode = {}", code, e);
201             execution.setVariable(HANDLING_CODE, code);
202         }
203         try {
204             int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
205             execution.setVariable("maxRetries", envMaxRetries);
206         } catch (Exception ex) {
207             logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
208             execution.setVariable("maxRetries", 5);
209         }
210     }
211
212     public void setHandlingStatusSuccess(DelegateExecution execution) {
213         execution.setVariable(HANDLING_CODE, "Success");
214     }
215
216     public void updateExtSystemErrorSource(DelegateExecution execution) {
217         try {
218             String requestId = (String) execution.getVariable("mso-request-id");
219             WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
220             TargetEntities extSystemErrorSource = exception.getExtSystemErrorSource();
221             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
222             Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
223             if (isRollbackFailure == null) {
224                 isRollbackFailure = false;
225             }
226
227             if (extSystemErrorSource != null) {
228                 String extSystemErrorSourceString = extSystemErrorSource.toString();
229                 if (isRollbackFailure) {
230                     logger.debug("Updating extSystemErrorSource for isRollbackFailure to {} for request: {}",
231                             extSystemErrorSourceString, requestId);
232                     request.setRollbackExtSystemErrorSource(extSystemErrorSourceString);
233                 } else {
234                     logger.debug("Updating extSystemErrorSource to {} for request: {}", extSystemErrorSourceString,
235                             requestId);
236                     request.setExtSystemErrorSource(extSystemErrorSourceString);
237                 }
238             } else if (isRollbackFailure) {
239                 logger.debug(
240                         "rollbackExtSystemErrorSource is null for isRollbackFailure. Setting rollbackExtSystemErrorSource to UNKNOWN");
241                 request.setRollbackExtSystemErrorSource(TargetEntity.UNKNOWN.toString());
242             } else {
243                 logger.debug("extSystemErrorSource is null. Setting extSystemErrorSource to UNKNOWN");
244                 request.setExtSystemErrorSource(TargetEntity.UNKNOWN.toString());
245             }
246
247             request.setLastModifiedBy("CamundaBPMN");
248             requestDbclient.updateInfraActiveRequests(request);
249         } catch (Exception e) {
250             logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: "
251                     + e.getMessage());
252         }
253     }
254
255 }