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