219a2efcac1c6e5c8904aa3ff23c885d39388114
[so.git] /
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
90                 String operationalEnvironmentId = "";
91
92                         String sdcDistributionId = request.getDistributionId();
93                         Distribution sdcStatus = request.getDistribution();
94
95                         // Distribution, Query for operationalEnvironmentId, serviceModelVersionId
96                         this.queryDistributionDbResponse = client.getDistributionStatusById(sdcDistributionId);
97                         operationalEnvironmentId = this.queryDistributionDbResponse.getOperationalEnvId();
98                         
99                         // ServiceModel, Query for dbRequestId, recoveryAction, retryCountString
100                         this.queryServiceModelResponse = client.findOneByOperationalEnvIdAndServiceModelVersionId(operationalEnvironmentId, queryDistributionDbResponse.getServiceModelVersionId());
101                         this.origRequestId = this.queryServiceModelResponse.getRequestId();
102                         
103                         processActivateSDCStatus(sdcDistributionId, sdcStatus, this.queryDistributionDbResponse, this.queryServiceModelResponse);
104                         
105                         // After EVERY status processed, need to query the status of all service modelId 
106                         //  to determine the OVERALL status if "COMPLETE" or "FAILURE":
107                         checkOrUpdateOverallStatus(operationalEnvironmentId, this.origRequestId);                       
108
109         }
110         
111         /**
112          * The Method to process the Activation Status from SDC
113          * @param sdcDistributionId - string
114          * @param sdcStatus - Distribution object
115          * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
116          * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
117          * @return void - nothing  
118          */             
119         public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus, OperationalEnvDistributionStatus queryDistributionDbResponse, 
120                         OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException {
121
122                 String sdcStatusValue = sdcStatus.getStatus().toString();
123                 String recoveryAction = queryServiceModelResponse.getRecoveryAction();
124                 int retryCount = queryServiceModelResponse.getRetryCount();
125                 
126                 // Validate/process status
127                 if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) {
128                         // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK"
129                         OperationalEnvDistributionStatus updateDistStatusOk = 
130                                         dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, 
131                                                                                                                                                         sdcStatusValue,
132                                                                                                                                                         "");                            
133                         client.save(updateDistStatusOk);
134                         // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!)
135                         OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk = 
136                                         dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, 
137                                                                                                                                                                                  sdcStatusValue,
138                                                                                                                                                                                  RETRY_COUNT_ZERO);                     
139                         client.save(updateRetryCountZeroAndStatusOk);                           
140                 } else {
141                         
142                           // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY" 
143                           if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) {
144                                         
145                                     // RESEND / RETRY serviceModelVersionId to SDC  
146
147                                   JSONObject jsonResponse = callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus);
148
149                          } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP' 
150
151                                         if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
152                                                 String modifiedStatus = "";
153                                                 String errorReason = "";
154                                                 if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) {  // considered SUCCESS
155                                                         modifiedStatus = DISTRIBUTION_STATUS_OK;
156                                                 } else { 
157                                                         if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
158                                                                 modifiedStatus = DISTRIBUTION_STATUS_ERROR;  // ABORT, error
159                                                                 errorReason = ERROR_REASON_ABORTED;
160                                                         }
161                                                 }
162                                                 
163                                                 sdcStatusValue = modifiedStatus;
164                                             // should update 1 row, modified status & retryCount set 0
165                                                 OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus = 
166                                                                 dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, 
167                                                                                                                                                                                                          modifiedStatus, 
168                                                                                                                                                                                                          RETRY_COUNT_ZERO);                                             
169                                                 client.save(updateRetryCountZeroAndStatus);
170                                                 // should update 1 row, modified status
171                                                 OperationalEnvDistributionStatus updateDistStatus = 
172                                                                 dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, 
173                                                                                                                                                                                 modifiedStatus,
174                                                                                                                                                                                 errorReason);
175                                                 client.save(updateDistStatus);
176                                         } else {
177                                                 // RETRY & Count = 0 (do nothing!)
178                                         }
179                           }             
180                 } 
181         }
182         
183         /**
184          * The Method to call SDC for recoveryActioin RETRY
185          * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
186          * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object   
187          * @param sdcStatus - Distribution object
188          * @return JSONObject object 
189          */                     
190         public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse, 
191                                                                                         OperationalEnvServiceModelStatus queryServiceModelResponse,
192                                                                             Distribution sdcStatus) throws ApiException {
193
194                 JSONObject jsonResponse = null;         
195                 
196                 String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId();
197                 String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId();          
198                 String originalRequestId = queryServiceModelResponse.getRequestId();            
199                 int retryCount = queryServiceModelResponse.getRetryCount();
200                 String workloadContext  = queryServiceModelResponse.getWorkloadContext();               
201
202
203                 jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId, workloadContext);
204                 String statusCode = jsonResponse.get("statusCode").toString();
205                 if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
206                         String newDistributionId = jsonResponse.get("distributionId").toString();
207                         // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record
208                         OperationalEnvDistributionStatus insertNewDistributionId =
209                                         dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId,
210                                                         operEnvironmentId,
211                                                         serviceModelVersionId,
212                                                         originalRequestId,
213                                                         DISTRIBUTION_STATUS_SENT,
214                                                         "");
215                         client.save(insertNewDistributionId);
216                                                 
217                         // update retryCount (less 1) for the serviceModelServiceId
218                         retryCount = retryCount - 1;
219                         // should update 1 row, original insert
220                         OperationalEnvServiceModelStatus updateRetryCountAndStatus =
221                                         dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
222                                                         DISTRIBUTION_STATUS_SENT,
223                                                         retryCount);
224                         client.save(updateRetryCountAndStatus);
225         
226                         // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!).
227                         OperationalEnvDistributionStatus updateStatus =
228                                         dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
229                                                         DISTRIBUTION_STATUS_ERROR,
230                                                         sdcStatus.getErrorReason());
231                         client.save(updateStatus);
232                 } else {
233             String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode +
234                     "; messageId: " + jsonResponse.get("messageId") +
235                     "; message: " + jsonResponse.get("message");
236                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
237                         ValidateException validateException = new ValidateException.Builder(dbErrorMessage,
238                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
239                     requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId);
240                         throw validateException;
241                         }
242
243                 return jsonResponse;
244                 
245         }
246         
247         
248         /**
249          * The Method to check the overall status of the Activation for an operationalEnvironmentId
250          * @param operationalEnvironmentId - string
251          * @param origRequestId - string
252          * @return void - nothing 
253          */                     
254         public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException{
255
256                 List<OperationalEnvServiceModelStatus> queryServiceModelResponseList = client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId);
257
258                 String status = "Waiting";
259                 int count = 0;
260                 // loop through the statuses of the service model
261                 for (OperationalEnvServiceModelStatus  querySrvModelResponse : queryServiceModelResponseList) {
262                                 status = querySrvModelResponse.getServiceModelVersionDistrStatus();
263                                 // all should be OK to be completed.
264                                 if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString()) &&
265                                         (querySrvModelResponse.getRetryCount() == 0))) {
266                                         status = "Completed";
267                                         count ++;                                       
268                                 } 
269                                 // one error with zero retry, means all are failures.
270                                 if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString()) &&
271                                         (querySrvModelResponse.getRetryCount() == 0))) {
272                                         status = "Failure";
273                                         count = queryServiceModelResponseList.size();
274                                         break;
275                                 } 
276                 }
277                 
278                 if (status.equals("Completed") && queryServiceModelResponseList.size() == count) {
279                         String messageStatus = "Overall Activation process is complete. " + status;
280                         requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId);
281                 } else {        
282                         if (status.equals("Failure") && queryServiceModelResponseList.size() == count) {
283                                 this.errorMessage = "Overall Activation process is a Failure. " + status;
284                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
285                                 ValidateException validateException = new ValidateException.Builder(this.errorMessage,
286                                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
287                 requestDb.updateInfraFailureCompletion(this.errorMessage, origRequestId, operationalEnvironmentId);
288                                 throw validateException;
289                         } 
290                         
291                 }       
292         }
293 }