Merge "Added null check to prevent call of getVnfResources() method for null vf object"
[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                 RainyDayHandlerStatus rainyDayHandlerStatus;
148                 rainyDayHandlerStatus = catalogDbClient.getRainyDayHandlerStatus(bbName, serviceType, vnfType,
149                         errorCode, workStep, errorMessage);
150
151                 if (rainyDayHandlerStatus == null) {
152                     handlingCode = "Abort";
153                 } else {
154                     if (primaryPolicy) {
155                         handlingCode = rainyDayHandlerStatus.getPolicy();
156                     } else {
157                         handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
158                     }
159                 }
160                 if (!primaryPolicy) {
161                     try {
162                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
163                         request.setRetryStatusMessage("Retries have been exhausted.");
164                         requestDbclient.updateInfraActiveRequests(request);
165                     } catch (Exception ex) {
166                         logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex);
167                     }
168                 }
169                 if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) {
170                     handlingCode = "Rollback";
171                 }
172                 if (handlingCode.startsWith("Rollback")) {
173                     String targetState = "";
174                     if (handlingCode.equalsIgnoreCase("RollbackToAssigned")) {
175                         targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString();
176                     } else if (handlingCode.equalsIgnoreCase("RollbackToCreated")) {
177                         targetState = Status.ROLLED_BACK_TO_CREATED.toString();
178                     } else {
179                         targetState = Status.ROLLED_BACK.toString();
180                     }
181                     execution.setVariable(ROLLBACK_TARGET_STATE, targetState);
182                     logger.debug("Rollback target state is: {}", targetState);
183                 }
184             }
185             logger.debug("RainyDayHandler Status Code is: {}", handlingCode);
186             execution.setVariable(HANDLING_CODE, handlingCode);
187         } catch (Exception e) {
188             String code = this.environment.getProperty(defaultCode);
189             logger.error("Failed to determine RainyDayHandler Status. Seting handlingCode = {}", code, e);
190             execution.setVariable(HANDLING_CODE, code);
191         }
192         try {
193             int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
194             execution.setVariable("maxRetries", envMaxRetries);
195         } catch (Exception ex) {
196             logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
197             execution.setVariable("maxRetries", 5);
198         }
199     }
200
201     public void setHandlingStatusSuccess(DelegateExecution execution) {
202         execution.setVariable(HANDLING_CODE, "Success");
203     }
204
205     public void updateExtSystemErrorSource(DelegateExecution execution) {
206         try {
207             String requestId = (String) execution.getVariable("mso-request-id");
208             WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
209             TargetEntities extSystemErrorSource = exception.getExtSystemErrorSource();
210             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
211             Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
212             if (isRollbackFailure == null) {
213                 isRollbackFailure = false;
214             }
215
216             if (extSystemErrorSource != null) {
217                 String extSystemErrorSourceString = extSystemErrorSource.toString();
218                 if (isRollbackFailure) {
219                     logger.debug("Updating extSystemErrorSource for isRollbackFailure to {} for request: {}",
220                             extSystemErrorSourceString, requestId);
221                     request.setRollbackExtSystemErrorSource(extSystemErrorSourceString);
222                 } else {
223                     logger.debug("Updating extSystemErrorSource to {} for request: {}", extSystemErrorSourceString,
224                             requestId);
225                     request.setExtSystemErrorSource(extSystemErrorSourceString);
226                 }
227             } else if (isRollbackFailure) {
228                 logger.debug(
229                         "rollbackExtSystemErrorSource is null for isRollbackFailure. Setting rollbackExtSystemErrorSource to UNKNOWN");
230                 request.setRollbackExtSystemErrorSource(TargetEntity.UNKNOWN.toString());
231             } else {
232                 logger.debug("extSystemErrorSource is null. Setting extSystemErrorSource to UNKNOWN");
233                 request.setExtSystemErrorSource(TargetEntity.UNKNOWN.toString());
234             }
235
236             request.setLastModifiedBy("CamundaBPMN");
237             requestDbclient.updateInfraActiveRequests(request);
238         } catch (Exception e) {
239             logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: "
240                     + e.getMessage());
241         }
242     }
243
244 }