Removed MsoLogger class
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / process / CreateVnfOperationalEnvironment.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 import java.util.ArrayList;
26 import java.util.List;
27
28 import javax.ws.rs.NotFoundException;
29
30 import org.apache.commons.lang3.StringUtils;
31 import org.apache.http.HttpStatus;
32 import org.onap.aai.domain.yang.OperationalEnvironment;
33 import org.onap.so.apihandler.common.ErrorNumbers;
34 import org.onap.so.apihandlerinfra.exceptions.ApiException;
35 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
36 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
37 import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest;
38 import org.onap.so.apihandlerinfra.tenantisolation.exceptions.TenantIsolationException;
39 import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper;
40 import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientObjectBuilder;
41 import org.onap.so.apihandlerinfra.tenantisolationbeans.RelatedInstanceList;
42 import org.onap.so.client.aai.entities.AAIResultWrapper;
43 import org.onap.so.client.grm.GRMClient;
44 import org.onap.so.client.grm.beans.OperationalInfo;
45 import org.onap.so.client.grm.beans.Property;
46 import org.onap.so.client.grm.beans.ServiceEndPoint;
47 import org.onap.so.client.grm.beans.ServiceEndPointList;
48 import org.onap.so.client.grm.beans.ServiceEndPointRequest;
49 import org.onap.so.client.grm.beans.Version;
50 import org.onap.so.logger.ErrorCode;
51 import org.onap.so.logger.MessageEnum;
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.stereotype.Component;
57
58 import com.fasterxml.jackson.databind.ObjectMapper;
59
60 @Component
61 public class CreateVnfOperationalEnvironment {
62         
63         private static Logger logger = LoggerFactory.getLogger(CreateVnfOperationalEnvironment.class);
64         protected CloudOrchestrationRequest request;
65         
66         @Autowired 
67         private AAIClientObjectBuilder aaiClientObjectBuilder;
68         @Autowired 
69         private AAIClientHelper aaiHelper;
70         @Autowired 
71         private RequestsDBHelper requestDb;
72         private GRMClient grmClient;
73         
74         public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{
75                 try {
76                         setRequest(request);
77                         ObjectMapper objectMapper = new ObjectMapper();
78                         AAIResultWrapper aaiResultWrapper = aaiHelper.getAaiOperationalEnvironment(getEcompManagingEnvironmentId());
79                         if (aaiResultWrapper.isEmpty()) {
80                                 throw new NotFoundException(getEcompManagingEnvironmentId() + " not found in A&AI");
81                         }
82                         OperationalEnvironment aaiEnv = aaiResultWrapper.asBean(OperationalEnvironment.class).get();
83
84                         //Find ECOMP environments in GRM
85                         logger.debug(" Start of GRM findRunningServicesAsString");
86                         String searchKey = getSearchKey(aaiEnv);
87                         String tenantContext = getTenantContext().toUpperCase();
88                         String jsonResponse = getGrmClient().findRunningServicesAsString(searchKey, 1, tenantContext);
89                         ServiceEndPointList sel = objectMapper.readValue(jsonResponse, ServiceEndPointList.class);
90                         if(sel.getServiceEndPointList().size() == 0) {
91                                 throw new TenantIsolationException("GRM did not find any matches for " + searchKey + " in " + tenantContext);
92                         }
93
94                         //Replicate end-point for VNF Operating environment in GRM
95                         List<ServiceEndPointRequest> serviceEndpointRequestList = buildEndPointRequestList(sel);
96                         int ctr = 0;
97                         int total = serviceEndpointRequestList.size();
98                         for (ServiceEndPointRequest requestList : serviceEndpointRequestList) {
99                                 logger.debug("Creating endpoint " + ++ctr + " of " + total + ": " + requestList.getServiceEndPoint().getName());
100                                 getGrmClient().addServiceEndPoint(requestList);
101                         }
102
103                         //Create VNF operating in A&AI
104                         aaiHelper.createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("INACTIVE", request));
105                         aaiHelper.createRelationship(request.getOperationalEnvironmentId(), getEcompManagingEnvironmentId());
106
107                         //Update request database
108                         requestDb.updateInfraSuccessCompletion("SUCCESSFULLY created VNF operational environment", requestId, request.getOperationalEnvironmentId());
109
110                 }catch(Exception e) {
111                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
112
113
114                         ValidateException validateException = new ValidateException.Builder(e.getMessage(),
115                                         HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
116
117                         throw validateException;
118                 }
119         }
120         
121         
122         protected String getEcompManagingEnvironmentId() throws TenantIsolationException {
123                 RelatedInstanceList[] relatedInstances = request.getRequestDetails().getRelatedInstanceList();
124                 if (relatedInstances.length > 0 && relatedInstances[0].getRelatedInstance() != null) {
125                         return relatedInstances[0].getRelatedInstance().getInstanceId();
126                 } else {
127                         return null;
128                 }
129         }
130         
131         
132         protected String getTenantContext() throws TenantIsolationException {
133                 if(!StringUtils.isEmpty(request.getRequestDetails().getRequestParameters().getTenantContext())) {
134                         return request.getRequestDetails().getRequestParameters().getTenantContext();
135                 }
136                 else {
137                         throw new TenantIsolationException("Tenant Context is missing from request!");
138                 }
139         }
140         
141         
142         private List<ServiceEndPointRequest> buildEndPointRequestList(ServiceEndPointList serviceEndPointList) throws TenantIsolationException {
143                 List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList();
144                 logger.debug("Number of service endpoints from GRM: {}", endpointList.size());
145                 List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>(); 
146                 for(ServiceEndPoint serviceEndpoint : endpointList) {
147                         serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint));
148                 }
149                 return serviceEndPointRequestList;
150         }
151         
152         
153         private ServiceEndPointRequest buildServiceEndpoint(ServiceEndPoint serviceEndpoint) throws TenantIsolationException {
154                 
155                 //@TODO: handle nulls? Put in a ServiceEndpointWrapper class which will check for nulls and flatten access to fields
156                 Version ver = new Version();
157                 ver.setMajor(serviceEndpoint.getVersion().getMajor());
158                 ver.setMinor(serviceEndpoint.getVersion().getMinor());
159                 ver.setPatch(serviceEndpoint.getVersion().getPatch());
160
161                 ServiceEndPoint endpoint = new ServiceEndPoint();
162                 endpoint.setName(buildServiceNameForVnf(serviceEndpoint.getName()));
163
164                 endpoint.setVersion(ver);
165                 endpoint.setHostAddress(serviceEndpoint.getHostAddress());
166                 endpoint.setListenPort(serviceEndpoint.getListenPort());
167                 endpoint.setLatitude(serviceEndpoint.getLatitude());
168                 endpoint.setLongitude(serviceEndpoint.getLongitude());
169                 endpoint.setContextPath(serviceEndpoint.getContextPath());
170                 endpoint.setRouteOffer(serviceEndpoint.getRouteOffer());
171                 
172                 OperationalInfo operInfo = new OperationalInfo();
173                 operInfo.setCreatedBy(serviceEndpoint.getOperationalInfo().getCreatedBy());
174                 operInfo.setUpdatedBy(serviceEndpoint.getOperationalInfo().getUpdatedBy());
175                 
176                 endpoint.setOperationalInfo(operInfo);
177                 endpoint.setProperties(serviceEndpoint.getProperties());
178                         
179                 String env = getEnvironmentName(serviceEndpoint.getProperties());
180                 
181                 ServiceEndPointRequest serviceEndPontRequest = new ServiceEndPointRequest();
182                 serviceEndPontRequest.setEnv(env);
183                 serviceEndPontRequest.setServiceEndPoint(endpoint);
184                 
185                 return serviceEndPontRequest;
186         }
187         
188         
189         protected String getEnvironmentName(List<Property> props) {
190                 String env = "";
191                 for(Property prop : props) {
192                         if(prop.getName().equalsIgnoreCase("Environment")) {
193                                 env = prop.getValue();
194                         }
195                 }
196                 return env;
197         }
198         
199         
200         protected String buildServiceNameForVnf(String fqName) throws TenantIsolationException {
201                 // Service name format is: {tenantContext}.{workloadContext}.{serviceName}  e.g. TEST.ECOMP_PSL.Inventory
202                 // We need to extract the serviceName, in the above example: "Inventory"
203                 String[] tokens = fqName.split("[.]");
204                 String serviceName;
205                 if(tokens.length > 0) {
206                         serviceName = tokens[tokens.length-1];
207                 }
208                 else {
209                         throw new TenantIsolationException("Fully qualified service name is null.");
210                 }
211                 String tenantContext = request.getRequestDetails().getRequestParameters().getTenantContext();
212                 String workloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
213                 return tenantContext + "." + workloadContext + "." + serviceName;
214         }
215         
216         protected String getSearchKey(OperationalEnvironment aaiEnv)  {
217                 return aaiEnv.getTenantContext() + "." + aaiEnv.getWorkloadContext() + ".*";
218         }
219
220         public void setRequest(CloudOrchestrationRequest request) {
221                 this.request = request;
222         }
223         
224         private GRMClient getGrmClient() {
225                 if(grmClient == null) {
226                         this.grmClient = new GRMClient();
227                 }
228                 
229                 return grmClient;
230         }
231 }