rename package for external use
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / client / exception / ExceptionBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 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.client.exception;
24
25 import java.io.IOException;
26 import java.util.List;
27 import java.util.stream.Collectors;
28 import java.util.stream.Stream;
29 import org.camunda.bpm.engine.delegate.BpmnError;
30 import org.camunda.bpm.engine.delegate.DelegateExecution;
31 import org.onap.aai.domain.yang.LInterface;
32 import org.onap.aai.domain.yang.Vserver;
33 import org.onap.logging.filter.base.ONAPComponents;
34 import org.onap.logging.filter.base.ONAPComponentsList;
35 import org.onap.so.bpmn.common.BuildingBlockExecution;
36 import org.onap.so.bpmn.common.DelegateExecutionImpl;
37 import org.onap.so.bpmn.core.WorkflowException;
38 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
39 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
40 import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
41 import org.onap.aaiclient.client.aai.AAIObjectType;
42 import org.onap.aaiclient.client.graphinventory.GraphInventoryCommonObjectMapperProvider;
43 import org.onap.logging.filter.base.ErrorCode;
44 import org.onap.so.logger.LoggingAnchor;
45 import org.onap.so.logger.MessageEnum;
46 import org.onap.so.objects.audit.AAIObjectAudit;
47 import org.onap.so.objects.audit.AAIObjectAuditList;
48 import org.onap.so.utils.Components;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.stereotype.Component;
52
53
54 @Component
55 public class ExceptionBuilder {
56     private static final Logger logger = LoggerFactory.getLogger(ExceptionBuilder.class);
57
58
59     protected ExtractPojosForBB getExtractPojosForBB() {
60         return new ExtractPojosForBB();
61     }
62
63     public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, Exception exception) {
64         String msg = "Exception in %s.%s ";
65         try {
66             logger.error("Exception occurred", exception);
67
68             String errorVariable = "Error%s%s";
69
70             StackTraceElement[] trace = Thread.currentThread().getStackTrace();
71             for (StackTraceElement traceElement : trace) {
72                 if (!traceElement.getClassName().equals(this.getClass().getName())
73                         && !traceElement.getClassName().equals(Thread.class.getName())) {
74                     msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
75                     String shortClassName =
76                             traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
77                     errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
78                     break;
79                 }
80             }
81
82             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
83                     ErrorCode.UnknownError.getValue(), msg.toString());
84             execution.setVariable(errorVariable, exception.getMessage());
85         } catch (Exception ex) {
86             // log trace, allow process to complete gracefully
87             logger.error("Exception occurred", ex);
88         }
89
90         if (exception.getMessage() != null)
91             msg = msg.concat(exception.getMessage());
92         buildAndThrowWorkflowException(execution, errorCode, msg);
93     }
94
95     public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, Exception exception,
96             ONAPComponentsList extSystemErrorSource) {
97         String msg = "Exception in %s.%s ";
98         try {
99             logger.error("Exception occurred", exception);
100
101             String errorVariable = "Error%s%s";
102
103             StackTraceElement[] trace = Thread.currentThread().getStackTrace();
104             for (StackTraceElement traceElement : trace) {
105                 if (!traceElement.getClassName().equals(this.getClass().getName())
106                         && !traceElement.getClassName().equals(Thread.class.getName())) {
107                     msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
108                     String shortClassName =
109                             traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
110                     errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
111                     break;
112                 }
113             }
114
115             logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
116                     ErrorCode.UnknownError.getValue(), msg.toString());
117             execution.setVariable(errorVariable, exception.getMessage());
118         } catch (Exception ex) {
119             // log trace, allow process to complete gracefully
120             logger.error("Exception occurred", ex);
121         }
122
123         if (exception.getMessage() != null)
124             msg = msg.concat(exception.getMessage());
125         buildAndThrowWorkflowException(execution, errorCode, msg, extSystemErrorSource);
126     }
127
128     public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, Exception exception) {
129         String msg = "Exception in %s.%s ";
130         try {
131             logger.error("Exception occurred", exception);
132
133             String errorVariable = "Error%s%s";
134
135             StackTraceElement[] trace = Thread.currentThread().getStackTrace();
136             for (StackTraceElement traceElement : trace) {
137                 if (!traceElement.getClassName().equals(this.getClass().getName())
138                         && !traceElement.getClassName().equals(Thread.class.getName())) {
139                     msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
140                     String shortClassName =
141                             traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
142                     errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
143                     break;
144                 }
145             }
146             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
147                     ErrorCode.UnknownError.getValue(), msg.toString());
148             execution.setVariable(errorVariable, exception.getMessage());
149         } catch (Exception ex) {
150             // log trace, allow process to complete gracefully
151             logger.error("Exception occurred", ex);
152         }
153
154         if (exception.getMessage() != null)
155             msg = msg.concat(exception.getMessage());
156         buildAndThrowWorkflowException(execution, errorCode, msg);
157     }
158
159     public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, Exception exception,
160             ONAPComponentsList extSystemErrorSource) {
161         String msg = "Exception in %s.%s ";
162         try {
163             logger.error("Exception occurred", exception);
164
165             String errorVariable = "Error%s%s";
166
167             StackTraceElement[] trace = Thread.currentThread().getStackTrace();
168             for (StackTraceElement traceElement : trace) {
169                 if (!traceElement.getClassName().equals(this.getClass().getName())
170                         && !traceElement.getClassName().equals(Thread.class.getName())) {
171                     msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
172                     String shortClassName =
173                             traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
174                     errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
175                     break;
176                 }
177             }
178             logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
179                     ErrorCode.UnknownError.getValue(), msg.toString());
180             execution.setVariable(errorVariable, exception.getMessage());
181         } catch (Exception ex) {
182             // log trace, allow process to complete gracefully
183             logger.error("Exception occurred", ex);
184         }
185
186         if (exception.getMessage() != null)
187             msg = msg.concat(exception.getMessage());
188         buildAndThrowWorkflowException(execution, errorCode, msg, extSystemErrorSource);
189     }
190
191     /**
192      * @deprecated Please utilize method that specifies where the failure occured
193      */
194     @Deprecated
195     public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, String errorMessage) {
196         if (execution instanceof DelegateExecutionImpl) {
197             buildAndThrowWorkflowException(((DelegateExecutionImpl) execution).getDelegateExecution(), errorCode,
198                     errorMessage);
199         }
200     }
201
202     public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, String errorMessage,
203             ONAPComponentsList extSystemErrorSource) {
204         if (execution instanceof DelegateExecutionImpl) {
205             buildAndThrowWorkflowException(((DelegateExecutionImpl) execution).getDelegateExecution(), errorCode,
206                     errorMessage, extSystemErrorSource);
207         }
208     }
209
210     public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) {
211
212         buildWorkflowException(execution, errorCode, errorMessage);
213         logger.info("Throwing MSOWorkflowException");
214         throw new BpmnError("MSOWorkflowException");
215     }
216
217     public void buildWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) {
218         String processKey = getProcessKey(execution);
219         logger.info("Building a WorkflowException");
220
221         WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage);
222         execution.setVariable("WorkflowException", exception);
223         execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
224         logger.info("Outgoing WorkflowException is {}", exception);
225     }
226
227     public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage,
228             ONAPComponentsList extSystemErrorSource) {
229
230         buildWorkflowException(execution, errorCode, errorMessage, extSystemErrorSource);
231         logger.info("Throwing MSOWorkflowException");
232         throw new BpmnError("MSOWorkflowException");
233     }
234
235     public WorkflowException buildWorkflowException(DelegateExecution execution, int errorCode, String errorMessage,
236             ONAPComponentsList extSystemErrorSource) {
237         String processKey = getProcessKey(execution);
238         logger.info("Building a WorkflowException for Subflow");
239
240         WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage, extSystemErrorSource);
241         execution.setVariable("WorkflowException", exception);
242         execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
243         logger.info("Outgoing WorkflowException is {}", exception);
244         return exception;
245     }
246
247     public void buildAndThrowWorkflowException(DelegateExecution execution, String errorCode, String errorMessage) {
248         execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
249         throw new BpmnError(errorCode, errorMessage);
250     }
251
252     public String getProcessKey(DelegateExecution execution) {
253         String testKey = (String) execution.getVariable("testProcessKey");
254         if (testKey != null) {
255             return testKey;
256         }
257         return execution.getProcessEngineServices().getRepositoryService()
258                 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
259     }
260
261     public void processAuditException(DelegateExecutionImpl execution, boolean flowShouldContinue) {
262         logger.debug("Processing Audit Results");
263         String auditListString = (String) execution.getVariable("auditInventoryResult");
264         String processKey = getProcessKey(execution.getDelegateExecution());
265         if (auditListString != null) {
266             StringBuilder errorMessage = new StringBuilder();
267             try {
268                 ExtractPojosForBB extractPojosForBB = getExtractPojosForBB();
269                 VfModule module = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
270                 String cloudRegionId = execution.getGeneralBuildingBlock().getCloudRegion().getLcpCloudRegionId();
271
272                 GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
273                 AAIObjectAuditList auditList =
274                         objectMapper.getMapper().readValue(auditListString, AAIObjectAuditList.class);
275
276                 errorMessage = errorMessage.append(auditList.getAuditType() + " VF-Module " + module.getVfModuleId()
277                         + " failed due to incomplete AAI vserver inventory population after stack "
278                         + auditList.getHeatStackName() + " was successfully " + auditList.getAuditType()
279                         + "d in cloud region " + cloudRegionId + ". MSO Audit indicates that the following was not "
280                         + auditList.getAuditType() + "d in AAI: ");
281
282                 Stream<AAIObjectAudit> vServerLInterfaceAuditStream = auditList.getAuditList().stream()
283                         .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName())
284                                 || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName()));
285                 List<AAIObjectAudit> filteredAuditStream =
286                         vServerLInterfaceAuditStream.filter(a -> !a.isDoesObjectExist()).collect(Collectors.toList());
287
288                 for (AAIObjectAudit object : filteredAuditStream) {
289                     if (object.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())) {
290                         LInterface li = objectMapper.getMapper().convertValue(object.getAaiObject(), LInterface.class);
291                         errorMessage = errorMessage
292                                 .append(AAIObjectType.L_INTERFACE.typeName() + " " + li.getInterfaceId() + ", ");
293                     } else {
294                         Vserver vs = objectMapper.getMapper().convertValue(object.getAaiObject(), Vserver.class);
295                         errorMessage =
296                                 errorMessage.append(AAIObjectType.VSERVER.typeName() + " " + vs.getVserverId() + ", ");
297                     }
298                 }
299
300                 if (errorMessage.length() > 0) {
301                     errorMessage.setLength(errorMessage.length() - 2);
302                     errorMessage = errorMessage.append(".");
303                 }
304
305             } catch (IOException | BBObjectNotFoundException e) {
306                 errorMessage = errorMessage.append("process objects in AAI. ");
307             }
308
309             if (flowShouldContinue) {
310                 execution.setVariable("StatusMessage", errorMessage.toString());
311             } else {
312                 WorkflowException exception =
313                         new WorkflowException(processKey, 400, errorMessage.toString(), ONAPComponents.SO);
314                 execution.setVariable("WorkflowException", exception);
315                 execution.setVariable("WorkflowExceptionErrorMessage", errorMessage.toString());
316                 logger.info("Outgoing WorkflowException is {}", exception);
317                 logger.info("Throwing AAIInventoryFailure");
318                 throw new BpmnError("AAIInventoryFailure");
319             }
320
321         } else {
322             String errorMessage = "Unable to process audit results due to auditInventoryResult being null";
323             WorkflowException exception = new WorkflowException(processKey, 400, errorMessage, ONAPComponents.SO);
324             execution.setVariable("WorkflowException", exception);
325             execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
326             logger.info("Outgoing WorkflowException is {}", exception);
327             logger.info("Throwing AAIInventoryFailure");
328             throw new BpmnError("AAIInventoryFailure");
329         }
330     }
331
332     public void processOpenstackAdapterException(DelegateExecution execution) {
333         StringBuilder workflowExceptionMessage = new StringBuilder();
334         logger.debug("Processing Vnf Adapter Exception");
335         try {
336             String errorMessage = (String) execution.getVariable("openstackAdapterErrorMessage");
337             boolean openstackRollbackPollSuccess = (boolean) execution.getVariable("OpenstackPollSuccess");
338             boolean rollbackPerformed = (boolean) execution.getVariable("rollbackPerformed");
339             boolean openstackRollbackSuccess = (boolean) execution.getVariable("OpenstackRollbackSuccess");
340             boolean pollRollbackStatus = (boolean) execution.getVariable("PollRollbackStatus");
341
342             workflowExceptionMessage.append("Exception occured during vnf adapter: " + errorMessage + ".");
343
344             boolean rollbackCompleted = false;
345             if (rollbackPerformed) {
346                 if (openstackRollbackSuccess && !pollRollbackStatus) {
347                     rollbackCompleted = true;
348                 } else if (openstackRollbackSuccess && pollRollbackStatus) {
349                     if (openstackRollbackPollSuccess) {
350                         rollbackCompleted = true;
351                     }
352                 }
353                 workflowExceptionMessage
354                         .append(" The resource was rollbacked in openstack: " + rollbackCompleted + ".");
355             }
356         } catch (Exception e) {
357             logger.debug("Error while Processing Vnf Adapter Exception", e);
358         }
359         buildWorkflowException(execution, 500, workflowExceptionMessage.toString(), Components.OPENSTACK);
360         throw new BpmnError("MSOWorkflowException");
361
362
363     }
364
365 }