dde45a81c967816f276a8cd585b0dba2f133f231
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / process / ActivateVnfOperationalEnvironment.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 import java.util.List;
24 import java.util.Optional;
25
26 import javax.ws.rs.core.Response;
27
28 import org.apache.http.HttpStatus;
29 import org.json.JSONObject;
30 import org.onap.aai.domain.yang.OperationalEnvironment;
31 import org.onap.so.apihandler.common.ErrorNumbers;
32 import org.onap.so.db.request.client.RequestsDbClient;
33 import org.onap.so.apihandlerinfra.exceptions.ApiException;
34 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
35 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
36 import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest;
37 import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper;
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.ServiceModelList;
41 import org.onap.so.client.aai.AAIObjectType;
42 import org.onap.so.client.aai.entities.AAIResultWrapper;
43 import org.onap.so.client.aai.entities.Relationships;
44 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
45 import org.onap.so.db.request.beans.OperationalEnvDistributionStatus;
46 import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus;
47 import org.onap.so.logger.ErrorCode;
48 import org.onap.so.logger.MessageEnum;
49 import org.onap.so.requestsdb.RequestsDBHelper;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.beans.factory.annotation.Value;
54 import org.springframework.stereotype.Component;
55
56
57 @Component
58 public class ActivateVnfOperationalEnvironment {
59
60         private static final Logger logger = LoggerFactory.getLogger(ActivateVnfOperationalEnvironment.class);
61         private static final int DEFAULT_ACTIVATE_RETRY_COUNT = 3;
62         private static final String DISTRIBUTION_STATUS_SENT = "SENT";  
63         private static final String OPER_ENVIRONMENT_ID_KEY = "operational-environment-id";
64         
65         @Autowired
66         private ActivateVnfDBHelper dbHelper;   
67         @Autowired
68         private AAIClientHelper aaiHelper;
69         @Autowired
70         private RequestsDBHelper requestDb;
71         @Autowired 
72         private SDCClientHelper sdcClientHelper;
73         
74         @Value("${mso.tenant.isolation.retry.count}")
75         private String sdcRetryCount;
76         
77         @Autowired
78         RequestsDbClient client;
79         
80         /**
81          * The Point-Of-Entry from APIH with VID request to send activate request
82          * @param requestId - String
83          * @param request - CloudOrchestrationRequest object
84          * @return void - nothing
85          */             
86         public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{
87                 String vnfOperationalEnvironmentId = request.getOperationalEnvironmentId();
88
89                 String vidWorkloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
90                 List<ServiceModelList> serviceModelVersionIdList = request.getRequestDetails().getRequestParameters().getManifest().getServiceModelList();
91                 
92                 String ecompOperationalEnvironmentId = null;
93                 AAIResultWrapper wrapper = getAAIOperationalEnvironment(vnfOperationalEnvironmentId);
94                 Optional<Relationships> optRelationships = wrapper.getRelationships();
95                 if (optRelationships.isPresent()) {
96                    Relationships relationships = optRelationships.get();
97                    List<AAIResourceUri> operationalEnvironments = relationships.getRelatedAAIUris(AAIObjectType.OPERATIONAL_ENVIRONMENT);
98                    if (!operationalEnvironments.isEmpty()) {
99                            ecompOperationalEnvironmentId = operationalEnvironments.get(0).getURIKeys().get(OPER_ENVIRONMENT_ID_KEY);
100                    }
101                 }
102                 logger.debug("  vnfOperationalEnvironmentId   : {}", vnfOperationalEnvironmentId);
103                 logger.debug("  ecompOperationalEnvironmentId : {}", ecompOperationalEnvironmentId);
104
105                 OperationalEnvironment operationalEnv = wrapper.asBean(OperationalEnvironment.class).get();
106                 String workloadContext = operationalEnv.getWorkloadContext();
107                 logger.debug("  aai workloadContext: {}", workloadContext);
108                 if (!vidWorkloadContext.equals(workloadContext)) {
109                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
110                         throw new ValidateException.Builder(" The vid workloadContext did not match from aai record. " + " vid workloadContext:" + vidWorkloadContext + " aai workloadContext:" + workloadContext,
111                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
112                 }
113                 if (ecompOperationalEnvironmentId==null) {
114                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
115                         throw new ValidateException.Builder(" The ECOMP OE was not in aai record; the value of relationship.relationship-data key: " + OPER_ENVIRONMENT_ID_KEY,
116                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
117                 }               
118
119                 processActivateSDCRequest(requestId, ecompOperationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId);
120
121         }       
122         
123         
124         /**
125          * The Method to send the Activation Requests to SDC
126          * @param requestId - String
127          * @param operationalEnvironmentId - String   
128          * @param serviceModelVersionIdList - List<ServiceModelList> list
129          * @param workloadContext - String        
130          * @return jsonResponse - JSONObject object  
131          */             
132         public void processActivateSDCRequest(String requestId, String operationalEnvironmentId, 
133                                                                                   List<ServiceModelList> serviceModelVersionIdList, 
134                                                                                   String workloadContext, String vnfOperationalEnvironmentId) throws ApiException {
135                 
136                 JSONObject jsonResponse = null;         
137                 int retryCount = 0;
138                 try {
139                         retryCount = Integer.parseInt(sdcRetryCount);
140                 } catch (NumberFormatException e) {
141                         retryCount = DEFAULT_ACTIVATE_RETRY_COUNT;
142                 }
143
144                 // loop through the serviceModelVersionId, and send request SDC
145                 for(ServiceModelList serviceModelList : serviceModelVersionIdList){
146                         String serviceModelVersionId = serviceModelList.getServiceModelVersionId();
147                         String recoveryAction = serviceModelList.getRecoveryAction().toString().toUpperCase();
148
149                         // should insert 1 row
150                         OperationalEnvServiceModelStatus serviceModelStatus = 
151                                 dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId,
152                                                                                                                                             operationalEnvironmentId,
153                                                                                                                                             serviceModelVersionId,
154                                                                                                                                             DISTRIBUTION_STATUS_SENT,
155                                                                                                                                             recoveryAction, 
156                                                                                                                                             retryCount,
157                                                                                                                                             workloadContext,
158                                                                                                                                             vnfOperationalEnvironmentId);                                       
159                         client.save(serviceModelStatus);
160                         
161                         String distributionId = "";
162
163                         jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext);
164
165                         String statusCode = jsonResponse.get("statusCode").toString();
166                         if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
167                                 distributionId = jsonResponse.get("distributionId").toString();
168                                 // should insert 1 row
169                                 OperationalEnvDistributionStatus distStatus =
170                                                 dbHelper.insertRecordToOperationalEnvDistributionStatus(distributionId,
171                                                                 operationalEnvironmentId,
172                                                                 serviceModelVersionId,
173                                                                 requestId,
174                                                                 DISTRIBUTION_STATUS_SENT,
175                                                                 "");
176                                 client.save(distStatus);
177
178                         } else {
179                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
180                 String dbErrorMessage = " Failure calling SDC: statusCode: " + statusCode +
181                         "; messageId: " + jsonResponse.get("messageId") +
182                         "; message: " + jsonResponse.get("message");
183
184                 requestDb.updateInfraFailureCompletion(dbErrorMessage, requestId, operationalEnvironmentId);
185                                 throw new ValidateException.Builder(dbErrorMessage,
186                                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
187                         }
188                 }
189
190         }
191
192         /**
193          * Get AAIOperationalEnvironment object
194          * @param  operationalEnvironmentId - String 
195          * @return operationalEnv - AAIOperationalEnvironment object
196          */
197         public AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId) {
198                 return aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
199         }
200
201 }