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