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