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;
30 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
32 import com.fasterxml.jackson.core.JsonProcessingException;
33 import com.fasterxml.jackson.databind.JsonNode;
34 import com.fasterxml.jackson.databind.ObjectMapper;
35 import com.google.common.collect.ImmutableList;
36 import com.google.common.collect.ImmutableMap;
37 import java.io.IOException;
38 import java.io.Serializable;
39 import java.io.UnsupportedEncodingException;
41 import java.net.URLEncoder;
42 import java.util.LinkedHashMap;
43 import java.util.List;
45 import java.util.UUID;
46 import java.util.function.Function;
47 import java.util.stream.Stream;
48 import javax.inject.Inject;
49 import javax.ws.rs.WebApplicationException;
50 import javax.ws.rs.core.Response;
51 import org.apache.commons.lang3.StringUtils;
52 import org.apache.commons.lang3.exception.ExceptionUtils;
53 import org.apache.http.HttpStatus;
54 import org.apache.http.client.utils.URIBuilder;
55 import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
56 import org.jetbrains.annotations.NotNull;
57 import org.jetbrains.annotations.Nullable;
58 import org.json.simple.JSONArray;
59 import org.json.simple.JSONObject;
60 import org.json.simple.parser.JSONParser;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.vid.aai.exceptions.InvalidAAIResponseException;
63 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
64 import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion;
65 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetails;
66 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetailsHelper;
67 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetRelatedInstanceGroupsByVnfId;
68 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.CloudRegion;
69 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.InstanceGroup;
70 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network;
71 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
72 import org.onap.vid.aai.model.AaiGetPnfResponse;
73 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
74 import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
75 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
76 import org.onap.vid.aai.model.CustomQuerySimpleResult;
77 import org.onap.vid.aai.model.GetServiceModelsByDistributionStatusResponse;
78 import org.onap.vid.aai.model.LogicalLinkResponse;
79 import org.onap.vid.aai.model.ModelVer;
80 import org.onap.vid.aai.model.ModelVersions;
81 import org.onap.vid.aai.model.OwningEntityResponse;
82 import org.onap.vid.aai.model.PortDetailsTranslator;
83 import org.onap.vid.aai.model.ProjectResponse;
84 import org.onap.vid.aai.model.Properties;
85 import org.onap.vid.aai.model.ResourceType;
86 import org.onap.vid.aai.model.ServiceRelationships;
87 import org.onap.vid.aai.model.SimpleResult;
88 import org.onap.vid.aai.util.AAIRestInterface;
89 import org.onap.vid.aai.util.CacheProvider;
90 import org.onap.vid.aai.util.VidObjectMapperType;
91 import org.onap.vid.exceptions.GenericUncheckedException;
92 import org.onap.vid.model.SubscriberList;
93 import org.onap.vid.model.probes.ErrorMetadata;
94 import org.onap.vid.model.probes.ExternalComponentStatus;
95 import org.onap.vid.model.probes.HttpRequestMetadata;
96 import org.onap.vid.utils.Logging;
97 import org.onap.vid.utils.Unchecked;
98 import org.springframework.http.HttpMethod;
99 import org.springframework.web.util.UriUtils;
101 public class AaiClient implements AaiClientInterface {
104 public static final String QUERY_FORMAT_RESOURCE = "query?format=resource";
105 private static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/";
106 private static final String MODEL_INVARIANT_ID = "&model-invariant-id=";
107 private static final String QUERY_FORMAT_SIMPLE = "query?format=simple";
108 private static final String BUSINESS_CUSTOMER = "/business/customers/customer/";
109 private static final String SERVICE_INSTANCE = "/service-instances/service-instance/";
110 private static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/";
112 protected String fromAppId = "VidAaiController";
114 private PortDetailsTranslator portDetailsTranslator;
116 private final AAIRestInterface restController;
118 private final CacheProvider cacheProvider;
120 ObjectMapper objectMapper = jacksonObjectMapper();
125 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
127 private static final String GET_SERVICE_MODELS_REQUEST_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
130 public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) {
131 this.restController = restController;
132 this.portDetailsTranslator = portDetailsTranslator;
133 this.cacheProvider = cacheProvider;
137 private static String checkForNull(String local) {
146 public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){
147 Response resp = doAaiGet(getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false);
148 return processAaiResponse(resp, OwningEntityResponse.class, null);
152 public AaiResponse getServicesByProjectNames(List<String> projectNames){
153 Response resp = doAaiGet(getUrlFromLIst("business/projects?", "project-name=", projectNames), false);
154 return processAaiResponse(resp, ProjectResponse.class, null);
158 public AaiResponse getServiceModelsByDistributionStatus() {
159 return getFromCache("getServiceModelsByDistributionStatus", this::getServiceModelsByDistributionStatusNonCached,
160 true, "Failed to get service models by distribution status");
163 private AaiResponse getServiceModelsByDistributionStatusNonCached(boolean propagateExceptions) {
164 GetServiceModelsByDistributionStatusResponse response = typedAaiRest(QUERY_FORMAT_RESOURCE, GetServiceModelsByDistributionStatusResponse.class,
165 GET_SERVICE_MODELS_REQUEST_BODY, HttpMethod.PUT, propagateExceptions);
166 return new AaiResponse(response, "", HttpStatus.SC_OK);
170 public AaiResponse getNetworkCollectionDetails(String serviceInstanceId) {
171 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, "{\"start\": [\"nodes/service-instances/service-instance/" + serviceInstanceId + "\"],\"query\": \"query/network-collection-ByServiceInstance\"}\n", false);
172 AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse = processAaiResponse(resp, AaiGetNetworkCollectionDetailsHelper.class, null, VidObjectMapperType.FASTERXML);
173 return getNetworkCollectionDetailsResponse(aaiResponse);
177 public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) {
178 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE,
179 "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + encodePathSegment(cloudOwner) + "/" + encodePathSegment(cloudRegionId) + "\"]," +
180 "\"query\": \"query/instance-groups-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + encodePathSegment(networkFunction) + "\"}\n", false);
181 return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML);
184 private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){
185 if(aaiResponse.getHttpCode() == 200) {
186 ObjectMapper om = objectMapper;
187 AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails();
189 for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) {
190 LinkedHashMap<String, Object> temp = ((LinkedHashMap) aaiResponse.getT().getResults().get(i));
191 if (temp.get("service-instance") != null)
192 aaiGetNetworkCollectionDetails.getResults().setServiceInstance(om.readValue(om.writeValueAsString(temp.get("service-instance")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance.class));
193 else if (temp.get("collection") != null)
194 aaiGetNetworkCollectionDetails.getResults().setCollection(om.readValue(om.writeValueAsString(temp.get("collection")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Collection.class));
195 else if (temp.get("instance-group") != null)
196 aaiGetNetworkCollectionDetails.getResults().setInstanceGroup(om.readValue(om.writeValueAsString(temp.get("instance-group")), InstanceGroup.class));
197 else if (temp.get("l3-network") != null)
198 aaiGetNetworkCollectionDetails.getResults().getNetworks().add(om.readValue(om.writeValueAsString(temp.get("l3-network")), Network.class));
200 return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK);
202 catch (com.fasterxml.jackson.databind.JsonMappingException e) {
203 logger.error(EELFLoggerDelegate.errorLogger, "AAI response parsing Error", e);
204 return new AaiResponse(e.getCause(), "AAI response parsing Error" , HttpStatus.SC_INTERNAL_SERVER_ERROR);
206 catch (Exception e) {
207 logger.error(EELFLoggerDelegate.errorLogger,"Exception in aai response parsing", e);
208 return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode());
215 public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) {
216 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
217 String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel);
218 String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}";
219 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
220 return processAaiResponse(resp, AaiGetPnfResponse.class, null);
225 public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
226 Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false);
227 return processAaiResponse(resp, Pnf.class, null);
231 public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){
232 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId + "?depth=0", false);
233 return processAaiResponse(resp, AaiGetRelatedInstanceGroupsByVnfId.class , null, null);
238 public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID) {
239 String payload = "{\"start\":\"/network/configurations/configuration/" + configurationID + "\",\"query\":\"query/pserver-fromConfiguration\"}";
240 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
241 resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems
242 String rawPayload = resp.readEntity(String.class);
243 AaiResponse<CustomQuerySimpleResult> aaiResponse = processAaiResponse(resp, CustomQuerySimpleResult.class, rawPayload);
244 return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload);
249 public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
250 String getServiceInstancePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId+ SERVICE_SUBSCRIPTIONS_PATH +serviceType+ SERVICE_INSTANCE +serviceInstanceId;
251 Response resp = doAaiGet(getServiceInstancePath , false);
252 return processAaiResponse(resp, ServiceRelationships.class, null);
256 public AaiResponse getLogicalLink(String link) {
257 Response resp = doAaiGet("network/logical-links/logical-link/" + link , false);
258 return processAaiResponse(resp, LogicalLinkResponse.class, null);
262 public boolean isNodeTypeExistsByName(String name, ResourceType type) {
264 throw new GenericUncheckedException("Empty resource-name provided to searchNodeTypeByName; request is rejected as this will cause full resources listing");
267 URI path = Unchecked.toURI(String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name}
270 type.getNameFilter(),
271 encodePathSegment(name)
273 final ResponseWithRequestInfo responseWithRequestInfo = restController.RestGet(fromAppId, UUID.randomUUID().toString(), path, false, true);
275 return isResourceExistByStatusCode(responseWithRequestInfo);
278 public Map<String, Properties> getCloudRegionAndTenantByVnfId(String vnfId) {
279 String start = "/network/generic-vnfs/generic-vnf/" + vnfId;
280 String query = "/query/cloud-region-fromVnf";
282 String payload = "{\"start\":[\"" + start + "\"],\"query\":\"" + query + "\"}";
283 CustomQuerySimpleResult result = typedAaiRest(QUERY_FORMAT_SIMPLE, CustomQuerySimpleResult.class, payload, HttpMethod.PUT, false);
285 return result.getResults().stream()
286 .filter(res -> StringUtils.equals(res.getNodeType(), "tenant") ||
287 StringUtils.equals(res.getNodeType(), "cloud-region"))
288 .collect(toMap(SimpleResult::getNodeType, SimpleResult::getProperties));
292 public AaiResponse getVnfsByParamsForChangeManagement(String subscriberId, String serviceType, @Nullable String nfRole,
293 @Nullable String cloudRegion) {
294 String payloadAsString = "";
295 ResponseWithRequestInfo response;
296 ImmutableMap<String, Serializable> payload = getMapForAAIQueryByParams(subscriberId, serviceType,
297 nfRole, cloudRegion);
299 payloadAsString = JACKSON_OBJECT_MAPPER.writeValueAsString(payload);
300 } catch (JsonProcessingException e) {
301 logger.error(e.getMessage());
302 ExceptionUtils.rethrow(e);
304 response = doAaiPut(QUERY_FORMAT_SIMPLE, payloadAsString, false, false);
305 AaiResponseWithRequestInfo aaiResponse = processAaiResponse(response, JsonNode.class, false);
306 verifyAaiResponseValidityOrThrowExc(aaiResponse, aaiResponse.getAaiResponse().getHttpCode());
307 return aaiResponse.getAaiResponse();
310 private ImmutableMap<String, Serializable> getMapForAAIQueryByParams(String subscriberId,
311 String serviceType, @Nullable String nfRole, @Nullable String cloudRegion) {
312 String nfRoleParam = nfRole != null ? "?nfRole=" + nfRole : "";
313 String query = "query/vnfs-fromServiceInstance-filter" + nfRoleParam;
314 return ImmutableMap.of(
315 "start", ImmutableList
316 .of("/business/customers/customer/" + subscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances"),
321 private boolean isResourceExistByStatusCode(ResponseWithRequestInfo responseWithRequestInfo) {
323 // 404 - resource not found
324 Response.Status statusInfo = responseWithRequestInfo.getResponse().getStatusInfo().toEnum();
325 switch (statusInfo) {
331 throw new GenericUncheckedException("Unexpected response-code (only OK and NOT_FOUND are expected): " +
332 responseWithRequestInfo.getResponse().getStatusInfo());
337 public <T> T typedAaiGet(URI uri, Class<T> clz) {
338 return typedAaiRest(uri, clz, null, HttpMethod.GET, false);
341 public <T> T typedAaiRest(String path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
342 return typedAaiRest(Unchecked.toURI(path), clz, payload, method, propagateExceptions);
346 public <T> T typedAaiRest(URI path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
347 ResponseWithRequestInfo responseWithRequestInfo;
349 responseWithRequestInfo = restController.doRest(fromAppId, UUID.randomUUID().toString(), path, payload, method, false, propagateExceptions);
350 } catch (Exception e) {
351 responseWithRequestInfo = handleExceptionFromRestCall(propagateExceptions, "doAai"+method.name(), e);
354 final AaiResponseWithRequestInfo<T> aaiResponse = processAaiResponse(responseWithRequestInfo, clz, VidObjectMapperType.FASTERXML, true);
355 verifyAaiResponseValidityOrThrowExc(aaiResponse, responseWithRequestInfo.getResponse().getStatus());
356 return aaiResponse.getAaiResponse().getT();
359 private void verifyAaiResponseValidityOrThrowExc(AaiResponseWithRequestInfo aaiResponse, int httpCode) {
360 if (aaiResponse.getAaiResponse().getHttpCode() > 399 || aaiResponse.getAaiResponse().getT() == null) {
361 throw new ExceptionWithRequestInfo(aaiResponse.getHttpMethod(),
362 aaiResponse.getRequestedUrl(),
363 aaiResponse.getRawData(),
365 new InvalidAAIResponseException(aaiResponse.getAaiResponse()));
369 private String getUrlFromLIst(String url, String paramKey, List<String> params){
371 for(String param: params){
373 url = url.concat(paramKey);
374 String encodedParam= param;
376 encodedParam= URLEncoder.encode(param, "UTF-8");
377 } catch (UnsupportedEncodingException e) {
378 String methodName = "getUrlFromList";
379 logger.error(EELFLoggerDelegate.errorLogger, methodName, e);
380 logger.debug(EELFLoggerDelegate.debugLogger, methodName, e);
382 url = url.concat(encodedParam);
383 if(i != params.size()){
384 url = url.concat("&");
393 public AaiResponse<SubscriberList> getAllSubscribers() {
394 return getFromCache("getAllSubscribers", this::getAllSubscribersNonCached, true, "Failed to get all subscribers");
397 private <K> AaiResponse getFromCache(String cacheName, Function<K, AaiResponse> function, K argument, String errorMessage) {
400 .aaiClientCacheFor(cacheName, function)
402 } catch (ExceptionWithRequestInfo exception) {
403 logger.error(errorMessage, exception);
404 return new AaiResponse(null, exception.getRawData(), exception.getHttpCode());
406 catch (Exception exception) {
407 logger.error(errorMessage, exception);
408 return new AaiResponse(null, exception.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
412 private AaiResponse<SubscriberList> getAllSubscribersNonCached(boolean propagateExceptions) {
413 AaiResponse<SubscriberList> aaiResponse = getAllSubscribers(propagateExceptions).getAaiResponse();
414 if (propagateExceptions && (aaiResponse.getT() == null || aaiResponse.getT().customer == null || aaiResponse.getT().customer.isEmpty())) {
415 throw new GenericUncheckedException("Failed to get Subscribers data. The data is null or empty.");
421 AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){
423 ResponseWithRequestInfo aaiGetResult = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false, propagateExceptions);
424 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = processAaiResponse(aaiGetResult, SubscriberList.class, propagateExceptions);
425 responseWithRequestInfo.setRequestedUrl(aaiGetResult.getRequestUrl());
426 responseWithRequestInfo.setHttpMethod(aaiGetResult.getRequestHttpMethod());
427 return responseWithRequestInfo;
432 public AaiResponse getAllAicZones() {
433 Response resp = doAaiGet("network/zones", false);
434 return processAaiResponse(resp, AicZones.class, null);
438 public AaiResponse getVNFData(String globalSubscriberId, String serviceType) {
439 String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," +
440 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
441 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
442 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
446 public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
447 String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + SERVICE_INSTANCE + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
448 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
449 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
453 public Response getVersionByInvariantId(List<String> modelInvariantId) {
454 if (modelInvariantId.isEmpty()) {
455 throw new GenericUncheckedException("Zero invariant-ids provided to getVersionByInvariantId; request is rejected as this will cause full models listing");
458 StringBuilder sb = new StringBuilder();
459 for (String id : modelInvariantId){
460 sb.append(MODEL_INVARIANT_ID);
464 return doAaiGet("service-design-and-creation/models?depth=2" + sb.toString(), false);
468 public ModelVer getLatestVersionByInvariantId(String modelInvariantId) {
469 if (modelInvariantId.isEmpty()) {
470 throw new GenericUncheckedException("no invariant-id provided to getLatestVersionByInvariantId; request is rejected");
473 Response response = doAaiPut("query?format=resource&depth=0", "{\"start\": [\"service-design-and-creation/models/model/" + modelInvariantId + "\"],\"query\": \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}",false);
474 AaiResponse<ModelVersions> aaiResponse = processAaiResponse(response, ModelVersions.class, null, VidObjectMapperType.FASTERXML);
476 Stream<ModelVer> modelVerStream = toModelVerStream(aaiResponse.getT());
477 return maxModelVer(modelVerStream);
480 protected Stream<ModelVer> toModelVerStream(ModelVersions modelVersions) {
481 if (modelVersions == null)
484 if (modelVersions == null)
487 return Stream.of(modelVersions)
488 .map(ModelVersions::getResults)
489 .flatMap(java.util.Collection::stream)
490 .flatMap(map -> map.entrySet().stream())
491 .filter(kv -> StringUtils.equals(kv.getKey(), "model-ver"))
492 .map(Map.Entry::getValue);
496 protected ModelVer maxModelVer(Stream<ModelVer> modelVerStream) {
497 if (modelVerStream == null)
500 return modelVerStream
501 .filter(modelVer -> StringUtils.isNotEmpty(modelVer.getModelVersion()))
502 .max(comparing(ModelVer::getModelVersion, comparing(DefaultArtifactVersion::new)))
503 .orElseThrow(() -> new GenericUncheckedException("Could not find any version"));
507 public AaiResponse getSubscriberData(String subscriberId, boolean omitServiceInstances) {
508 String depth = omitServiceInstances ? "1" : "2";
509 AaiResponse subscriberDataResponse;
510 Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false);
511 subscriberDataResponse = processAaiResponse(resp, Services.class, null);
512 return subscriberDataResponse;
516 public AaiResponse getServices() {
517 Response resp = doAaiGet("service-design-and-creation/services", false);
518 return processAaiResponse(resp, GetServicesAAIRespone.class, null);
522 public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) {
523 String url = "cloud-infrastructure/operational-environments";
524 URIBuilder urlBuilder = new URIBuilder();
525 if (operationalEnvironmentType != null)
526 urlBuilder.addParameter("operational-environment-type", operationalEnvironmentType);
527 if (operationalEnvironmentStatus != null)
528 urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus);
529 url += urlBuilder.toString();
530 Response resp = doAaiGet(url, false);
531 return processAaiResponse(resp, OperationalEnvironmentList.class, null);
535 public AaiResponse getTenants(String globalCustomerId, String serviceType) {
536 if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty()))){
537 return buildAaiResponseForGetTenantsFailure(" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.");
541 .aaiClientCacheFor("getTenants", this::getTenantsByKey)
542 .get(CacheProvider.compileKey(globalCustomerId, serviceType));
544 catch (ParsingGetTenantsResponseFailure exception) {
545 logger.error("Failed to get tenants ", exception);
546 return buildAaiResponseForGetTenantsFailure(exception.getMessage());
551 public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
553 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
554 String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion);
555 String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}";
557 Response resp1 = doAaiPut(QUERY_FORMAT_SIMPLE, payload1, false);
558 AaiResponse aaiResponse1 = processAaiResponse(resp1, AaiGetVnfResponse.class, null);
559 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1);
564 public AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId) {
565 final String start = "[\"network/configurations/configuration/" + configurationId + "\"]";
566 final String query = "\"query/cloud-region-and-source-FromConfiguration\"";
567 String payload = "{\"start\":" + start + ",\"query\":" + query + "}";
569 Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false);
570 AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null);
572 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse);
576 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) {
577 return processAaiResponse(responseWithRequestInfo, classType, VidObjectMapperType.CODEHAUS, propagateExceptions);
580 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, VidObjectMapperType omType, boolean propagateExceptions) {
581 String responseBody = null;
582 Integer responseHttpCode = null;
584 Response response = responseWithRequestInfo.getResponse();
585 responseHttpCode = (response != null) ? response.getStatus() : null;
586 responseBody = (response != null) ? response.readEntity(String.class) : null;
587 AaiResponse<T> processedAaiResponse = processAaiResponse(response, classType, responseBody, omType, propagateExceptions);
588 return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse,
590 } catch (Exception e) {
591 throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(),
592 responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e);
596 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) {
597 return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS);
600 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType) {
601 return processAaiResponse(resp, classType, responseBody, omType, false);
604 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
605 AaiResponse<T> subscriberDataResponse;
607 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
608 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
610 logger.debug(EELFLoggerDelegate.debugLogger, "getSubscribers() resp=" + resp.getStatusInfo().toString());
611 if (resp.getStatus() != HttpStatus.SC_OK) {
612 subscriberDataResponse = processFailureResponse(resp,responseBody);
614 subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
617 return subscriberDataResponse;
620 private AaiResponse processFailureResponse(Response resp, String responseBody) {
621 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
623 if (responseBody != null) {
624 rawData = responseBody;
626 rawData = resp.readEntity(String.class);
628 return new AaiResponse<>(null, rawData, resp.getStatus());
631 private <T> AaiResponse<T> processOkResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
632 AaiResponse<T> subscriberDataResponse;
633 String finalResponse = null;
635 if (responseBody != null) {
636 finalResponse = responseBody;
638 finalResponse = resp.readEntity(String.class);
641 if(omType == VidObjectMapperType.CODEHAUS)
642 subscriberDataResponse = parseCodeHausObject(classType, finalResponse);
644 subscriberDataResponse = parseFasterXmlObject(classType, finalResponse);
646 } catch(Exception e){
647 if (propagateExceptions) {
648 throw new GenericUncheckedException(e);
650 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
651 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
654 return subscriberDataResponse;
657 private <T> AaiResponse<T> parseFasterXmlObject(Class<? extends T> classType, String finalResponse) throws IOException {
658 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
661 private <T> AaiResponse<T> parseCodeHausObject(Class<? extends T> classType, String finalResponse) throws IOException {
662 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
666 public Response doAaiGet(String uri, boolean xml) {
667 return doAaiGet(uri, xml, false).getResponse();
671 public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) {
672 return doAaiGet(Unchecked.toURI(uri), xml, propagateExceptions);
675 public ResponseWithRequestInfo doAaiGet(URI uri, boolean xml, boolean propagateExceptions) {
676 String methodName = "doAaiGet";
677 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
679 ResponseWithRequestInfo resp;
681 resp = restController.RestGet(fromAppId, UUID.randomUUID().toString(), uri, xml, propagateExceptions);
683 } catch (Exception e) {
684 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
690 protected ResponseWithRequestInfo handleExceptionFromRestCall(boolean propagateExceptions, String methodName, Exception e) {
691 ResponseWithRequestInfo resp;
692 if (propagateExceptions) {
693 throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e);
695 final Exception actual =
696 e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e;
698 final String message =
699 actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString();
701 //ToDo: change parameter of requestUrl to real url from doRest function
702 resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET);
703 logger.info(EELFLoggerDelegate.errorLogger, methodName + message);
704 logger.debug(EELFLoggerDelegate.debugLogger, methodName + message);
709 private String parseForTenantsByServiceSubscription(String relatedToKey, String resp) {
710 String tenantList = "";
713 JSONParser jsonParser = new JSONParser();
715 JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
717 return parseServiceSubscriptionObjectForTenants(relatedToKey, jsonObject);
718 } catch (Exception ex) {
719 logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex);
724 protected Response doAaiPut(String uri, String payload, boolean xml) {
725 return doAaiPut(uri, payload, xml, false).getResponse();
728 protected ResponseWithRequestInfo doAaiPut(String uri, String payload, boolean xml, boolean propagateExceptions) {
729 String methodName = "doAaiPut";
730 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
732 ResponseWithRequestInfo resp;
735 resp = restController.RestPut(fromAppId, uri, payload, xml, propagateExceptions);
737 } catch (Exception e) {
738 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
744 private String parseServiceSubscriptionObjectForTenants(String relatedToKey, JSONObject jsonObject) {
745 JSONArray tenantArray = new JSONArray();
746 boolean bconvert = false;
748 JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
749 if (relationShipListsObj != null) {
750 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
751 for (Object innerObj : defaultIfNull(rShipArray, emptyList())) {
752 if (innerObj != null) {
753 bconvert = parseTenant(relatedToKey, tenantArray, bconvert, (JSONObject) innerObj);
757 } catch (NullPointerException ex) {
758 logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex);
762 return tenantArray.toJSONString();
768 private static boolean parseTenant(String relatedToKey, JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) {
769 String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
770 if (relatedTo.equalsIgnoreCase(relatedToKey)) {
771 JSONObject tenantNewObj = new JSONObject();
773 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
774 tenantNewObj.put("link", relatedLink);
776 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
777 for (Object innerObj : defaultIfNull(rDataArray, emptyList())) {
778 parseRelationShip(tenantNewObj, (JSONObject) innerObj);
781 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
782 for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) {
783 parseRelatedTProp(tenantNewObj, (JSONObject) innerObj);
786 tenantArray.add(tenantNewObj);
791 private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) {
792 if (innerObj == null)
795 String propKey = checkForNull((String) innerObj.get("property-key"));
796 String propVal = checkForNull((String) innerObj.get("property-value"));
797 if (equalsIgnoreCase(propKey, "tenant.tenant-name")) {
798 tenantNewObj.put("tenantName", propVal);
802 private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) {
803 if (inner2Obj == null)
806 String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
807 String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
808 if (equalsIgnoreCase(rShipKey, "cloud-region.cloud-owner")) {
809 tenantNewObj.put("cloudOwner", rShipVal);
810 } else if (equalsIgnoreCase(rShipKey, "cloud-region.cloud-region-id")) {
811 tenantNewObj.put("cloudRegionID", rShipVal);
812 } else if (equalsIgnoreCase(rShipKey, "tenant.tenant-id")) {
813 tenantNewObj.put("tenantID", rShipVal);
817 private static String encodePathSegment(String segmentToEncode) {
818 return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
822 public ExternalComponentStatus probeComponent(){
823 long startTime = System.currentTimeMillis();
825 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true);
826 AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse();
827 long duration = System.currentTimeMillis() - startTime;
829 SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null;
830 boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty();
832 HttpRequestMetadata metadata = new HttpRequestMetadata(
833 responseWithRequestInfo.getHttpMethod(),
834 (aaiResponse != null) ? aaiResponse.getHttpCode() : 0,
835 responseWithRequestInfo.getRequestedUrl(),
836 responseWithRequestInfo.getRawData(),
837 isAvailable ? "OK" : "No subscriber received",
840 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata);
842 } catch (ExceptionWithRequestInfo e) {
843 long duration = System.currentTimeMillis() - startTime;
844 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
845 new HttpRequestMetadata(e, duration));
846 } catch (Exception e) {
847 long duration = System.currentTimeMillis() - startTime;
848 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
849 new ErrorMetadata(Logging.exceptionToDescription(e), duration));
854 public String getCloudOwnerByCloudRegionId(String cloudRegionId) {
856 .aaiClientCacheFor("getCloudOwnerByCloudRegionId", this::getCloudOwnerByCloudRegionIdNonCached)
862 public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) {
864 if (isEmpty(vnfInstanceId)|| isEmpty(vfModuleId)){
865 throw new GenericUncheckedException("Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.");
867 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId +"/vf-modules/vf-module/"+ vfModuleId, false);
868 String responseAsString = parseForTenantsByServiceSubscription("vserver",resp.readEntity(String.class));
869 if (isEmpty(responseAsString)){
870 throw new GenericUncheckedException( String.format("A&AI has no homing data associated to vfModule '%s' of vnf '%s'", vfModuleId, vnfInstanceId));
873 AaiResponse aaiResponse = processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
874 return ((GetTenantsResponse[])aaiResponse.getT())[0];
879 public void resetCache(String cacheName) {
880 cacheProvider.resetCache(cacheName);
883 String getCloudOwnerByCloudRegionIdNonCached(String cloudRegionId) {
884 String uri = "cloud-infrastructure/cloud-regions?cloud-region-id=" + encodePathSegment(cloudRegionId);
886 final CloudRegion.Collection cloudRegionCollection =
887 typedAaiGet(Unchecked.toURI(uri), CloudRegion.Collection.class);
889 return cloudRegionCollection
890 .getCloudRegions().stream()
891 .map(CloudRegion::getCloudOwner)
892 // from here we assure that the cloud owner is given, and not null
893 // and non-empty, and that if more than one cloud-owner is given -
894 // it is only a single value.
895 // exception is thrown if none or more than a single values are
897 .filter(StringUtils::isNotEmpty)
900 // will be invoked only if distinct() leaves more than a single element
901 throw new GenericUncheckedException("Conflicting cloud-owner found for " + cloudRegionId + ": '" + a + "' / '" + b + "'");
903 .orElseThrow(() -> new GenericUncheckedException("No cloud-owner found for " + cloudRegionId));
906 private AaiResponse getTenantsByKey(String key) {
907 String[] args = CacheProvider.decompileKey(key);
908 String globalCustomerId = safeGetFromArray(args, 0);
909 String serviceType = safeGetFromArray(args, 1);
910 return getTenantsNonCached(globalCustomerId, serviceType);
913 AaiResponse getTenantsNonCached(String globalCustomerId, String serviceType) {
914 String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType;
916 Response resp = doAaiGet(url, false);
917 String responseAsString = parseForTenantsByServiceSubscription("tenant",resp.readEntity(String.class));
918 if (isEmpty(responseAsString)){
919 throw new ParsingGetTenantsResponseFailure(String.format("A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'", globalCustomerId, serviceType));
922 return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
926 public static class ParsingGetTenantsResponseFailure extends GenericUncheckedException {
928 public ParsingGetTenantsResponseFailure(String message) {
934 private AaiResponse<String> buildAaiResponseForGetTenantsFailure(String errorText) {
935 return new AaiResponse<>(null, String.format("{\"statusText\":\"%s\"}", errorText), HttpStatus.SC_INTERNAL_SERVER_ERROR);
938 private static String safeGetFromArray(String[] array, int i) {
939 if (i < 0 || i >= array.length) {