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