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