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