aboutsummaryrefslogtreecommitdiffstats
path: root/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
blob: e95db6b18834779cdaf55c67a253a258fb6cf05c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.so.apihandlerinfra.tenantisolation.process;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.NotFoundException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest;
import org.onap.so.apihandlerinfra.tenantisolation.exceptions.TenantIsolationException;
import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper;
import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientObjectBuilder;
import org.onap.so.apihandlerinfra.tenantisolationbeans.RelatedInstanceList;
import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.client.aai.objects.AAIOperationalEnvironment;
import org.onap.so.client.grm.GRMClient;
import org.onap.so.client.grm.beans.OperationalInfo;
import org.onap.so.client.grm.beans.Property;
import org.onap.so.client.grm.beans.ServiceEndPoint;
import org.onap.so.client.grm.beans.ServiceEndPointList;
import org.onap.so.client.grm.beans.ServiceEndPointRequest;
import org.onap.so.client.grm.beans.Version;
import org.onap.so.logger.MessageEnum;
import org.onap.so.logger.MsoLogger;
import org.onap.so.requestsdb.RequestsDBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class CreateVnfOperationalEnvironment {
	
	private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, CreateVnfOperationalEnvironment.class);
	protected CloudOrchestrationRequest request;
	
	@Autowired 
	private AAIClientObjectBuilder aaiClientObjectBuilder;
	@Autowired 
	private AAIClientHelper aaiHelper;
	@Autowired 
	private RequestsDBHelper requestDb;
	private GRMClient grmClient;
	
	public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{
		try {
			setRequest(request);
			ObjectMapper objectMapper = new ObjectMapper();
			AAIResultWrapper aaiResultWrapper = aaiHelper.getAaiOperationalEnvironment(getEcompManagingEnvironmentId());
			if (aaiResultWrapper.isEmpty()) {
				throw new NotFoundException(getEcompManagingEnvironmentId() + " not found in A&AI");
			}
			AAIOperationalEnvironment aaiEnv = objectMapper.readValue(aaiResultWrapper.getJson(), AAIOperationalEnvironment.class);

			//Find ECOMP environments in GRM
			msoLogger.debug(" Start of GRM findRunningServicesAsString");
			String searchKey = getSearchKey(aaiEnv);
			String tenantContext = getTenantContext().toUpperCase();
			String jsonResponse = getGrmClient().findRunningServicesAsString(searchKey, 1, tenantContext);
			ServiceEndPointList sel = objectMapper.readValue(jsonResponse, ServiceEndPointList.class);
			if(sel.getServiceEndPointList().size() == 0) {
				throw new TenantIsolationException("GRM did not find any matches for " + searchKey + " in " + tenantContext);
			}

			//Replicate end-point for VNF Operating environment in GRM
			List<ServiceEndPointRequest> serviceEndpointRequestList = buildEndPointRequestList(sel);
			int ctr = 0;
			int total = serviceEndpointRequestList.size();
			for (ServiceEndPointRequest requestList : serviceEndpointRequestList) {
				msoLogger.debug("Creating endpoint " + ++ctr + " of " + total + ": " + requestList.getServiceEndPoint().getName());
				getGrmClient().addServiceEndPoint(requestList);
			}

			//Create VNF operating in A&AI
			aaiHelper.createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("INACTIVE", request));
			aaiHelper.createRelationship(request.getOperationalEnvironmentId(), getEcompManagingEnvironmentId());

			//Update request database
			requestDb.updateInfraSuccessCompletion("SUCCESSFULLY created VNF operational environment", requestId, request.getOperationalEnvironmentId());

		}catch(Exception e) {
			ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.DataError).build();


			ValidateException validateException = new ValidateException.Builder(e.getMessage(),
					HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();

			throw validateException;
		}
	}
	
	
	protected String getEcompManagingEnvironmentId() throws TenantIsolationException {
		RelatedInstanceList[] relatedInstances = request.getRequestDetails().getRelatedInstanceList();
		if (relatedInstances.length > 0 && relatedInstances[0].getRelatedInstance() != null) {
			return relatedInstances[0].getRelatedInstance().getInstanceId();
		} else {
			return null;
		}
	}
	
	
	protected String getTenantContext() throws TenantIsolationException {
		if(!StringUtils.isEmpty(request.getRequestDetails().getRequestParameters().getTenantContext())) {
			return request.getRequestDetails().getRequestParameters().getTenantContext();
		}
		else {
			throw new TenantIsolationException("Tenant Context is missing from request!");
		}
	}
	
	
	private List<ServiceEndPointRequest> buildEndPointRequestList(ServiceEndPointList serviceEndPointList) throws TenantIsolationException {
		List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList();
		msoLogger.debug("Number of service endpoints from GRM: " + endpointList.size());
		List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>(); 
		for(ServiceEndPoint serviceEndpoint : endpointList) {
			serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint));
		}
		return serviceEndPointRequestList;
	}
	
	
	private ServiceEndPointRequest buildServiceEndpoint(ServiceEndPoint serviceEndpoint) throws TenantIsolationException {
		
		//@TODO: handle nulls? Put in a ServiceEndpointWrapper class which will check for nulls and flatten access to fields
		Version ver = new Version();
		ver.setMajor(serviceEndpoint.getVersion().getMajor());
		ver.setMinor(serviceEndpoint.getVersion().getMinor());
		ver.setPatch(serviceEndpoint.getVersion().getPatch());

		ServiceEndPoint endpoint = new ServiceEndPoint();
		endpoint.setName(buildServiceNameForVnf(serviceEndpoint.getName()));

		endpoint.setVersion(ver);
		endpoint.setHostAddress(serviceEndpoint.getHostAddress());
		endpoint.setListenPort(serviceEndpoint.getListenPort());
		endpoint.setLatitude(serviceEndpoint.getLatitude());
		endpoint.setLongitude(serviceEndpoint.getLongitude());
		endpoint.setContextPath(serviceEndpoint.getContextPath());
		endpoint.setRouteOffer(serviceEndpoint.getRouteOffer());
		
		OperationalInfo operInfo = new OperationalInfo();
		operInfo.setCreatedBy(serviceEndpoint.getOperationalInfo().getCreatedBy());
		operInfo.setUpdatedBy(serviceEndpoint.getOperationalInfo().getUpdatedBy());
		
		endpoint.setOperationalInfo(operInfo);
		endpoint.setProperties(serviceEndpoint.getProperties());
			
		String env = getEnvironmentName(serviceEndpoint.getProperties());
		
		ServiceEndPointRequest serviceEndPontRequest = new ServiceEndPointRequest();
		serviceEndPontRequest.setEnv(env);
		serviceEndPontRequest.setServiceEndPoint(endpoint);
		
		return serviceEndPontRequest;
	}
	
	
	protected String getEnvironmentName(List<Property> props) {
		String env = "";
		for(Property prop : props) {
			if(prop.getName().equalsIgnoreCase("Environment")) {
				env = prop.getValue();
			}
		}
		return env;
	}
	
	
	protected String buildServiceNameForVnf(String fqName) throws TenantIsolationException {
		// Service name format is: {tenantContext}.{workloadContext}.{serviceName}  e.g. TEST.ECOMP_PSL.Inventory
		// We need to extract the serviceName, in the above example: "Inventory"
		String[] tokens = fqName.split("[.]");
		String serviceName;
		if(tokens.length > 0) {
			serviceName = tokens[tokens.length-1];
		}
		else {
			throw new TenantIsolationException("Fully qualified service name is null.");
		}
		String tenantContext = request.getRequestDetails().getRequestParameters().getTenantContext();
		String workloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
		return tenantContext + "." + workloadContext + "." + serviceName;
	}
	
	protected String getSearchKey(AAIOperationalEnvironment aaiEnv)  {
		return aaiEnv.getTenantContext() + "." + aaiEnv.getWorkloadContext() + ".*";
	}

	public void setRequest(CloudOrchestrationRequest request) {
		this.request = request;
	}
	
	private GRMClient getGrmClient() {
		if(grmClient == null) {
			this.grmClient = new GRMClient();
		}
		
		return grmClient;
	}
}