[SO] Release so 1.13.0 image
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / process / ActivateVnfStatusOperationalEnvironment.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.apihandlerinfra.tenantisolation.process;
24
25
26 import java.util.List;
27 import java.util.Optional;
28 import javax.ws.rs.core.Response;
29 import org.apache.http.HttpStatus;
30 import org.json.JSONObject;
31 import org.onap.aai.domain.yang.OperationalEnvironment;
32 import org.onap.so.apihandler.common.ErrorNumbers;
33 import org.onap.so.db.request.client.RequestsDbClient;
34 import org.onap.so.apihandlerinfra.exceptions.ApiException;
35 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
36 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
37 import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest;
38 import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper;
39 import org.onap.so.apihandlerinfra.tenantisolation.helpers.ActivateVnfDBHelper;
40 import org.onap.so.apihandlerinfra.tenantisolation.helpers.SDCClientHelper;
41 import org.onap.so.apihandlerinfra.tenantisolationbeans.Distribution;
42 import org.onap.so.apihandlerinfra.tenantisolationbeans.DistributionStatus;
43 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
44 import org.onap.so.db.request.beans.OperationalEnvDistributionStatus;
45 import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus;
46 import org.onap.logging.filter.base.ErrorCode;
47 import org.onap.so.logger.MessageEnum;
48 import org.onap.so.requestsdb.RequestsDBHelper;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.stereotype.Component;
53
54 @Component
55 public class ActivateVnfStatusOperationalEnvironment {
56
57     private static Logger logger = LoggerFactory.getLogger(ActivateVnfStatusOperationalEnvironment.class);
58     private String origRequestId = "";
59     private String errorMessage = "";
60     private OperationalEnvDistributionStatus queryDistributionDbResponse = null;
61     private OperationalEnvServiceModelStatus queryServiceModelResponse = null;
62     private boolean isOverallSuccess = false;
63
64     private static final int RETRY_COUNT_ZERO = 0;
65     private static final String ERROR_REASON_ABORTED = "ABORTED";
66     private static final String RECOVERY_ACTION_RETRY = "RETRY";
67     private static final String RECOVERY_ACTION_ABORT = "ABORT";
68     private static final String RECOVERY_ACTION_SKIP = "SKIP";
69     private static final String DISTRIBUTION_STATUS_OK = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString();
70     private static final String DISTRIBUTION_STATUS_ERROR = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
71     private static final String DISTRIBUTION_STATUS_SENT = "SENT";
72
73     @Autowired
74     private ActivateVnfDBHelper dbHelper;
75     @Autowired
76     private RequestsDBHelper requestDb;
77     @Autowired
78     private SDCClientHelper sdcClientHelper;
79     @Autowired
80     private RequestsDbClient client;
81     @Autowired
82     private AAIClientHelper aaiHelper;
83
84     /**
85      * The Point-Of-Entry from APIH with activate status from SDC
86      * 
87      * @param requestId - String
88      * @param request - CloudOrchestrationRequest - object
89      * @return void - nothing
90      */
91     public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
92
93         try {
94
95             String operationalEnvironmentId = "";
96
97             String sdcDistributionId = request.getDistributionId();
98             Distribution sdcStatus = request.getDistribution();
99
100             // Distribution, Query for operationalEnvironmentId, serviceModelVersionId, origRequestId
101             this.queryDistributionDbResponse = client.getDistributionStatusById(sdcDistributionId);
102             operationalEnvironmentId = this.queryDistributionDbResponse.getOperationalEnvId();
103             this.origRequestId = this.queryDistributionDbResponse.getRequestId();
104
105             // ServiceModel, Query for recoveryAction, retryCountString
106             this.queryServiceModelResponse =
107                     client.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(operationalEnvironmentId,
108                             queryDistributionDbResponse.getServiceModelVersionId(), this.origRequestId);
109
110             processActivateSDCStatus(sdcDistributionId, sdcStatus, this.queryDistributionDbResponse,
111                     this.queryServiceModelResponse);
112
113             // After EVERY status processed, need to query the status of all service modelId
114             // to determine the OVERALL status if "COMPLETE" or "FAILURE":
115             checkOrUpdateOverallStatus(operationalEnvironmentId, this.origRequestId);
116
117             // Update AAI to ACTIVE if Overall success
118             if (isOverallSuccess) {
119                 String vnfOperationalEnvironmentId = this.queryServiceModelResponse.getVnfOperationalEnvId();
120                 OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(vnfOperationalEnvironmentId);
121                 if (aaiOpEnv != null) {
122                     aaiOpEnv.setOperationalEnvironmentStatus("ACTIVE");
123                     aaiHelper.updateAaiOperationalEnvironment(vnfOperationalEnvironmentId, aaiOpEnv);
124                 } else {
125                     requestDb.updateInfraFailureCompletion("Unable to update ACTIVATE status in AAI. ",
126                             this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId());
127                 }
128             }
129
130         } catch (Exception e) {
131             logger.error("Exception in execute", e);
132             requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId,
133                     this.queryServiceModelResponse.getVnfOperationalEnvId());
134         }
135
136     }
137
138     /**
139      * The Method to process the Activation Status from SDC
140      * 
141      * @param sdcDistributionId - string
142      * @param sdcStatus - Distribution object
143      * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
144      * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
145      * @return void - nothing
146      */
147     public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus,
148             OperationalEnvDistributionStatus queryDistributionDbResponse,
149             OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException {
150
151         String sdcStatusValue = sdcStatus.getStatus().toString();
152         String recoveryAction = queryServiceModelResponse.getRecoveryAction();
153         int retryCount = queryServiceModelResponse.getRetryCount();
154
155         // Validate/process status
156         if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) {
157             // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK"
158             OperationalEnvDistributionStatus updateDistStatusOk = dbHelper
159                     .updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, sdcStatusValue, "");
160             client.save(updateDistStatusOk);
161             // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!)
162             OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk =
163                     dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
164                             sdcStatusValue, RETRY_COUNT_ZERO);
165             client.save(updateRetryCountZeroAndStatusOk);
166         } else {
167
168             // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY"
169             if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) {
170
171                 // RESEND / RETRY serviceModelVersionId to SDC
172
173                 JSONObject jsonResponse =
174                         callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus);
175
176             } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP'
177
178                 if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
179                     String modifiedStatus = "";
180                     String errorReason = "";
181                     if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) { // considered SUCCESS
182                         modifiedStatus = DISTRIBUTION_STATUS_OK;
183                     } else {
184                         if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
185                             modifiedStatus = DISTRIBUTION_STATUS_ERROR; // ABORT, error
186                             errorReason = ERROR_REASON_ABORTED;
187                         }
188                     }
189
190                     sdcStatusValue = modifiedStatus;
191                     OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus =
192                             dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(
193                                     queryServiceModelResponse, modifiedStatus, RETRY_COUNT_ZERO);
194                     client.save(updateRetryCountZeroAndStatus);
195                     OperationalEnvDistributionStatus updateDistStatus =
196                             dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
197                                     modifiedStatus, errorReason);
198                     client.save(updateDistStatus);
199                 } else {
200                     // RETRY & Count = 0 (do nothing!)
201                 }
202             }
203         }
204     }
205
206     /**
207      * The Method to call SDC for recoveryActioin RETRY
208      * 
209      * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
210      * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
211      * @param sdcStatus - Distribution object
212      * @return JSONObject object
213      */
214     public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse,
215             OperationalEnvServiceModelStatus queryServiceModelResponse, Distribution sdcStatus) throws ApiException {
216
217         JSONObject jsonResponse = null;
218
219         String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId();
220         String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId();
221         String originalRequestId = queryServiceModelResponse.getRequestId();
222         int retryCount = queryServiceModelResponse.getRetryCount();
223         String workloadContext = queryServiceModelResponse.getWorkloadContext();
224
225
226         jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId,
227                 workloadContext);
228         String statusCode = jsonResponse.get("statusCode").toString();
229         if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
230             String newDistributionId = jsonResponse.get("distributionId").toString();
231             // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record
232             OperationalEnvDistributionStatus insertNewDistributionId =
233                     dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId, operEnvironmentId,
234                             serviceModelVersionId, originalRequestId, DISTRIBUTION_STATUS_SENT, "");
235             client.save(insertNewDistributionId);
236
237             // update retryCount (less 1) for the serviceModelServiceId
238             retryCount = retryCount - 1;
239             // should update 1 row, original insert
240             OperationalEnvServiceModelStatus updateRetryCountAndStatus =
241                     dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
242                             DISTRIBUTION_STATUS_SENT, retryCount);
243             client.save(updateRetryCountAndStatus);
244
245             // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!).
246             OperationalEnvDistributionStatus updateStatus = dbHelper.updateStatusInOperationalEnvDistributionStatus(
247                     queryDistributionDbResponse, DISTRIBUTION_STATUS_ERROR, sdcStatus.getErrorReason());
248             client.save(updateStatus);
249         } else {
250             String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode + "; messageId: "
251                     + jsonResponse.get("messageId") + "; message: " + jsonResponse.get("message");
252             ErrorLoggerInfo errorLoggerInfo =
253                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError)
254                             .build();
255             ValidateException validateException =
256                     new ValidateException.Builder(dbErrorMessage, HttpStatus.SC_BAD_REQUEST,
257                             ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
258             requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId);
259             throw validateException;
260         }
261
262         return jsonResponse;
263
264     }
265
266
267     /**
268      * The Method to check the overall status of the Activation for an operationalEnvironmentId
269      * 
270      * @param operationalEnvironmentId - string
271      * @param origRequestId - string
272      * @return void - nothing
273      */
274     public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException {
275
276         List<OperationalEnvServiceModelStatus> queryServiceModelResponseList =
277                 client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId);
278
279         String status = "Waiting";
280         int count = 0;
281         // loop through the statuses of the service model
282         for (OperationalEnvServiceModelStatus querySrvModelResponse : queryServiceModelResponseList) {
283             status = querySrvModelResponse.getServiceModelVersionDistrStatus();
284             // all should be OK to be completed.
285             if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString())
286                     && (querySrvModelResponse.getRetryCount() == 0))) {
287                 status = "Completed";
288                 count++;
289             }
290             // one error with zero retry, means all are failures.
291             if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString())
292                     && (querySrvModelResponse.getRetryCount() == 0))) {
293                 status = "Failure";
294                 count = queryServiceModelResponseList.size();
295                 break;
296             }
297         }
298
299         if (status.equals("Completed") && queryServiceModelResponseList.size() == count) {
300             String messageStatus = "Overall Activation process is complete. " + status;
301             isOverallSuccess = true;
302             requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId);
303         } else {
304             if (status.equals("Failure") && queryServiceModelResponseList.size() == count) {
305                 this.errorMessage = "Overall Activation process is a Failure. " + status;
306                 ErrorLoggerInfo errorLoggerInfo =
307                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError)
308                                 .build();
309                 ValidateException validateException =
310                         new ValidateException.Builder(this.errorMessage, HttpStatus.SC_BAD_REQUEST,
311                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
312                 requestDb.updateInfraFailureCompletion(this.errorMessage, origRequestId, operationalEnvironmentId);
313                 throw validateException;
314             }
315
316         }
317     }
318
319     /**
320      * Get OperationalEnvironment object
321      * 
322      * @param operationalEnvironmentId - String
323      * @return operationalEnv - OperationalEnvironment object
324      */
325     private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) {
326         AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
327         Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class);
328         return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null;
329     }
330 }