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