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