2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.aai;
23 import static com.fasterxml.jackson.module.kotlin.ExtensionsKt.jacksonObjectMapper;
24 import static java.util.Collections.emptyList;
25 import static java.util.Comparator.comparing;
26 import static java.util.stream.Collectors.toMap;
27 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
28 import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
29 import static org.apache.commons.lang3.StringUtils.isEmpty;
31 import com.fasterxml.jackson.databind.JsonNode;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import java.io.IOException;
34 import java.io.UnsupportedEncodingException;
36 import java.net.URLEncoder;
37 import java.util.LinkedHashMap;
38 import java.util.List;
40 import java.util.UUID;
41 import java.util.function.Function;
42 import java.util.stream.Stream;
43 import javax.inject.Inject;
44 import javax.ws.rs.WebApplicationException;
45 import javax.ws.rs.core.Response;
46 import org.apache.commons.lang3.StringUtils;
47 import org.apache.http.HttpStatus;
48 import org.apache.http.client.utils.URIBuilder;
49 import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
50 import org.jetbrains.annotations.NotNull;
51 import org.json.simple.JSONArray;
52 import org.json.simple.JSONObject;
53 import org.json.simple.parser.JSONParser;
54 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
55 import org.onap.vid.aai.exceptions.InvalidAAIResponseException;
56 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
57 import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion;
58 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetails;
59 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetailsHelper;
60 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetRelatedInstanceGroupsByVnfId;
61 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.CloudRegion;
62 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.InstanceGroup;
63 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network;
64 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
65 import org.onap.vid.aai.model.AaiGetPnfResponse;
66 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
67 import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
68 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
69 import org.onap.vid.aai.model.CustomQuerySimpleResult;
70 import org.onap.vid.aai.model.GetServiceModelsByDistributionStatusResponse;
71 import org.onap.vid.aai.model.LogicalLinkResponse;
72 import org.onap.vid.aai.model.ModelVer;
73 import org.onap.vid.aai.model.ModelVersions;
74 import org.onap.vid.aai.model.OwningEntityResponse;
75 import org.onap.vid.aai.model.PortDetailsTranslator;
76 import org.onap.vid.aai.model.ProjectResponse;
77 import org.onap.vid.aai.model.Properties;
78 import org.onap.vid.aai.model.ResourceType;
79 import org.onap.vid.aai.model.ServiceRelationships;
80 import org.onap.vid.aai.model.SimpleResult;
81 import org.onap.vid.aai.util.AAIRestInterface;
82 import org.onap.vid.aai.util.CacheProvider;
83 import org.onap.vid.aai.util.VidObjectMapperType;
84 import org.onap.vid.exceptions.GenericUncheckedException;
85 import org.onap.vid.model.SubscriberList;
86 import org.onap.vid.model.probes.ErrorMetadata;
87 import org.onap.vid.model.probes.ExternalComponentStatus;
88 import org.onap.vid.model.probes.HttpRequestMetadata;
89 import org.onap.vid.utils.Logging;
90 import org.onap.vid.utils.Unchecked;
91 import org.springframework.http.HttpMethod;
92 import org.springframework.web.util.UriUtils;
94 public class AaiClient implements AaiClientInterface {
97 public static final String QUERY_FORMAT_RESOURCE = "query?format=resource";
98 private static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/";
99 private static final String MODEL_INVARIANT_ID = "&model-invariant-id=";
100 private static final String QUERY_FORMAT_SIMPLE = "query?format=simple";
101 private static final String BUSINESS_CUSTOMER = "/business/customers/customer/";
102 private static final String SERVICE_INSTANCE = "/service-instances/service-instance/";
103 private static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/";
105 protected String fromAppId = "VidAaiController";
107 private PortDetailsTranslator portDetailsTranslator;
109 private final AAIRestInterface restController;
111 private final CacheProvider cacheProvider;
113 ObjectMapper objectMapper = jacksonObjectMapper();
118 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
120 private static final String GET_SERVICE_MODELS_REQUEST_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
123 public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) {
124 this.restController = restController;
125 this.portDetailsTranslator = portDetailsTranslator;
126 this.cacheProvider = cacheProvider;
130 private static String checkForNull(String local) {
139 public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){
140 Response resp = doAaiGet(getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false);
141 return processAaiResponse(resp, OwningEntityResponse.class, null);
145 public AaiResponse getServicesByProjectNames(List<String> projectNames){
146 Response resp = doAaiGet(getUrlFromLIst("business/projects?", "project-name=", projectNames), false);
147 return processAaiResponse(resp, ProjectResponse.class, null);
151 public AaiResponse getServiceModelsByDistributionStatus() {
152 return getFromCache("getServiceModelsByDistributionStatus", this::getServiceModelsByDistributionStatusNonCached,
153 true, "Failed to get service models by distribution status");
156 private AaiResponse getServiceModelsByDistributionStatusNonCached(boolean propagateExceptions) {
157 GetServiceModelsByDistributionStatusResponse response = typedAaiRest(QUERY_FORMAT_RESOURCE, GetServiceModelsByDistributionStatusResponse.class,
158 GET_SERVICE_MODELS_REQUEST_BODY, HttpMethod.PUT, propagateExceptions);
159 return new AaiResponse(response, "", HttpStatus.SC_OK);
163 public AaiResponse getNetworkCollectionDetails(String serviceInstanceId) {
164 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, "{\"start\": [\"nodes/service-instances/service-instance/" + serviceInstanceId + "\"],\"query\": \"query/network-collection-ByServiceInstance\"}\n", false);
165 AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse = processAaiResponse(resp, AaiGetNetworkCollectionDetailsHelper.class, null, VidObjectMapperType.FASTERXML);
166 return getNetworkCollectionDetailsResponse(aaiResponse);
170 public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) {
171 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE,
172 "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + encodePathSegment(cloudOwner) + "/" + encodePathSegment(cloudRegionId) + "\"]," +
173 "\"query\": \"query/instance-groups-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + encodePathSegment(networkFunction) + "\"}\n", false);
174 return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML);
177 private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){
178 if(aaiResponse.getHttpCode() == 200) {
179 ObjectMapper om = objectMapper;
180 AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails();
182 for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) {
183 LinkedHashMap<String, Object> temp = ((LinkedHashMap) aaiResponse.getT().getResults().get(i));
184 if (temp.get("service-instance") != null)
185 aaiGetNetworkCollectionDetails.getResults().setServiceInstance(om.readValue(om.writeValueAsString(temp.get("service-instance")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance.class));
186 else if (temp.get("collection") != null)
187 aaiGetNetworkCollectionDetails.getResults().setCollection(om.readValue(om.writeValueAsString(temp.get("collection")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Collection.class));
188 else if (temp.get("instance-group") != null)
189 aaiGetNetworkCollectionDetails.getResults().setInstanceGroup(om.readValue(om.writeValueAsString(temp.get("instance-group")), InstanceGroup.class));
190 else if (temp.get("l3-network") != null)
191 aaiGetNetworkCollectionDetails.getResults().getNetworks().add(om.readValue(om.writeValueAsString(temp.get("l3-network")), Network.class));
193 return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK);
195 catch (com.fasterxml.jackson.databind.JsonMappingException e) {
196 logger.error(EELFLoggerDelegate.errorLogger, "AAI response parsing Error", e);
197 return new AaiResponse(e.getCause(), "AAI response parsing Error" , HttpStatus.SC_INTERNAL_SERVER_ERROR);
199 catch (Exception e) {
200 logger.error(EELFLoggerDelegate.errorLogger,"Exception in aai response parsing", e);
201 return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode());
208 public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) {
209 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
210 String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel);
211 String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}";
212 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
213 return processAaiResponse(resp, AaiGetPnfResponse.class, null);
218 public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
219 Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false);
220 return processAaiResponse(resp, Pnf.class, null);
224 public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){
225 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId + "?depth=0", false);
226 return processAaiResponse(resp, AaiGetRelatedInstanceGroupsByVnfId.class , null, null);
231 public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID) {
232 String payload = "{\"start\":\"/network/configurations/configuration/" + configurationID + "\",\"query\":\"query/pserver-fromConfiguration\"}";
233 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
234 resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems
235 String rawPayload = resp.readEntity(String.class);
236 AaiResponse<CustomQuerySimpleResult> aaiResponse = processAaiResponse(resp, CustomQuerySimpleResult.class, rawPayload);
237 return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload);
242 public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
243 String getServiceInstancePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId+ SERVICE_SUBSCRIPTIONS_PATH +serviceType+ SERVICE_INSTANCE +serviceInstanceId;
244 Response resp = doAaiGet(getServiceInstancePath , false);
245 return processAaiResponse(resp, ServiceRelationships.class, null);
249 public AaiResponse getLogicalLink(String link) {
250 Response resp = doAaiGet("network/logical-links/logical-link/" + link , false);
251 return processAaiResponse(resp, LogicalLinkResponse.class, null);
255 public boolean isNodeTypeExistsByName(String name, ResourceType type) {
257 throw new GenericUncheckedException("Empty resource-name provided to searchNodeTypeByName; request is rejected as this will cause full resources listing");
260 URI path = Unchecked.toURI(String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name}
263 type.getNameFilter(),
264 encodePathSegment(name)
266 final ResponseWithRequestInfo responseWithRequestInfo = restController.RestGet(fromAppId, UUID.randomUUID().toString(), path, false, true);
268 return isResourceExistByStatusCode(responseWithRequestInfo);
271 public Map<String, Properties> getCloudRegionAndTenantByVnfId(String vnfId) {
272 String start = "/network/generic-vnfs/generic-vnf/" + vnfId;
273 String query = "/query/cloud-region-fromVnf";
275 String payload = "{\"start\":[\"" + start + "\"],\"query\":\"" + query + "\"}";
276 CustomQuerySimpleResult result = typedAaiRest(QUERY_FORMAT_SIMPLE, CustomQuerySimpleResult.class, payload, HttpMethod.PUT, false);
278 return result.getResults().stream()
279 .filter(res -> StringUtils.equals(res.getNodeType(), "tenant") ||
280 StringUtils.equals(res.getNodeType(), "cloud-region"))
281 .collect(toMap(SimpleResult::getNodeType, SimpleResult::getProperties));
284 private boolean isResourceExistByStatusCode(ResponseWithRequestInfo responseWithRequestInfo) {
286 // 404 - resource not found
287 Response.Status statusInfo = responseWithRequestInfo.getResponse().getStatusInfo().toEnum();
288 switch (statusInfo) {
294 throw new GenericUncheckedException("Unexpected response-code (only OK and NOT_FOUND are expected): " +
295 responseWithRequestInfo.getResponse().getStatusInfo());
300 public <T> T typedAaiGet(URI uri, Class<T> clz) {
301 return typedAaiRest(uri, clz, null, HttpMethod.GET, false);
304 public <T> T typedAaiRest(String path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
305 return typedAaiRest(Unchecked.toURI(path), clz, payload, method, propagateExceptions);
309 public <T> T typedAaiRest(URI path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
310 ResponseWithRequestInfo responseWithRequestInfo;
312 responseWithRequestInfo = restController.doRest(fromAppId, UUID.randomUUID().toString(), path, payload, method, false, propagateExceptions);
313 } catch (Exception e) {
314 responseWithRequestInfo = handleExceptionFromRestCall(propagateExceptions, "doAai"+method.name(), e);
317 final AaiResponseWithRequestInfo<T> aaiResponse = processAaiResponse(responseWithRequestInfo, clz, VidObjectMapperType.FASTERXML, true);
319 if (aaiResponse.getAaiResponse().getHttpCode() > 399 || aaiResponse.getAaiResponse().getT() == null) {
320 throw new ExceptionWithRequestInfo(aaiResponse.getHttpMethod(),
321 aaiResponse.getRequestedUrl(),
322 aaiResponse.getRawData(),
323 responseWithRequestInfo.getResponse().getStatus(),
324 new InvalidAAIResponseException(aaiResponse.getAaiResponse()));
327 return aaiResponse.getAaiResponse().getT();
331 private String getUrlFromLIst(String url, String paramKey, List<String> params){
333 for(String param: params){
335 url = url.concat(paramKey);
336 String encodedParam= param;
338 encodedParam= URLEncoder.encode(param, "UTF-8");
339 } catch (UnsupportedEncodingException e) {
340 String methodName = "getUrlFromList";
341 logger.error(EELFLoggerDelegate.errorLogger, methodName, e);
342 logger.debug(EELFLoggerDelegate.debugLogger, methodName, e);
344 url = url.concat(encodedParam);
345 if(i != params.size()){
346 url = url.concat("&");
355 public AaiResponse<SubscriberList> getAllSubscribers() {
356 return getFromCache("getAllSubscribers", this::getAllSubscribersNonCached, true, "Failed to get all subscribers");
359 private <K> AaiResponse getFromCache(String cacheName, Function<K, AaiResponse> function, K argument, String errorMessage) {
362 .aaiClientCacheFor(cacheName, function)
364 } catch (ExceptionWithRequestInfo exception) {
365 logger.error(errorMessage, exception);
366 return new AaiResponse(null, exception.getRawData(), exception.getHttpCode());
368 catch (Exception exception) {
369 logger.error(errorMessage, exception);
370 return new AaiResponse(null, exception.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
374 private AaiResponse<SubscriberList> getAllSubscribersNonCached(boolean propagateExceptions) {
375 AaiResponse<SubscriberList> aaiResponse = getAllSubscribers(propagateExceptions).getAaiResponse();
376 if (propagateExceptions && (aaiResponse.getT() == null || aaiResponse.getT().customer == null || aaiResponse.getT().customer.isEmpty())) {
377 throw new GenericUncheckedException("Failed to get Subscribers data. The data is null or empty.");
383 AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){
385 ResponseWithRequestInfo aaiGetResult = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false, propagateExceptions);
386 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = processAaiResponse(aaiGetResult, SubscriberList.class, propagateExceptions);
387 responseWithRequestInfo.setRequestedUrl(aaiGetResult.getRequestUrl());
388 responseWithRequestInfo.setHttpMethod(aaiGetResult.getRequestHttpMethod());
389 return responseWithRequestInfo;
394 public AaiResponse getAllAicZones() {
395 Response resp = doAaiGet("network/zones", false);
396 return processAaiResponse(resp, AicZones.class, null);
400 public AaiResponse getVNFData(String globalSubscriberId, String serviceType) {
401 String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," +
402 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
403 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
404 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
408 public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
409 String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + SERVICE_INSTANCE + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
410 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
411 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
415 public Response getVersionByInvariantId(List<String> modelInvariantId) {
416 if (modelInvariantId.isEmpty()) {
417 throw new GenericUncheckedException("Zero invariant-ids provided to getVersionByInvariantId; request is rejected as this will cause full models listing");
420 StringBuilder sb = new StringBuilder();
421 for (String id : modelInvariantId){
422 sb.append(MODEL_INVARIANT_ID);
426 return doAaiGet("service-design-and-creation/models?depth=2" + sb.toString(), false);
430 public ModelVer getLatestVersionByInvariantId(String modelInvariantId) {
431 if (modelInvariantId.isEmpty()) {
432 throw new GenericUncheckedException("no invariant-id provided to getLatestVersionByInvariantId; request is rejected");
435 // add the modelInvariantId to the payload
436 StringBuilder payload = new StringBuilder(GET_SERVICE_MODELS_REQUEST_BODY);
437 payload.insert(50, modelInvariantId);
439 Response response = doAaiPut("service-design-and-creation/models/model/", payload.toString(),false);
440 AaiResponse<ModelVersions> aaiResponse = processAaiResponse(response, ModelVersions.class, null, VidObjectMapperType.FASTERXML);
441 Stream<ModelVer> modelVerStream = toModelVerStream(aaiResponse.getT());
442 return maxModelVer(modelVerStream);
446 protected Stream<ModelVer> toModelVerStream(ModelVersions modelVersions) {
448 return Stream.of(modelVersions)
449 .map(ModelVersions::getResults)
450 .flatMap(java.util.Collection::stream)
451 .flatMap(map -> map.entrySet().stream())
452 .filter(kv -> StringUtils.equals(kv.getKey(), "model-ver"))
453 .map(Map.Entry::getValue);
457 protected ModelVer maxModelVer(Stream<ModelVer> modelVerStream) {
458 return modelVerStream
459 .filter(modelVer -> StringUtils.isNotEmpty(modelVer.getModelVersion()))
460 .max(comparing(ModelVer::getModelVersion, comparing(DefaultArtifactVersion::new)))
461 .orElseThrow(() -> new GenericUncheckedException("Could not find any version"));
465 public AaiResponse getSubscriberData(String subscriberId, boolean omitServiceInstances) {
466 String depth = omitServiceInstances ? "1" : "2";
467 AaiResponse subscriberDataResponse;
468 Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false);
469 subscriberDataResponse = processAaiResponse(resp, Services.class, null);
470 return subscriberDataResponse;
474 public AaiResponse getServices() {
475 Response resp = doAaiGet("service-design-and-creation/services", false);
476 return processAaiResponse(resp, GetServicesAAIRespone.class, null);
480 public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) {
481 String url = "cloud-infrastructure/operational-environments";
482 URIBuilder urlBuilder = new URIBuilder();
483 if (operationalEnvironmentType != null)
484 urlBuilder.addParameter("operational-environment-type", operationalEnvironmentType);
485 if (operationalEnvironmentStatus != null)
486 urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus);
487 url += urlBuilder.toString();
488 Response resp = doAaiGet(url, false);
489 return processAaiResponse(resp, OperationalEnvironmentList.class, null);
493 public AaiResponse getTenants(String globalCustomerId, String serviceType) {
494 if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty()))){
495 return buildAaiResponseForGetTenantsFailure(" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.");
499 .aaiClientCacheFor("getTenants", this::getTenantsByKey)
500 .get(CacheProvider.compileKey(globalCustomerId, serviceType));
502 catch (ParsingGetTenantsResponseFailure exception) {
503 logger.error("Failed to get tenants ", exception);
504 return buildAaiResponseForGetTenantsFailure(exception.getMessage());
509 public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
511 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
512 String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion);
513 String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}";
515 Response resp1 = doAaiPut(QUERY_FORMAT_SIMPLE, payload1, false);
516 AaiResponse aaiResponse1 = processAaiResponse(resp1, AaiGetVnfResponse.class, null);
517 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1);
522 public AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId) {
523 final String start = "[\"network/configurations/configuration/" + configurationId + "\"]";
524 final String query = "\"query/cloud-region-and-source-FromConfiguration\"";
525 String payload = "{\"start\":" + start + ",\"query\":" + query + "}";
527 Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false);
528 AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null);
530 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse);
534 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) {
535 return processAaiResponse(responseWithRequestInfo, classType, VidObjectMapperType.CODEHAUS, propagateExceptions);
538 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, VidObjectMapperType omType, boolean propagateExceptions) {
539 String responseBody = null;
540 Integer responseHttpCode = null;
542 Response response = responseWithRequestInfo.getResponse();
543 responseHttpCode = (response != null) ? response.getStatus() : null;
544 responseBody = (response != null) ? response.readEntity(String.class) : null;
545 AaiResponse<T> processedAaiResponse = processAaiResponse(response, classType, responseBody, omType, propagateExceptions);
546 return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse,
548 } catch (Exception e) {
549 throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(),
550 responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e);
554 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) {
555 return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS);
558 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType) {
559 return processAaiResponse(resp, classType, responseBody, omType, false);
562 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
563 AaiResponse<T> subscriberDataResponse;
565 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
566 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
568 logger.debug(EELFLoggerDelegate.debugLogger, "getSubscribers() resp=" + resp.getStatusInfo().toString());
569 if (resp.getStatus() != HttpStatus.SC_OK) {
570 subscriberDataResponse = processFailureResponse(resp,responseBody);
572 subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
575 return subscriberDataResponse;
578 private AaiResponse processFailureResponse(Response resp, String responseBody) {
579 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
581 if (responseBody != null) {
582 rawData = responseBody;
584 rawData = resp.readEntity(String.class);
586 return new AaiResponse<>(null, rawData, resp.getStatus());
589 private <T> AaiResponse<T> processOkResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
590 AaiResponse<T> subscriberDataResponse;
591 String finalResponse = null;
593 if (responseBody != null) {
594 finalResponse = responseBody;
596 finalResponse = resp.readEntity(String.class);
599 if(omType == VidObjectMapperType.CODEHAUS)
600 subscriberDataResponse = parseCodeHausObject(classType, finalResponse);
602 subscriberDataResponse = parseFasterXmlObject(classType, finalResponse);
604 } catch(Exception e){
605 if (propagateExceptions) {
606 throw new GenericUncheckedException(e);
608 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
609 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
612 return subscriberDataResponse;
615 private <T> AaiResponse<T> parseFasterXmlObject(Class<? extends T> classType, String finalResponse) throws IOException {
616 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
619 private <T> AaiResponse<T> parseCodeHausObject(Class<? extends T> classType, String finalResponse) throws IOException {
620 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
624 public Response doAaiGet(String uri, boolean xml) {
625 return doAaiGet(uri, xml, false).getResponse();
629 public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) {
630 return doAaiGet(Unchecked.toURI(uri), xml, propagateExceptions);
633 public ResponseWithRequestInfo doAaiGet(URI uri, boolean xml, boolean propagateExceptions) {
634 String methodName = "doAaiGet";
635 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
637 ResponseWithRequestInfo resp;
639 resp = restController.RestGet(fromAppId, UUID.randomUUID().toString(), uri, xml, propagateExceptions);
641 } catch (Exception e) {
642 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
648 protected ResponseWithRequestInfo handleExceptionFromRestCall(boolean propagateExceptions, String methodName, Exception e) {
649 ResponseWithRequestInfo resp;
650 if (propagateExceptions) {
651 throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e);
653 final Exception actual =
654 e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e;
656 final String message =
657 actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString();
659 //ToDo: change parameter of requestUrl to real url from doRest function
660 resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET);
661 logger.info(EELFLoggerDelegate.errorLogger, methodName + message);
662 logger.debug(EELFLoggerDelegate.debugLogger, methodName + message);
667 private String parseForTenantsByServiceSubscription(String relatedToKey, String resp) {
668 String tenantList = "";
671 JSONParser jsonParser = new JSONParser();
673 JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
675 return parseServiceSubscriptionObjectForTenants(relatedToKey, jsonObject);
676 } catch (Exception ex) {
677 logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex);
682 protected Response doAaiPut(String uri, String payload, boolean xml) {
683 return doAaiPut(uri, payload, xml, false).getResponse();
686 protected ResponseWithRequestInfo doAaiPut(String uri, String payload, boolean xml, boolean propagateExceptions) {
687 String methodName = "doAaiPut";
688 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
690 ResponseWithRequestInfo resp;
693 resp = restController.RestPut(fromAppId, uri, payload, xml, propagateExceptions);
695 } catch (Exception e) {
696 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
702 private String parseServiceSubscriptionObjectForTenants(String relatedToKey, JSONObject jsonObject) {
703 JSONArray tenantArray = new JSONArray();
704 boolean bconvert = false;
706 JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
707 if (relationShipListsObj != null) {
708 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
709 for (Object innerObj : defaultIfNull(rShipArray, emptyList())) {
710 if (innerObj != null) {
711 bconvert = parseTenant(relatedToKey, tenantArray, bconvert, (JSONObject) innerObj);
715 } catch (NullPointerException ex) {
716 logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex);
720 return tenantArray.toJSONString();
726 private static boolean parseTenant(String relatedToKey, JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) {
727 String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
728 if (relatedTo.equalsIgnoreCase(relatedToKey)) {
729 JSONObject tenantNewObj = new JSONObject();
731 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
732 tenantNewObj.put("link", relatedLink);
734 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
735 for (Object innerObj : defaultIfNull(rDataArray, emptyList())) {
736 parseRelationShip(tenantNewObj, (JSONObject) innerObj);
739 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
740 for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) {
741 parseRelatedTProp(tenantNewObj, (JSONObject) innerObj);
744 tenantArray.add(tenantNewObj);
749 private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) {
750 if (innerObj == null)
753 String propKey = checkForNull((String) innerObj.get("property-key"));
754 String propVal = checkForNull((String) innerObj.get("property-value"));
755 if (equalsIgnoreCase(propKey, "tenant.tenant-name")) {
756 tenantNewObj.put("tenantName", propVal);
760 private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) {
761 if (inner2Obj == null)
764 String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
765 String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
766 if (equalsIgnoreCase(rShipKey, "cloud-region.cloud-owner")) {
767 tenantNewObj.put("cloudOwner", rShipVal);
768 } else if (equalsIgnoreCase(rShipKey, "cloud-region.cloud-region-id")) {
769 tenantNewObj.put("cloudRegionID", rShipVal);
770 } else if (equalsIgnoreCase(rShipKey, "tenant.tenant-id")) {
771 tenantNewObj.put("tenantID", rShipVal);
775 private static String encodePathSegment(String segmentToEncode) {
776 return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
780 public ExternalComponentStatus probeComponent(){
781 long startTime = System.currentTimeMillis();
783 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true);
784 AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse();
785 long duration = System.currentTimeMillis() - startTime;
787 SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null;
788 boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty();
790 HttpRequestMetadata metadata = new HttpRequestMetadata(
791 responseWithRequestInfo.getHttpMethod(),
792 (aaiResponse != null) ? aaiResponse.getHttpCode() : 0,
793 responseWithRequestInfo.getRequestedUrl(),
794 responseWithRequestInfo.getRawData(),
795 isAvailable ? "OK" : "No subscriber received",
798 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata);
800 } catch (ExceptionWithRequestInfo e) {
801 long duration = System.currentTimeMillis() - startTime;
802 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
803 new HttpRequestMetadata(e, duration));
804 } catch (Exception e) {
805 long duration = System.currentTimeMillis() - startTime;
806 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
807 new ErrorMetadata(Logging.exceptionToDescription(e), duration));
812 public String getCloudOwnerByCloudRegionId(String cloudRegionId) {
814 .aaiClientCacheFor("getCloudOwnerByCloudRegionId", this::getCloudOwnerByCloudRegionIdNonCached)
820 public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) {
822 if (isEmpty(vnfInstanceId)|| isEmpty(vfModuleId)){
823 throw new GenericUncheckedException("Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.");
825 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId +"/vf-modules/vf-module/"+ vfModuleId, false);
826 String responseAsString = parseForTenantsByServiceSubscription("vserver",resp.readEntity(String.class));
827 if (isEmpty(responseAsString)){
828 throw new GenericUncheckedException( String.format("A&AI has no homing data associated to vfModule '%s' of vnf '%s'", vfModuleId, vnfInstanceId));
831 AaiResponse aaiResponse = processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
832 return ((GetTenantsResponse[])aaiResponse.getT())[0];
837 public void resetCache(String cacheName) {
838 cacheProvider.resetCache(cacheName);
841 String getCloudOwnerByCloudRegionIdNonCached(String cloudRegionId) {
842 String uri = "cloud-infrastructure/cloud-regions?cloud-region-id=" + encodePathSegment(cloudRegionId);
844 final CloudRegion.Collection cloudRegionCollection =
845 typedAaiGet(Unchecked.toURI(uri), CloudRegion.Collection.class);
847 return cloudRegionCollection
848 .getCloudRegions().stream()
849 .map(CloudRegion::getCloudOwner)
850 // from here we assure that the cloud owner is given, and not null
851 // and non-empty, and that if more than one cloud-owner is given -
852 // it is only a single value.
853 // exception is thrown if none or more than a single values are
855 .filter(StringUtils::isNotEmpty)
858 // will be invoked only if distinct() leaves more than a single element
859 throw new GenericUncheckedException("Conflicting cloud-owner found for " + cloudRegionId + ": '" + a + "' / '" + b + "'");
861 .orElseThrow(() -> new GenericUncheckedException("No cloud-owner found for " + cloudRegionId));
864 private AaiResponse getTenantsByKey(String key) {
865 String[] args = CacheProvider.decompileKey(key);
866 String globalCustomerId = safeGetFromArray(args, 0);
867 String serviceType = safeGetFromArray(args, 1);
868 return getTenantsNonCached(globalCustomerId, serviceType);
871 AaiResponse getTenantsNonCached(String globalCustomerId, String serviceType) {
872 String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType;
874 Response resp = doAaiGet(url, false);
875 String responseAsString = parseForTenantsByServiceSubscription("tenant",resp.readEntity(String.class));
876 if (isEmpty(responseAsString)){
877 throw new ParsingGetTenantsResponseFailure(String.format("A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'", globalCustomerId, serviceType));
880 return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
884 public static class ParsingGetTenantsResponseFailure extends GenericUncheckedException {
886 public ParsingGetTenantsResponseFailure(String message) {
892 private AaiResponse<String> buildAaiResponseForGetTenantsFailure(String errorText) {
893 return new AaiResponse<>(null, String.format("{\"statusText\":\"%s\"}", errorText), HttpStatus.SC_INTERNAL_SERVER_ERROR);
896 private static String safeGetFromArray(String[] array, int i) {
897 if (i < 0 || i >= array.length) {