diff options
61 files changed, 4182 insertions, 409 deletions
diff --git a/adapters/mso-cnf-adapter/pom.xml b/adapters/mso-cnf-adapter/pom.xml index fb25157a96..0928da084e 100644 --- a/adapters/mso-cnf-adapter/pom.xml +++ b/adapters/mso-cnf-adapter/pom.xml @@ -110,11 +110,11 @@ <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> - <!-- <dependency> + <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> - </dependency> --> + </dependency> <!-- <dependency> <groupId>org.onap.so</groupId> <artifactId>mso-requests-db</artifactId> diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java new file mode 100644 index 0000000000..c950cf6b2a --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/exceptions/ApplicationException.java @@ -0,0 +1,66 @@ +/*- + * ============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.exceptions; + +import static org.onap.so.adapters.cnf.util.CNfAdapterUtil.marshal; +import org.onap.so.adapters.cnf.model.ErrorResponse; +import org.springframework.http.ResponseEntity; + +public class ApplicationException extends Exception { + + private static final long serialVersionUID = 1L; + + private int errorCode; + + private String errorMsg; + + public ApplicationException(int errorCode, String errorMsg) { + this.errorCode = errorCode; + this.errorMsg = errorMsg; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public ResponseEntity buildErrorResponse() { + String message; + try { + ErrorResponse err = new ErrorResponse(errorCode, errorMsg); + message = marshal(err); + } catch (ApplicationException e) { + return ResponseEntity.status(500).body("Internal Server Error"); + } + return ResponseEntity.status(errorCode).body(message); + } +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/BpmnInstanceRequest.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/BpmnInstanceRequest.java new file mode 100644 index 0000000000..2e76d51da2 --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/BpmnInstanceRequest.java @@ -0,0 +1,87 @@ +package org.onap.so.adapters.cnf.model; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(value = "true") +public class BpmnInstanceRequest { + + @JsonProperty(value = "modelInvariantId") + private String modelInvariantId; + + @JsonProperty(value = "modelVersionId") + private String modelVersionId; + + @JsonProperty(value = "k8sRBProfileName") + private String k8sRBProfileName; + + @JsonProperty(value = "cloudRegionId") + private String cloudRegionId; + + @JsonProperty(value = "vfModuleUUID") + private String vfModuleUUID; + + @JsonProperty(value = "labels") + private Map<String, String> labels; + + @JsonProperty(value = "overrideValues") + private Map<String, String> overrideValues; + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getK8sRBProfileName() { + return k8sRBProfileName; + } + + public void setK8sRBProfileName(String k8sRBProfileName) { + this.k8sRBProfileName = k8sRBProfileName; + } + + public String getCloudRegionId() { + return cloudRegionId; + } + + public void setCloudRegionId(String cloudRegionId) { + this.cloudRegionId = cloudRegionId; + } + + public String getVfModuleUUID() { + return vfModuleUUID; + } + + public void setVfModuleUUID(String vfModuleUUID) { + this.vfModuleUUID = vfModuleUUID; + } + + public Map<String, String> getLabels() { + return labels; + } + + public void setLabels(Map<String, String> labels) { + this.labels = labels; + } + + public Map<String, String> getOverrideValues() { + return overrideValues; + } + + public void setOverrideValues(Map<String, String> overrideValues) { + this.overrideValues = overrideValues; + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/ErrorResponse.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/ErrorResponse.java index 188349c0bf..135adcc143 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/ErrorResponse.java +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/ErrorResponse.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.model; +package org.onap.so.adapters.cnf.model; public class ErrorResponse { diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceEntity.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/MulticloudInstanceRequest.java index 04f2f9d030..b1719cbd7d 100644 --- a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceEntity.java +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/MulticloudInstanceRequest.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(value = "true") -public class InstanceEntity { +public class MulticloudInstanceRequest { @JsonProperty(value = "cloud-region") private String cloudRegion; @@ -25,6 +25,9 @@ public class InstanceEntity { @JsonProperty(value = "override-values") private Map<String, String> overrideValues; + @JsonProperty(value = "release-name") + private String vfModuleUuid; + public String getCloudRegion() { return cloudRegion; } @@ -73,4 +76,12 @@ public class InstanceEntity { this.overrideValues = overrideValues; } + public String getVfModuleUuid() { + return vfModuleUuid; + } + + public void setVfModuleUuid(String vfModuleUuid) { + this.vfModuleUuid = vfModuleUuid; + } + } diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java index 952edef7f6..b6d50da557 100644 --- a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java @@ -1,27 +1,39 @@ package org.onap.so.adapters.cnf.rest; +import java.io.File; +import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; +import org.onap.so.adapters.cnf.model.BpmnInstanceRequest; 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.InstanceEntity; +import org.onap.so.adapters.cnf.model.MulticloudInstanceRequest; import org.onap.so.adapters.cnf.model.ProfileEntity; import org.onap.so.adapters.cnf.model.ResourceBundleEntity; +import org.onap.so.adapters.cnf.model.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -32,14 +44,14 @@ public class CnfAdapterRest { private final CloseableHttpClient httpClient = HttpClients.createDefault(); @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/healthcheck"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/healthcheck"}, method = RequestMethod.GET, produces = "application/json") public String healthCheck() throws Exception { logger.info("health check called."); // TODO - HttpGet req = new HttpGet("https://localhost:32780/api/multicloud-k8s/v1/healthcheck"); + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/healthcheck"); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); return EntityUtils.toString(response.getEntity()); @@ -47,7 +59,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/rb/definition"}, method = RequestMethod.POST, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition"}, method = RequestMethod.POST, produces = "application/json") public String createRB(@RequestBody ResourceBundleEntity rB) throws Exception { @@ -55,7 +67,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("https://localhost:32780/api/multicloud-k8s/v1/v1/rb/definition"); + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/rb/definition"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); String requestBody = objectMapper.writeValueAsString(rB); @@ -70,8 +82,8 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/rb/definition/{rb-name}/{rb-version}"}, - method = RequestMethod.GET, produces = "application/json") + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}"}, method = RequestMethod.GET, + produces = "application/json") public String getRB(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -79,16 +91,101 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet( - "https://localhost:32780/api/multicloud-k8s/v1/v1/rb/definition/" + rbName + "/" + rbVersion); + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion); + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}"}, + method = RequestMethod.DELETE, produces = "application/json") + public String deleteRB(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) + throws Exception { + + logger.info("delete RB called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}"}, method = RequestMethod.GET, + produces = "application/json") + public String getListOfRB(@PathVariable("rb-name") String rbName) throws Exception { + + logger.info("getListOfRB called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition/" + rbName); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition"}, method = RequestMethod.GET, + produces = "application/json") + public String getListOfRBWithoutUsingRBName() throws Exception { + + logger.info("getListOfRBWithoutUsingRBName called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition"); + try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); return EntityUtils.toString(response.getEntity()); } + } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/rb/definition/{rb-name}/{rb-version}/profile"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/content"}, + method = RequestMethod.POST, produces = "multipart/form-data") + public String uploadArtifactForRB(@RequestParam("file") MultipartFile file, @PathVariable("rb-name") String rbName, + @PathVariable("rb-version") String rbVersion) throws Exception { + + logger.info("Upload Artifact For RB called."); + + File convFile = new File(file.getOriginalFilename()); + file.transferTo(convFile); + FileBody fileBody = new FileBody(convFile, ContentType.DEFAULT_BINARY); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.addPart("file", fileBody); + HttpEntity entity = builder.build(); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPost post = + new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/content"); + post.setHeader("Content-Type", "multipart/form-data"); + logger.info(String.valueOf(post)); + post.setEntity(entity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile"}, method = RequestMethod.POST, produces = "application/json") public String createProfile(@RequestBody ProfileEntity fE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -97,8 +194,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://localhost:32780/api/multicloud-k8s/v1/v1/rb/definition/" + rbName + "/" - + rbVersion + "/profile"); + HttpPost post = + new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(fE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -112,7 +209,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, method = RequestMethod.GET, produces = "application/json") public String getProfile(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("pr-name") String prName) throws Exception { @@ -121,8 +218,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("https://localhost:32780/api/multicloud-k8s/v1/v1/rb/definition/" + rbName + "/" - + rbVersion + "/profile/" + prName); + HttpGet req = new HttpGet( + "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -131,18 +228,130 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/instance"}, method = RequestMethod.POST, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile"}, + method = RequestMethod.GET, produces = "application/json") + public String getListOfProfile(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) + throws Exception { + + logger.info("getListOfProfile called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile"); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, + method = RequestMethod.DELETE, produces = "application/json") + public String deleteProfile(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, + @PathVariable("pr-name") String prName) throws Exception { + + logger.info("delete Profile called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpDelete req = new HttpDelete( + "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}/content"}, + method = RequestMethod.POST, produces = "multipart/form-data") + public String uploadArtifactForProfile(@RequestParam("file") MultipartFile file, + @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, + @PathVariable("pr-name") String prName) throws Exception { + + logger.info("Upload Artifact For Profile called."); + + File convFile = new File(file.getOriginalFilename()); + file.transferTo(convFile); + FileBody fileBody = new FileBody(convFile, ContentType.DEFAULT_BINARY); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.addPart("file", fileBody); + HttpEntity entity = builder.build(); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + + "/profile/" + prName + "/content"); + post.setHeader("Content-Type", "multipart/form-data"); + + logger.info(String.valueOf(post)); + post.setEntity(entity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance"}, method = RequestMethod.POST, produces = "application/json") - public String createInstance(@RequestBody InstanceEntity iE) throws Exception { + public String createInstance(@RequestBody BpmnInstanceRequest bpmnInstanceRequest) throws Exception { logger.info("create Instance called."); + MulticloudInstanceRequest multicloudInstanceRequest = new MulticloudInstanceRequest(); + + if (bpmnInstanceRequest.getK8sRBProfileName() != null) { + multicloudInstanceRequest.setCloudRegion(bpmnInstanceRequest.getCloudRegionId()); + multicloudInstanceRequest.setLabels(bpmnInstanceRequest.getLabels()); + multicloudInstanceRequest.setOverrideValues(bpmnInstanceRequest.getOverrideValues()); + multicloudInstanceRequest.setProfileName(bpmnInstanceRequest.getK8sRBProfileName()); + multicloudInstanceRequest.setRbName(bpmnInstanceRequest.getModelInvariantId()); + multicloudInstanceRequest.setRbVersion(bpmnInstanceRequest.getModelVersionId()); + multicloudInstanceRequest.setVfModuleUuid(bpmnInstanceRequest.getVfModuleUUID()); + } else { + + logger.info("K8sRBProfileName is required"); + return "K8sRBProfileName is required"; + } + // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("https://localhost:32780/api/multicloud-k8s/v1/v1/instance"); + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/instance"); + ObjectMapper objectMapper = new ObjectMapper(); + + String requestBody = objectMapper.writeValueAsString(multicloudInstanceRequest); + StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); + post.setEntity(requestEntity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + // This api is not enabled in multicloud project ,but this is required in + // future. + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{vnfInstanceId}"}, method = RequestMethod.PUT, + produces = "application/json") + public String updateInstance(@RequestBody MulticloudInstanceRequest iE, + @PathVariable("vnfInstanceId") String instanceId) throws Exception { + + logger.info("create Instance called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPut post = new HttpPut("http://172.17.0.2:31770/v1/instance/" + instanceId); ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); String requestBody = objectMapper.writeValueAsString(iE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); post.setEntity(requestEntity); @@ -155,14 +364,15 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/instance/{instID}"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{instID}"}, method = RequestMethod.GET, produces = "application/json") public String getInstance(@PathVariable("instID") String instanceId) throws Exception { logger.info("get Instance called."); + // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("https://localhost:32780/api/multicloud-k8s/v1/v1/instance/" + instanceId); + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/instance/" + instanceId); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -171,8 +381,62 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping( - value = {"/api/multicloud-k8s/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{instID}/status"}, method = RequestMethod.GET, + produces = "application/json") + public String getInstanceStatus(@PathVariable("instID") String instanceId) throws Exception { + + logger.info("getInstanceStatus called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/instance/" + instanceId + "/status"); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance"}, method = RequestMethod.GET, + produces = "application/json") + public String getInstanceBasedOnRBNameOrRBVersionOrProfileName( + @RequestParam(value = "rb-name", required = false) String rbName, + @RequestParam(value = "rb-version", required = false) String rbVersion, + @RequestParam(value = "profile-name", required = false) String profileName) throws Exception { + + logger.info("getInstanceBasedOnRBNameOrRBVersionOrProfileName called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/instance?rb-name=" + rbName + "&rb-version=" + rbVersion + + "&profile-name=" + profileName); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{instID}"}, method = RequestMethod.DELETE, + produces = "application/json") + public String deleteInstance(@PathVariable("instID") String instanceID) throws Exception { + + logger.info("delete Instance called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/instance/" + instanceID); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config"}, method = RequestMethod.POST, produces = "application/json") public String createConfiguration(@RequestBody ConfigurationEntity cE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName) @@ -182,8 +446,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("https://localhost:32780/api/multicloud-k8s/v1/v1/definition/" + rbName + "/" - + rbVersion + "/profile/" + prName + "/config"); + HttpPost post = new HttpPost( + "http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + prName + "/config"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(cE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -198,7 +462,7 @@ public class CnfAdapterRest { @ResponseBody @RequestMapping(value = { - "/api/multicloud-k8s/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, + "/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, method = RequestMethod.GET, produces = "application/json") public String getConfiguration(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName, @PathVariable("cfg-name") String cfgName) throws Exception { @@ -207,8 +471,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("https://localhost:32780/api/multicloud-k8s/v1/v1/definition/" + rbName + "/" - + rbVersion + "/profile/" + prName + "/config/" + cfgName); + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + + prName + "/config/" + cfgName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -217,7 +481,79 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/connectivity-info"}, method = RequestMethod.POST, + @RequestMapping(value = { + "/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, + method = RequestMethod.DELETE, produces = "application/json") + public String deleteConfiguration(@PathVariable("rb-name") String rbName, + @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName, + @PathVariable("cfg-name") String cfgName) throws Exception { + + logger.info("delete Configuration called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + + "/profile/" + prName + "/config/" + cfgName); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping(value = { + "/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, + method = RequestMethod.PUT, produces = "application/json") + public String updateConfiguration(@RequestBody ConfigurationEntity cE, @PathVariable("rb-name") String rbName, + @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName, + @PathVariable("cfg-name") String cfgName) throws Exception { + + logger.info("update Configuration called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPut post = new HttpPut("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + + prName + "/config/" + cfgName); + ObjectMapper objectMapper = new ObjectMapper(); + String requestBody = objectMapper.writeValueAsString(cE); + StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); + post.setEntity(requestEntity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/tagit"}, + method = RequestMethod.POST, produces = "application/json") + public String tagConfigurationValue(@RequestBody Tag tag, @PathVariable("rb-name") String rbName, + @PathVariable("rb-version") String rbVersion, @PathVariable("pr-name") String prName) throws Exception { + logger.info("Tag Configuration called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + + prName + "/config/tagit"); + + ObjectMapper objectMapper = new ObjectMapper(); + String requestBody = objectMapper.writeValueAsString(tag); + StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); + post.setEntity(requestEntity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/connectivity-info"}, method = RequestMethod.POST, produces = "application/json") public String createConnectivityInfo(@RequestBody ConnectivityInfo cIE) throws Exception { @@ -225,7 +561,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("https://localhost:32780/api/multicloud-k8s/v1/v1/connectivity-info"); + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/connectivity-info"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(cIE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -239,7 +575,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/connectivity-info/{connname}"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/connectivity-info/{connname}"}, method = RequestMethod.GET, produces = "application/json") public String getConnectivityInfo(@PathVariable("connname") String connName) throws Exception { @@ -247,7 +583,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("https://localhost:32780/api/multicloud-k8s/v1/v1/connectivity-info/" + connName); + HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/connectivity-info/" + connName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -256,7 +592,25 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/connectivity-info/{connname}"}, method = RequestMethod.DELETE, + produces = "application/json") + public String deleteConnectivityInfo(@PathVariable("connname") String connName) throws Exception { + + logger.info("delete Connectivity Info called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/connectivity-info/" + connName); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template"}, method = RequestMethod.POST, produces = "application/json") public String createConfigTemplate(@RequestBody ConfigTemplateEntity tE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -265,8 +619,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://localhost:32780/api/multicloud-k8s/v1/v1/rb/definition/" + rbName + "/" - + rbVersion + "/config-template"); + HttpPost post = new HttpPost( + "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(tE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -280,7 +634,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/multicloud-k8s/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, method = RequestMethod.GET, produces = "application/json") public String getConfigTemplate(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("tname") String tName) throws Exception { @@ -289,8 +643,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("https://localhost:32780/api/multicloud-k8s/v1/v1/rb/definition/" + rbName + "/" - + rbVersion + "/config-template/" + tName); + HttpGet req = new HttpGet( + "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template/" + tName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -298,4 +652,83 @@ public class CnfAdapterRest { } } + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, + method = RequestMethod.DELETE, produces = "application/json") + public String deleteTemplate(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, + @PathVariable("tname") String tName) throws Exception { + + logger.info("deleteTemplate called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpDelete req = new HttpDelete( + "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template/" + tName); + + try (CloseableHttpResponse response = httpClient.execute(req)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + + } + + @ResponseBody + @RequestMapping( + value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}/content"}, + method = RequestMethod.POST, produces = "multipart/form-data") + public String uploadTarFileForTemplate(@RequestParam("file") MultipartFile file, + @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, + @PathVariable("tname") String tName) throws Exception { + + logger.info("uploadTarFileForTemplate called."); + + File convFile = new File(file.getOriginalFilename()); + file.transferTo(convFile); + FileBody fileBody = new FileBody(convFile, ContentType.DEFAULT_BINARY); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.addPart("file", fileBody); + HttpEntity entity = builder.build(); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + + "/config-template/" + tName + "/content"); + post.setHeader("Content-Type", "multipart/form-data"); + + logger.info(String.valueOf(post)); + post.setEntity(entity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/v1/definition/{rbName}/{rbVersion}/profile/{prName}/config/rollback"}, + method = RequestMethod.DELETE, produces = "application/json") + public String rollbackConfiguration(@RequestBody ConfigurationRollbackEntity rE, + @PathVariable("rbName") String rbName, @PathVariable("rbVersion") String rbVersion, + @PathVariable("prName") String prName) throws Exception { + logger.info("rollbackConfiguration called."); + + // TODO + // Below URL should be changed as appropriate multicloud URL. + HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + + prName + "/config/rollback"); + + ObjectMapper objectMapper = new ObjectMapper(); + String requestBody = objectMapper.writeValueAsString(rE); + StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); + post.setEntity(requestEntity); + + try (CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = httpClient.execute(post)) { + logger.info("response:" + response.getEntity()); + return EntityUtils.toString(response.getEntity()); + } + } + } diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/util/CNfAdapterUtil.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/util/CNfAdapterUtil.java new file mode 100644 index 0000000000..25e506c55e --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/util/CNfAdapterUtil.java @@ -0,0 +1,94 @@ +/*- + * ============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.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 { + + private static final Logger LOGGER = LoggerFactory.getLogger(CNfAdapterUtil.class); + + public static final int BAD_REQUEST = 400; + + private static final String UNMARSHAL_FAIL_MSG = "Failed to unmarshal json"; + + private static final String MARSHAL_FAIL_MSG = "Failed to marshal object"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static class StatusDesc { + + public static final String ALLOCATE_NSS_SUCCESS = "Allocating nss is " + "successful"; + + public static final String CREATE_NSS_SUCCESS = "Creating nss is " + "successful"; + + public static final String DEALLOCATE_NSS_SUCCESS = "Deallocate nss " + "is successful"; + + public static final String ACTIVATE_NSS_SUCCESS = "Activate nss " + "is successful"; + + public static final String DEACTIVATE_NSS_SUCCESS = "Deactivate nss " + "is successful"; + + public static final String QUERY_JOB_STATUS_FAILED = "Query job " + "status failed"; + + public static final String QUERY_JOB_STATUS_SUCCESS = "Query job " + "status is successful"; + + private StatusDesc() { + + } + } + + private CNfAdapterUtil() { + + } + + public static void assertObjectNotNull(Object object) throws ApplicationException { + if (null == object) { + LOGGER.error("Object is null."); + throw new ApplicationException(BAD_REQUEST, "An object is null."); + } + } + + public static <T> T unMarshal(String jsonstr, Class<T> type) throws ApplicationException { + try { + return MAPPER.readValue(jsonstr, type); + } catch (IOException e) { + LOGGER.error(THREE, RA_NS_EXC.toString(), ErrorCode.BusinessProcessError.getValue(), UNMARSHAL_FAIL_MSG, e); + throw new ApplicationException(BAD_REQUEST, UNMARSHAL_FAIL_MSG); + } + } + + public static String marshal(Object srcObj) throws ApplicationException { + try { + return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(srcObj); + } catch (IOException e) { + LOGGER.error(THREE, RA_NS_EXC.toString(), ErrorCode.BusinessProcessError.getValue(), MARSHAL_FAIL_MSG, e); + throw new ApplicationException(BAD_REQUEST, MARSHAL_FAIL_MSG); + } + } + +} diff --git a/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java new file mode 100644 index 0000000000..38a10918bc --- /dev/null +++ b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java @@ -0,0 +1,62 @@ +/*- + * ============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; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.onap.so.adapters.cnf.model.BpmnInstanceRequest; +import org.onap.so.adapters.cnf.rest.CnfAdapterRest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +public class CnfAdapterRestTest { + + @InjectMocks + CnfAdapterRest cnfAdapterRest; + + @Test + public void createInstanceTest() throws Exception { + + Map<String, String> labels = new HashMap<String, String>(); + labels.put("custom-label-1", "label1"); + Map<String, String> overrideValues = new HashMap<String, String>(); + labels.put("image.tag", "latest"); + labels.put("dcae_collector_ip", "1.2.3.4"); + BpmnInstanceRequest bpmnInstanceRequest = new BpmnInstanceRequest(); + bpmnInstanceRequest.setCloudRegionId("v1"); + bpmnInstanceRequest.setLabels(labels); + bpmnInstanceRequest.setModelInvariantId("krd"); + bpmnInstanceRequest.setModelVersionId("p1"); + bpmnInstanceRequest.setOverrideValues(overrideValues); + bpmnInstanceRequest.setVfModuleUUID("20200824"); + + String mockedResponse = "K8sRBProfileName is required"; + String actualResponse = cnfAdapterRest.createInstance(bpmnInstanceRequest); + assertNotNull(actualResponse); + assertEquals(mockedResponse, actualResponse); + } + +} diff --git a/adapters/mso-nssmf-adapter/pom.xml b/adapters/mso-nssmf-adapter/pom.xml index db791826c3..45fe77eecc 100644 --- a/adapters/mso-nssmf-adapter/pom.xml +++ b/adapters/mso-nssmf-adapter/pom.xml @@ -162,7 +162,6 @@ <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> - <version>1.18.2</version> </dependency> </dependencies> </project> diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java index cd011e6437..83a09dc343 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java @@ -20,6 +20,7 @@ package org.onap.so.adapters.nssmf; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/NssmfAdapterConfig.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/NssmfAdapterConfig.java new file mode 100644 index 0000000000..6a592448a6 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/NssmfAdapterConfig.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.config; + +import lombok.Getter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +@Configuration +@Getter +public class NssmfAdapterConfig { + + @Value("${mso.infra.endpoint}") + private String infraEndpoint; + + @Value("${mso.infra.auth}") + private String infraAuth; +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/RequestDbConfig.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/RequestDbConfig.java index 484f7624aa..dcb5d6198c 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/RequestDbConfig.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/RequestDbConfig.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf; +package org.onap.so.adapters.nssmf.config; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/WebSecurityConfig.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/WebSecurityConfig.java index 1522ca9c6d..dfb2b61978 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/WebSecurityConfig.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/config/WebSecurityConfig.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf; +package org.onap.so.adapters.nssmf.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/consts/NssmfAdapterConsts.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/consts/NssmfAdapterConsts.java new file mode 100644 index 0000000000..e762bc04e8 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/consts/NssmfAdapterConsts.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.consts; + +import org.onap.so.adapters.nssmf.entity.NssmfUrlInfo; +import org.onap.so.adapters.nssmf.enums.ActionType; +import org.onap.so.adapters.nssmf.enums.ExecutorType; +import org.onap.so.adapters.nssmf.enums.HttpMethod; +import org.onap.so.beans.nsmf.NetworkType; +import java.util.HashMap; +import java.util.Map; + +public class NssmfAdapterConsts { + + public final static String ONAP_INTERNAL_TAG = "ONAP_internal"; + + public final static String CURRENT_INTERNAL_NSSMF_API_VERSION = "v1"; + + private static Map<String, NssmfUrlInfo> urlInfoMap = new HashMap<>(); + + private final static String EXTERNAL_CN_ALLOCATE_URL = "/api/rest/provMns/{apiVersion}/NSS/SliceProfiles"; + + private final static String EXTERNAL_TN_ALLOCATE_URL = "/api/rest/provMns/{apiVersion}/tn/NSS/SliceProfiles"; + + private final static String EXTERNAL_AN_ALLOCATE_URL = "/ObjectManagement/NSS/SliceProfiles"; + + private final static String INTERNAL_ALLOCATE_URL = "/onap/so/infra/3gppservices/{apiVersion}/allocate"; + + private final static String EXTERNAL_CN_DEALLOCATE_URL = + "/api/rest/provMns/{apiVersion}/NSS/SliceProfiles/{sliceProfileId}"; + + private final static String EXTERNAL_TN_DEALLOCATE_URL = + "/api/rest/provMns/{apiVersion}/tn/NSS/SliceProfiles/{sliceProfileId}"; + + private final static String EXTERNAL_AN_DEALLOCATE_URL = "/ObjectManagement/NSS/SliceProfiles/{SliceProfileId}"; + + private final static String INTERNAL_DEALLOCATE_URL = "/onap/so/infra/3gppservices/{apiVersion}/deAllocate"; + + private final static String EXTERNAL_CN_ACTIVATE_URL = "/api/rest/provMns/{apiVersion}/NSS/{snssai}/activation"; + + private final static String EXTERNAL_TN_ACTIVATE_URL = "/api/rest/provMns/{apiVersion}/tn/NSS/{snssai}/activation"; + + private final static String EXTERNAL_AN_ACTIVATE_URL = "/api/rest/provMns/{apiVersion}/an/NSS/{snssai}/activations"; + + private final static String INTERNAL_ACTIVATE_URL = "/onap/so/infra/3gppservices/{apiVersion}/activate"; + + private final static String EXTERNAL_CN_DEACTIVATE_URL = "/api/rest/provMns/{apiVersion}/NSS/{snssai}/deactivation"; + + private final static String EXTERNAL_TN_DEACTIVATE_URL = + "/api/rest/provMns/{apiVersion}/tn/NSS/{snssai}/deactivation"; + + private final static String EXTERNAL_AN_DEACTIVATE_URL = + "/api/rest/provMns/{apiVersion}/an/NSS/{snssai}/deactivation"; + + private final static String INTERNAL_DEACTIVATE_URL = "/onap/so/infra/3gppservices/{apiVersion}/deActivate"; + + // + private final static String EXTERNAL_CN_TERMINATE_URL = + "/api/rest/provMns/{apiVersion}/NSS/SliceProfiles/{SliceProfileId}"; + + private final static String EXTERNAL_TN_TERMINATE_URL = + "/api/rest/provMns/{apiVersion}/tn/NSS/SliceProfiles/{SliceProfileId}"; + + private final static String EXTERNAL_AN_TERMINATE_URL = + "/api/rest/provMns/{apiVersion}/an/NSS/SliceProfiles/{SliceProfileId}"; + + private final static String INTERNAL_TERMINATE_URL = "/onap/so/infra/3gppservices/{apiVersion}/terminate"; + + // + private final static String EXTERNAL_AN_MODIFY_URL = + "/api/rest/provMns/{apiVersion}/an/NSS/SliceProfiles/{SliceProfileId}"; + + private final static String INTERNAL_MODIFY_URL = "/onap/so/infra/3gppservices/{apiVersion}/modify"; + + // + private final static String EXTERNAL_QUERY_JOB_STATUS = + "/api/rest/provMns/{apiVersion}/NSS/jobs/{jobId}?responseId={responseId}"; + + private final static String INTERNAL_QUERY_SUB_NET_CAPABILITY = + "/onap/so/infra/3gppservices/{apiVersion}/subnetCapabilityQuery"; + + static { + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.ALLOCATE), + new NssmfUrlInfo(EXTERNAL_AN_ALLOCATE_URL, HttpMethod.POST)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.TRANSPORT, ActionType.ALLOCATE), + new NssmfUrlInfo(EXTERNAL_TN_ALLOCATE_URL, HttpMethod.POST)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.ALLOCATE), + new NssmfUrlInfo(EXTERNAL_CN_ALLOCATE_URL, HttpMethod.POST)); + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.ALLOCATE), + new NssmfUrlInfo(INTERNAL_ALLOCATE_URL, HttpMethod.POST)); + + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.DEALLOCATE), + new NssmfUrlInfo(EXTERNAL_AN_DEALLOCATE_URL, HttpMethod.DELETE)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.TRANSPORT, ActionType.DEALLOCATE), + new NssmfUrlInfo(EXTERNAL_TN_DEALLOCATE_URL, HttpMethod.DELETE)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.DEALLOCATE), + new NssmfUrlInfo(EXTERNAL_CN_DEALLOCATE_URL, HttpMethod.DELETE)); + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.DEALLOCATE), + new NssmfUrlInfo(INTERNAL_DEALLOCATE_URL, HttpMethod.DELETE)); + + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.ACTIVATE), + new NssmfUrlInfo(EXTERNAL_AN_ACTIVATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.TRANSPORT, ActionType.ACTIVATE), + new NssmfUrlInfo(EXTERNAL_TN_ACTIVATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.ACTIVATE), + new NssmfUrlInfo(EXTERNAL_CN_ACTIVATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.ACTIVATE), + new NssmfUrlInfo(INTERNAL_ACTIVATE_URL, HttpMethod.PUT)); + + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.DEACTIVATE), + new NssmfUrlInfo(EXTERNAL_AN_DEACTIVATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.TRANSPORT, ActionType.DEACTIVATE), + new NssmfUrlInfo(EXTERNAL_TN_DEACTIVATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.DEACTIVATE), + new NssmfUrlInfo(EXTERNAL_CN_DEACTIVATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.DEACTIVATE), + new NssmfUrlInfo(INTERNAL_DEACTIVATE_URL, HttpMethod.PUT)); + + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.TERMINATE), + new NssmfUrlInfo(EXTERNAL_AN_TERMINATE_URL, HttpMethod.DELETE)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.TRANSPORT, ActionType.TERMINATE), + new NssmfUrlInfo(EXTERNAL_TN_TERMINATE_URL, HttpMethod.DELETE)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.TERMINATE), + new NssmfUrlInfo(EXTERNAL_CN_TERMINATE_URL, HttpMethod.DELETE)); + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.TERMINATE), + new NssmfUrlInfo(INTERNAL_TERMINATE_URL, HttpMethod.DELETE)); + + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.MODIFY), + new NssmfUrlInfo(EXTERNAL_AN_MODIFY_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.MODIFY), + new NssmfUrlInfo(EXTERNAL_CN_ALLOCATE_URL, HttpMethod.PUT)); + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.MODIFY), + new NssmfUrlInfo(INTERNAL_MODIFY_URL, HttpMethod.PUT)); + + + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.CORE, ActionType.QUERY_JOB_STATUS), + new NssmfUrlInfo(EXTERNAL_QUERY_JOB_STATUS, HttpMethod.GET)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.ACCESS, ActionType.QUERY_JOB_STATUS), + new NssmfUrlInfo(EXTERNAL_QUERY_JOB_STATUS, HttpMethod.GET)); + urlInfoMap.put(generateKey(ExecutorType.EXTERNAL, NetworkType.TRANSPORT, ActionType.QUERY_JOB_STATUS), + new NssmfUrlInfo(EXTERNAL_QUERY_JOB_STATUS, HttpMethod.GET)); + + urlInfoMap.put(generateKey(ExecutorType.INTERNAL, null, ActionType.QUERY_SUB_NET_CAPABILITY), + new NssmfUrlInfo(INTERNAL_QUERY_SUB_NET_CAPABILITY, HttpMethod.POST)); + } + + /** + * get nssmf url info from consts + * + * @param executorType {@link ExecutorType} + * @param networkType {@link NetworkType} + * @param actionType {@link ActionType} + * @return {@link NssmfUrlInfo} + */ + public static NssmfUrlInfo getNssmfUrlInfo(ExecutorType executorType, NetworkType networkType, + ActionType actionType) { + + return urlInfoMap.get(generateKey(executorType, networkType, actionType)); + } + + private static String generateKey(ExecutorType executorType, NetworkType networkType, ActionType actionType) { + if (ExecutorType.EXTERNAL.equals(executorType)) { + return executorType.name() + "_" + networkType.name() + "_" + actionType.name(); + } + return executorType.name() + "_" + actionType.name(); + } + + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/controller/NssmfAdapterController.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/controller/NssmfAdapterController.java new file mode 100644 index 0000000000..5360657f4f --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/controller/NssmfAdapterController.java @@ -0,0 +1,61 @@ +package org.onap.so.adapters.nssmf.controller; + +import org.onap.so.adapters.nssmf.service.NssmfManagerService; +import org.onap.so.beans.nsmf.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; + +@RestController +@RequestMapping(value = "/api/rest/provMns/v1", produces = {APPLICATION_JSON}, consumes = {APPLICATION_JSON}) +public class NssmfAdapterController { + + private static final Logger logger = LoggerFactory.getLogger(NssmfAdapterController.class); + + @Autowired + private NssmfManagerService nssmfManagerService; + + @PostMapping(value = "/NSS/SliceProfiles") + public ResponseEntity allocateNssi(@RequestBody NssmfAdapterNBIRequest nbiRequest) { + return nssmfManagerService.allocateNssi(nbiRequest); + } + + @PostMapping(value = "/NSS/SliceProfiles/{sliceProfileId}") + public ResponseEntity deAllocateNssi(@RequestBody NssmfAdapterNBIRequest nbiRequest, + @PathVariable("sliceProfileId") final String sliceProfileId) { + return nssmfManagerService.deAllocateNssi(nbiRequest, sliceProfileId); + } + + + @PostMapping(value = "/NSS/{snssai}/activation") + public ResponseEntity activateNssi(@RequestBody NssmfAdapterNBIRequest nbiRequest, + @PathVariable("snssai") String snssai) { + return nssmfManagerService.activateNssi(nbiRequest, snssai); + } + + @PostMapping(value = "/NSS/{snssai}/deactivation") + public ResponseEntity deactivateNssi(@RequestBody NssmfAdapterNBIRequest nbiRequest, + @PathVariable("snssai") String snssai) { + return nssmfManagerService.deActivateNssi(nbiRequest, snssai); + } + + @PostMapping(value = "/NSS/jobs/{jobId}") + public ResponseEntity queryJobStatus(@RequestBody NssmfAdapterNBIRequest nbiRequest, + @PathVariable("jobId") String jobId) { + return nssmfManagerService.queryJobStatus(nbiRequest, jobId); + } + + @PostMapping(value = "/NSS/NSSISelectionCapability") + public ResponseEntity queryNSSISelectionCapability(@RequestBody NssmfAdapterNBIRequest nbiRequest) { + return nssmfManagerService.queryNSSISelectionCapability(nbiRequest); + } + + @PostMapping(value = "/NSS/subnetCapabilityQuery") + public ResponseEntity querySubnetCapability(@RequestBody NssmfAdapterNBIRequest nbiRequest) { + return nssmfManagerService.querySubnetCapability(nbiRequest); + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/ErrorResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/ErrorResponse.java new file mode 100644 index 0000000000..a8653f8d73 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/ErrorResponse.java @@ -0,0 +1,63 @@ +/*- + * ============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.nssmf.entity; + +public class ErrorResponse { + + private int status; + + private String error; + + private String message; + + public ErrorResponse(int status, String message) { + this.status = status; + this.message = message; + this.error = "Bad Request"; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getError() { + if (status == 500) { + this.error = "Internal Server Error"; + } + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/NssmfInfo.java index 6306643a97..af26264074 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/NssmfInfo.java @@ -18,8 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.rest; +package org.onap.so.adapters.nssmf.entity; +import lombok.Data; + +@Data public class NssmfInfo { private String url; @@ -35,60 +38,4 @@ public class NssmfInfo { private String userName; private String password; - - public String getInsecure() { - return insecure; - } - - public void setInsecure(String insecure) { - this.insecure = insecure; - } - - public String getCacert() { - return cacert; - } - - public void setCacert(String cacert) { - this.cacert = cacert; - } - - public String getIpAddress() { - return ipAddress; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } - - public String getPort() { - return port; - } - - public void setPort(String port) { - this.port = port; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/NssmfUrlInfo.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/NssmfUrlInfo.java new file mode 100644 index 0000000000..f55ff10f1c --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/NssmfUrlInfo.java @@ -0,0 +1,17 @@ +package org.onap.so.adapters.nssmf.entity; + +import lombok.Data; +import org.onap.so.adapters.nssmf.enums.HttpMethod; + +@Data +public class NssmfUrlInfo { + + private String url; + + private HttpMethod httpMethod; + + public NssmfUrlInfo(String url, HttpMethod httpMethod) { + this.url = url; + this.httpMethod = httpMethod; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/RestResponse.java index cc047e45c7..218867c1ab 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/RestResponse.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.rest; +package org.onap.so.adapters.nssmf.entity; import java.util.Map; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenRequest.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/TokenRequest.java index 3590c683e6..bfcb875290 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenRequest.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/TokenRequest.java @@ -18,8 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.model; +package org.onap.so.adapters.nssmf.entity; +import lombok.Data; + +@Data public class TokenRequest { private String grantType; @@ -27,28 +30,4 @@ public class TokenRequest { private String userName; private String value; - - public String getGrantType() { - return grantType; - } - - public void setGrantType(String grantType) { - this.grantType = grantType; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/TokenResponse.java index 8007075e04..552612a6fb 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenResponse.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/entity/TokenResponse.java @@ -18,27 +18,15 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.model; +package org.onap.so.adapters.nssmf.entity; + +import lombok.Data; + +@Data public class TokenResponse { private String accessToken; private int expires; - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public int getExpires() { - return expires; - } - - public void setExpires(int expires) { - this.expires = expires; - } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java new file mode 100644 index 0000000000..ed327fd981 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.enums; + +public enum ActionType { + ALLOCATE, + + DEALLOCATE, + + CREATE, + + TERMINATE, + + ACTIVATE, + + DEACTIVATE, + + QUERY_JOB_STATUS, + + MODIFY_BY_ID, + + MODIFY, + + QUERY_NSSI_SELECTION_CAPABILITY, + + QUERY_SUB_NET_CAPABILITY +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ExecutorType.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ExecutorType.java new file mode 100644 index 0000000000..a76a54c348 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ExecutorType.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.enums; + +public enum ExecutorType { + INTERNAL, EXTERNAL +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/HttpMethod.java index f6abd98794..9271bb50b3 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/HttpMethod.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.rest; +package org.onap.so.adapters.nssmf.enums; public enum HttpMethod { GET, POST, PUT, DELETE, PATCH; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/JobStatus.java index f2e651fd6e..d5cc1df377 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/JobStatus.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.rest; +package org.onap.so.adapters.nssmf.enums; import org.onap.so.adapters.nssmf.exceptions.ApplicationException; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/SelectionType.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/SelectionType.java new file mode 100644 index 0000000000..420dfdce49 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/SelectionType.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.enums; + +public enum SelectionType { + NSSMF, + + NSMF +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java index f63ba356a1..2461f5ca78 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java @@ -20,7 +20,7 @@ package org.onap.so.adapters.nssmf.exceptions; -import org.onap.so.adapters.nssmf.model.ErrorResponse; +import org.onap.so.adapters.nssmf.entity.ErrorResponse; import org.springframework.http.ResponseEntity; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java index c737ba6440..665b111e03 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java @@ -22,6 +22,7 @@ package org.onap.so.adapters.nssmf.extclients.aai; import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.EsrThirdpartySdncList; +import org.onap.aai.domain.yang.ServiceInstance; public interface AaiServiceProvider { @@ -29,4 +30,7 @@ public interface AaiServiceProvider { EsrSystemInfoList invokeGetThirdPartySdncEsrSystemInfo(String sdncId); + void invokeCreateServiceInstance(ServiceInstance nssiInstance, String globalSubscriberId, String serviceType, + String serviceInstanceId); + } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java index 8cb47ebf38..3f2e5b23f2 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java @@ -23,7 +23,9 @@ package org.onap.so.adapters.nssmf.extclients.aai; import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.EsrThirdpartySdncList; +import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,4 +65,12 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { }); } + + @Override + public void invokeCreateServiceInstance(ServiceInstance nssiInstance, String globalSubscriberId, String serviceType, + String serviceInstanceId) { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, + serviceType, serviceInstanceId); + aaiClientProvider.getAaiClient().create(uri, nssiInstance); + } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/NssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/NssmfManager.java new file mode 100644 index 0000000000..54ef1e09dd --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/NssmfManager.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.beans.nsmf.*; + +public interface NssmfManager { + + RestResponse allocateNssi(NssmfAdapterNBIRequest nssmfRequest) throws ApplicationException; + + RestResponse deAllocateNssi(NssmfAdapterNBIRequest nssmfRequest, String sliceId) throws ApplicationException; + + RestResponse activateNssi(NssmfAdapterNBIRequest nssmfRequest, String snssai) throws ApplicationException; + + RestResponse deActivateNssi(NssmfAdapterNBIRequest nssmfRequest, String snssai) throws ApplicationException; + + RestResponse queryJobStatus(NssmfAdapterNBIRequest jobReq, String jobId) throws ApplicationException; + + RestResponse queryNSSISelectionCapability(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + RestResponse querySubnetCapability(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + RestResponse modifyNssi(NssmfAdapterNBIRequest modifyRequest) throws ApplicationException; +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/NssmfManagerBuilder.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/NssmfManagerBuilder.java new file mode 100644 index 0000000000..0b332af607 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/NssmfManagerBuilder.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager; + +import org.onap.so.adapters.nssmf.config.NssmfAdapterConfig; +import org.onap.so.adapters.nssmf.consts.NssmfAdapterConsts; +import org.onap.so.adapters.nssmf.enums.ActionType; +import org.onap.so.adapters.nssmf.enums.ExecutorType; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.impl.external.ExternalAnNssmfManager; +import org.onap.so.adapters.nssmf.manager.impl.external.ExternalCnNssmfManager; +import org.onap.so.adapters.nssmf.manager.impl.internal.InternalAnNssmfManager; +import org.onap.so.adapters.nssmf.manager.impl.internal.InternalCnNssmfManager; +import org.onap.so.adapters.nssmf.manager.impl.internal.InternalTnNssmfManager; +import org.onap.so.adapters.nssmf.manager.impl.*; +import org.onap.so.adapters.nssmf.util.RestUtil; +import org.onap.so.beans.nsmf.EsrInfo; +import org.onap.so.beans.nsmf.NetworkType; +import org.onap.so.beans.nsmf.ServiceInfo; +import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; + +public class NssmfManagerBuilder { + + private BaseNssmfManager nssmfManger; + + private RestUtil restUtil; + + private ActionType actionType; + + private ResourceOperationStatusRepository repository; + + private ServiceInfo serviceInfo; + + private NssmfAdapterConfig adapterConfig; + + public NssmfManagerBuilder(EsrInfo esrInfo) throws ApplicationException { + + ExecutorType executorType = getExecutorType(esrInfo); + NetworkType networkType = esrInfo.getNetworkType(); + + if (ExecutorType.INTERNAL.equals(executorType) && NetworkType.CORE.equals(networkType)) { + this.nssmfManger = new InternalCnNssmfManager().setEsrInfo(esrInfo).setExecutorType(executorType); + return; + } + + if (ExecutorType.INTERNAL.equals(executorType) && NetworkType.TRANSPORT.equals(networkType)) { + this.nssmfManger = new InternalTnNssmfManager().setEsrInfo(esrInfo).setExecutorType(executorType); + return; + } + + if (ExecutorType.INTERNAL.equals(executorType) && NetworkType.ACCESS.equals(networkType)) { + this.nssmfManger = new InternalAnNssmfManager().setEsrInfo(esrInfo).setExecutorType(executorType); + return; + } + + if (ExecutorType.EXTERNAL.equals(executorType) && NetworkType.CORE.equals(networkType)) { + this.nssmfManger = new ExternalCnNssmfManager().setEsrInfo(esrInfo).setExecutorType(executorType) + .setInitStatus("deactivated"); + return; + } + + if (ExecutorType.EXTERNAL.equals(executorType) && NetworkType.ACCESS.equals(networkType)) { + this.nssmfManger = new ExternalAnNssmfManager().setEsrInfo(esrInfo).setExecutorType(executorType) + .setInitStatus("activated"); + return; + } + + throw new ApplicationException(404, "invalid domain and simulator"); + } + + private ExecutorType getExecutorType(EsrInfo esrInfo) { + if (NssmfAdapterConsts.ONAP_INTERNAL_TAG.equals(esrInfo.getVendor())) { + return ExecutorType.INTERNAL; + } + return ExecutorType.EXTERNAL; + } + + public NssmfManagerBuilder setRestUtil(RestUtil restUtil) { + this.restUtil = restUtil; + return this; + } + + public NssmfManagerBuilder setActionType(ActionType actionType) { + this.actionType = actionType; + return this; + } + + public NssmfManagerBuilder setRepository(ResourceOperationStatusRepository repository) { + this.repository = repository; + return this; + } + + public NssmfManagerBuilder setServiceInfo(ServiceInfo serviceInfo) { + this.serviceInfo = serviceInfo; + return this; + } + + public NssmfManagerBuilder setAdapterConfig(NssmfAdapterConfig adapterConfig) { + this.adapterConfig = adapterConfig; + return this; + } + + public NssmfManager build() { + return this.nssmfManger.setRestUtil(restUtil).setAdapterConfig(adapterConfig).setRepository(repository) + .setActionType(actionType).setServiceInfo(serviceInfo); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/BaseNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/BaseNssmfManager.java new file mode 100644 index 0000000000..185dfaff34 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/BaseNssmfManager.java @@ -0,0 +1,273 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl; + +import org.onap.so.adapters.nssmf.config.NssmfAdapterConfig; +import org.onap.so.adapters.nssmf.consts.NssmfAdapterConsts; +import org.onap.so.adapters.nssmf.entity.NssmfUrlInfo; +import org.onap.so.adapters.nssmf.enums.*; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.adapters.nssmf.manager.NssmfManager; +import org.onap.so.adapters.nssmf.util.RestUtil; +import org.onap.so.beans.nsmf.*; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Example; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ALLOCATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.MODIFY_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public abstract class BaseNssmfManager implements NssmfManager { + + private static final Logger logger = LoggerFactory.getLogger(BaseNssmfManager.class); + + protected RestUtil restUtil; + + protected ResourceOperationStatusRepository repository; + + protected NssmfAdapterConfig adapterConfig; + + protected ActionType actionType; + + protected EsrInfo esrInfo; + + protected String nssmfUrl; + + protected HttpMethod httpMethod; + + protected String initStatus; + + protected ServiceInfo serviceInfo; + + protected RestResponse restResponse; + + private ExecutorType executorType = ExecutorType.INTERNAL; + + private Map<String, String> params = new HashMap<>(); // request params + + @Override + public RestResponse allocateNssi(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + + this.params.clear(); + this.urlHandler(); + String requestBody = wrapAllocateReqBody(nbiRequest); + + this.restResponse = sendRequest(requestBody); + + this.afterRequest(); + + return restResponse; + } + + protected abstract String wrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + @Override + public RestResponse modifyNssi(NssmfAdapterNBIRequest modifyRequest) throws ApplicationException { + this.params.clear(); + this.urlHandler(); + String requestBody = wrapModifyReqBody(modifyRequest); + + this.restResponse = sendRequest(requestBody); + + this.afterRequest(); + + return restResponse; + } + + protected abstract String wrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + @Override + public RestResponse deAllocateNssi(NssmfAdapterNBIRequest nbiRequest, String sliceId) throws ApplicationException { + this.params.clear(); + this.params.put("sliceProfileId", sliceId); + + this.urlHandler(); + + String reqBody = wrapDeAllocateReqBody(nbiRequest.getDeAllocateNssi()); + + this.restResponse = sendRequest(reqBody); + + this.afterRequest(); + + return restResponse; + } + + protected abstract String wrapDeAllocateReqBody(DeAllocateNssi deAllocateNssi) throws ApplicationException; + + protected abstract String wrapReqBody(Object object) throws ApplicationException; + + @Override + public RestResponse activateNssi(NssmfAdapterNBIRequest nbiRequest, String snssai) throws ApplicationException { + this.params.clear(); + this.params.put("snssai", snssai); + + this.urlHandler(); + + String reqBody = wrapActDeActReqBody(nbiRequest.getActDeActNssi()); + + this.restResponse = sendRequest(reqBody); + + this.afterRequest(); + + return restResponse; + } + + @Override + public RestResponse deActivateNssi(NssmfAdapterNBIRequest nbiRequest, String snssai) throws ApplicationException { + return activateNssi(nbiRequest, snssai); + } + + protected abstract String wrapActDeActReqBody(ActDeActNssi actDeActNssi) throws ApplicationException; + + @Override + public RestResponse queryJobStatus(NssmfAdapterNBIRequest jobReq, String jobId) throws ApplicationException { + this.params.clear(); + this.params.put("jobId", jobId); + this.params.put("responseId", jobReq.getResponseId()); + this.urlHandler(); + + /** + * find by jobId and nsiId jobId -> OperationId nsiId -> ServiceId serviceUuid -> resourceTemplateUUID + */ + ResourceOperationStatus status = + getOperationStatus(serviceInfo.getNsiId(), jobId, serviceInfo.getServiceUuid()); + + this.restResponse = doQueryJobStatus(status); + + afterQueryJobStatus(status); + return restResponse; + } + + protected abstract RestResponse doQueryJobStatus(ResourceOperationStatus status) throws ApplicationException; + + + protected abstract void afterQueryJobStatus(ResourceOperationStatus status); + + private ResourceOperationStatus getOperationStatus(String nsiId, String jobId, String serviceUuid) { + + ResourceOperationStatus status = new ResourceOperationStatus(nsiId, jobId, serviceUuid); + + Optional<ResourceOperationStatus> optional = repository.findOne(Example.of(status)); + + return optional.orElse(null); + } + + @Override + public RestResponse queryNSSISelectionCapability(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + SelectionType res = doQueryNSSISelectionCapability(); + HashMap<String, String> hashMap = new HashMap<>(); + hashMap.put("selection", res.name()); + RestResponse restResponse = new RestResponse(); + restResponse.setStatus(200); + restResponse.setResponseContent(marshal(hashMap)); + return restResponse; + } + + protected abstract SelectionType doQueryNSSISelectionCapability(); + + @Override + public RestResponse querySubnetCapability(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + this.params.clear(); + this.urlHandler(); + + return doQuerySubnetCapability(nbiRequest.getSubnetCapabilityQuery()); + } + + protected abstract RestResponse doQuerySubnetCapability(String req) throws ApplicationException; + + /** + * send request to nssmf + * + * @param content request body + * @return response + * @throws ApplicationException + */ + protected abstract RestResponse sendRequest(String content) throws ApplicationException; + + /** + * handle the url before request to nssmf, include get the nssmf request url, replace the path variable + */ + private void urlHandler() { + NssmfUrlInfo nssmfUrlInfo = + NssmfAdapterConsts.getNssmfUrlInfo(this.executorType, this.esrInfo.getNetworkType(), actionType); + this.nssmfUrl = nssmfUrlInfo.getUrl(); + this.httpMethod = nssmfUrlInfo.getHttpMethod(); + this.nssmfUrl = nssmfUrl.replaceAll("\\{apiVersion}", getApiVersion()); + this.params.forEach((k, v) -> this.nssmfUrl = this.nssmfUrl.replaceAll("\\{" + k + "}", v)); + } + + /** + * after request + */ + protected abstract void afterRequest() throws ApplicationException; + + protected abstract String getApiVersion(); + + public RestUtil getRestUtil() { + return restUtil; + } + + public BaseNssmfManager setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + return this; + } + + public BaseNssmfManager setExecutorType(ExecutorType executorType) { + this.executorType = executorType; + return this; + } + + public BaseNssmfManager setRestUtil(RestUtil restUtil) { + this.restUtil = restUtil; + return this; + } + + public BaseNssmfManager setActionType(ActionType actionType) { + this.actionType = actionType; + return this; + } + + public BaseNssmfManager setRepository(ResourceOperationStatusRepository repository) { + this.repository = repository; + return this; + } + + public BaseNssmfManager setServiceInfo(ServiceInfo serviceInfo) { + this.serviceInfo = serviceInfo; + return this; + } + + public BaseNssmfManager setInitStatus(String initStatus) { + this.initStatus = initStatus; + return this; + } + + public BaseNssmfManager setAdapterConfig(NssmfAdapterConfig adapterConfig) { + this.adapterConfig = adapterConfig; + return this; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java new file mode 100644 index 0000000000..f6584da931 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl; + +import org.apache.http.Header; +import org.apache.http.message.BasicHeader; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.so.adapters.nssmf.entity.NssmfInfo; +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.adapters.nssmf.enums.JobStatus; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.util.NssmfAdapterUtil; +import org.onap.so.beans.nsmf.*; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import static java.lang.String.valueOf; +import static org.onap.so.adapters.nssmf.enums.JobStatus.*; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.*; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; + +public abstract class ExternalNssmfManager extends BaseNssmfManager { + + private static final Logger logger = LoggerFactory.getLogger(ExternalNssmfManager.class); + + @Override + protected String wrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return doWrapExtAllocateReqBody(nbiRequest); + } + + protected abstract String doWrapExtAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + @Override + protected String wrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return doWrapModifyReqBody(nbiRequest); + } + + protected abstract String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + @Override + protected String wrapDeAllocateReqBody(DeAllocateNssi deAllocateNssi) throws ApplicationException { + return doWrapDeAllocateReqBody(deAllocateNssi); + } + + protected abstract String doWrapDeAllocateReqBody(DeAllocateNssi deAllocateNssi) throws ApplicationException; + + @Override + protected void afterQueryJobStatus(ResourceOperationStatus status) { + if (Integer.parseInt(status.getProgress()) == 100) { + + ServiceInstance nssiInstance = new ServiceInstance(); + nssiInstance.setServiceInstanceId(serviceInfo.getNssiId()); + nssiInstance.setServiceInstanceName(serviceInfo.getNssiName()); + nssiInstance.setServiceType(serviceInfo.getSST()); + + nssiInstance.setOrchestrationStatus(initStatus); + nssiInstance.setModelInvariantId(serviceInfo.getServiceInvariantUuid()); + nssiInstance.setModelVersionId(serviceInfo.getServiceUuid()); + nssiInstance.setServiceInstanceLocationId(serviceInfo.getPLMNIdList()); + nssiInstance.setEnvironmentContext(esrInfo.getNetworkType().getNetworkType()); + nssiInstance.setServiceRole("nssi"); + + restUtil.createServiceInstance(nssiInstance, serviceInfo); + } + } + + + + @Override + protected String wrapActDeActReqBody(ActDeActNssi actDeActNssi) throws ApplicationException { + return marshal(actDeActNssi); + } + + protected RestResponse doQueryJobStatus(ResourceOperationStatus status) throws ApplicationException { + return doResponseStatus(status); + } + + private RestResponse doResponseStatus(ResourceOperationStatus status) throws ApplicationException { + RestResponse restResponse = sendRequest(null); + ResponseDescriptor rspDesc = + unMarshal(restResponse.getResponseContent(), JobStatusResponse.class).getResponseDescriptor(); + updateRequestDbJobStatus(rspDesc, status, restResponse); + return restResponse; + } + + @Override + protected String wrapReqBody(Object object) throws ApplicationException { + return marshal(object); + } + + @Override + protected RestResponse sendRequest(String content) throws ApplicationException { + return sendExternalRequest(content); + } + + protected void createStatus(JobStatus jobStatus) throws ApplicationException { + if (valueOf(restResponse.getStatus()).startsWith("2")) { + logger.info("save segment and operaton info -> begin"); + NssiResponse response = unMarshal(restResponse.getResponseContent(), NssiResponse.class); + ResourceOperationStatus status = new ResourceOperationStatus(serviceInfo.getNsiId(), response.getJobId(), + serviceInfo.getServiceUuid()); + status.setResourceInstanceID(response.getNssiId()); + + updateDbStatus(status, restResponse.getStatus(), jobStatus, NssmfAdapterUtil.getStatusDesc(actionType)); + logger.info("save segment and operaton info -> end"); + } + } + + @Override + protected String getApiVersion() { + return "v1"; + } + + + // external + protected RestResponse sendExternalRequest(String content) throws ApplicationException { + NssmfInfo nssmfInfo = restUtil.getNssmfHost(esrInfo); + Header header = new BasicHeader("X-Auth-Token", restUtil.getToken(nssmfInfo)); + String nssmfUrl = nssmfInfo.getUrl() + this.nssmfUrl; + return restUtil.send(nssmfUrl, this.httpMethod, content, header); + } + + private void updateRequestDbJobStatus(ResponseDescriptor rspDesc, ResourceOperationStatus status, RestResponse rsp) + throws ApplicationException { + + switch (fromString(rspDesc.getStatus())) { + case STARTED: + updateDbStatus(status, rsp.getStatus(), STARTED, QUERY_JOB_STATUS_SUCCESS); + break; + case PROCESSING: + updateDbStatus(status, rsp.getStatus(), PROCESSING, QUERY_JOB_STATUS_SUCCESS); + break; + case FINISHED: + if (rspDesc.getProgress() == 100) { + updateDbStatus(status, rsp.getStatus(), FINISHED, QUERY_JOB_STATUS_SUCCESS); + } + break; + case ERROR: + updateDbStatus(status, rsp.getStatus(), ERROR, QUERY_JOB_STATUS_FAILED); + throw new ApplicationException(500, QUERY_JOB_STATUS_FAILED); + } + } + + protected void updateDbStatus(ResourceOperationStatus status, int rspStatus, JobStatus jobStatus, + String description) { + status.setErrorCode(valueOf(rspStatus)); + status.setStatus(jobStatus.toString()); + status.setStatusDescription(description); + logger.info("Updating DB status"); + repository.save(status); + logger.info("Updating successful"); + } + + @Override + protected RestResponse doQuerySubnetCapability(String req) throws ApplicationException { + RestResponse response = new RestResponse(); + response.setStatus(200); + response.setResponseContent(null); + return response; + } + + /** + * after request, if response code is 2XX, continue handle, else return + */ + @Override + protected void afterRequest() throws ApplicationException { + if (valueOf(restResponse.getStatus()).startsWith("2")) { + doAfterRequest(); + } + } + + + protected void doAfterRequest() throws ApplicationException { + // + NssiResponse response = unMarshal(restResponse.getResponseContent(), NssiResponse.class); + ResourceOperationStatus status = + new ResourceOperationStatus(serviceInfo.getNsiId(), response.getJobId(), serviceInfo.getServiceUuid()); + status.setResourceInstanceID(response.getNssiId()); + + updateDbStatus(status, restResponse.getStatus(), STARTED, NssmfAdapterUtil.getStatusDesc(actionType)); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java new file mode 100644 index 0000000000..a945823f99 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl; + +import org.apache.http.Header; +import org.apache.http.message.BasicHeader; +import org.onap.so.adapters.nssmf.consts.NssmfAdapterConsts; +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.adapters.nssmf.enums.JobStatus; +import org.onap.so.adapters.nssmf.enums.SelectionType; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.beans.nsmf.*; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import static org.onap.so.adapters.nssmf.enums.JobStatus.PROCESSING; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public abstract class InternalNssmfManager extends BaseNssmfManager { + + private static final Logger logger = LoggerFactory.getLogger(InternalNssmfManager.class); + + @Override + protected String wrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return doWrapAllocateReqBody(nbiRequest); + } + + protected abstract String doWrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + @Override + protected String wrapReqBody(Object object) throws ApplicationException { + NssmfRequest nssmfRequest = new NssmfRequest(serviceInfo, esrInfo.getNetworkType(), object); + return marshal(nssmfRequest); + } + + + @Override + protected String wrapActDeActReqBody(ActDeActNssi actDeActNssi) throws ApplicationException { + + return wrapReqBody(actDeActNssi); + } + + + @Override + protected String wrapDeAllocateReqBody(DeAllocateNssi deAllocateNssi) throws ApplicationException { + return wrapReqBody(deAllocateNssi); + } + + + @Override + protected RestResponse doQueryJobStatus(ResourceOperationStatus status) throws ApplicationException { + return responseDBStatus(status); + } + + private RestResponse responseDBStatus(ResourceOperationStatus status) throws ApplicationException { + ResponseDescriptor descriptor = new ResponseDescriptor(); + if (status == null) { + descriptor.setProgress(0); + descriptor.setStatus(PROCESSING.name()); + descriptor.setStatusDescription("Initiating Nssi Instance"); + return restUtil.createResponse(200, marshal(descriptor)); + } + descriptor.setStatus(status.getStatus()); + descriptor.setStatusDescription(status.getStatusDescription()); + descriptor.setProgress(Integer.parseInt(status.getProgress())); + // descriptor.setResponseId(status.getOperationId()); + return restUtil.createResponse(200, marshal(descriptor)); + } + + @Override + protected RestResponse sendRequest(String content) { + return sendInternalRequest(content); + } + + @Override + protected void afterRequest() { + // + } + + @Override + protected void afterQueryJobStatus(ResourceOperationStatus status) { + // internal + } + + // internal + private RestResponse sendInternalRequest(String content) { + Header header = new BasicHeader("X-Auth-Token", adapterConfig.getInfraAuth()); + this.nssmfUrl = adapterConfig.getInfraEndpoint() + this.nssmfUrl; + return restUtil.send(this.nssmfUrl, this.httpMethod, content, header); + } + + @Override + protected String getApiVersion() { + return NssmfAdapterConsts.CURRENT_INTERNAL_NSSMF_API_VERSION; + } + + + @Override + protected SelectionType doQueryNSSISelectionCapability() { + return SelectionType.NSSMF; + } + + @Override + protected String wrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return doWrapModifyReqBody(nbiRequest); + } + + protected abstract String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException; + + @Override + protected RestResponse doQuerySubnetCapability(String req) throws ApplicationException { + // handler + return sendRequest(req); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/external/ExternalAnNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/external/ExternalAnNssmfManager.java new file mode 100644 index 0000000000..e244a85a6c --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/external/ExternalAnNssmfManager.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl.external; + +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.adapters.nssmf.enums.ActionType; +import org.onap.so.adapters.nssmf.enums.JobStatus; +import org.onap.so.adapters.nssmf.enums.SelectionType; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.impl.ExternalNssmfManager; +import org.onap.so.adapters.nssmf.util.NssmfAdapterUtil; +import org.onap.so.beans.nsmf.DeAllocateNssi; +import org.onap.so.beans.nsmf.NssiResponse; +import org.onap.so.beans.nsmf.NssmfAdapterNBIRequest; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.Map; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; + + +public class ExternalAnNssmfManager extends ExternalNssmfManager { + + private static final Logger logger = LoggerFactory.getLogger(ExternalAnNssmfManager.class); + + @Override + protected String doWrapExtAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return marshal(nbiRequest.getAllocateAnNssi().getSliceProfile()); + } + + @Override + protected void doAfterRequest() throws ApplicationException { + if (ActionType.ALLOCATE.equals(actionType) || ActionType.DEALLOCATE.equals(actionType)) { + @SuppressWarnings("unchecked") + Map<String, String> response = unMarshal(restResponse.getResponseContent(), Map.class); + + String nssiId = response.get("nSSId"); + + NssiResponse resp = new NssiResponse(); + resp.setJobId(nssiId); + resp.setNssiId(nssiId); + + RestResponse returnRsp = new RestResponse(); + + returnRsp.setStatus(202); + returnRsp.setResponseContent(marshal(resp)); + restResponse = returnRsp; + + ResourceOperationStatus status = + new ResourceOperationStatus(serviceInfo.getNsiId(), nssiId, serviceInfo.getServiceUuid()); + status.setResourceInstanceID(nssiId); + + updateDbStatus(status, restResponse.getStatus(), JobStatus.FINISHED, + NssmfAdapterUtil.getStatusDesc(actionType)); + } + // todo + } + + @Override + protected String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + // TODO + return null; + } + + @Override + protected String doWrapDeAllocateReqBody(DeAllocateNssi deAllocateNssi) throws ApplicationException { + Map<String, String> request = new HashMap<>(); + request.put("nSSId", deAllocateNssi.getNssiId()); + return marshal(request); + } + + + @Override + public RestResponse modifyNssi(NssmfAdapterNBIRequest modifyRequest) throws ApplicationException { + // TODO + return null; + } + + @Override + public RestResponse activateNssi(NssmfAdapterNBIRequest nbiRequest, String snssai) throws ApplicationException { + // TODO + return null; + } + + @Override + protected SelectionType doQueryNSSISelectionCapability() { + return SelectionType.NSSMF; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/external/ExternalCnNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/external/ExternalCnNssmfManager.java new file mode 100644 index 0000000000..fb76adcce6 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/external/ExternalCnNssmfManager.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl.external; + +import org.onap.so.adapters.nssmf.enums.SelectionType; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.impl.ExternalNssmfManager; +import org.onap.so.beans.nsmf.DeAllocateNssi; +import org.onap.so.beans.nsmf.NssmfAdapterNBIRequest; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public class ExternalCnNssmfManager extends ExternalNssmfManager { + + @Override + protected String doWrapExtAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return marshal(nbiRequest.getAllocateCnNssi()); + } + + @Override + protected String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + return marshal(nbiRequest.getAllocateCnNssi()); + } + + @Override + protected String doWrapDeAllocateReqBody(DeAllocateNssi deAllocateNssi) throws ApplicationException { + return marshal(deAllocateNssi); + } + + @Override + protected SelectionType doQueryNSSISelectionCapability() { + + return SelectionType.NSMF; + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalAnNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalAnNssmfManager.java new file mode 100644 index 0000000000..dc6528381b --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalAnNssmfManager.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl.internal; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.impl.InternalNssmfManager; +import org.onap.so.beans.nsmf.*; +import java.util.HashMap; +import java.util.Map; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + + +public class InternalAnNssmfManager extends InternalNssmfManager { + + @Override + protected String doWrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + NssmfRequest request = + new NssmfRequest(serviceInfo, nbiRequest.getEsrInfo().getNetworkType(), nbiRequest.getAllocateAnNssi()); + request.setName(nbiRequest.getAllocateAnNssi().getNssiName()); + return marshal(request); + } + + @Override + protected String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + AllocateAnNssi allocateAnNssi = nbiRequest.getAllocateAnNssi(); + AnSliceProfile sliceProfile = allocateAnNssi.getSliceProfile(); + Map<String, Object> additional = new HashMap<>(); + additional.put("modifyAction", "allocate"); + additional.put("snssaiList", sliceProfile.getSNSSAIList()); + additional.put("sliceProfileId", sliceProfile.getSliceProfileId()); + additional.put("nsiInfo", allocateAnNssi.getNsiInfo()); + additional.put("scriptName", allocateAnNssi.getScriptName()); + NssmfRequest request = new NssmfRequest(serviceInfo, esrInfo.getNetworkType(), additional); + return marshal(request); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalCnNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalCnNssmfManager.java new file mode 100644 index 0000000000..4a93b3007c --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalCnNssmfManager.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl.internal; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.impl.InternalNssmfManager; +import org.onap.so.beans.nsmf.*; +import java.util.HashMap; +import java.util.Map; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public class InternalCnNssmfManager extends InternalNssmfManager { + + @Override + protected String doWrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + + NssmfRequest request = + new NssmfRequest(serviceInfo, nbiRequest.getEsrInfo().getNetworkType(), nbiRequest.getAllocateCnNssi()); + request.setName(nbiRequest.getAllocateCnNssi().getNssiName()); + return marshal(request); + } + + @Override + protected String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + AllocateCnNssi allocateCnNssi = nbiRequest.getAllocateCnNssi(); + CnSliceProfile cnSliceProfile = allocateCnNssi.getSliceProfile(); + Map<String, Object> additional = new HashMap<>(); + additional.put("modifyAction", "allocate"); + additional.put("nsiInfo", allocateCnNssi.getNsiInfo()); + additional.put("scriptName", allocateCnNssi.getScriptName()); + additional.put("snssaiList", cnSliceProfile.getSnssaiList()); + additional.put("sliceProfileId", cnSliceProfile.getSliceProfileId()); + + NssmfRequest request = new NssmfRequest(serviceInfo, esrInfo.getNetworkType(), additional); + return marshal(request); + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalTnNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalTnNssmfManager.java new file mode 100644 index 0000000000..8bfbd55387 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/internal/InternalTnNssmfManager.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.manager.impl.internal; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.impl.InternalNssmfManager; +import org.onap.so.beans.nsmf.*; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public class InternalTnNssmfManager extends InternalNssmfManager { + + @Override + protected String doWrapAllocateReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + + return marshal(new NssmfRequest(serviceInfo, nbiRequest.getEsrInfo().getNetworkType(), + nbiRequest.getAllocateTnNssi())); + } + + @Override + protected String doWrapModifyReqBody(NssmfAdapterNBIRequest nbiRequest) throws ApplicationException { + // TODO + return null; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java index d8e1e36058..4fdcbf110f 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java @@ -20,6 +20,7 @@ package org.onap.so.adapters.nssmf.rest; +import org.onap.so.adapters.nssmf.entity.RestResponse; import org.onap.so.adapters.nssmf.exceptions.ApplicationException; import org.onap.so.beans.nsmf.JobStatusRequest; import org.onap.so.beans.nsmf.NssiActDeActRequest; @@ -43,6 +44,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.assertObjectNotNull; +@Deprecated @Controller @RequestMapping(value = "/api/rest/provMns/v1", produces = {APPLICATION_JSON}, consumes = {APPLICATION_JSON}) public class NssmfAdapterRest { @@ -52,17 +54,6 @@ public class NssmfAdapterRest { @Autowired private NssmfManager nssmfMgr; - @PostMapping(value = "/NSS/SliceProfiles") - public ResponseEntity allocateNssi(@RequestBody NssiAllocateRequest allocate) { - try { - logger.info("Nssmi allocate request is invoked"); - assertObjectNotNull(allocate); - RestResponse rsp = getNssmfMgr().allocateNssi(allocate); - return buildResponse(rsp); - } catch (ApplicationException e) { - return e.buildErrorResponse(); - } - } @PostMapping(value = "/NSS/nssi") public ResponseEntity createNssi(@RequestBody NssiCreateRequest create) { @@ -76,19 +67,6 @@ public class NssmfAdapterRest { } } - @PostMapping(value = "/NSS/SliceProfiles/{sliceProfileId}") - public ResponseEntity deAllocateNssi(@RequestBody NssiDeAllocateRequest deAllocate, - @PathVariable("sliceProfileId") final String sliceId) { - try { - logger.info("Nssmf deallocate request is invoked"); - assertObjectNotNull(deAllocate); - RestResponse rsp = getNssmfMgr().deAllocateNssi(deAllocate, sliceId); - return buildResponse(rsp); - } catch (ApplicationException e) { - return e.buildErrorResponse(); - } - } - @PostMapping(value = "/NSS/nssi/{nssiId}") public ResponseEntity terminateNssi(@RequestBody NssiTerminateRequest terminate, @PathVariable("nssiId") String nssiId) { @@ -128,44 +106,6 @@ public class NssmfAdapterRest { } } - @PostMapping(value = "/NSS/{snssai}/activation") - public ResponseEntity activateNssi(@RequestBody NssiActDeActRequest activate, - @PathVariable("snssai") String snssai) { - try { - logger.info("Nssmf activate request is invoked"); - assertObjectNotNull(activate); - RestResponse rsp = getNssmfMgr().activateNssi(activate, snssai); - return buildResponse(rsp); - } catch (ApplicationException e) { - return e.buildErrorResponse(); - } - } - - @PostMapping(value = "/NSS/{snssai}/deactivation") - public ResponseEntity deactivateNssi(@RequestBody NssiActDeActRequest deActivate, - @PathVariable("snssai") String snssai) { - try { - logger.info("Nssmf activate request is invoked"); - assertObjectNotNull(deActivate); - RestResponse rsp = getNssmfMgr().deActivateNssi(deActivate, snssai); - return buildResponse(rsp); - } catch (ApplicationException e) { - return e.buildErrorResponse(); - } - } - - @PostMapping(value = "/NSS/jobs/{jobId}") - public ResponseEntity queryJobStatus(@RequestBody JobStatusRequest jobStatusReq, - @PathVariable("jobId") String jobId) { - try { - logger.info("Nssmf query job status request is invoked"); - assertObjectNotNull(jobStatusReq); - RestResponse rsp = getNssmfMgr().queryJobStatus(jobStatusReq, jobId); - return buildResponse(rsp); - } catch (ApplicationException e) { - return e.buildErrorResponse(); - } - } @GetMapping(value = "/vendor/{vendorName}/type/{networkType}/NSS" + "/SliceProfiles/{sliceProfileId}") public ResponseEntity queryNssi(@PathVariable("vendorName") String vendorName, diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java index 00e5c4aaec..bcce69fb0b 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java @@ -20,7 +20,10 @@ package org.onap.so.adapters.nssmf.rest; +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.adapters.nssmf.enums.JobStatus; import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.util.RestUtil; import org.onap.so.beans.nsmf.ActDeActNssi; import org.onap.so.beans.nsmf.AllocateAnNssi; import org.onap.so.beans.nsmf.AllocateCnNssi; @@ -52,15 +55,15 @@ import org.springframework.context.annotation.Primary; import org.springframework.data.domain.Example; import org.springframework.stereotype.Component; import static java.lang.String.valueOf; -import static org.onap.so.adapters.nssmf.rest.HttpMethod.DELETE; -import static org.onap.so.adapters.nssmf.rest.HttpMethod.GET; -import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST; -import static org.onap.so.adapters.nssmf.rest.HttpMethod.PUT; -import static org.onap.so.adapters.nssmf.rest.JobStatus.ERROR; -import static org.onap.so.adapters.nssmf.rest.JobStatus.FINISHED; -import static org.onap.so.adapters.nssmf.rest.JobStatus.PROCESSING; -import static org.onap.so.adapters.nssmf.rest.JobStatus.STARTED; -import static org.onap.so.adapters.nssmf.rest.JobStatus.fromString; +import static org.onap.so.adapters.nssmf.enums.HttpMethod.DELETE; +import static org.onap.so.adapters.nssmf.enums.HttpMethod.GET; +import static org.onap.so.adapters.nssmf.enums.HttpMethod.POST; +import static org.onap.so.adapters.nssmf.enums.HttpMethod.PUT; +import static org.onap.so.adapters.nssmf.enums.JobStatus.ERROR; +import static org.onap.so.adapters.nssmf.enums.JobStatus.FINISHED; +import static org.onap.so.adapters.nssmf.enums.JobStatus.PROCESSING; +import static org.onap.so.adapters.nssmf.enums.JobStatus.STARTED; +import static org.onap.so.adapters.nssmf.enums.JobStatus.fromString; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ACTIVATE_NSS_SUCCESS; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ALLOCATE_NSS_SUCCESS; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.CREATE_NSS_SUCCESS; @@ -76,6 +79,7 @@ import static org.onap.so.beans.nsmf.ActDeActNssi.DE_ACT_URL; @Component @Primary +@Deprecated public class NssmfManager { private static final Logger logger = LoggerFactory.getLogger(NssmfManager.class); @@ -127,9 +131,20 @@ public class NssmfManager { break; case TRANSPORT: + AllocateTnNssi tn = nssmiAllocate.getAllocateTnNssi(); + assertObjectNotNull(tn); + // assertObjectNotNull(tn.getNsiInfo()); + // assertObjectNotNull(tn.getNsiInfo().getNsiId()); + // nsiId = tn.getNsiInfo().getNsiId(); + allocateReq = marshal(tn); + // allocateUrl = AllocateTnNssi.URL; break; } + + /** + * 内部的,调用 workflow 外部的,访问第三方api + */ RestResponse rsp = restUtil.sendRequest(allocateUrl, POST, allocateReq, nssmiAllocate.getEsrInfo()); assertObjectNotNull(rsp); @@ -145,6 +160,8 @@ public class NssmfManager { return rsp; } + + public RestResponse createNssi(NssiCreateRequest nssiCreate) throws ApplicationException { assertObjectNotNull(nssiCreate.getEsrInfo()); @@ -185,6 +202,7 @@ public class NssmfManager { return rsp; } + @Deprecated public RestResponse deAllocateNssi(NssiDeAllocateRequest nssiDeallocate, String sliceId) throws ApplicationException { diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java index 254186bda8..fc0f3ddde5 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java @@ -23,6 +23,7 @@ package org.onap.so.adapters.nssmf.rest; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; +@Deprecated public class TrustAllHostNameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/NssmfManagerService.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/NssmfManagerService.java new file mode 100644 index 0000000000..9ad191b675 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/NssmfManagerService.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.service; + +import org.onap.so.beans.nsmf.*; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +@Service +public interface NssmfManagerService { + ResponseEntity allocateNssi(NssmfAdapterNBIRequest allocateRequest); + + ResponseEntity deAllocateNssi(NssmfAdapterNBIRequest allocateRequest, String sliceProfileId); + + ResponseEntity activateNssi(NssmfAdapterNBIRequest deActRequest, String snssai); + + ResponseEntity deActivateNssi(NssmfAdapterNBIRequest nssiDeActivate, String snssai); + + ResponseEntity queryJobStatus(NssmfAdapterNBIRequest jobReq, String jobId); + + ResponseEntity queryNSSISelectionCapability(NssmfAdapterNBIRequest nbiRequest); + + ResponseEntity querySubnetCapability(NssmfAdapterNBIRequest nbiRequest); + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java new file mode 100644 index 0000000000..1408123be7 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.service.impl; + +import org.apache.commons.lang3.StringUtils; +import org.onap.so.adapters.nssmf.config.NssmfAdapterConfig; +import org.onap.so.adapters.nssmf.enums.ActionType; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.manager.NssmfManagerBuilder; +import org.onap.so.adapters.nssmf.entity.RestResponse; +import org.onap.so.adapters.nssmf.manager.NssmfManager; +import org.onap.so.adapters.nssmf.service.NssmfManagerService; +import org.onap.so.adapters.nssmf.util.RestUtil; +import org.onap.so.beans.nsmf.*; +import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + + +@Service +public class NssmfManagerServiceImpl implements NssmfManagerService { + + @Autowired + private RestUtil restUtil; + + @Autowired + private ResourceOperationStatusRepository repository; + + @Autowired + private NssmfAdapterConfig nssmfAdapterConfig; + + @Override + public ResponseEntity allocateNssi(NssmfAdapterNBIRequest request) { + try { + + if (StringUtils.isNotBlank(request.getServiceInfo().getNssiId())) { + return buildResponse(buildNssmfManager(request, ActionType.MODIFY).modifyNssi(request)); + } + + return buildResponse(buildNssmfManager(request, ActionType.ALLOCATE).allocateNssi(request)); + + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @Override + public ResponseEntity deAllocateNssi(NssmfAdapterNBIRequest request, String sliceProfileId) { + try { + return buildResponse( + buildNssmfManager(request, ActionType.DEALLOCATE).deAllocateNssi(request, sliceProfileId)); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @Override + public ResponseEntity activateNssi(NssmfAdapterNBIRequest request, String snssai) { + try { + return buildResponse(buildNssmfManager(request, ActionType.ACTIVATE).activateNssi(request, snssai)); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @Override + public ResponseEntity deActivateNssi(NssmfAdapterNBIRequest request, String snssai) { + try { + return buildResponse(buildNssmfManager(request, ActionType.DEACTIVATE).deActivateNssi(request, snssai)); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @Override + public ResponseEntity queryJobStatus(NssmfAdapterNBIRequest jobReq, String jobId) { + try { + return buildResponse(buildNssmfManager(jobReq, ActionType.QUERY_JOB_STATUS).queryJobStatus(jobReq, jobId)); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @Override + public ResponseEntity queryNSSISelectionCapability(NssmfAdapterNBIRequest nbiRequest) { + EsrInfo esrInfo = nbiRequest.getEsrInfo(); + try { + return buildResponse(buildNssmfManager(esrInfo, ActionType.QUERY_JOB_STATUS, null) + .queryNSSISelectionCapability(nbiRequest)); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @Override + public ResponseEntity querySubnetCapability(NssmfAdapterNBIRequest nbiRequest) { + EsrInfo esrInfo = nbiRequest.getEsrInfo(); + try { + return buildResponse( + buildNssmfManager(esrInfo, ActionType.QUERY_JOB_STATUS, null).querySubnetCapability(nbiRequest)); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + private ResponseEntity buildResponse(RestResponse rsp) { + return ResponseEntity.status(rsp.getStatus()).body(rsp.getResponseContent()); + } + + + private NssmfManager buildNssmfManager(NssmfAdapterNBIRequest request, ActionType actionType) + throws ApplicationException { + return buildNssmfManager(request.getEsrInfo(), actionType, request.getServiceInfo()); + } + + private NssmfManager buildNssmfManager(EsrInfo esrInfo, ActionType actionType, ServiceInfo serviceInfo) + throws ApplicationException { + + return new NssmfManagerBuilder(esrInfo).setActionType(actionType).setRepository(repository) + .setRestUtil(restUtil).setAdapterConfig(nssmfAdapterConfig).setServiceInfo(serviceInfo).build(); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java index 3a7c2f19df..090417ddc2 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java @@ -22,10 +22,12 @@ package org.onap.so.adapters.nssmf.util; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; +import org.onap.so.adapters.nssmf.enums.ActionType; import org.onap.so.adapters.nssmf.exceptions.ApplicationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.onap.logging.filter.base.ErrorCode; +import org.springframework.stereotype.Component; import static org.onap.so.logger.LoggingAnchor.THREE; import static org.onap.so.logger.MessageEnum.RA_NS_EXC; @@ -45,6 +47,8 @@ public class NssmfAdapterUtil { public static final String ALLOCATE_NSS_SUCCESS = "Allocating nss is " + "successful"; + public static final String MODIFY_NSS_SUCCESS = "Modify nss is " + "successful"; + public static final String CREATE_NSS_SUCCESS = "Creating nss is " + "successful"; public static final String DEALLOCATE_NSS_SUCCESS = "Deallocate nss " + "is successful"; @@ -91,4 +95,29 @@ public class NssmfAdapterUtil { } } + + public static String getStatusDesc(ActionType actionType) { + String desc = ""; + switch (actionType) { + case ALLOCATE: + desc = StatusDesc.ALLOCATE_NSS_SUCCESS; + break; + case DEALLOCATE: + desc = StatusDesc.DEALLOCATE_NSS_SUCCESS; + break; + case ACTIVATE: + desc = StatusDesc.ACTIVATE_NSS_SUCCESS; + break; + case DEACTIVATE: + desc = StatusDesc.DEACTIVATE_NSS_SUCCESS; + break; + case MODIFY: + desc = StatusDesc.MODIFY_NSS_SUCCESS; + break; + default: + break; + } + + return desc; + } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/RestUtil.java index dcc6f5ba72..0c5999b20e 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/RestUtil.java @@ -18,11 +18,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.nssmf.rest; +package org.onap.so.adapters.nssmf.util; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; +import javax.net.ssl.*; import javax.ws.rs.core.UriBuilder; import java.net.SocketTimeoutException; import java.net.URI; @@ -30,32 +28,29 @@ import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.methods.*; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.EsrThirdpartySdnc; -import org.onap.aai.domain.yang.EsrThirdpartySdncList; +import org.onap.aai.domain.yang.*; import org.onap.so.adapters.nssmf.exceptions.ApplicationException; import org.onap.so.adapters.nssmf.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.nssmf.model.TokenRequest; -import org.onap.so.adapters.nssmf.model.TokenResponse; +import org.onap.so.adapters.nssmf.entity.TokenRequest; +import org.onap.so.adapters.nssmf.entity.TokenResponse; +import org.onap.so.adapters.nssmf.enums.HttpMethod; +import org.onap.so.adapters.nssmf.entity.NssmfInfo; +import org.onap.so.adapters.nssmf.entity.RestResponse; import org.onap.so.beans.nsmf.EsrInfo; +import org.onap.so.beans.nsmf.ServiceInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static org.apache.http.entity.ContentType.APPLICATION_JSON; -import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST; +import static org.onap.so.adapters.nssmf.enums.HttpMethod.POST; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.BAD_REQUEST; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; @@ -77,6 +72,10 @@ public class RestUtil { @Autowired private AaiServiceProvider aaiSvcProv; + public void createServiceInstance(ServiceInstance serviceInstance, ServiceInfo serviceInfo) { + aaiSvcProv.invokeCreateServiceInstance(serviceInstance, serviceInfo.getGlobalSubscriberId(), + serviceInfo.getSubscriptionServiceType(), serviceInfo.getNssiId()); + } public NssmfInfo getNssmfHost(EsrInfo esrInfo) throws ApplicationException { EsrThirdpartySdncList sdncList = aaiSvcProv.invokeGetThirdPartySdncList(); @@ -112,10 +111,9 @@ public class RestUtil { throw new ApplicationException(BAD_REQUEST, "ESR information is improper"); } - public RestResponse sendRequest(String url, HttpMethod methodType, String content, EsrInfo esrInfo) - throws ApplicationException { - NssmfInfo nssmfInfo = getNssmfHost(esrInfo); + public String getToken(NssmfInfo nssmfInfo) throws ApplicationException { + TokenRequest req = new TokenRequest(); req.setGrantType("password"); @@ -128,13 +126,12 @@ public class RestUtil { RestResponse tokenRes = send(nssmfInfo.getUrl() + TOKEN_URL, POST, tokenReq, null); TokenResponse res = unMarshal(tokenRes.getResponseContent(), TokenResponse.class); - String token = res.getAccessToken(); - Header header = new BasicHeader("X-Auth-Token", token); - String nssmfUrl = nssmfInfo.getUrl() + url; - return send(nssmfUrl, methodType, content, header); + + return res.getAccessToken(); } - private RestResponse send(String url, HttpMethod methodType, String content, Header header) { + + public RestResponse send(String url, HttpMethod methodType, String content, Header header) { HttpRequestBase req = null; HttpResponse res = null; @@ -168,8 +165,6 @@ public class RestUtil { } if (null != req) { req.reset(); - } else { - logger.debug("method is NULL:"); } req = null; @@ -201,7 +196,7 @@ public class RestUtil { } } - private RestResponse createResponse(int statusCode, String errMsg) { + public RestResponse createResponse(int statusCode, String errMsg) { RestResponse restResponse = new RestResponse(); restResponse.setStatus(statusCode); restResponse.setResponseContent(errMsg); @@ -210,7 +205,7 @@ public class RestUtil { private HttpRequestBase getHttpReq(String url, HttpMethod method, Header header, RequestConfig config, String content) throws ApplicationException { - HttpRequestBase base = null; + HttpRequestBase base; switch (method) { case POST: HttpPost post = new HttpPost(url); @@ -229,6 +224,7 @@ public class RestUtil { break; case PATCH: + base = new HttpPatch(url); break; case DELETE: @@ -238,6 +234,8 @@ public class RestUtil { } base = delete; break; + default: + throw new ApplicationException(404, "invalid method: " + method); } base.setConfig(config); @@ -247,6 +245,14 @@ public class RestUtil { return base; } + public RestResponse sendRequest(String allocateUrl, HttpMethod post, String allocateReq, EsrInfo esrInfo) + throws ApplicationException { + NssmfInfo nssmfInfo = getNssmfHost(esrInfo); + Header header = new BasicHeader("X-Auth-Token", getToken(nssmfInfo)); + String nssmfUrl = nssmfInfo.getUrl() + allocateUrl; + return send(nssmfUrl, post, allocateReq, header); + } + class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE"; @@ -289,7 +295,7 @@ public class RestUtil { // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); SSLConnectionSocketFactory sslsf = - new SSLConnectionSocketFactory(sc, new String[] {"TLSv1"}, null, new TrustAllHostNameVerifier()); + new SSLConnectionSocketFactory(sc, new String[] {"TLSv1"}, null, (s, sslSession) -> true); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (Exception e) { throw new IllegalArgumentException(e); diff --git a/adapters/mso-nssmf-adapter/src/main/resources/application-test.yaml b/adapters/mso-nssmf-adapter/src/main/resources/application-test.yaml new file mode 100644 index 0000000000..8e10dfb72b --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/resources/application-test.yaml @@ -0,0 +1,60 @@ + +aai: + auth: 2A11B07DB6214A839394AA1EC5844695F5114FC407FF5422625FB00175A3DCB8A1FF745F22867EFA72D5369D599BBD88DA8BED4233CF5586 + endpoint: https://aai.onap:30233 +logging: + path: logs + +spring: + datasource: + jdbcUrl: jdbc:mariadb://49.232.146.162:8989/requestdb + username: root + password: 123456 + driver-class-name: org.mariadb.jdbc.Driver + initialization-mode: always + jpa: + generate-ddl: false + show-sql: false + hibernate: + ddl-auto: none + naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy + enable-lazy-load-no-trans: true + database-platform: org.hibernate.dialect.MySQL5InnoDBDialect + security: + usercredentials: + - username: bpel + password: '$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke' + role: BPEL-Client + - username: mso_admin + password: '$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke' + role: ACTUATOR +server: + port: 8080 + tomcat: + max-threads: 50 + +mso: + key: 07a7159d3bf51a0e53be7a8f89699be7 + site-name: localSite + logPath: ./logs/nssmf + adapters: + requestDb: + endpoint: https://so-request-db-adapter.onap:8083 + auth: Basic YnBlbDpwYXNzd29yZDEk + infra: + endpoint: https://so.onap:8080 + auth: Basic SW5mcmFQb3J0YWxDbGllbnQ6cGFzc3dvcmQxJA== + +#Actuator +management: + endpoints: + web: + base-path: /manage + exposure: + include: "*" + metrics: + se-global-registry: false + export: + prometheus: + enabled: true # Whether exporting of metrics to Prometheus is enabled. + step: 1m # Step size (i.e. reporting frequency) to use.
\ No newline at end of file diff --git a/adapters/mso-nssmf-adapter/src/main/resources/application.yaml b/adapters/mso-nssmf-adapter/src/main/resources/application.yaml index 303d63d4a2..8da911d4e0 100644 --- a/adapters/mso-nssmf-adapter/src/main/resources/application.yaml +++ b/adapters/mso-nssmf-adapter/src/main/resources/application.yaml @@ -58,6 +58,9 @@ mso: requestDb: endpoint: https://so-request-db-adapter.{{ include "common.namespace" . }}:8083 auth: Basic YnBlbDpwYXNzd29yZDEk + infra: + endpoint: https://so.{{ include "common.namespace" . }}:8080 + auth: Basic SW5mcmFQb3J0YWxDbGllbnQ6cGFzc3dvcmQxJA== #Actuator management: diff --git a/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java b/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java index 5bfd39096c..a9c732e6e3 100644 --- a/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java +++ b/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java @@ -24,6 +24,7 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.LinkedList; import java.util.List; +import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; @@ -35,12 +36,12 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.onap.so.adapters.nssmf.model.TokenResponse; -import org.onap.so.adapters.nssmf.rest.HttpMethod; +import org.onap.so.adapters.nssmf.entity.TokenResponse; +import org.onap.so.adapters.nssmf.enums.HttpMethod; import org.onap.so.adapters.nssmf.rest.NssmfAdapterRest; -import org.onap.so.adapters.nssmf.rest.NssmfInfo; +import org.onap.so.adapters.nssmf.entity.NssmfInfo; import org.onap.so.adapters.nssmf.rest.NssmfManager; -import org.onap.so.adapters.nssmf.rest.RestUtil; +import org.onap.so.adapters.nssmf.util.RestUtil; import org.onap.so.beans.nsmf.ActDeActNssi; import org.onap.so.beans.nsmf.AllocateCnNssi; import org.onap.so.beans.nsmf.CnSliceProfile; @@ -127,13 +128,16 @@ public class NssmfAdapterRestTest { } private void createCommonMock(int statusCode, NssmfInfo nssmf) throws Exception { + when(this.restUtil.send(any(String.class), any(HttpMethod.class), any(String.class), any(Header.class))) + .thenCallRealMethod(); + when(this.restUtil.createResponse(any(Integer.class), any(String.class))).thenCallRealMethod(); when(nssmfRest.getNssmfMgr()).thenReturn(nssmfMgr); - when(nssmfRest.allocateNssi(any(NssiAllocateRequest.class))).thenCallRealMethod(); - when(nssmfRest.deAllocateNssi(any(NssiDeAllocateRequest.class), any(String.class))).thenCallRealMethod(); - when(nssmfRest.activateNssi(any(NssiActDeActRequest.class), any(String.class))).thenCallRealMethod(); - when(nssmfRest.deactivateNssi(any(NssiActDeActRequest.class), any(String.class))).thenCallRealMethod(); - - when(nssmfRest.queryJobStatus(any(JobStatusRequest.class), any(String.class))).thenCallRealMethod(); + // when(nssmfRest.createAllocateNssi(any(NssiAllocateRequest.class))).thenCallRealMethod(); + // when(nssmfRest.deAllocateNssi(any(NssiDeAllocateRequest.class), any(String.class))).thenCallRealMethod(); + // when(nssmfRest.activateNssi(any(NssiActDeActRequest.class), any(String.class))).thenCallRealMethod(); + // when(nssmfRest.deactivateNssi(any(NssiActDeActRequest.class), any(String.class))).thenCallRealMethod(); + // + // when(nssmfRest.queryJobStatus(any(JobStatusRequest.class), any(String.class))).thenCallRealMethod(); when(restUtil.sendRequest(any(String.class), any(HttpMethod.class), any(String.class), any(EsrInfo.class))) .thenCallRealMethod(); when(restUtil.getHttpsClient()).thenReturn(httpClient); @@ -168,113 +172,113 @@ public class NssmfAdapterRestTest { doAnswer(answer).when(httpClient).execute(any(HttpRequestBase.class)); } - @Test - public void testNssiAllocate() throws Exception { - NssmfInfo nssmf = new NssmfInfo(); - nssmf.setUserName("nssmf-user"); - nssmf.setPassword("nssmf-pass"); - nssmf.setPort("8080"); - nssmf.setIpAddress("127.0.0.1"); - - NssiResponse nssiRes = new NssiResponse(); - nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); - nssiRes.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); - - TokenResponse token = new TokenResponse(); - token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); - token.setExpires(1800); - - postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); - tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); - - createCommonMock(200, nssmf); - // assertEquals(prettyPrint(allocateNssi()), ALLOCATE); - ResponseEntity res = nssmfRest.allocateNssi(allocateNssi()); - assertNotNull(res); - assertNotNull(res.getBody()); - NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); - assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); - assertEquals(allRes.getNssiId(), "NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); - } - - @Test - public void testNssiDeAllocate() throws Exception { - NssmfInfo nssmf = new NssmfInfo(); - nssmf.setUserName("nssmf-user"); - nssmf.setPassword("nssmf-pass"); - nssmf.setPort("8080"); - nssmf.setIpAddress("127.0.0.1"); - - NssiResponse nssiRes = new NssiResponse(); - nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); - - TokenResponse token = new TokenResponse(); - token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); - token.setExpires(1800); - - postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); - tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); - - createCommonMock(200, nssmf); - ResponseEntity res = nssmfRest.deAllocateNssi(deAllocateNssi(), "ab9af40f13f721b5f13539d87484098"); - assertNotNull(res); - assertNotNull(res.getBody()); - NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); - assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); - } - - @Test - public void testNssiActivate() throws Exception { - NssmfInfo nssmf = new NssmfInfo(); - nssmf.setUserName("nssmf-user"); - nssmf.setPassword("nssmf-pass"); - nssmf.setPort("8080"); - nssmf.setIpAddress("127.0.0.1"); - - NssiResponse nssiRes = new NssiResponse(); - nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); - - TokenResponse token = new TokenResponse(); - token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); - token.setExpires(1800); - - postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); - tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); - - createCommonMock(200, nssmf); - ResponseEntity res = nssmfRest.activateNssi(activateNssi(), "001-100001"); - assertNotNull(res); - assertNotNull(res.getBody()); - NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); - assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); - } - - @Test - public void testNssiDeActivate() throws Exception { - NssmfInfo nssmf = new NssmfInfo(); - nssmf.setUserName("nssmf-user"); - nssmf.setPassword("nssmf-pass"); - nssmf.setPort("8080"); - nssmf.setIpAddress("127.0.0.1"); - - NssiResponse nssiRes = new NssiResponse(); - nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); - - TokenResponse token = new TokenResponse(); - token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); - token.setExpires(1800); - - postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); - tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); - - createCommonMock(200, nssmf); - ResponseEntity res = nssmfRest.deactivateNssi(deActivateNssi(), "001-100001"); - assertNotNull(res); - assertNotNull(res.getBody()); - NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); - assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); - } - + // @Test + // public void testNssiAllocate() throws Exception { + // NssmfInfo nssmf = new NssmfInfo(); + // nssmf.setUserName("nssmf-user"); + // nssmf.setPassword("nssmf-pass"); + // nssmf.setPort("8080"); + // nssmf.setIpAddress("127.0.0.1"); + // + // NssiResponse nssiRes = new NssiResponse(); + // nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + // nssiRes.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + // + // TokenResponse token = new TokenResponse(); + // token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + // token.setExpires(1800); + // + // postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + // tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + // + // createCommonMock(200, nssmf); + // // assertEquals(prettyPrint(createAllocateNssi()), ALLOCATE); + // ResponseEntity res = nssmfRest.createAllocateNssi(createAllocateNssi()); + // assertNotNull(res); + // assertNotNull(res.getBody()); + // NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + // assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + // assertEquals(allRes.getNssiId(), "NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + // } + // + // @Test + // public void testNssiDeAllocate() throws Exception { + // NssmfInfo nssmf = new NssmfInfo(); + // nssmf.setUserName("nssmf-user"); + // nssmf.setPassword("nssmf-pass"); + // nssmf.setPort("8080"); + // nssmf.setIpAddress("127.0.0.1"); + // + // NssiResponse nssiRes = new NssiResponse(); + // nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + // + // TokenResponse token = new TokenResponse(); + // token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + // token.setExpires(1800); + // + // postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + // tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + // + // createCommonMock(200, nssmf); + // ResponseEntity res = nssmfRest.deAllocateNssi(deAllocateNssi(), "ab9af40f13f721b5f13539d87484098"); + // assertNotNull(res); + // assertNotNull(res.getBody()); + // NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + // assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + // } + // + // @Test + // public void testNssiActivate() throws Exception { + // NssmfInfo nssmf = new NssmfInfo(); + // nssmf.setUserName("nssmf-user"); + // nssmf.setPassword("nssmf-pass"); + // nssmf.setPort("8080"); + // nssmf.setIpAddress("127.0.0.1"); + // + // NssiResponse nssiRes = new NssiResponse(); + // nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + // + // TokenResponse token = new TokenResponse(); + // token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + // token.setExpires(1800); + // + // postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + // tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + // + // createCommonMock(200, nssmf); + // ResponseEntity res = nssmfRest.activateNssi(activateNssi(), "001-100001"); + // assertNotNull(res); + // assertNotNull(res.getBody()); + // NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + // assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + // } + // + // @Test + // public void testNssiDeActivate() throws Exception { + // NssmfInfo nssmf = new NssmfInfo(); + // nssmf.setUserName("nssmf-user"); + // nssmf.setPassword("nssmf-pass"); + // nssmf.setPort("8080"); + // nssmf.setIpAddress("127.0.0.1"); + // + // NssiResponse nssiRes = new NssiResponse(); + // nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + // + // TokenResponse token = new TokenResponse(); + // token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + // token.setExpires(1800); + // + // postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + // tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + // + // createCommonMock(200, nssmf); + // ResponseEntity res = nssmfRest.deactivateNssi(deActivateNssi(), "001-100001"); + // assertNotNull(res); + // assertNotNull(res.getBody()); + // NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + // assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + // } + // @Test public void testAllocateJsonSerDeSer() throws Exception { assertEquals(marshal(allocateNssi()), ALLOCATE); @@ -334,50 +338,51 @@ public class NssmfAdapterRestTest { return allocate; } - public NssiDeAllocateRequest deAllocateNssi() throws Exception { - DeAllocateNssi deAllocateNssi = new DeAllocateNssi(); - deAllocateNssi.setTerminateNssiOption(0); - List<String> snssai = new LinkedList<>(); - snssai.add("001-100001"); - deAllocateNssi.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); - deAllocateNssi.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); - deAllocateNssi.setScriptName("CN1"); - deAllocateNssi.setSnssaiList(snssai); - EsrInfo esrInfo = new EsrInfo(); - esrInfo.setVendor("huawei"); - esrInfo.setNetworkType(CORE); - NssiDeAllocateRequest deAllocate = new NssiDeAllocateRequest(); - deAllocate.setDeAllocateNssi(deAllocateNssi); - deAllocate.setEsrInfo(esrInfo); - return deAllocate; - } - - public NssiActDeActRequest activateNssi() throws Exception { - EsrInfo esrInfo = new EsrInfo(); - esrInfo.setVendor("huawei"); - esrInfo.setNetworkType(CORE); - ActDeActNssi act = new ActDeActNssi(); - act.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); - act.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); - NssiActDeActRequest actReq = new NssiActDeActRequest(); - actReq.setActDeActNssi(act); - actReq.setEsrInfo(esrInfo); - return actReq; - } - - public NssiActDeActRequest deActivateNssi() throws Exception { - EsrInfo esrInfo = new EsrInfo(); - esrInfo.setVendor("huawei"); - esrInfo.setNetworkType(CORE); - ActDeActNssi deAct = new ActDeActNssi(); - deAct.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); - deAct.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); - NssiActDeActRequest deActReq = new NssiActDeActRequest(); - deActReq.setActDeActNssi(deAct); - deActReq.setEsrInfo(esrInfo); - return deActReq; - } - + // + // public NssiDeAllocateRequest deAllocateNssi() throws Exception { + // DeAllocateNssi deAllocateNssi = new DeAllocateNssi(); + // deAllocateNssi.setTerminateNssiOption(0); + // List<String> snssai = new LinkedList<>(); + // snssai.add("001-100001"); + // deAllocateNssi.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + // deAllocateNssi.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + // deAllocateNssi.setScriptName("CN1"); + // deAllocateNssi.setSnssaiList(snssai); + // EsrInfo esrInfo = new EsrInfo(); + // esrInfo.setVendor("huawei"); + // esrInfo.setNetworkType(CORE); + // NssiDeAllocateRequest deAllocate = new NssiDeAllocateRequest(); + // deAllocate.setDeAllocateNssi(deAllocateNssi); + // deAllocate.setEsrInfo(esrInfo); + // return deAllocate; + // } + // + // public NssiActDeActRequest activateNssi() throws Exception { + // EsrInfo esrInfo = new EsrInfo(); + // esrInfo.setVendor("huawei"); + // esrInfo.setNetworkType(CORE); + // ActDeActNssi act = new ActDeActNssi(); + // act.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + // act.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + // NssiActDeActRequest actReq = new NssiActDeActRequest(); + // actReq.setActDeActNssi(act); + // actReq.setEsrInfo(esrInfo); + // return actReq; + // } + // + // public NssiActDeActRequest deActivateNssi() throws Exception { + // EsrInfo esrInfo = new EsrInfo(); + // esrInfo.setVendor("huawei"); + // esrInfo.setNetworkType(CORE); + // ActDeActNssi deAct = new ActDeActNssi(); + // deAct.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + // deAct.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + // NssiActDeActRequest deActReq = new NssiActDeActRequest(); + // deActReq.setActDeActNssi(deAct); + // deActReq.setEsrInfo(esrInfo); + // return deActReq; + // } + // public String queryJobStatusNssi() throws Exception { EsrInfo esrInfo = new EsrInfo(); esrInfo.setVendor("huawei"); diff --git a/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImplTest.java b/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImplTest.java new file mode 100644 index 0000000000..3108ade5a6 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImplTest.java @@ -0,0 +1,438 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2020, CMCC Technologies Co., Ltd. + # + # 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.nssmf.service.impl; + + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpRequestBase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.stubbing.Answer; +import org.onap.so.adapters.nssmf.consts.NssmfAdapterConsts; +import org.onap.so.adapters.nssmf.entity.NssmfInfo; +import org.onap.so.adapters.nssmf.entity.TokenResponse; +import org.onap.so.adapters.nssmf.enums.HttpMethod; +import org.onap.so.adapters.nssmf.util.RestUtil; +import org.onap.so.beans.nsmf.*; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.*; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; +import static org.onap.so.beans.nsmf.NetworkType.CORE; +import static org.onap.so.beans.nsmf.ResourceSharingLevel.NON_SHARED; + +@RunWith(SpringRunner.class) +public class NssmfManagerServiceImplTest { + + @Mock + private RestUtil restUtil; + + + private NssmfManagerServiceImpl nssiManagerService; + + @Mock + private HttpResponse tokenResponse; + + @Mock + private HttpEntity tokenEntity; + + @Mock + private HttpResponse commonResponse; + + @Mock + private HttpEntity commonEntity; + + @Mock + private StatusLine statusLine; + + @Mock + private HttpClient httpClient; + + private InputStream postStream; + + private InputStream tokenStream; + + @Mock + private ResourceOperationStatusRepository repository; + + @Before + public void setUp() throws Exception { + initMocks(this); + + nssiManagerService = new NssmfManagerServiceImpl(); + + Field restUtil = nssiManagerService.getClass().getDeclaredField("restUtil"); + restUtil.setAccessible(true); + restUtil.set(nssiManagerService, this.restUtil); + + Field repository = nssiManagerService.getClass().getDeclaredField("repository"); + repository.setAccessible(true); + repository.set(nssiManagerService, this.repository); + // nssiManagerService.setRestUtil(this.restUtil); + + when(this.restUtil.send(any(String.class), any(HttpMethod.class), any(), any(Header.class))) + .thenCallRealMethod(); + when(this.restUtil.createResponse(any(Integer.class), any(String.class))).thenCallRealMethod(); + } + + private void createCommonMock(int statusCode, NssmfInfo nssmf) throws Exception { + when(restUtil.getToken(any(NssmfInfo.class))).thenReturn("7512eb3feb5249eca5ddd742fedddd39"); + when(restUtil.getHttpsClient()).thenReturn(httpClient); + + when(statusLine.getStatusCode()).thenReturn(statusCode); + when(restUtil.getNssmfHost(any(EsrInfo.class))).thenReturn(nssmf); + + when(tokenResponse.getEntity()).thenReturn(tokenEntity); + when(tokenResponse.getStatusLine()).thenReturn(statusLine); + when(tokenEntity.getContent()).thenReturn(tokenStream); + + when(commonResponse.getEntity()).thenReturn(commonEntity); + when(commonResponse.getStatusLine()).thenReturn(statusLine); + when(commonEntity.getContent()).thenReturn(postStream); + + Answer<HttpResponse> answer = invocation -> { + Object[] arguments = invocation.getArguments(); + if (arguments != null && arguments.length == 1 && arguments[0] != null) { + + HttpRequestBase base = (HttpRequestBase) arguments[0]; + if (base.getURI().toString().endsWith("/oauth/token")) { + return tokenResponse; + } else { + return commonResponse; + } + } + return commonResponse; + }; + + doAnswer(answer).when(httpClient).execute(any(HttpRequestBase.class)); + + } + + @Test + public void allocateNssi() throws Exception { + + NssmfInfo nssmf = new NssmfInfo(); + nssmf.setUserName("nssmf-user"); + nssmf.setPassword("nssmf-pass"); + nssmf.setPort("8080"); + nssmf.setIpAddress("127.0.0.1"); + nssmf.setUrl("http://127.0.0.1:8080"); + + NssiResponse nssiRes = new NssiResponse(); + nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + nssiRes.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + + TokenResponse token = new TokenResponse(); + token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + token.setExpires(1800); + + postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + + createCommonMock(200, nssmf); + + + NssmfAdapterNBIRequest nbiRequest = createAllocateNssi(); + assertNotNull(nbiRequest); + System.out.println(marshal(nbiRequest)); + ResponseEntity res = nssiManagerService.allocateNssi(nbiRequest); + assertNotNull(res); + assertNotNull(res.getBody()); + NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + assertEquals(allRes.getNssiId(), "NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + + System.out.println(res); + } + + + + private NssmfAdapterNBIRequest createAllocateNssi() { + CnSliceProfile sP = new CnSliceProfile(); + List<String> sns = new LinkedList<>(); + sns.add("001-100001"); + List<String> plmn = new LinkedList<>(); + plmn.add("460-00"); + plmn.add("460-01"); + PerfReqEmbbList embb = new PerfReqEmbbList(); + embb.setActivityFactor(50); + List<PerfReqEmbbList> embbList = new LinkedList<>(); + embbList.add(embb); + PerfReq perfReq = new PerfReq(); + perfReq.setPerfReqEmbbList(embbList); + List<String> taList = new LinkedList<>(); + taList.add("1"); + taList.add("2"); + taList.add("3"); + sP.setSnssaiList(sns); + sP.setSliceProfileId("ab9af40f13f721b5f13539d87484098"); + sP.setPlmnIdList(plmn); + sP.setPerfReq(perfReq); + sP.setMaxNumberofUEs(200); + sP.setCoverageAreaTAList(taList); + sP.setLatency(6); + sP.setResourceSharingLevel(NON_SHARED); + NsiInfo nsiInfo = new NsiInfo(); + nsiInfo.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + nsiInfo.setNsiName("eMBB-001"); + AllocateCnNssi cnNssi = new AllocateCnNssi(); + cnNssi.setNssiId("NSST-C-001-HDBNJ-NSSMF-01-A-ZX"); + cnNssi.setNssiName("eMBB-001"); + cnNssi.setScriptName("CN1"); + cnNssi.setSliceProfile(sP); + cnNssi.setNsiInfo(nsiInfo); + + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + nbiRequest.setAllocateCnNssi(cnNssi); + return nbiRequest; + } + + @Test + public void deAllocateNssi() throws Exception { + DeAllocateNssi deAllocateNssi = new DeAllocateNssi(); + deAllocateNssi.setTerminateNssiOption(0); + List<String> snssai = new LinkedList<>(); + snssai.add("001-100001"); + deAllocateNssi.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + deAllocateNssi.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + deAllocateNssi.setScriptName("CN1"); + deAllocateNssi.setSnssaiList(snssai); + + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + nbiRequest.setDeAllocateNssi(deAllocateNssi); + + NssmfInfo nssmf = new NssmfInfo(); + nssmf.setUserName("nssmf-user"); + nssmf.setPassword("nssmf-pass"); + nssmf.setPort("8080"); + nssmf.setIpAddress("127.0.0.1"); + + NssiResponse nssiRes = new NssiResponse(); + nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + + TokenResponse token = new TokenResponse(); + token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + token.setExpires(1800); + + postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + + createCommonMock(202, nssmf); + ResponseEntity res = nssiManagerService.deAllocateNssi(nbiRequest, "ab9af40f13f721b5f13539d87484098"); + assertNotNull(res); + assertNotNull(res.getBody()); + NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + assertNotNull(res); + assertNotNull(res.getBody()); + } + + @Test + public void activateNssi() throws Exception { + NssmfInfo nssmf = new NssmfInfo(); + nssmf.setUserName("nssmf-user"); + nssmf.setPassword("nssmf-pass"); + nssmf.setPort("8080"); + nssmf.setIpAddress("127.0.0.1"); + + NssiResponse nssiRes = new NssiResponse(); + nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + + TokenResponse token = new TokenResponse(); + token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + token.setExpires(1800); + + postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + + ActDeActNssi act = new ActDeActNssi(); + act.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + act.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + nbiRequest.setActDeActNssi(act); + + createCommonMock(200, nssmf); + ResponseEntity res = nssiManagerService.activateNssi(nbiRequest, "001-100001"); + assertNotNull(res); + assertNotNull(res.getBody()); + NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + } + + @Test + public void deActivateNssi() throws Exception { + NssmfInfo nssmf = new NssmfInfo(); + nssmf.setUserName("nssmf-user"); + nssmf.setPassword("nssmf-pass"); + nssmf.setPort("8080"); + nssmf.setIpAddress("127.0.0.1"); + + NssiResponse nssiRes = new NssiResponse(); + nssiRes.setJobId("4b45d919816ccaa2b762df5120f72067"); + + TokenResponse token = new TokenResponse(); + token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + token.setExpires(1800); + + postStream = new ByteArrayInputStream(marshal(nssiRes).getBytes(UTF_8)); + tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + + ActDeActNssi act = new ActDeActNssi(); + act.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + act.setNssiId("NSSI-C-001-HDBNJ-NSSMF-01-A-ZX"); + + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + nbiRequest.setActDeActNssi(act); + + createCommonMock(200, nssmf); + ResponseEntity res = nssiManagerService.deActivateNssi(nbiRequest, "001-100001"); + assertNotNull(res); + assertNotNull(res.getBody()); + NssiResponse allRes = unMarshal(res.getBody().toString(), NssiResponse.class); + assertEquals(allRes.getJobId(), "4b45d919816ccaa2b762df5120f72067"); + } + + @Test + public void queryJobStatus() throws Exception { + NssmfInfo nssmf = new NssmfInfo(); + nssmf.setUserName("nssmf-user"); + nssmf.setPassword("nssmf-pass"); + nssmf.setPort("8080"); + nssmf.setIpAddress("127.0.0.1"); + + JobStatusResponse jobStatusResponse = new JobStatusResponse(); + ResponseDescriptor descriptor = new ResponseDescriptor(); + descriptor.setResponseId("7512eb3feb5249eca5ddd742fedddd39"); + descriptor.setProgress(20); + descriptor.setStatusDescription("Initiating VNF Instance"); + descriptor.setStatus("processing"); + jobStatusResponse.setResponseDescriptor(descriptor); + + TokenResponse token = new TokenResponse(); + token.setAccessToken("7512eb3feb5249eca5ddd742fedddd39"); + token.setExpires(1800); + + postStream = new ByteArrayInputStream(marshal(jobStatusResponse).getBytes(UTF_8)); + tokenStream = new ByteArrayInputStream(marshal(token).getBytes(UTF_8)); + + ResourceOperationStatus operationStatus = new ResourceOperationStatus(); + operationStatus.setOperationId("4b45d919816ccaa2b762df5120f72067"); + operationStatus.setResourceTemplateUUID("8ee5926d-720b-4bb2-86f9-d20e921c143b"); + operationStatus.setServiceId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + nbiRequest.setResponseId("7512eb3feb5249eca5ddd742fedddd39"); + Optional<ResourceOperationStatus> optional = Optional.of(operationStatus); + + doAnswer(invocation -> optional).when(repository).findOne(any()); + + createCommonMock(200, nssmf); + + ResponseEntity res = nssiManagerService.queryJobStatus(nbiRequest, "4b45d919816ccaa2b762df5120f72067"); + assertNotNull(res); + assertNotNull(res.getBody()); + JobStatusResponse allRes = unMarshal(res.getBody().toString(), JobStatusResponse.class); + assertEquals(allRes.getResponseDescriptor().getProgress(), 20); + assertEquals(allRes.getResponseDescriptor().getStatus(), "processing"); + assertEquals(allRes.getResponseDescriptor().getResponseId(), "7512eb3feb5249eca5ddd742fedddd39"); + + System.out.println(res); + + } + + @Test + public void queryNSSISelectionCapability() throws Exception { + + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + ResponseEntity res = nssiManagerService.queryNSSISelectionCapability(nbiRequest); + assertNotNull(res); + assertNotNull(res.getBody()); + Map allRes = unMarshal(res.getBody().toString(), Map.class); + assertEquals(allRes.get("selection"), "NSMF"); + + System.out.println(res); + + nbiRequest.getEsrInfo().setVendor(NssmfAdapterConsts.ONAP_INTERNAL_TAG); + res = nssiManagerService.queryNSSISelectionCapability(nbiRequest); + assertNotNull(res); + assertNotNull(res.getBody()); + allRes = unMarshal(res.getBody().toString(), Map.class); + assertEquals(allRes.get("selection"), "NSSMF"); + + System.out.println(res); + + nbiRequest.getEsrInfo().setNetworkType(NetworkType.ACCESS); + res = nssiManagerService.queryNSSISelectionCapability(nbiRequest); + assertNotNull(res); + assertNotNull(res.getBody()); + allRes = unMarshal(res.getBody().toString(), Map.class); + assertEquals(allRes.get("selection"), "NSSMF"); + + System.out.println(res); + } + + private NssmfAdapterNBIRequest createNbiRequest() { + NssmfAdapterNBIRequest nbiRequest = new NssmfAdapterNBIRequest(); + EsrInfo esrInfo = new EsrInfo(); + esrInfo.setVendor("huawei"); + esrInfo.setNetworkType(CORE); + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setServiceUuid("8ee5926d-720b-4bb2-86f9-d20e921c143b"); + serviceInfo.setServiceInvariantUuid("e75698d9-925a-4cdd-a6c0-edacbe6a0b51"); + serviceInfo.setGlobalSubscriberId("5GCustomer"); + serviceInfo.setServiceType("5G"); + serviceInfo.setNsiId("NSI-M-001-HDBNJ-NSMF-01-A-ZX"); + nbiRequest.setEsrInfo(esrInfo); + nbiRequest.setServiceInfo(serviceInfo); + return nbiRequest; + } + + @Test + public void querySubnetCapability() { + NssmfAdapterNBIRequest nbiRequest = createNbiRequest(); + + String subnetCapabilityQuery = "\"subnetTypes\": [\"TN-FH\",\"TN-MH\",\"TN-BH\"]"; + nbiRequest.setSubnetCapabilityQuery(subnetCapabilityQuery); + ResponseEntity res = nssiManagerService.queryNSSISelectionCapability(nbiRequest); + assertNotNull(res); + assertNotNull(res.getBody()); + } +} diff --git a/adapters/mso-nssmf-adapter/src/test/resources/application-test.yaml b/adapters/mso-nssmf-adapter/src/test/resources/application-test.yaml new file mode 100644 index 0000000000..fa323e887b --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/test/resources/application-test.yaml @@ -0,0 +1,60 @@ + +aai: + auth: 2A11B07DB6214A839394AA1EC5844695F5114FC407FF5422625FB00175A3DCB8A1FF745F22867EFA72D5369D599BBD88DA8BED4233CF5586 + endpoint: https://aai.onap:30233 +logging: + path: logs + +spring: + datasource: + username: root + password: 123456 + driver-class-name: org.mariadb.jdbc.Driver + initialization-mode: always + url: jdbc:mariadb://49.232.146.162:8989/requestdb + jpa: + generate-ddl: false + show-sql: false + hibernate: + ddl-auto: none + naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy + enable-lazy-load-no-trans: true + database-platform: org.hibernate.dialect.MySQL5InnoDBDialect + security: + usercredentials: + - username: bpel + password: '$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke' + role: BPEL-Client + - username: mso_admin + password: '$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke' + role: ACTUATOR +server: + port: 8080 + tomcat: + max-threads: 50 + +mso: + key: 07a7159d3bf51a0e53be7a8f89699be7 + site-name: localSite + logPath: ./logs/nssmf + adapters: + requestDb: + endpoint: https://so-request-db-adapter.{{ include "common.namespace" . }}:8083 + auth: Basic YnBlbDpwYXNzd29yZDEk + infra: + endpoint: https://so.{{ include "common.namespace" . }}:8080 + auth: Basic SW5mcmFQb3J0YWxDbGllbnQ6cGFzc3dvcmQxJA== + +#Actuator +management: + endpoints: + web: + base-path: /manage + exposure: + include: "*" + metrics: + se-global-registry: false + export: + prometheus: + enabled: true # Whether exporting of metrics to Prometheus is enabled. + step: 1m # Step size (i.e. reporting frequency) to use.
\ No newline at end of file diff --git a/docs/developer_info/Mso_Openstack_Adapter.rst b/docs/developer_info/Mso_Openstack_Adapter.rst new file mode 100644 index 0000000000..a8ca362537 --- /dev/null +++ b/docs/developer_info/Mso_Openstack_Adapter.rst @@ -0,0 +1,796 @@ +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons.org/licenses/by/4.0 +.. Copyright 2020 Huawei Technologies Co., Ltd. + +MSO-OPENSTACK-ADAPTER : +======================= + +.. contents:: :depth: 3 + +Cloud site operations +++++++++++++++++++++++ +* Here we have 3 api's createCloudRegion, updateCloudRegion, deleteCloudRegion. + +1.Create Cloud site/Cloud region: + +Path: /v1/cloud-region + +Method Type: POST + +Request Body: +************* +{ + "id": "MTN13", + "regionId": "mtn13", + "cloudVersion": "3.0", + "clli": "MDT13", + "platform": "testFlatform", + "orchestrator": "testOrchestrator", + "cloudifyId": "mtn13", + "cloudOwner": "testCloudOwner", + + "identityService": { + "identityUrl": "testUrl", + "msoId": "admin", + "msoPass": "admin", + "projectDomainName": "testDomain", + "userDomainName": "testDomain", + "adminTenant": "test", + "memberRole": "test", + "tenantMetadata": "test", + "identityServerType": "test", + "identityAuthenticationType": "test", + "lastUpdatedBy": "test", + "created": "date", + "updated": "date" + + }, + + "identityServiceId": "123", + "lastUpdatedBy": "test", + "created": "test", + "updated": "test", + "supportFabric": "true", + "uri": "test" + +} + +* In this api we can create cloud region and cloud site and saving in catalog db and in AAI. + +* This api requires cloud-region-id and cloudSite as inputs. + +* In createCloudRegion two steps are there. + +* CreateRegionInCatalogDb(cloudSite) :- here we are creating cloud region in catalogdb if it is not exists in db(cloud_sites). + +* CreateCloudRegionInAAI(cloudSite) :- mapping cloudSite into cloudregion , this cloudregion we are creating in AAI and create CloudRegion NetworkTechnology Relationship. + +2.Delete Cloud site: + +* Path:/v1/cloud-region/{cloud-region-id}/{cloud-owner} + +* Here we can delete Cloud site by cloud region id + +3.Update Cloud site: + +* Path:/v1/cloud-region/{cloud-region-id}/{cloud-owner} + +* Here we can update Cloud site by cloud region id + +Create Tenant in Cloud: +++++++++++++++++++++++++ + +Path: http://host:port/vnfs/rest/v1/tenants + +Method Type: POST + +Request Body: +************* + +{ +"cloudSiteId": "DAN", +"tenantName":"RAA_1", +"failIfExists": true, +"msoRequest": { +"requestId": "ra1", +"serviceInstanceId":"sa1" +} +} + +RESPONSE: +********** + +{ + +"cloudSiteId": "DAN", +"tenantId": "128e10b9996d43a7874f19bbc4eb6749", +"tenantCreated": true, +"tenantRollback": { +"tenantId": "128e10b9996d43a7874f19bbc4eb6749", +"cloudId": "DAN", // RAA? cloudId instead of cloudSiteId +"tenantCreated": true, +"msoRequest": { +"requestId": "ra1", +"serviceInstanceId": "sa1" + +} +} +} + +Code Flow: + +* Call to MSO createTenant adapter then call to catalog db for cloud site info and from cloud site get IdentityServerType. +* based on Cloud IdentityServerType it returns ORM or KEYSTONE Utils +* Query for a tenant with the specified name in the given cloud. If the tenant exists, return an MsoTenant object. If not, return null. +* Create a tenant with the specified name in the given cloud. If the tenant already exists, an Exception will be thrown. The MSO User will also be added to the "member" list of the new tenant to perform subsequent Nova/Heat commands in the tenant. If the MSO User association fails, the entire transaction will be rolled back. + +TaskServices +++++++++++++++ +**1. CreateInventory** + +Flow Diagram: + +.. image :: ../images/InventoryCreate.png + +Code Flow: + +* Get cloud site using cloud region id from catalog db. + +* Instantiate heat bridge client by passing required values. + +* Authenticate heat bridge client. + +* If authentication is success we are getting all stack resources(openstack servers. servers contains openstack images and flavours.) + +* From stack resources we are getting osServers/ compute resources. + +* CreatePserversAndPinterfacesIfNotPresentInAai --Transform Openstack Server object to AAI Pserver object. create pserver in AAI if it is not exist. and get openstackresource id's / ports -- transform ports to pinterface Object in AAI. + +* After extract osimages and os flavours from osservers. + +* After that transform osimages to AAI images and osflavours to AAI flavors and add to AAI. + +* Create Vservers in AAI and make relationships to AAI image, AAI flavor, AAI pserver, vf-module. + +* Add Vservers and Linterfaces to AAI--Transform port to Linterface and for that port Get Ip addresses and updateLInterfaceIps and updateLInterfaceVlan. + +* Finally update AAI. + +**2. AuditCreateStack** + +Flow Diagram: + +.. image :: ../images/InventoryAddAudit.png + +Code Flow: + +* First we are capturing entry timestamp, MSO REQUESTID, Servicename/topic name,partnername as openstack adapter, invocation id is generating one random uuid. + +* After that getting auditInventory details from externalTask object + +* From auditInventory object we are getting cloud region,clowd owner,tenant id, heatstack name.these details we are passing to get AAIObjectAuditList. + +* Use cloudRegion, tenantId, heatStackName to get resources from Heat client. + +* To get resources we need heat client it means getting keystone url and token. + +* Get keystone url based on server type(keystone/keystonev3) + +* From resources object we are getting novaResources and resource groups and neutronPortDetails. + +* Create VserverSet by passing resources, novaResources, neutronPortDetails and setting up servers with ports to Set of Servers. + +* From resource groups we are getting Link(stackLink) from that link we are extracting resource path .if path is present we are Fetching nested Resource Stack Information. + +* audit all vservers,l-interfaces and sub l-interfaces. and checking in these vservers , l-interfaces and sub interfaces are existed or not in AAI. + +* If AAIObjectAuditList is present then we are setting audit type as create and Heat stack name to AAIObjectAuditList. + +* If Audit create success putting in variable to complete external task other wise sending exception. + +* If retrycount=1 sending error as retrycount exhausted. + +**3. AuditQueryStack** + +Flow Diagram: + +.. image :: ../images/InventoryQueryAudit.png + + +Code Flow: + +* Get AuditInventory details from external task. + +* Get AAIObjectAuditList from auditHeatStack by passing these parametersauditInventory.getCloudRegion(),auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName(). + +* Fetching Top Level Stack Information.i.e get all the heat model resources. + +* From heat model resources get all OS::Nova::Servers and OS::Heat::ResourceGroups and neutronPortDetails. + +* Once u got all the stack info u create vserverset and add that vserverset to AAIObjectAuditList. + +* After add AAIObjectAuditList to requestdb if it is not exist in requestdb. + +* If it is success complete the external task. + +**4. AuditDeleteStack** + +Flow Diagram: + +.. image :: ../images/InventoryDeleteAudit.png + +Code Flow: + +* Get AuditInventory details from external task + +* GetStackDataFromRequestDb usiing AuditInventory details. + +* Get RequestProcessingData from requestdb using auditInventory.getVfModuleId(),auditInventory.getHeatStackName(), "AuditStackData". + +* From RequestProcessingData get AAIObjectAuditList. + +* If AAIObjectAuditList is empty check vservers is exist or not in AAI and set that result as setDoesObjectExist(true/false). + +* Else Auditing Vservers based on vf module relationships--i.e based on genericVnfId and vfModuleName get all the vservers and create AAIObject and set setDoesObjectExist(true) and set that object to list. + +* After that set audit type as delete and heatstackname and check that audit create success or not. + +* If it is success complete the external task. + +**5. DeleteInventory** + +Flow Diagram: + +.. image :: ../images/DeleteInventory.png + + +Code Flow: + +* Get CloudInformation from external task. + +* First get CloudSite details from catalog db by using regionid. + +* From CloudSite get CloudIdentity details. + +* Create a heatbridgeclient. and authenticate the heatbridge. + +* After that delete the VFmodule data using vnfid and vf moduleid. + +* Once delete success complete the external task. + +**6. StackService** + +Flow Diagram: + +.. image :: ../images/OpenstackAdapterInvoke.png + + +Code Flow: + +* From external task getting openstackAdapterTaskRequest and adding to string(xmlRequest). + +* From xmlrequest we are getting requestType. + +1. If requestType is createVolumeGroupRequest then we are creating volume group. + +* Marshalling xmlRequest to CreateVolumeGroupRequest. + +* From CreateVolumeGroupRequest getting completeVnfVfModuleType. + +* After that we are creating vf module by passing required paremeters. + +* If request type Start with X then we are orchestrating a VNF - *NOT* a module! + +* RequestType start with Volume then then we are sending true as volume request. + +* Creating a VnfRollback object by passing required parameters. + +* If nestedStackId is not null we are getting nested heat stack(stack information). + +* If nested heat stack is not null we are getting that output and storing into nestedVolumeOutputs object. + +* If nestedBaseStackId is not null we are getting nestedBaseHeatStack information and setting output to nestedBaseHeatStack. + +* If modelCustomizationUuid is available then with that mcu we are getting VFModuleCustomization(vfmc); + +* If we get VFModuleCustomization then we are extracting VfModule. + +* If vf version is not null then we will get vnfresource by passing vnftype and vnfversion. + +* By here - we would have either a vf or vnfResource. + +* If vf module is not null we are geting vnfresource from vf and from this vnfresource we are getting minversionvnf and maxversionvnf. + +* If minversionvnf and maxversionvnf are not null we are checking cloudConfig is null or not, if cloudConfig is not null then we are getting cloud site intormation by passing cloud site id. once we get the cloud site details we are getting min and max cloud site versions. + +* By the time we get here - heatTemplateId and heatEnvtId should be populated (or null) + +* If it is old way we will get heatTemplate directly. else if vf module is not null then +* If it is a volume request then we will get volumeheattemplate and volumeheatenvironment. +* If it is not a volume request then we will get ModuleHeatTemplate and HeatEnvironment. + +* Once we get heat templates we are getting nestedtemplates. + +* Also add the files: for any get_files associated with this vnf_resource_id + +* Add ability to turn on adding get_files with volume requests (by property). + +* If it is not a volume request get heat files from vf module. + +* CheckRequiredParameters in MsoVnfAdapterImpl.CHECK_REQD_PARAMS. + +* Parse envt entries to see if reqd parameter is there (before used a simple grep + +* Only submit to openstack the parameters in the envt that are in the heat template + +* Convert what we got as inputs (Map<String, String>) to a Map<String, Object> - where the object matches the param type identified in the template This will also not copy over params that aren't identified in the template + +* Now simply add the outputs as we received them - no need to convert to string + +* Add in the volume stack outputs if applicable + +* Get all heat template parameters and add to list. + +* Check for missing parameters null or not.if no missing parameters we can proceed for next step. + +* Next create stack with all required values. + +* After creating add heat stackname to vfrollback and copy heatstack outputs to outputs value. so now vf module is created successfully. + +* After sending the response to create volume group.once it is created that response we are setting to VolumeGroup response object. + +2. If requestType is createVfModuleRequest then we are creating VfModule. + +* Marshalling xmlRequest to CreateVolumeGroupRequest. + +* From CreateVolumeGroupRequest getting completeVnfVfModuleType. + +* After that we are creating vf module by passing required paremeters. + +* If request type Start with X then we are orchestrating a VNF - *NOT* a module! + +* RequestType start with Volume then then we are sending true as volume request. + +* Creating a VnfRollback object by passing required parameters. + +* If nestedStackId is not null we are getting nested heat stack(stack information). + +* If nested heat stack is not null we are getting that output and storing into nestedVolumeOutputs object. + +* If nestedBaseStackId is not null we are getting nestedBaseHeatStack information and setting output to nestedBaseHeatStack. + +* If modelCustomizationUuid is available then with that mcu we are getting VFModuleCustomization(vfmc); + +* If we get VFModuleCustomization then we are extracting VfModule. + +* If vf version is not null then we will get vnfresource by passing vnftype and vnfversion. + +* By here - we would have either a vf or vnfResource. + +* If vf module is not null we are geting vnfresource from vf and from this vnfresource we are getting minversionvnf and maxversionvnf. + +* If minversionvnf and maxversionvnf are not null we are checking cloudConfig is null or not, if cloudConfig is not null then we are getting cloud site intormation by passing cloud site id. once we get the cloud site details we are getting min and max cloud site versions. + +* By the time we get here - heatTemplateId and heatEnvtId should be populated (or null) + +* If it is old way we will get heatTemplate directly. else if vf module is not null then + +* If it is a volume request then we will get volumeheattemplate and volumeheatenvironment. + +* If it is not a volume request then we will get ModuleHeatTemplate and HeatEnvironment. + +* Once we get heat templates we are getting nestedtemplates. + +* Also add the files: for any get_files associated with this vnf_resource_id + +* Add ability to turn on adding get_files with volume requests (by property). + +* If it is not a volume request get heat files from vf module. + +* CheckRequiredParameters in MsoVnfAdapterImpl.CHECK_REQD_PARAMS. + +* Parse envt entries to see if reqd parameter is there (before used a simple grep + +* Only submit to openstack the parameters in the envt that are in the heat template + +* Convert what we got as inputs (Map<String, String>) to a Map<String, Object> - where the object matches the param type identified in the template This will also not copy over params that aren't identified in the template + +* Now simply add the outputs as we received them - no need to convert to string + +* Add in the volume stack outputs if applicable + +* Get all heat template parameters and add to list. + +* Check for missing parameters null or not.if no missing parameters we can proceed for next step. + +* Next create stack with all required values. + +* After creating add heat stackname to vfrollback and copy heatstack outputs to outputs value. so now vf module is created successfully. + +3. If requestType is deleteVfModuleRequest then we are deleting VfModule . + +* Get stackinfo using msoHeatUtils by passing cloudSiteId, cloudOwner, tenantId, vnfName parameters. + +* After that using modelCustomizationUuid we are getting VFModuleCustomizaiton--VFModule--heattemplate. + +* After that we are callling msoHeatUtils.deleteStack to delete StackInfo once it deletes we are updating status as deleted using msoHeatUtils.updateResourceStatus. + +4. If requestType is deleteVolumeGroupRequest then we are deleting volume group. + +* Making DeleteVolumeGroupRequest by Unmarshalling xml request. + +* Getting stack information by passing stackName, cloudSiteId, tenantId. + +* If current stack is null then we confirm that heat status not found. + +* If current stack is not null then we are deleting the stack. + +* Once volumegroup is deleted we are setting the response to perticular response class. + +5. If requestType is createNetworkRequest then we are creating network. + +* Making CreateNetworkRequest by Unmarshalling xmlrequest. + +* Check request is contrailRequest or not if it is contrailRequest we are setting shared,external,routeTargets,fqdns,routeTable values else we are setting physicalNetworkName and vlans. + +* Now all the above required values we are passing to create network. + +* Build a default NetworkRollback object (if no actions performed). + +* Getting the cloud site by passing cloudsite id. + +* After we are doing a network check and Retrieve the Network Resource definition. + +* If modelCustomizationUuid null and networkType is not null based on networkType we are getting Network Resource. + +* If modelCustomizationUuid not null then based on modelCustomizationUuid we are getting NetworkResourceCustomization and from that we are getting Network Resource. + +* If NetworkResourceCustomization is null then based on modelCustomizationUuid we are getting CollectionNetworkResourceCustomization and from that we are getting Network Resource. + +* Even though Network Resource is null we are sending error Unable to get network resource with NetworkType. + +* From the network resource we are extracting mode and network type. + +* All Networks are orchestrated via HEAT or Neutron if it is other than that we are sending error. + +* After that we are checking network resorce min and max versions with cloud site version if version is not supported throwing error. + +* After that validating the network parameters that if any parameter is missing. + +* Once we Retrieve the Network Resource we are getting heat template and NetworkType from that. + +* From the heat template we are getting template and checking that template contains os3nw if it is contains making flag is true. + +* First, look up to see if the Network already exists (by name).For HEAT orchestration of networks, the stack name will always match the network name + +* If stack is already exist with the network name throw an error. + +* After that from stackinfo get network id and network fqdn and get outputs from Stackinfo. + +* After that get subnetIdMap based on one subnet_id output or multiples subnet_%aaid% outputs from Stackinfo outputs. + +* After that update the updateResourceStatus as exits in requestdb. + +* Now we are Ready to deploy the new Network and Build the common set of HEAT template parameters + +* Validate (and update) the input parameters against the DB definition + +* Shouldn't happen unless DB config is wrong, since all networks use same inputs and inputs were already validated. + +* If subnets are not null and template is os3template then mergesubnetsAIC3. + +* If subnets are not null and template is not os3template then merge subnets. + +* If policyFqdns are not null & os3template true then mergePolicyRefs. + +* After that deploy the network stack-- create stack and once stack is created save into stackinfo. + +* For Heat-based orchestration, the MSO-tracked network ID is the heat stack, and the neutronNetworkId is the network UUID returned in stack outputs. + +* After update the resource status like network created successfully. + +* After set response to CreateNetworkResponse object. + + +6. If requestType is deleteNetworkRequest then we are deleting network. + +* Form a DeleteNetworkRequest by unmarshlling Xml request. + +* check for mandatory fields networkId, cloudSiteId, tenantId. + +* If it is there Retrieve the Network Resource definition. + +* After that get networkResource.from networkResource get heat template. + +* After that delete stackinfo udpate resource status as deleted. + +7. If requestType is updateNetworkRequest then we are updating Network. + +* Make UpdateNetworkRequest by unmarshalling xmlRequest. + +* Check the params contains key shared and external if it is contains get that shared and external keys. + +* Check the request is ContrailRequest or not, if it is ContrailRequest then get routeTargets , fqdns, routeTable from the actual request. + +* If it is not ContrailRequest then get the ProviderVlanNetwork details like physicalNetworkName and vlans. + +* Params to update network-req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(),req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getNetworkName(), physicalNetworkName,vlans, routeTargets, shared, external, req.getSubnets(), fqdns, routeTable, req.getMsoRequest(), subnetIdMap, networkRollback. + +* Update Network adapter with Network using networkName, networkType,cloudSiteId, tenantId. + +* Capture execution time for metrics. + +* Build a default rollback object (no actions performed) + +* Get cloud site details from catalog db using cloud site id. + +* If cloud site is not present send the error message like CloudSite does not exist in MSO Configuration. + +* Getting the cloud site by passing cloudsite id. + +* After we are doing a network check and Retrieve the Network Resource definition. + +* If modelCustomizationUuid null and networkType is not null based on networkType we are getting Network Resource. + +* If modelCustomizationUuid not null then based on modelCustomizationUuid we are getting NetworkResourceCustomization and from that we are getting Network Resource. + +* If NetworkResourceCustomization is null then based on modelCustomizationUuid we are getting CollectionNetworkResourceCustomization and from that we are getting Network Resource. + +* Even though Network Resource is null we are sending error Unable to get network resource with NetworkType. + +* From the network resource we are extracting mode and network type. + +* All Networks are orchestrated via HEAT or Neutron if it is other than that we are sending error. + +* After that we are checking network resorce min and max versions with cloud site version if version is not supported throwing error. + +* After that validating the network parameters that if any parameter is missing. + +* Once we Retrieve the Network Resource we are getting heat template and NetworkType from that. + +* Use an MsoNeutronUtils for all Neutron commands + +* If Orchestaration mode is NEUTRON Verify that the Network exists and For Neutron-based orchestration, the networkId is the Neutron Network UUID. + +* Get NetworkInfo from cloud site using networkId, tenantId, cloudSiteId as params. + +* If NetworkInfo is null then throw the error message as Network is does not exist. + +* Update the network in cloud site which is in catalog db using cloudSiteId,tenantId,networkId, neutronNetworkType, physicalNetworkName, vlans as params. + +* Add the network ID and previously queried vlans to the rollback object. + +* Save previous parameters such as NetworkName,PhysicalNetwork,Vlans to the NetworkRollback. + +* If Orchestaration mode is HEAT then First, look up to see that the Network already exists. For Heat-based orchestration, the networkId is the network Stack ID. + +* Get StackInfo by querystack using cloudSiteId, CLOUD_OWNER, tenantId, networkName. + +* If StackInfo is null throw error as Network not found else continue the flow. + +* Get the previous parameters such as previousNetworkName and previousPhysicalNetwork for rollback from StackInfo. + +* Get the previous vlans from the heat params and Update Stack with Previous VLANS. + +* Now we are Ready to deploy the updated Network via Heat. + +* Get the HeatTemplate from NetworkResource and now we got HEAT Template from DB. + +* Now get the OS::ContrailV2::VirtualNetwork property from property file , if template contains os3nw set flag as true. + +* Build the common set of HEAT template parameters such as neutronNetworkType, networkName, physicalNetworkName, vlans, routeTargets, shared, external, os3template. + +* Validate and update the input parameters against the DB definition and Shouldn't happen unless DB config is wrong, since all networks use same inputs. + +* If subnets are not null and template is os3template then mergesubnetsAIC3. + +* If subnets are not null and template is not os3template then merge subnets. + +* If policyFqdns are not null & os3template true then mergePolicyRefs. + +* If routeTableFqdns are not null os3template not null then mergeRouteTableRefs using routeTableFqdns, stackParams as params. + +* Get outputs from StackInfo and if key is contains subnet and os3template not null then one subnet output expected else multiples subnet outputs allowed. + +* Reach this point if createStack is successful.Populate remaining rollback info and response parameters and save previous parameters. + +* Now Network successfully updated via HEAT. + +8. If requestType is rollbackNetworkRequest then we are doing rollbackNetwork. + +* Make RollbackNetworkRequest by unmarshalling xmlRequest. + +* Get NetworkRollback from RollbackNetworkRequest. + +* If pollForCompletion is null then set flag as true. + +* Get the elements of the VnfRollback object for easier access. + +* ROLLBACK Network using networkId, cloudSiteId, tenantId. + +* If NetworkCreated then use tenantId, CLOUD_OWNER, cloudSiteId, networkId, pollForCompletion, timeoutMinutes params to delete stack. + +* Once deletion is success set the response to RollbackNetworkResponse. + +* Once task stack service is success set the status completed for the external task. + + +**7. PollService** + +Flow Diagram: + +.. image :: ../images/OpenstackAdapterPoller.png + + +Code Flow: + +* Get openstackAdapterTaskRequest as xmlRequest from the the external task. + +* Get requestType from the xmlRequest. + +1. If request type is createVolumeGroupRequest then Execute External Task Rollback Service for Create Volume Group. + +* Create CreateVolumeGroupRequest by unmarshalling xmlRequest. + +* Use CloudSiteId, CloudOwner, TenantId,VolumeGroupName, MsoRequest ,pollStackStatus as params to delete vnf. + +* Call to openstack to delete vnf if it is success nothing to return if it is failure return failure exception. + +* Once it is success set the boolean flags pollRollbackStatus and status as true. + +2. If request type is createVfModuleRequest then Execute External Task Rollback Service for Create Vf Module. + +* Create CreateVfModuleRequest by unmarshalling xmlRequest. + +* Use CloudSiteId, CloudOwner, TenantId,VfModuleName, VnfId, VfModuleId, ModelCustomizationUuid,MsoRequest ,Holder as params to delete vf module. + +* Call to openstack to get the stack outputs. + +* If modelCustomizationUuid is not null then use as a param to get the VfModuleCustomization and from VfModuleCustomization get the vf module details. + +* Use tenantId, cloudOwner, cloudSiteId, vnfName, pollForCompletion, timeoutMinutes as params to delete the stack .once it is success update the resources. + +* Once it is success set the boolean flags pollRollbackStatus and status as true. + +3. If requestType is deleteVfModuleRequest then Execute External Task Poll Service for Delete Vf Module. + +* Create DeleteVfModuleRequest by unmarshalling xmlRequest. + +* Get stackId from external task by using that get Stack. + +* Get pollingFrequency from properties file and calculate no.of polling attempts. + +* Using cloudSiteId, tenantId get Heatclient and once you got heatclient querystack to get the Stack object. + +* If Stack object is not null update the stack status in requestdb and it returns Stack object. + +* If Stack object is not null check the status is DELETE_COMPLETE then Stack Deletion completed successfully. + + +4. If requestType is deleteVolumeGroupRequest then Execute Execute External Task Poll Service for Delete Volume Group. + +* Create DeleteVfModuleRequest by unmarshalling xmlRequest. + +* Get stackId from external task by using that get Stack. + +* Get pollingFrequency from properties file and calculate no.of polling attempts. + +* Using cloudSiteId, tenantId get Heatclient and once you got heatclient querystack to get the Stack object. + +* If Stack object is not null update the stack status in requestdb and it returns Stack object. + +* If Stack object is not null check the status is DELETE_COMPLETE then Stack Deletion completed successfully. + +5. If requestType is deleteNetworkRequest then Execute External Task Poll Service for Delete Network. + +* Create DeleteVfModuleRequest by unmarshalling xmlRequest. + +* Get stackId from external task by using that get Stack. + +* Get pollingFrequency from properties file and calculate no.of polling attempts. + +* Using cloudSiteId, tenantId get Heatclient and once you got heatclient querystack to get the Stack object. + +* If Stack object is not null update the stack status in requestdb and it returns Stack object. + +* If Stack object is not null check the status is DELETE_COMPLETE then Stack Deletion completed successfully. + +6. If requestType is createNetworkRequest then get the PollRollbackStatus from the external task. + +* If pollRollbackStatus is true then Execute External Task Poll Service for Rollback Create Network. + +* Get stackId from external task by using that get Stack. + +* Get pollingFrequency from properties file and calculate no.of polling attempts. + +* Using cloudSiteId, tenantId get Heatclient and once you got heatclient querystack to get the Stack object. + +* If Stack object is not null update the stack status in requestdb and it returns Stack object. + +* If Stack object is not null check the status is DELETE_COMPLETE then Stack Deletion completed successfully. + +* If pollRollbackStatus is false then Execute External Task Poll Service for Create Network. + +* Get stackId from external task by using that get Stack. + +* Get pollingFrequency from properties file and calculate no.of polling attempts. + +* Using cloudSiteId, tenantId get Heatclient and once you got heatclient querystack to get the Stack object. + +* If Stack object is not null update the stack status in requestdb and it returns Stack object. + +* If Stack object is not null check the status is CREATE_COMPLETE then Stack Creation completed successfully. + +7. If requestType is createNetworkRequest then Execute External Task Rollback Service for Create Network. + +* Get stackId from external task by using that get Stack. + +* Get pollingFrequency from properties file and calculate no.of polling attempts. + +* Using cloudSiteId, tenantId get Heatclient and once you got heatclient querystack to get the Stack object. + +* If Stack object is not null update the stack status in requestdb and it returns Stack object. + +* If Stack object is not null check the status is UPDATE_COMPLETE then Stack Updation completed successfully. + +* Once task stack service is success set the status completed for the external task. + +**8. RollbackService** + +Flow Diagram: + +.. image :: ../images/OpenstackAdapterRollback.png + + +Code Flow: + +* Get openstackAdapterTaskRequest as xmlRequest from the the external task. + +* Get requestType from the xmlRequest. + +1. If request type is createVolumeGroupRequest then Execute External Task Rollback Service for Create Volume Group. + +* Making DeleteVolumeGroupRequest by Unmarshalling xml request. + +* Getting stack information by passing stackName, cloudSiteId, tenantId. + +* If current stack is null then we confirm that heat status not found. + +* If current stack is not null then we are deleting the stack. + +* Once volumegroup is deleted we are setting the response to perticular response class. + +2. If request type is createVfModuleRequest then Execute External Task Rollback Service for Create Vf Module. + +* Get stackinfo using msoHeatUtils by passing cloudSiteId, cloudOwner, tenantId, vnfName parameters. + +* After that using modelCustomizationUuid we are getting VFModuleCustomizaiton--VFModule--heattemplate. + +* After that we are callling msoHeatUtils.deleteStack to delete StackInfo once it deletes we are updating status as deleted using msoHeatUtils.updateResourceStatus. + +* Once it is success set the boolean flags pollRollbackStatus and status as true. + +3. If request type is createNetworkRequest then Execute External Task Rollback Service for Create Network. + +* Form a DeleteNetworkRequest by unmarshlling Xml request. + +* Check for mandatory fields networkId, cloudSiteId, tenantId. + +* If it is there Retrieve the Network Resource definition. + +* After that get networkResource.from networkResource get heat template. + +* After that delete stackinfo udpate resource status as deleted. + +* Once task stack service is success set the status completed for the external task. + + + + + + + + + + + diff --git a/docs/developer_info/developer_information.rst b/docs/developer_info/developer_information.rst index 570861345c..1b9e83b840 100644 --- a/docs/developer_info/developer_information.rst +++ b/docs/developer_info/developer_information.rst @@ -20,5 +20,6 @@ SO Developer Information BPMN_Subprocess_Process_Flows.rst BPMN_Project_Deployment_Strategy.rst BPMN-INFRA_Workflow_Understanding.rst + Mso_Openstack_Adapter.rst instantiate/index.rst FAQs.rst diff --git a/docs/images/DeleteInventory.png b/docs/images/DeleteInventory.png Binary files differnew file mode 100644 index 0000000000..0fd6629db8 --- /dev/null +++ b/docs/images/DeleteInventory.png diff --git a/docs/images/InventoryAddAudit.png b/docs/images/InventoryAddAudit.png Binary files differnew file mode 100644 index 0000000000..9e61c15804 --- /dev/null +++ b/docs/images/InventoryAddAudit.png diff --git a/docs/images/InventoryCreate.png b/docs/images/InventoryCreate.png Binary files differnew file mode 100644 index 0000000000..7df732f1d1 --- /dev/null +++ b/docs/images/InventoryCreate.png diff --git a/docs/images/InventoryDeleteAudit.png b/docs/images/InventoryDeleteAudit.png Binary files differnew file mode 100644 index 0000000000..f2f08bf52b --- /dev/null +++ b/docs/images/InventoryDeleteAudit.png diff --git a/docs/images/InventoryQueryAudit.png b/docs/images/InventoryQueryAudit.png Binary files differnew file mode 100644 index 0000000000..34f6cad128 --- /dev/null +++ b/docs/images/InventoryQueryAudit.png diff --git a/docs/images/OpenstackAdapterInvoke.png b/docs/images/OpenstackAdapterInvoke.png Binary files differnew file mode 100644 index 0000000000..998c4721b0 --- /dev/null +++ b/docs/images/OpenstackAdapterInvoke.png diff --git a/docs/images/OpenstackAdapterPoller.png b/docs/images/OpenstackAdapterPoller.png Binary files differnew file mode 100644 index 0000000000..e95bede9a2 --- /dev/null +++ b/docs/images/OpenstackAdapterPoller.png diff --git a/docs/images/OpenstackAdapterRollback.png b/docs/images/OpenstackAdapterRollback.png Binary files differnew file mode 100644 index 0000000000..1e554263b0 --- /dev/null +++ b/docs/images/OpenstackAdapterRollback.png |