Updated to use vnfOperationalEnvironmentId
[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                                 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. ", this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId());
126                                 }
127                         }
128                         
129                  } catch(Exception e) {
130                     requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId());
131         }
132                         
133         }
134         
135         /**
136          * The Method to process the Activation Status from SDC
137          * @param sdcDistributionId - string
138          * @param sdcStatus - Distribution object
139          * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
140          * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
141          * @return void - nothing  
142          */             
143         public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus, OperationalEnvDistributionStatus queryDistributionDbResponse, 
144                         OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException {
145
146                 String sdcStatusValue = sdcStatus.getStatus().toString();
147                 String recoveryAction = queryServiceModelResponse.getRecoveryAction();
148                 int retryCount = queryServiceModelResponse.getRetryCount();
149                 
150                 // Validate/process status
151                 if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) {
152                         // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK"
153                         OperationalEnvDistributionStatus updateDistStatusOk = 
154                                         dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, 
155                                                                                                                                                         sdcStatusValue,
156                                                                                                                                                         "");                            
157                         client.save(updateDistStatusOk);
158                         // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!)
159                         OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk = 
160                                         dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, 
161                                                                                                                                                                                  sdcStatusValue,
162                                                                                                                                                                                  RETRY_COUNT_ZERO);                     
163                         client.save(updateRetryCountZeroAndStatusOk);                           
164                 } else {
165                         
166                           // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY" 
167                           if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) {
168                                         
169                                     // RESEND / RETRY serviceModelVersionId to SDC  
170
171                                   JSONObject jsonResponse = callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus);
172
173                          } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP' 
174
175                                         if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
176                                                 String modifiedStatus = "";
177                                                 String errorReason = "";
178                                                 if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) {  // considered SUCCESS
179                                                         modifiedStatus = DISTRIBUTION_STATUS_OK;
180                                                 } else { 
181                                                         if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
182                                                                 modifiedStatus = DISTRIBUTION_STATUS_ERROR;  // ABORT, error
183                                                                 errorReason = ERROR_REASON_ABORTED;
184                                                         }
185                                                 }
186                                                 
187                                                 sdcStatusValue = modifiedStatus;
188                                                 OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus = 
189                                                                 dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, 
190                                                                                                                                                                                                          modifiedStatus, 
191                                                                                                                                                                                                          RETRY_COUNT_ZERO);
192                                                 client.save(updateRetryCountZeroAndStatus);
193                                                 OperationalEnvDistributionStatus updateDistStatus = 
194                                                                 dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, 
195                                                                                                                                                                                 modifiedStatus,
196                                                                                                                                                                                 errorReason);
197                                                 client.save(updateDistStatus);
198                                         } else {
199                                                 // RETRY & Count = 0 (do nothing!)
200                                         }
201                           }             
202                 } 
203         }
204         
205         /**
206          * The Method to call SDC for recoveryActioin RETRY
207          * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
208          * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object   
209          * @param sdcStatus - Distribution object
210          * @return JSONObject object 
211          */                     
212         public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse, 
213                                                                                         OperationalEnvServiceModelStatus queryServiceModelResponse,
214                                                                             Distribution sdcStatus) throws ApiException {
215
216                 JSONObject jsonResponse = null;         
217                 
218                 String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId();
219                 String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId();          
220                 String originalRequestId = queryServiceModelResponse.getRequestId();            
221                 int retryCount = queryServiceModelResponse.getRetryCount();
222                 String workloadContext  = queryServiceModelResponse.getWorkloadContext();               
223
224
225                 jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId, workloadContext);
226                 String statusCode = jsonResponse.get("statusCode").toString();
227                 if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
228                         String newDistributionId = jsonResponse.get("distributionId").toString();
229                         // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record
230                         OperationalEnvDistributionStatus insertNewDistributionId =
231                                         dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId,
232                                                         operEnvironmentId,
233                                                         serviceModelVersionId,
234                                                         originalRequestId,
235                                                         DISTRIBUTION_STATUS_SENT,
236                                                         "");
237                         client.save(insertNewDistributionId);
238                                                 
239                         // update retryCount (less 1) for the serviceModelServiceId
240                         retryCount = retryCount - 1;
241                         // should update 1 row, original insert
242                         OperationalEnvServiceModelStatus updateRetryCountAndStatus =
243                                         dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
244                                                         DISTRIBUTION_STATUS_SENT,
245                                                         retryCount);
246                         client.save(updateRetryCountAndStatus);
247         
248                         // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!).
249                         OperationalEnvDistributionStatus updateStatus =
250                                         dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
251                                                         DISTRIBUTION_STATUS_ERROR,
252                                                         sdcStatus.getErrorReason());
253                         client.save(updateStatus);
254                 } else {
255             String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode +
256                     "; messageId: " + jsonResponse.get("messageId") +
257                     "; message: " + jsonResponse.get("message");
258                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
259                         ValidateException validateException = new ValidateException.Builder(dbErrorMessage,
260                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
261                     requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId);
262                         throw validateException;
263                         }
264
265                 return jsonResponse;
266                 
267         }
268         
269         
270         /**
271          * The Method to check the overall status of the Activation for an operationalEnvironmentId
272          * @param operationalEnvironmentId - string
273          * @param origRequestId - string
274          * @return void - nothing 
275          */                     
276         public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException{
277
278                 List<OperationalEnvServiceModelStatus> queryServiceModelResponseList = client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId);
279
280                 String status = "Waiting";
281                 int count = 0;
282                 // loop through the statuses of the service model
283                 for (OperationalEnvServiceModelStatus  querySrvModelResponse : queryServiceModelResponseList) {
284                                 status = querySrvModelResponse.getServiceModelVersionDistrStatus();
285                                 // all should be OK to be completed.
286                                 if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString()) &&
287                                         (querySrvModelResponse.getRetryCount() == 0))) {
288                                         status = "Completed";
289                                         count ++;                                       
290                                 } 
291                                 // one error with zero retry, means all are failures.
292                                 if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString()) &&
293                                         (querySrvModelResponse.getRetryCount() == 0))) {
294                                         status = "Failure";
295                                         count = queryServiceModelResponseList.size();
296                                         break;
297                                 } 
298                 }
299                 
300                 if (status.equals("Completed") && queryServiceModelResponseList.size() == count) {
301                         String messageStatus = "Overall Activation process is complete. " + status;
302                         isOverallSuccess = true;
303                         requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId);
304                 } else {        
305                         if (status.equals("Failure") && queryServiceModelResponseList.size() == count) {
306                                 this.errorMessage = "Overall Activation process is a Failure. " + status;
307                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
308                                 ValidateException validateException = new ValidateException.Builder(this.errorMessage,
309                                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
310                 requestDb.updateInfraFailureCompletion(this.errorMessage, origRequestId, operationalEnvironmentId);
311                                 throw validateException;
312                         } 
313                         
314                 }       
315         }
316         
317         /**
318          * Get OperationalEnvironment object
319          * @param  operationalEnvironmentId - String 
320          * @return operationalEnv - OperationalEnvironment object
321          */
322         private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) {
323                 AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
324                 Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class);
325                 return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null;
326         }       
327 }