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