if audit fails write sub interface data to a ai
[so.git] / adapters / mso-openstack-adapters / src / main / java / org / onap / so / adapters / audit / AuditStackServiceData.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017-2019 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.adapters.audit;
24
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Optional;
28
29 import org.camunda.bpm.client.task.ExternalTask;
30 import org.camunda.bpm.client.task.ExternalTaskService;
31 import org.onap.logging.ref.slf4j.ONAPLogConstants;
32 import org.onap.so.audit.beans.AuditInventory;
33 import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.slf4j.MDC;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.beans.factory.annotation.Value;
39 import org.springframework.core.env.Environment;
40 import org.springframework.stereotype.Component;
41
42 @Component
43 public class AuditStackServiceData {
44         
45         private static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI = "Unable to find all VServers and L-Interaces in A&AI";
46         
47         private static final Logger logger = LoggerFactory.getLogger(AuditStackServiceData.class);
48         
49         @Autowired
50         public HeatStackAudit heatStackAudit; 
51         
52         @Autowired
53         public Environment env;
54
55         protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService){
56                 AuditInventory auditInventory = externalTask.getVariable("auditInventory");
57         Map<String, Object> variables = new HashMap<>();
58                 setupMDC(externalTask);
59                 boolean success = false;
60                 try {
61                         logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,externalTask.getRetries());
62                         Optional<AAIObjectAuditList> auditListOpt= heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(),
63                                         auditInventory.getTenantId(), auditInventory.getHeatStackName());
64                 if (auditListOpt.isPresent()) {
65                         GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
66                         variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get()));
67                         success = !didAuditFail(auditListOpt);
68                 }
69                 } catch (Exception e) {
70                         logger.error("Error during audit of stack", e);
71                 }
72                 variables.put("auditIsSuccessful", success);
73                 if (success) {
74                         externalTaskService.complete(externalTask,variables);
75                         logger.debug("The External Task Id: {}  Successful", externalTask.getId());
76                 } else {
77                         if(externalTask.getRetries() == null){
78                                 logger.debug("The External Task Id: {}  Failed, Setting Retries to Default Start Value: {}", externalTask.getId(),getRetrySequence().length);
79                                 externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000);                  
80                         }else if(externalTask.getRetries() != null &&
81                                         externalTask.getRetries()-1 == 0){
82                                 logger.debug("The External Task Id: {}  Failed, All Retries Exhausted", externalTask.getId());                           
83                                 externalTaskService.complete(externalTask, variables);
84                         }else{
85                                 logger.debug("The External Task Id: {}  Failed, Decrementing Retries: {} , Retry Delay: ", externalTask.getId(),externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries()));
86                                 externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries()));
87                         }
88                         logger.debug("The External Task Id: {} Failed", externalTask.getId());
89                 }
90         }
91         private void setupMDC(ExternalTask externalTask) {
92                 String msoRequestId = externalTask.getVariable("mso-request-id");
93                 if(msoRequestId != null && !msoRequestId.isEmpty())
94                         MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId);
95         }
96         protected long calculateRetryDelay(int currentRetries){
97                 int retrySequence = getRetrySequence().length - currentRetries;
98                 long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier","6000"));
99                 return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier;
100         }
101         
102         /**
103          * @param auditHeatStackFailed
104          * @param auditList
105          * @return
106          */
107         protected boolean didAuditFail(Optional<AAIObjectAuditList> auditList) {
108                 if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) {
109                         if (logger.isInfoEnabled()) {
110                                 logger.info("Audit Results: {}", auditList.get().toString());
111                         }
112                         return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist())
113                                         .findFirst().map(v -> true).orElse(false);
114                 } else {
115                         return false;
116                 }
117         }
118         public String[] getRetrySequence() {
119                  return env.getProperty("mso.workflow.topics.retrySequence",String[].class);
120         }
121
122 }