diff options
Diffstat (limited to 'so-cnf-adapter-application/src')
21 files changed, 606 insertions, 181 deletions
diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java index 0ba40e2..a437b9d 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java @@ -34,7 +34,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @SpringBootApplication -@ComponentScan(basePackages = {"org.onap.so.adapters.cnf"}) +@ComponentScan(basePackages = {"org.onap.so.adapters.cnf", "org.onap.so.spring"}) @EnableAutoConfiguration(exclude = {LiquibaseAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, SecurityAutoConfiguration.class}) diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java index c950cf6..926bfec 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java @@ -20,10 +20,12 @@ package org.onap.so.adapters.cnf.exceptions; -import static org.onap.so.adapters.cnf.util.CNfAdapterUtil.marshal; +import static org.onap.so.adapters.cnf.util.CnfAdapterUtil.marshal; import org.onap.so.adapters.cnf.model.ErrorResponse; import org.springframework.http.ResponseEntity; +import static org.onap.so.adapters.cnf.util.CnfAdapterUtil.marshal; + public class ApplicationException extends Exception { private static final long serialVersionUID = 1L; diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/model/instantiation/AaiRequest.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/model/instantiation/AaiRequest.java index 0665d9a..80a2cf7 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/model/instantiation/AaiRequest.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/model/instantiation/AaiRequest.java @@ -1,3 +1,22 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.adapters.cnf.model.instantiation; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -18,6 +37,10 @@ public class AaiRequest { private String tenantId; @JsonProperty("callbackUrl") private String callbackUrl; + @JsonProperty("genericVnfId") + private String genericVnfId; + @JsonProperty("vfModuleId") + private String vfModuleId; public String getInstanceId() { return instanceId; @@ -59,6 +82,22 @@ public class AaiRequest { this.callbackUrl = callbackUrl; } + public String getVfModuleId() { + return vfModuleId; + } + + public void setVfModuleId(String vfModuleId) { + this.vfModuleId = vfModuleId; + } + + public String getGenericVnfId() { + return genericVnfId; + } + + public void setGenericVnfId(String genericVnfId) { + this.genericVnfId = genericVnfId; + } + @Override public String toString() { return "AaiRequest{" + @@ -67,6 +106,8 @@ public class AaiRequest { ", cloudOwner='" + cloudOwner + '\'' + ", tenantId='" + tenantId + '\'' + ", callbackUrl='" + callbackUrl + '\'' + + ", genericVnfId='" + genericVnfId + '\'' + + ", vfModuleId='" + vfModuleId + '\'' + '}'; } } diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java index 63d9880..647d144 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.onap.so.adapters.cnf.rest; import com.fasterxml.jackson.core.JsonParseException; @@ -134,7 +133,11 @@ public class CnfAdapterRest { new Thread(() -> { logger.info("Processing aai update"); -// aaiService.aaiUpdate(aaiRequest); + try { + aaiService.aaiUpdate(aaiRequest); + } catch (BadResponseException e) { + throw new RuntimeException("Failed to insert resource into AAI", e); + } AaiCallbackResponse mockCallbackResponse = new AaiCallbackResponse(); mockCallbackResponse.setCompletionStatus(AaiCallbackResponse.CompletionStatus.COMPLETED); try { @@ -156,18 +159,23 @@ public class CnfAdapterRest { logger.info("aai-delete called."); DeferredResult<ResponseEntity> response = new DeferredResult<>(); - new Thread(() -> { + ForkJoinPool.commonPool().execute(() -> { logger.info("Processing aai delete"); -// aaiService.aaiDelete(aaiRequest); AaiCallbackResponse mockCallbackResponse = new AaiCallbackResponse(); - mockCallbackResponse.setCompletionStatus(AaiCallbackResponse.CompletionStatus.COMPLETED); + try { + aaiService.aaiDelete(aaiRequest); + mockCallbackResponse.setCompletionStatus(AaiCallbackResponse.CompletionStatus.COMPLETED); + } catch (BadResponseException e) { + logger.warn("Failed to delete resource from AAI", e); + mockCallbackResponse.setCompletionStatus(AaiCallbackResponse.CompletionStatus.FAILED); + } try { Thread.sleep(10_000L); } catch (InterruptedException e) { logger.error("InterruptedException occurred when aai-delete"); } callbackClient.sendPostCallback(aaiRequest.getCallbackUrl(), mockCallbackResponse); - }).start(); + }); response.setResult(ResponseEntity.accepted().build()); return response; diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiRequestSender.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiRequestSender.java deleted file mode 100644 index 8dd7647..0000000 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiRequestSender.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.onap.so.adapters.cnf.service.aai; - -import com.google.gson.Gson; -import org.onap.aaiclient.client.aai.AAIResourcesClient; -import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; -import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; -import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; -import org.onap.so.adapters.cnf.model.instantiation.AaiRequest; -import org.springframework.stereotype.Component; - -@Component -class AaiRequestSender { - - private final static Gson gson = new Gson(); - private AAIResourcesClient aaiClient; - - void sendUpdateRequestToAai(ParseResult parseResult, AaiRequest aaiRequest) { - AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() - .cloudRegion(aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion()) - .tenant(aaiRequest.getTenantId()) - .build()); - String payload = gson.toJson(parseResult); - getAaiClient().create(aaiUri, payload); - } - - void sendDeleteRequestToAai(AaiRequest aaiRequest) { - AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() - .cloudRegion(aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion()) - .tenant(aaiRequest.getTenantId()) - .build()); - getAaiClient().delete(aaiUri); - } - - private AAIResourcesClient getAaiClient() { - if (aaiClient == null) { - aaiClient = new AAIResourcesClient(); - } - return aaiClient; - } -} diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParser.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParser.java index 304c023..d83b8e0 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParser.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParser.java @@ -1,5 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2021 Samsung Electronics Co. Ltd. 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.adapters.cnf.service.aai; +import org.apache.http.client.utils.URIBuilder; import org.onap.so.adapters.cnf.model.instantiation.AaiRequest; import org.onap.so.adapters.cnf.model.statuscheck.K8sRbInstanceGvk; import org.onap.so.adapters.cnf.model.statuscheck.K8sRbInstanceResourceStatus; @@ -7,20 +28,24 @@ import org.onap.so.adapters.cnf.model.statuscheck.K8sStatus; import org.onap.so.adapters.cnf.model.statuscheck.K8sStatusMetadata; import org.springframework.stereotype.Component; +import java.net.URISyntaxException; import java.util.ArrayList; -import java.util.Collection; +import java.util.List; +import java.util.Map; @Component public class AaiResponseParser { + private final static String INSTANCE_ID = "k8splugin.io/rb-instance-id"; + private final AaiIdGeneratorService aaiIdGeneratorService; public AaiResponseParser(AaiIdGeneratorService aaiIdGeneratorService) { this.aaiIdGeneratorService = aaiIdGeneratorService; } - ParseResult parse(K8sRbInstanceResourceStatus status, AaiRequest aaiRequest) { - ParseResult result = new ParseResult(); + KubernetesResource parse(K8sRbInstanceResourceStatus status, AaiRequest aaiRequest) { + KubernetesResource result = new KubernetesResource(); K8sRbInstanceGvk gvk = status.getGvk(); K8sStatus k8sStatus = status.getStatus(); K8sStatusMetadata metadata = k8sStatus.getK8sStatusMetadata(); @@ -31,14 +56,46 @@ public class AaiResponseParser { result.setVersion(gvk.getVersion()); result.setKind(gvk.getKind()); result.setNamespace(metadata.getNamespace()); - Collection<String> labels = new ArrayList<>(); - metadata.getLabels().forEach((key, value) -> { - labels.add(key); - labels.add(value); - }); + List<String> labels = parseLabels(metadata.getLabels()); result.setLabels(labels); - result.setK8sResourceSelfLink(String.format("http://so-cnf-adapter:8090/api/cnf-adapter/v1/instance/%s/query", aaiRequest.getInstanceId())); + URIBuilder uriBuilder = new URIBuilder(); + String selfLink; + try { + selfLink = uriBuilder + .setScheme("http") + .setHost("so-cnf-adapter") + .setPort(8090) + .setPath("/api/cnf-adapter/v1/instance/" + aaiRequest.getInstanceId() + "/query") + .setParameter("ApiVersion", gvk.getVersion()) + .setParameter("Kind", gvk.getKind()) + .setParameter("Name", status.getName()) + .setParameter("Namespace", metadata.getNamespace()) + .build() + .toString(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + result.setK8sResourceSelfLink(selfLink); + return result; + } + + private List<String> parseLabels(Map<String, String> labels) { + List<String> result = new ArrayList<>(); + labels.entrySet().stream() + .filter(i -> i.getKey().equals(INSTANCE_ID)) + .findFirst() + .ifPresent(i -> addInstanceIdFist(i, result)); + labels.entrySet().stream() + .filter(i -> !i.getKey().equals(INSTANCE_ID)) + .forEach(i -> { + result.add(i.getKey()); + result.add(i.getValue()); + }); return result; } + private void addInstanceIdFist(Map.Entry<String, String> instanceId, List<String> result) { + result.add(instanceId.getKey()); + result.add(instanceId.getValue()); + } } diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiService.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiService.java index 71d34a3..68d2f8a 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiService.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/AaiService.java @@ -5,6 +5,7 @@ import org.onap.so.adapters.cnf.client.MulticloudClient; import org.onap.so.adapters.cnf.model.instantiation.AaiRequest; import org.onap.so.adapters.cnf.model.statuscheck.K8sRbInstanceResourceStatus; import org.onap.so.adapters.cnf.model.statuscheck.K8sRbInstanceStatus; +import org.onap.so.adapters.cnf.util.IAaiRepository; import org.onap.so.client.exception.BadResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,39 +20,31 @@ public class AaiService { private final static Logger log = LoggerFactory.getLogger(AaiService.class); private final MulticloudClient multicloudClient; - private final AaiRequestSender aaiRequestSender; private final AaiResponseParser responseParser; - private final AaiConfiguration aaiConfiguration; + private final AaiConfiguration configuration; - public AaiService(MulticloudClient multicloudClient, - AaiRequestSender aaiRequestSender, - AaiResponseParser responseParser, - AaiConfiguration aaiConfiguration) { + public AaiService(MulticloudClient multicloudClient, AaiResponseParser responseParser, AaiConfiguration configuration) { this.multicloudClient = multicloudClient; - this.aaiRequestSender = aaiRequestSender; this.responseParser = responseParser; - this.aaiConfiguration = aaiConfiguration; + this.configuration = configuration; } public void aaiUpdate(AaiRequest aaiRequest) throws BadResponseException { - if (aaiConfiguration.isEnabled()) { - List<ParseResult> parseStatus = parseStatus(aaiRequest); - parseStatus.forEach(status -> aaiRequestSender.sendUpdateRequestToAai(status, aaiRequest)); - } else { - log.info("aai.enabled=false, do not execute aaiUpdate flow"); - } + List<KubernetesResource> parseStatus = parseStatus(aaiRequest); + IAaiRepository aaiRepository = IAaiRepository.instance(configuration.isEnabled()); + parseStatus.forEach(status -> aaiRepository.update(status, aaiRequest)); + aaiRepository.commit(true); } public void aaiDelete(AaiRequest aaiRequest) throws BadResponseException { - if (aaiConfiguration.isEnabled()) { - List<ParseResult> parseStatus = parseStatus(aaiRequest); - parseStatus.forEach(status -> aaiRequestSender.sendDeleteRequestToAai(aaiRequest)); - } else { - log.info("aai.enabled=false, do not execute aaiDelete flow"); - } + List<KubernetesResource> parseStatus = parseStatus(aaiRequest); + + IAaiRepository aaiRepository = IAaiRepository.instance(configuration.isEnabled()); + parseStatus.forEach(status -> aaiRepository.delete(status, aaiRequest)); + aaiRepository.commit(true); } - private List<ParseResult> parseStatus(AaiRequest aaiRequest) throws BadResponseException { + private List<KubernetesResource> parseStatus(AaiRequest aaiRequest) throws BadResponseException { String instanceId = aaiRequest.getInstanceId(); K8sRbInstanceStatus instanceStatus = multicloudClient.getInstanceStatus(instanceId); diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/ParseResult.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/KubernetesResource.java index e44a885..457d01b 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/ParseResult.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/service/aai/KubernetesResource.java @@ -1,15 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2021 Samsung Electronics Co. Ltd. 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.adapters.cnf.service.aai; -import java.util.Collection; +import java.util.List; -class ParseResult { +public class KubernetesResource { private String id; private String name; private String group; private String version; private String kind; private String namespace; - private Collection<String> labels; + private List<String> labels; private String k8sResourceSelfLink; public String getId() { @@ -60,11 +80,11 @@ class ParseResult { this.namespace = namespace; } - public Collection<String> getLabels() { + public List<String> getLabels() { return labels; } - public void setLabels(Collection<String> labels) { + public void setLabels(List<String> labels) { this.labels = labels; } diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiClientPropertiesImpl.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiClientPropertiesImpl.java new file mode 100644 index 0000000..466eefa --- /dev/null +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiClientPropertiesImpl.java @@ -0,0 +1,103 @@ +/*- + * ============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.adapters.cnf.util; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.onap.aaiclient.client.aai.AAIProperties; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.so.client.CacheProperties; +import org.onap.so.spring.SpringContextHelper; +import org.springframework.context.ApplicationContext; + +public class AaiClientPropertiesImpl implements AAIProperties { + + private String aaiEndpoint; + private String auth; + private String key; + private Long readTimeout; + private Long connectionTimeout; + private boolean enableCaching; + private Long cacheMaxAge; + private static final String SYSTEM_NAME = "MSO"; + + public AaiClientPropertiesImpl() { + ApplicationContext context = SpringContextHelper.getAppContext(); + aaiEndpoint = context.getEnvironment().getProperty("aai.endpoint"); + this.auth = context.getEnvironment().getProperty("aai.auth"); + this.key = context.getEnvironment().getProperty("mso.msoKey"); + this.readTimeout = context.getEnvironment().getProperty("aai.readTimeout", Long.class, 60000L); + this.connectionTimeout = context.getEnvironment().getProperty("aai.connectionTimeout", Long.class, 60000L); + this.enableCaching = context.getEnvironment().getProperty("aai.caching.enabled", Boolean.class, false); + this.cacheMaxAge = context.getEnvironment().getProperty("aai.caching.maxAge", Long.class, 60000L); + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(aaiEndpoint); + } + + @Override + public String getSystemName() { + return SYSTEM_NAME; + } + + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } + + @Override + public String getAuth() { + return this.auth; + } + + @Override + public String getKey() { + return this.key; + } + + @Override + public Long getReadTimeout() { + return this.readTimeout; + } + + @Override + public Long getConnectionTimeout() { + return this.connectionTimeout; + } + + @Override + public boolean isCachingEnabled() { + return this.enableCaching; + } + + @Override + public CacheProperties getCacheProperties() { + return new AAICacheProperties() { + @Override + public Long getMaxAge() { + return cacheMaxAge; + } + }; + } +} diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiRepository.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiRepository.java new file mode 100644 index 0000000..b816105 --- /dev/null +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiRepository.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2021 Samsung Electronics Co. Ltd. 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.adapters.cnf.util; + +import com.google.gson.Gson; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.AAITransactionalClient; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types; +import org.onap.aaiclient.client.generated.fluentbuilders.K8sResource; +import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed; +import org.onap.so.adapters.cnf.model.instantiation.AaiRequest; +import org.onap.so.adapters.cnf.service.aai.KubernetesResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class AaiRepository implements IAaiRepository { + private final static Logger logger = LoggerFactory.getLogger(IAaiRepository.class); + private final static Gson gson = new Gson(); + + private final AAIResourcesClient aaiClient; + private final AAITransactionalClient transaction; + + public static IAaiRepository instance() { + return new AaiRepository(); + } + + private AaiRepository() { + aaiClient = new AAIResourcesClient(AAIVersion.LATEST); + transaction = aaiClient.beginTransaction(); + } + + @Override + public void commit(boolean dryrun) { + try { + transaction.execute(dryrun); + } catch (BulkProcessFailed bulkProcessFailed) { + throw new RuntimeException("Failed to exectute transaction", bulkProcessFailed); + } + } + + @Override + public void update(KubernetesResource resource, AaiRequest aaiRequest) { + logger.info("updating AAI with resource {} and request {}", resource, aaiRequest); + + K8sResource k8sResource = AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion()) + .tenant(aaiRequest.getTenantId()) + .k8sResource(resource.getId()); + + AAIResourceUri k8sResourceUri = + AAIUriFactory.createResourceUri(k8sResource.build(), aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion(), aaiRequest.getTenantId(), resource.getId()); + + String payload = gson.toJson(resource); + logger.debug("K8s resource URI: " + k8sResourceUri + " with payload [" + payload + "]"); + transaction.createIfNotExists(k8sResourceUri, Optional.of(payload)); + // add edge from vf module to k8s resource + final String genericVnfId = aaiRequest.getGenericVnfId(); + final String vfModuleId = aaiRequest.getVfModuleId(); + + + var vfModuleUri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId)); + var instance = aaiClient.get(vfModuleUri); + + var foundUri = instance.getRelationships().get().getRelatedUris(Types.K8S_RESOURCE) + .stream().filter(resourceUri -> resourceUri + .getURIKeys() + .get("k8s_resource-id") + .startsWith(resource.getId())) + .findFirst(); + + transaction.connect(foundUri.get(), k8sResourceUri); + + var genericVnfUri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.network().genericVnf(genericVnfId)); + instance = aaiClient.get(genericVnfUri); + + foundUri = instance.getRelationships().get().getRelatedUris(Types.K8S_RESOURCE) + .stream().filter(resourceUri -> resourceUri + .getURIKeys() + .get("k8s_resource-id") // FIXME double check names + .startsWith(resource.getId())) + .findFirst(); + + transaction.connect(foundUri.get(), k8sResourceUri); + } + + @Override + public void delete(KubernetesResource resource, AaiRequest aaiRequest) { + logger.info("deleting from AAI resource {}", aaiRequest); + // dge from vf module to k8s resource + final String genericVnfId = aaiRequest.getGenericVnfId(); + final String vfModuleId = aaiRequest.getVfModuleId(); + + var vfModuleUri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId)); + var instance = aaiClient.get(vfModuleUri); + + if (instance.hasRelationshipsTo(Types.K8S_RESOURCE)) { + List<KubernetesResource> resources = instance.getRelationships().get().getByType(Types.K8S_RESOURCE) + .stream() + .map(r -> r.asBean(KubernetesResource.class)) + .filter(r -> r.get().getLabels().get(1).equals(resource.getLabels().get(1))) + .map(Optional::get) + .collect(Collectors.toList()); + resources.stream().map(r -> { + K8sResource k8sResource = AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion()) + .tenant(aaiRequest.getTenantId()) + .k8sResource(r.getId()); + AAIResourceUri k8sResourceUri = + AAIUriFactory.createResourceUri(k8sResource.build(), aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion(), aaiRequest.getTenantId(), r.getId()); + return k8sResourceUri; + }).forEach(uri -> transaction.delete(uri)); + } + + } +} diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/CNfAdapterUtil.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/CnfAdapterUtil.java index 25e506c..ef2453a 100644 --- a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/CNfAdapterUtil.java +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/CnfAdapterUtil.java @@ -21,17 +21,20 @@ package org.onap.so.adapters.cnf.util; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; + import org.onap.so.adapters.cnf.exceptions.ApplicationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.onap.logging.filter.base.ErrorCode; + import static org.onap.so.logger.LoggingAnchor.THREE; import static org.onap.so.logger.MessageEnum.RA_NS_EXC; -public class CNfAdapterUtil { +public class CnfAdapterUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(CNfAdapterUtil.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CnfAdapterUtil.class); public static final int BAD_REQUEST = 400; @@ -62,7 +65,7 @@ public class CNfAdapterUtil { } } - private CNfAdapterUtil() { + private CnfAdapterUtil() { } diff --git a/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/IAaiRepository.java b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/IAaiRepository.java new file mode 100644 index 0000000..d3dff9d --- /dev/null +++ b/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/IAaiRepository.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2021 Samsung Electronics Co. Ltd. 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.adapters.cnf.util; + +import org.onap.so.adapters.cnf.model.instantiation.AaiRequest; +import org.onap.so.adapters.cnf.service.aai.KubernetesResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static java.lang.Thread.sleep; + +public interface IAaiRepository { + static IAaiRepository instance(boolean enabled) { + if (enabled) + return AaiRepository.instance(); + else + return AaiRepositoryDummy.instance(); + } + + void update(KubernetesResource resource, AaiRequest request); + + void delete(KubernetesResource resource, AaiRequest request); + + void commit(boolean dryRun); + + static class AaiRepositoryDummy implements IAaiRepository { + private static final Logger logger = LoggerFactory.getLogger(IAaiRepository.class); + private static final IAaiRepository instance = new AaiRepositoryDummy(); + + private static final Long SLEEP_TIME = 3000l; + + public static IAaiRepository instance() { + return instance; + } + + private AaiRepositoryDummy() { + + } + + @Override + public void update(KubernetesResource resource, AaiRequest request) { + logger.info("aai synchronization disabled - mocking update AAI with resource {} and request {}", resource, request); + try { + sleep(SLEEP_TIME); + } catch (InterruptedException e) { + logger.debug("aai synchronization disabled [update] - sleep failed"); + } + } + + @Override + public void delete(KubernetesResource resource, AaiRequest aaiRequest) { + logger.info("aai synchronization disabled - mocking delete from AAI resource {}", aaiRequest); + try { + sleep(SLEEP_TIME); + } catch (InterruptedException e) { + logger.debug("aai synchronization disabled [delete] - sleep failed"); + } + + } + + @Override + public void commit(boolean dryrun) { + logger.info("aai synchronization disabled - commiting"); + } + } +} diff --git a/so-cnf-adapter-application/src/main/resources/META-INF/services/org.onap.so.client.RestProperties b/so-cnf-adapter-application/src/main/resources/META-INF/services/org.onap.so.client.RestProperties index bccd43a..98f7d2d 100644 --- a/so-cnf-adapter-application/src/main/resources/META-INF/services/org.onap.so.client.RestProperties +++ b/so-cnf-adapter-application/src/main/resources/META-INF/services/org.onap.so.client.RestProperties @@ -1 +1 @@ -org.onap.so.adapters.cnf.extclients.aai.AaiClientPropertiesImpl
\ No newline at end of file +org.onap.so.adapters.cnf.util.AaiClientPropertiesImpl
\ No newline at end of file diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/exceptions/ApplicationExceptionTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/exceptions/ApplicationExceptionTest.java index bc39e95..495c913 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/exceptions/ApplicationExceptionTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/exceptions/ApplicationExceptionTest.java @@ -22,8 +22,11 @@ package org.onap.so.adapters.cnf.exceptions; import org.junit.Test;
import org.junit.runner.RunWith;
-import org.onap.so.adapters.cnf.model.*;
-import org.springframework.http.HttpStatus;
+import org.onap.so.adapters.cnf.model.GroupVersionKind;
+import org.onap.so.adapters.cnf.model.InstanceStatusResponse;
+import org.onap.so.adapters.cnf.model.MulticloudInstanceRequest;
+import org.onap.so.adapters.cnf.model.PodStatus;
+import org.onap.so.adapters.cnf.model.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@@ -89,4 +92,5 @@ public class ApplicationExceptionTest { applicationexception.buildErrorResponse();
}
-}
\ No newline at end of file +
+}
diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java index 48eecaa..e5c50c4 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java @@ -27,7 +27,21 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.onap.so.adapters.cnf.MulticloudConfiguration; -import org.onap.so.adapters.cnf.model.*; +import org.onap.so.adapters.cnf.model.BpmnInstanceRequest; +import org.onap.so.adapters.cnf.model.CheckInstanceRequest; +import org.onap.so.adapters.cnf.model.ConfigTemplateEntity; +import org.onap.so.adapters.cnf.model.ConfigurationEntity; +import org.onap.so.adapters.cnf.model.ConfigurationRollbackEntity; +import org.onap.so.adapters.cnf.model.ConnectivityInfo; +import org.onap.so.adapters.cnf.model.InstanceMiniResponse; +import org.onap.so.adapters.cnf.model.InstanceMiniResponseList; +import org.onap.so.adapters.cnf.model.InstanceResponse; +import org.onap.so.adapters.cnf.model.InstanceStatusResponse; +import org.onap.so.adapters.cnf.model.MulticloudInstanceRequest; +import org.onap.so.adapters.cnf.model.ProfileEntity; +import org.onap.so.adapters.cnf.model.Resource; +import org.onap.so.adapters.cnf.model.ResourceBundleEntity; +import org.onap.so.adapters.cnf.model.Tag; import org.onap.so.adapters.cnf.model.healthcheck.HealthCheckResponse; import org.onap.so.adapters.cnf.service.CnfAdapterService; import org.springframework.http.HttpStatus; @@ -35,12 +49,14 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.multipart.MultipartFile; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; + import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java index f049310..7d161bc 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java @@ -20,12 +20,7 @@ package org.onap.so.adapters.cnf.service; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; - +import lombok.Data; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,20 +32,21 @@ import org.onap.so.adapters.cnf.service.healthcheck.HealthCheckService; import org.onap.so.adapters.cnf.service.statuscheck.SimpleStatusCheckService; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; +import javax.persistence.EntityNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import javax.persistence.EntityNotFoundException; - -import lombok.Data; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; @RunWith(SpringRunner.class) public class CnfAdapterServiceTest { diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiIdGeneratorServiceTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiIdGeneratorServiceTest.java index 70070e4..948bc0b 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiIdGeneratorServiceTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiIdGeneratorServiceTest.java @@ -6,8 +6,10 @@ import org.junit.runner.RunWith; import org.onap.so.adapters.cnf.model.instantiation.AaiRequest; import org.onap.so.adapters.cnf.model.statuscheck.K8sRbInstanceGvk; import org.onap.so.adapters.cnf.model.statuscheck.K8sRbInstanceResourceStatus; +import org.onap.so.adapters.cnf.util.IAaiRepository; import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParserTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParserTest.java index f3c0558..e962848 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParserTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiResponseParserTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2021 Samsung Electronics Co. Ltd. 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.adapters.cnf.service.aai; import org.junit.Assert; @@ -12,8 +32,6 @@ import org.onap.so.adapters.cnf.model.statuscheck.K8sStatus; import org.onap.so.adapters.cnf.model.statuscheck.K8sStatusMetadata; import org.springframework.test.context.junit4.SpringRunner; -import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -24,6 +42,9 @@ import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) public class AaiResponseParserTest { + private final static String INSTANCE_ID = "k8splugin.io/rb-instance-id"; + private final static String INSTANCE_ID_VALUE = "rb-instance-id_value"; + @InjectMocks private AaiResponseParser aaiResponseParser; @@ -42,6 +63,7 @@ public class AaiResponseParserTest { String namespace = "namespace"; Map<String, String> labelsMap = new HashMap<>(); labelsMap.put("key", "value"); + labelsMap.put(INSTANCE_ID, INSTANCE_ID_VALUE); K8sRbInstanceResourceStatus status = mock(K8sRbInstanceResourceStatus.class); AaiRequest aaiRequest = mock(AaiRequest.class); K8sRbInstanceGvk gvk = mock(K8sRbInstanceGvk.class); @@ -63,7 +85,7 @@ public class AaiResponseParserTest { when(metadata.getLabels()).thenReturn(labelsMap); // then - ParseResult actual = aaiResponseParser.parse(status, aaiRequest); + KubernetesResource actual = aaiResponseParser.parse(status, aaiRequest); Assert.assertNotNull(actual); assertEquals(id, actual.getId()); @@ -72,30 +94,9 @@ public class AaiResponseParserTest { assertEquals(version, actual.getVersion()); assertEquals(kind, actual.getKind()); assertEquals(namespace, actual.getNamespace()); - assertEquals(2, actual.getLabels().size()); - assertEquals("http://so-cnf-adapter:8090/api/cnf-adapter/v1/instance/id/query", actual.getK8sResourceSelfLink()); - - } - - ParseResult parse(K8sRbInstanceResourceStatus status, AaiRequest aaiRequest) { - ParseResult result = new ParseResult(); - K8sRbInstanceGvk gvk = status.getGvk(); - K8sStatus k8sStatus = status.getStatus(); - K8sStatusMetadata metadata = k8sStatus.getK8sStatusMetadata(); - String id = aaiIdGeneratorService.generateId(status, aaiRequest); - result.setId(id); - result.setName(status.getName()); - result.setGroup(gvk.getGroup()); - result.setVersion(gvk.getVersion()); - result.setKind(gvk.getKind()); - result.setNamespace(metadata.getNamespace()); - Collection<String> labels = new ArrayList<>(); - metadata.getLabels().forEach((key, value) -> { - labels.add(key); - labels.add(value); - }); - result.setLabels(labels); - result.setK8sResourceSelfLink(String.format("http://so-cnf-adapter:8090/api/cnf-adapter/v1/instance/%s/query", aaiRequest.getInstanceId())); - return result; + assertEquals(4, actual.getLabels().size()); + assertEquals(INSTANCE_ID, actual.getLabels().get(0)); + assertEquals(INSTANCE_ID_VALUE, actual.getLabels().get(1)); + assertEquals("http://so-cnf-adapter:8090/api/cnf-adapter/v1/instance/id/query?ApiVersion=version&Kind=kind&Name=name&Namespace=namespace", actual.getK8sResourceSelfLink()); } -}
\ No newline at end of file +} diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiServiceTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiServiceTest.java index f8f9597..a4e0625 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiServiceTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/aai/AaiServiceTest.java @@ -16,7 +16,6 @@ import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -30,8 +29,6 @@ public class AaiServiceTest { @Mock private MulticloudClient multicloudClient; @Mock - private AaiRequestSender aaiRequestSender; - @Mock private AaiResponseParser responseParser; @Mock private AaiConfiguration aaiConfiguration; @@ -45,8 +42,8 @@ public class AaiServiceTest { K8sRbInstanceResourceStatus status = mock(K8sRbInstanceResourceStatus.class); List<K8sRbInstanceResourceStatus> resourcesStatus = new ArrayList<>(); resourcesStatus.add(status); - ParseResult parseResult = mock(ParseResult.class); - List<ParseResult> parseResultList = new ArrayList<>(); + KubernetesResource parseResult = mock(KubernetesResource.class); + List<KubernetesResource> parseResultList = new ArrayList<>(); parseResultList.add(parseResult); // when @@ -54,14 +51,11 @@ public class AaiServiceTest { when(multicloudClient.getInstanceStatus(instanceId)).thenReturn(instanceStatus); when(instanceStatus.getResourcesStatus()).thenReturn(resourcesStatus); when(responseParser.parse(status, aaiRequest)).thenReturn(parseResult); - when(aaiConfiguration.isEnabled()).thenReturn(true); - doNothing().when(aaiRequestSender).sendUpdateRequestToAai(parseResult, aaiRequest); // then aaiServiceTested.aaiUpdate(aaiRequest); verify(responseParser, atLeast(1)).parse(status, aaiRequest); - verify(aaiRequestSender, atLeast(1)).sendUpdateRequestToAai(parseResult, aaiRequest); } @@ -74,8 +68,8 @@ public class AaiServiceTest { K8sRbInstanceResourceStatus status = mock(K8sRbInstanceResourceStatus.class); List<K8sRbInstanceResourceStatus> resourcesStatus = new ArrayList<>(); resourcesStatus.add(status); - ParseResult parseResult = mock(ParseResult.class); - List<ParseResult> parseResultList = new ArrayList<>(); + KubernetesResource parseResult = mock(KubernetesResource.class); + List<KubernetesResource> parseResultList = new ArrayList<>(); parseResultList.add(parseResult); // when @@ -83,13 +77,10 @@ public class AaiServiceTest { when(multicloudClient.getInstanceStatus(instanceId)).thenReturn(instanceStatus); when(instanceStatus.getResourcesStatus()).thenReturn(resourcesStatus); when(responseParser.parse(status, aaiRequest)).thenReturn(parseResult); - when(aaiConfiguration.isEnabled()).thenReturn(true); - doNothing().when(aaiRequestSender).sendUpdateRequestToAai(parseResult, aaiRequest); // then aaiServiceTested.aaiDelete(aaiRequest); verify(responseParser, atLeast(1)).parse(status, aaiRequest); - verify(aaiRequestSender, atLeast(1)).sendDeleteRequestToAai(aaiRequest); } -}
\ No newline at end of file +} diff --git a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/healthcheck/HealthCheckServiceTest.java b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/healthcheck/HealthCheckServiceTest.java index 9a043ba..33d3104 100644 --- a/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/healthcheck/HealthCheckServiceTest.java +++ b/so-cnf-adapter-application/src/test/java/org/onap/so/adapters/cnf/service/healthcheck/HealthCheckServiceTest.java @@ -1,81 +1,79 @@ package org.onap.so.adapters.cnf.service.healthcheck; -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.UUID; - -import org.junit.jupiter.api.BeforeEach; +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.Rule; import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.adapters.cnf.client.MulticloudClient; import org.onap.so.adapters.cnf.model.CheckInstanceRequest; import org.onap.so.adapters.cnf.model.InstanceRequest; import org.onap.so.adapters.cnf.model.healthcheck.HealthCheckResponse; import org.onap.so.adapters.cnf.model.healthcheck.K8sRbInstanceHealthCheck; import org.onap.so.adapters.cnf.model.healthcheck.K8sRbInstanceHealthCheckSimple; -import org.onap.so.client.exception.BadResponseException; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.UUID; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +@SpringBootTest +@RunWith(MockitoJUnitRunner.class) class HealthCheckServiceTest { + private final int portNumber = 8443; + @Rule + public WireMockRule wireMockRule = new WireMockRule(portNumber); @InjectMocks - HealthCheckService healthCheckService; + private HealthCheckService healthCheckService; @Mock - MulticloudClient multicloudClient; - - @BeforeEach - void setUp() { - MockitoAnnotations.initMocks(this); - } + private MulticloudClient multicloudClient; @Test - void healthCheckTest() { + public void healthCheckTest() { try { doReturn(getK8sRbInstanceHealthCheckSimple()).when(multicloudClient).startInstanceHealthCheck(any()); - doReturn(getK8sRbInstanceHealthCheck()).when(multicloudClient).getInstanceHealthCheck(any(),any()); + doReturn(getK8sRbInstanceHealthCheck()).when(multicloudClient).getInstanceHealthCheck(any(), any()); HealthCheckResponse response = healthCheckService.healthCheck(getTestCheckInstanceRequest()); verify(multicloudClient, times(3)).startInstanceHealthCheck(any()); - verify(multicloudClient, times(3)).getInstanceHealthCheck(any(),any()); + verify(multicloudClient, times(3)).getInstanceHealthCheck(any(), any()); assertThat(response.getInstanceResponse()).hasSize(getTestCheckInstanceRequest().getInstances().size()); } catch (Exception e) { e.printStackTrace(); } } - private CheckInstanceRequest getTestCheckInstanceRequest(){ - CheckInstanceRequest checkInstanceRequest=new CheckInstanceRequest() ; - checkInstanceRequest.setInstances(asList(getRandomInstance(),getRandomInstance(),getRandomInstance())); + private CheckInstanceRequest getTestCheckInstanceRequest() { + CheckInstanceRequest checkInstanceRequest = new CheckInstanceRequest(); + checkInstanceRequest.setInstances(asList(getRandomInstance(), getRandomInstance(), getRandomInstance())); return checkInstanceRequest; } - private InstanceRequest getRandomInstance(){ - InstanceRequest instanceRequest=new InstanceRequest(); + private InstanceRequest getRandomInstance() { + InstanceRequest instanceRequest = new InstanceRequest(); instanceRequest.setInstanceId(UUID.randomUUID().toString()); return instanceRequest; } - private K8sRbInstanceHealthCheckSimple getK8sRbInstanceHealthCheckSimple(){ - K8sRbInstanceHealthCheckSimple k8sRbInstanceHealthCheckSimple=new K8sRbInstanceHealthCheckSimple(); + private K8sRbInstanceHealthCheckSimple getK8sRbInstanceHealthCheckSimple() { + K8sRbInstanceHealthCheckSimple k8sRbInstanceHealthCheckSimple = new K8sRbInstanceHealthCheckSimple(); k8sRbInstanceHealthCheckSimple.setId(UUID.randomUUID().toString()); k8sRbInstanceHealthCheckSimple.setStatus("RUNNING"); return k8sRbInstanceHealthCheckSimple; } - private K8sRbInstanceHealthCheck getK8sRbInstanceHealthCheck(){ - K8sRbInstanceHealthCheck k8sRbInstanceHealthCheck=new K8sRbInstanceHealthCheck(); + private K8sRbInstanceHealthCheck getK8sRbInstanceHealthCheck() { + K8sRbInstanceHealthCheck k8sRbInstanceHealthCheck = new K8sRbInstanceHealthCheck(); k8sRbInstanceHealthCheck.setStatus("STOPPED"); return k8sRbInstanceHealthCheck; } -}
\ No newline at end of file +} diff --git a/so-cnf-adapter-application/src/test/resources/application.properties b/so-cnf-adapter-application/src/test/resources/application.properties new file mode 100644 index 0000000..154283c --- /dev/null +++ b/so-cnf-adapter-application/src/test/resources/application.properties @@ -0,0 +1,4 @@ +aai.enabled=true +aai.endpoint=http://localhost:8443 +aai.auth=5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C +mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7
\ No newline at end of file |