From 2b2091a87d004ccc3cdd7da567a794aac4fe65ca Mon Sep 17 00:00:00 2001 From: PatrikBuhr Date: Tue, 11 Aug 2020 09:24:25 +0200 Subject: REST Style alignment for A1 Policy Management Created a structure for support of different NBI APIs. A version 2 is started, which introduces changes initiated by reviews and aligns to https://opensource.zalando.com/restful-api-guidelines/#118 More alignment will be done in later commits. Issue-ID: CCSDK-2498 Change-Id: I810ecce79b5e2462cc77a1c2e7c638fbc6d54774 Signed-off-by: PatrikBuhr --- .../a1policymanagementservice/SwaggerConfig.java | 26 +- .../clients/A1ClientFactory.java | 15 +- .../clients/AsyncRestClient.java | 6 +- .../clients/OscA1Client.java | 8 +- .../clients/SdncOnapA1Client.java | 6 +- .../clients/SdncOscA1Client.java | 22 +- .../clients/StdA1ClientVersion1.java | 4 +- .../configuration/ApplicationConfig.java | 16 +- .../configuration/ApplicationConfigParser.java | 21 +- .../configuration/RicConfig.java | 2 +- .../controllers/PolicyController.java | 482 ------------------- .../controllers/PolicyInfo.java | 57 --- .../controllers/RicInfo.java | 51 -- .../controllers/RicRepositoryController.java | 109 ----- .../controllers/ServiceController.java | 184 -------- .../controllers/ServiceRegistrationInfo.java | 61 --- .../controllers/ServiceStatus.java | 51 -- .../controllers/StatusController.java | 48 -- .../controllers/VoidResponse.java | 32 ++ .../controllers/v1/Consts.java | 29 ++ .../controllers/v1/PolicyController.java | 480 +++++++++++++++++++ .../controllers/v1/PolicyInfo.java | 57 +++ .../controllers/v1/RicInfo.java | 51 ++ .../controllers/v1/RicRepositoryController.java | 109 +++++ .../controllers/v1/ServiceController.java | 186 ++++++++ .../controllers/v1/ServiceRegistrationInfo.java | 59 +++ .../controllers/v1/ServiceStatus.java | 51 ++ .../controllers/v1/StatusController.java | 48 ++ .../controllers/v2/Consts.java | 36 ++ .../controllers/v2/ErrorResponse.java | 106 +++++ .../controllers/v2/JsonObject.java | 30 ++ .../controllers/v2/JsonSchema.java | 30 ++ .../controllers/v2/PolicyController.java | 516 +++++++++++++++++++++ .../controllers/v2/PolicyIdList.java | 45 ++ .../controllers/v2/PolicyInfo.java | 73 +++ .../controllers/v2/PolicyInfoList.java | 46 ++ .../controllers/v2/PolicySchemaList.java | 53 +++ .../controllers/v2/PolicyTypeIdList.java | 45 ++ .../controllers/v2/RicInfo.java | 75 +++ .../controllers/v2/RicInfoList.java | 46 ++ .../controllers/v2/RicRepositoryController.java | 150 ++++++ .../controllers/v2/ServiceController.java | 194 ++++++++ .../controllers/v2/ServiceRegistrationInfo.java | 64 +++ .../controllers/v2/ServiceStatus.java | 62 +++ .../controllers/v2/ServiceStatusList.java | 46 ++ .../controllers/v2/StatusController.java | 64 +++ .../dmaap/DmaapMessageConsumer.java | 3 +- .../repository/Policies.java | 16 +- .../repository/Policy.java | 6 +- .../repository/PolicyType.java | 2 +- .../repository/PolicyTypes.java | 2 +- .../a1policymanagementservice/repository/Ric.java | 18 +- .../a1policymanagementservice/repository/Rics.java | 16 +- .../tasks/RefreshConfigTask.java | 11 +- .../tasks/RicSupervision.java | 10 +- .../tasks/RicSynchronizationTask.java | 30 +- .../tasks/ServiceSupervision.java | 4 +- 57 files changed, 2920 insertions(+), 1150 deletions(-) delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyController.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyInfo.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicInfo.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicRepositoryController.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceController.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceRegistrationInfo.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceStatus.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/StatusController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/VoidResponse.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/Consts.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyInfo.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicInfo.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicRepositoryController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceRegistrationInfo.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceStatus.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/StatusController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/Consts.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ErrorResponse.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonObject.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonSchema.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyIdList.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfo.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfoList.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicySchemaList.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyTypeIdList.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfo.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfoList.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicRepositoryController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceController.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceRegistrationInfo.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatus.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatusList.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/StatusController.java (limited to 'a1-policy-management/src/main/java/org') diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/SwaggerConfig.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/SwaggerConfig.java index 7e25ba13..4b684288 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/SwaggerConfig.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/SwaggerConfig.java @@ -31,14 +31,16 @@ import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Swagger configuration class that uses swagger2 documentation type and scans - * all the controllers under org.onap.ccsdk.oran.a1policymanagementservice.controllers package. To - * access the swagger gui go to http://ip:port/swagger-ui.html + * all the controllers under + * org.onap.ccsdk.oran.a1policymanagementservice.controllers package. To access + * the swagger gui go to http://ip:port/swagger-ui.html * */ @Configuration @@ -46,8 +48,17 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; public class SwaggerConfig extends WebMvcConfigurationSupport { static final String API_TITLE = "A1 Policy management service"; - static final String DESCRIPTION = "This page lists all the rest apis for the service."; - static final String VERSION = "1.0"; + static final String DESCRIPTION = + "The O-RAN NonRT-RIC PolicyAgent provides a REST API for management of policices. \n" + + "It provides support for: \n" + + "-Supervision of clients (R-APPs) to eliminate stray policies in case of failure \n" + + "-Consistency monitoring of the SMO view of policies and the actual situation in the NearRT-RICs \n" + + "-Consistency monitoring of NearRT-RIC capabilities (policy types)" + "-Policy configuration. \n" + + "This includes:" + "-One REST API towards all NearRT-RICs in the network \n" + + "-Query functions that can find all policies in a NearRT-RIC, all policies owned by a service (R-APP), \n" + + "all policies of a type etc. \n" + + "-Maps O1 resources (ManagedElement) as defined in O1 to the controlling NearRT-RIC of A1 policices.\n"; + static final String VERSION = "1.1.0"; @SuppressWarnings("squid:S1075") // Refactor your code to get this URI from a customizable parameter. static final String RESOURCES_PATH = "classpath:/META-INF/resources/"; static final String WEBJARS_PATH = RESOURCES_PATH + "webjars/"; @@ -57,7 +68,7 @@ public class SwaggerConfig extends WebMvcConfigurationSupport { /** * Gets the API info. * - * @return the API info. + * @return the API info.This page lists all the rest apis for the service. */ @Bean public Docket api() { @@ -78,9 +89,14 @@ public class SwaggerConfig extends WebMvcConfigurationSupport { .title(API_TITLE) // .description(DESCRIPTION) // .version(VERSION) // + .contact(contact()) // .build(); } + private static Contact contact() { + return new Contact("Ericsson Software Technology", "", "nonrtric@est.tech"); + } + @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(SWAGGER_UI) // diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java index f8f79e53..2b493575 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java @@ -60,9 +60,9 @@ public class A1ClientFactory { * means that after the first successful creation it won't have to try which * protocol to use, but can create the client directly. * - * @param ric The RIC to get a client for. + * @param ric The NearRT-RIC to get a client for. * @return a client with the correct protocol, or a ServiceException if none of - * the protocols are supported by the Ric. + * the protocols are supported by the NearRT-RIC. */ public Mono createA1Client(Ric ric) { return getProtocolVersion(ric) // @@ -91,7 +91,7 @@ public class A1ClientFactory { String controllerName = ric.getConfig().controllerName(); if (controllerName.isEmpty()) { ric.setProtocolVersion(A1ProtocolType.UNKNOWN); - throw new ServiceException("No controller configured for RIC: " + ric.name()); + throw new ServiceException("No controller configured for NearRT-RIC: " + ric.id()); } try { return this.appConfig.getControllerConfig(controllerName); @@ -105,7 +105,7 @@ public class A1ClientFactory { if (!ric.getConfig().controllerName().isEmpty()) { ric.setProtocolVersion(A1ProtocolType.UNKNOWN); throw new ServiceException( - "Controller config should be empty, ric: " + ric.name() + " when using protocol version: " + version); + "Controller config should be empty, ric: " + ric.id() + " when using protocol version: " + version); } } @@ -124,10 +124,11 @@ public class A1ClientFactory { .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.SDNC_OSC_STD_V1_1)) // .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.SDNC_ONAP)) // .doOnNext(ric::setProtocolVersion) - .doOnNext(version -> logger.debug("Established protocol version:{} for Ric: {}", version, ric.name())) // - .doOnError(notUsed -> logger.warn("Could not get protocol version from RIC: {}", ric.name())) // + .doOnNext( + version -> logger.debug("Established protocol version:{} for NearRT-RIC: {}", version, ric.id())) // + .doOnError(notUsed -> logger.warn("Could not get protocol version from NearRT-RIC: {}", ric.id())) // .onErrorResume( - notUsed -> Mono.error(new ServiceException("Protocol negotiation failed for " + ric.name()))); + notUsed -> Mono.error(new ServiceException("Protocol negotiation failed for " + ric.id()))); } else { return Mono.just(ric.getProtocolVersion()); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/AsyncRestClient.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/AsyncRestClient.java index 55532e6c..c3de6b2c 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/AsyncRestClient.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/AsyncRestClient.java @@ -185,10 +185,14 @@ public class AsyncRestClient { final Class clazz = String.class; return request.retrieve() // .toEntity(clazz) // - .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) // + .doOnNext(entity -> logReceivedData(traceTag, entity)) // .doOnError(throwable -> onHttpError(traceTag, throwable)); } + private void logReceivedData(Object traceTag, ResponseEntity entity) { + logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType()); + } + private static Object createTraceTag() { return sequenceNumber.incrementAndGet(); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java index 4f26b860..bdbb916b 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java @@ -123,7 +123,7 @@ public class OscA1Client implements A1Client { public OscA1Client(RicConfig ricConfig, AsyncRestClient restClient) { this.restClient = restClient; - logger.debug("OscA1Client for ric: {}", ricConfig.name()); + logger.debug("OscA1Client for ric: {}", ricConfig.ricId()); uri = new UriBuilder(ricConfig); } @@ -163,13 +163,13 @@ public class OscA1Client implements A1Client { @Override public Mono putPolicy(Policy policy) { - String policyUri = this.uri.createPutPolicyUri(policy.type().name(), policy.id()); + String policyUri = this.uri.createPutPolicyUri(policy.type().id(), policy.id()); return restClient.put(policyUri, policy.json()); } @Override public Mono deletePolicy(Policy policy) { - return deletePolicyById(policy.type().name(), policy.id()); + return deletePolicyById(policy.type().id(), policy.id()); } @Override @@ -186,7 +186,7 @@ public class OscA1Client implements A1Client { @Override public Mono getPolicyStatus(Policy policy) { - String statusUri = uri.createGetPolicyStatusUri(policy.type().name(), policy.id()); + String statusUri = uri.createGetPolicyStatusUri(policy.type().id(), policy.id()); return restClient.get(statusUri); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java index 90e61492..0591e668 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java @@ -67,7 +67,7 @@ public class SdncOnapA1Client implements A1Client { public SdncOnapA1Client(RicConfig ricConfig, ControllerConfig controllerConfig, WebClientConfig clientConfig) { this(ricConfig, controllerConfig, new AsyncRestClient(controllerConfig.baseUrl() + "/restconf/operations", clientConfig)); - logger.debug("SdncOnapA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.name(), + logger.debug("SdncOnapA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.ricId(), controllerConfig.baseUrl()); } @@ -110,7 +110,7 @@ public class SdncOnapA1Client implements A1Client { public Mono putPolicy(Policy policy) { SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // .nearRtRicId(ricConfig.baseUrl()) // - .policyTypeId(policy.type().name()) // + .policyTypeId(policy.type().id()) // .policyInstanceId(policy.id()) // .policyInstance(policy.json()) // .properties(new ArrayList<>()) // @@ -125,7 +125,7 @@ public class SdncOnapA1Client implements A1Client { @Override public Mono deletePolicy(Policy policy) { - return deletePolicyByTypeId(policy.type().name(), policy.id()); + return deletePolicyByTypeId(policy.type().id(), policy.id()); } @Override diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java index c9e613c5..dffb9dd8 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java @@ -81,9 +81,10 @@ public class SdncOscA1Client implements A1Client { /** * Constructor that creates the REST client to use. * - * @param protocolType the southbound protocol of the controller. Supported protocols are SDNC_OSC_STD_V1_1 and - * SDNC_OSC_OSC_V1 - * @param ricConfig the configuration of the Ric to communicate with + * @param protocolType the southbound protocol of the controller. Supported + * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1 + * @param ricConfig the configuration of the NearRT-RIC to communicate + * with * @param controllerConfig the configuration of the SDNC controller to use * * @throws IllegalArgumentException when the protocolType is wrong. @@ -92,15 +93,16 @@ public class SdncOscA1Client implements A1Client { WebClientConfig clientConfig) { this(protocolType, ricConfig, controllerConfig, new AsyncRestClient(controllerConfig.baseUrl() + "/restconf/operations", clientConfig)); - logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.name(), controllerConfig); + logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.ricId(), controllerConfig); } /** * Constructor where the REST client to use is provided. * - * @param protocolType the southbound protocol of the controller. Supported protocols are SDNC_OSC_STD_V1_1 and - * SDNC_OSC_OSC_V1 - * @param ricConfig the configuration of the Ric to communicate with + * @param protocolType the southbound protocol of the controller. Supported + * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1 + * @param ricConfig the configuration of the NearRT-RIC to communicate + * with * @param controllerConfig the configuration of the SDNC controller to use * @param restClient the REST client to use * @@ -155,14 +157,14 @@ public class SdncOscA1Client implements A1Client { public Mono putPolicy(Policy policy) { return getUriBuilder() // .flatMap(builder -> { - String ricUrl = builder.createPutPolicyUri(policy.type().name(), policy.id()); + String ricUrl = builder.createPutPolicyUri(policy.type().id(), policy.id()); return post("putA1Policy", ricUrl, Optional.of(policy.json())); }); } @Override public Mono deletePolicy(Policy policy) { - return deletePolicyById(policy.type().name(), policy.id()); + return deletePolicyById(policy.type().id(), policy.id()); } @Override @@ -198,7 +200,7 @@ public class SdncOscA1Client implements A1Client { public Mono getPolicyStatus(Policy policy) { return getUriBuilder() // .flatMap(builder -> { - String ricUrl = builder.createGetPolicyStatusUri(policy.type().name(), policy.id()); + String ricUrl = builder.createGetPolicyStatusUri(policy.type().id(), policy.id()); return post("getA1PolicyStatus", ricUrl, Optional.empty()); }); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java index 0f763537..51beea71 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java @@ -102,7 +102,7 @@ public class StdA1ClientVersion1 implements A1Client { @Override public Mono putPolicy(Policy policy) { - return restClient.put(uri.createPutPolicyUri(policy.type().name(), policy.id()), policy.json()); + return restClient.put(uri.createPutPolicyUri(policy.type().id(), policy.id()), policy.json()); } @Override @@ -134,7 +134,7 @@ public class StdA1ClientVersion1 implements A1Client { @Override public Mono getPolicyStatus(Policy policy) { - return restClient.get(uri.createGetPolicyStatusUri(policy.type().name(), policy.id())); + return restClient.get(uri.createGetPolicyStatusUri(policy.type().id(), policy.id())); } private Flux getPolicyIds() { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfig.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfig.java index f03a0ff8..4f8e87fd 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfig.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfig.java @@ -98,10 +98,10 @@ public class ApplicationConfig { return controllerConfig; } - public synchronized RicConfig getRic(String ricName) throws ServiceException { - RicConfig ricConfig = this.ricConfigs.get(ricName); + public synchronized RicConfig getRic(String ricId) throws ServiceException { + RicConfig ricConfig = this.ricConfigs.get(ricId); if (ricConfig == null) { - throw new ServiceException("Could not find ric configuration: " + ricName); + throw new ServiceException("Could not find ric configuration: " + ricId); } return ricConfig; } @@ -133,16 +133,16 @@ public class ApplicationConfig { Map newRicConfigs = new HashMap<>(); for (RicConfig newConfig : parserResult.ricConfigs()) { - RicConfig oldConfig = this.ricConfigs.get(newConfig.name()); - this.ricConfigs.remove(newConfig.name()); + RicConfig oldConfig = this.ricConfigs.get(newConfig.ricId()); + this.ricConfigs.remove(newConfig.ricId()); if (oldConfig == null) { - newRicConfigs.put(newConfig.name(), newConfig); + newRicConfigs.put(newConfig.ricId(), newConfig); modifications.add(new RicConfigUpdate(newConfig, RicConfigUpdate.Type.ADDED)); } else if (!newConfig.equals(oldConfig)) { modifications.add(new RicConfigUpdate(newConfig, RicConfigUpdate.Type.CHANGED)); - newRicConfigs.put(newConfig.name(), newConfig); + newRicConfigs.put(newConfig.ricId(), newConfig); } else { - newRicConfigs.put(oldConfig.name(), oldConfig); + newRicConfigs.put(oldConfig.ricId(), oldConfig); } } for (RicConfig deletedConfig : this.ricConfigs.values()) { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfigParser.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfigParser.java index f3fbb2fb..07c04e1a 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfigParser.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/ApplicationConfigParser.java @@ -25,6 +25,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -101,8 +102,8 @@ public class ApplicationConfigParser { if (!ricUrls.add(ric.baseUrl())) { throw new ServiceException("Configuration error, more than one RIC URL: " + ric.baseUrl()); } - if (!ricNames.add(ric.name())) { - throw new ServiceException("Configuration error, more than one RIC with name: " + ric.name()); + if (!ricNames.add(ric.ricId())) { + throw new ServiceException("Configuration error, more than one RIC with name: " + ric.ricId()); } if (!ric.controllerName().isEmpty() && controllerConfigs.get(ric.controllerName()) == null) { throw new ServiceException( @@ -117,8 +118,8 @@ public class ApplicationConfigParser { for (JsonElement ricElem : getAsJsonArray(config, "ric")) { JsonObject ricAsJson = ricElem.getAsJsonObject(); JsonElement controllerNameElement = ricAsJson.get(CONTROLLER); - ImmutableRicConfig ricConfig = ImmutableRicConfig.builder() // - .name(get(ricAsJson, "name").getAsString()) // + RicConfig ricConfig = ImmutableRicConfig.builder() // + .ricId(get(ricAsJson, "name", "id", "ricId").getAsString()) // .baseUrl(get(ricAsJson, "baseUrl").getAsString()) // .managedElementIds(parseManagedElementIds(get(ricAsJson, "managedElementIds").getAsJsonArray())) // .controllerName(controllerNameElement != null ? controllerNameElement.getAsString() : "") // @@ -160,12 +161,14 @@ public class ApplicationConfigParser { return managedElementIds; } - private static JsonElement get(JsonObject obj, String memberName) throws ServiceException { - JsonElement elem = obj.get(memberName); - if (elem == null) { - throw new ServiceException("Could not find member: '" + memberName + "' in: " + obj); + private static JsonElement get(JsonObject obj, String... alternativeMemberNames) throws ServiceException { + for (String memberName : alternativeMemberNames) { + JsonElement elem = obj.get(memberName); + if (elem != null) { + return elem; + } } - return elem; + throw new ServiceException("Could not find member: " + Arrays.toString(alternativeMemberNames) + " in: " + obj); } private JsonArray getAsJsonArray(JsonObject obj, String memberName) throws ServiceException { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/RicConfig.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/RicConfig.java index 4d141cc9..7f7f9f5e 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/RicConfig.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/RicConfig.java @@ -26,7 +26,7 @@ import org.immutables.value.Value; @Value.Immutable public interface RicConfig { - public String name(); + public String ricId(); public String controllerName(); diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyController.java deleted file mode 100644 index 39876cfc..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyController.java +++ /dev/null @@ -1,482 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -import java.lang.invoke.MethodHandles; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import lombok.Getter; - -import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory; -import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.reactive.function.client.WebClientResponseException; -import reactor.core.publisher.Mono; - -@RestController -@Api(tags = "A1 Policy Management") -public class PolicyController { - - public static class RejectionException extends Exception { - private static final long serialVersionUID = 1L; - @Getter - private final HttpStatus status; - - public RejectionException(String message, HttpStatus status) { - super(message); - this.status = status; - } - } - - @Autowired - private Rics rics; - @Autowired - private PolicyTypes policyTypes; - @Autowired - private Policies policies; - @Autowired - private A1ClientFactory a1ClientFactory; - @Autowired - private Services services; - - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - private static Gson gson = new GsonBuilder() // - .serializeNulls() // - .create(); // - - @GetMapping("/policy_schemas") - @ApiOperation(value = "Returns policy type schema definitions") - @ApiResponses( - value = { - @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), // - @ApiResponse(code = 404, message = "RIC is not found", response = String.class)}) - public ResponseEntity getPolicySchemas( // - @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get the definitions for.") // - @RequestParam(name = "ric", required = false) String ricName) { - if (ricName == null) { - Collection types = this.policyTypes.getAll(); - return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); - } else { - try { - Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); - return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); - } - } - } - - @GetMapping("/policy_schema") - @ApiOperation(value = "Returns one policy type schema definition") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "Policy schema", response = Object.class), - @ApiResponse(code = 404, message = "RIC is not found", response = String.class)}) - public ResponseEntity getPolicySchema( // - @ApiParam(name = "id", required = true, value = "The ID of the policy type to get the definition for.") // - @RequestParam(name = "id", required = true) String id) { - try { - PolicyType type = policyTypes.getType(id); - return new ResponseEntity<>(type.schema(), HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); - } - } - - @GetMapping("/policy_types") - @ApiOperation(value = "Query policy type names") - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "Policy type names", - response = String.class, - responseContainer = "List"), - @ApiResponse(code = 404, message = "RIC is not found", response = String.class)}) - public ResponseEntity getPolicyTypes( // - @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get types for.") // - @RequestParam(name = "ric", required = false) String ricName) { - if (ricName == null) { - Collection types = this.policyTypes.getAll(); - return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); - } else { - try { - Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); - return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); - } - } - } - - @GetMapping("/policy") - @ApiOperation(value = "Returns a policy configuration") // - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "Policy found", response = Object.class), // - @ApiResponse(code = 404, message = "Policy is not found")} // - ) - public ResponseEntity getPolicy( // - @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") // - @RequestParam(name = "id", required = true) String id) { - try { - Policy p = policies.getPolicy(id); - return new ResponseEntity<>(p.json(), HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); - } - } - - @DeleteMapping("/policy") - @ApiOperation(value = "Delete a policy", response = Object.class) - @ApiResponses( - value = { // - @ApiResponse(code = 204, message = "Policy deleted", response = Object.class), - @ApiResponse(code = 404, message = "Policy is not found", response = String.class), - @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)}) - public Mono> deletePolicy( // - @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") // - @RequestParam(name = "id", required = true) String id) { - try { - Policy policy = policies.getPolicy(id); - keepServiceAlive(policy.ownerServiceName()); - Ric ric = policy.ric(); - return ric.getLock().lock(LockType.SHARED) // - .flatMap(notUsed -> assertRicStateIdle(ric)) // - .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) // - .doOnNext(notUsed -> policies.remove(policy)) // - .flatMap(client -> client.deletePolicy(policy)) // - .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // - .doOnError(notUsed -> ric.getLock().unlockBlocking()) // - .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT))) - .onErrorResume(this::handleException); - } catch (ServiceException e) { - return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)); - } - } - - @PutMapping(path = "/policy") - @ApiOperation(value = "Put a policy", response = String.class) - @ApiResponses( - value = { // - @ApiResponse(code = 201, message = "Policy created", response = Object.class), // - @ApiResponse(code = 200, message = "Policy updated", response = Object.class), // - @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), // - @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) // - }) - public Mono> putPolicy( // - @ApiParam(name = "type", required = false, value = "The name of the policy type.") // - @RequestParam(name = "type", required = false, defaultValue = "") String typeName, // - @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") // - @RequestParam(name = "id", required = true) String instanceId, // - @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " + // - "created.") // - @RequestParam(name = "ric", required = true) String ricName, // - @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") // - @RequestParam(name = "service", required = true) String service, // - @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " + // - "defaulted to false). A policy is transient if it will be forgotten when the service needs to " + // - "reconnect to the Near-RT RIC.") // - @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, // - @RequestBody Object jsonBody) { - - String jsonString = gson.toJson(jsonBody); - Ric ric = rics.get(ricName); - PolicyType type = policyTypes.get(typeName); - keepServiceAlive(service); - if (ric == null || type == null) { - return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)); - } - Policy policy = ImmutablePolicy.builder() // - .id(instanceId) // - .json(jsonString) // - .type(type) // - .ric(ric) // - .ownerServiceName(service) // - .lastModified(getTimeStampUtc()) // - .isTransient(isTransient) // - .build(); - - final boolean isCreate = this.policies.get(policy.id()) == null; - - return ric.getLock().lock(LockType.SHARED) // - .flatMap(notUsed -> assertRicStateIdle(ric)) // - .flatMap(notUsed -> checkSupportedType(ric, type)) // - .flatMap(notUsed -> validateModifiedPolicy(policy)) // - .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) // - .flatMap(client -> client.putPolicy(policy)) // - .doOnNext(notUsed -> policies.put(policy)) // - .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // - .doOnError(trowable -> ric.getLock().unlockBlocking()) // - .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) // - .onErrorResume(this::handleException); - } - - @SuppressWarnings({"unchecked"}) - private Mono> createResponseEntity(String message, HttpStatus status) { - ResponseEntity re = new ResponseEntity<>((T) message, status); - return Mono.just(re); - } - - private Mono> handleException(Throwable throwable) { - if (throwable instanceof WebClientResponseException) { - WebClientResponseException e = (WebClientResponseException) throwable; - return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); - } else if (throwable instanceof RejectionException) { - RejectionException e = (RejectionException) throwable; - return createResponseEntity(e.getMessage(), e.getStatus()); - } else { - return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - private Mono validateModifiedPolicy(Policy policy) { - // Check that ric is not updated - Policy current = this.policies.get(policy.id()); - if (current != null && !current.ric().name().equals(policy.ric().name())) { - RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + // - ", RIC name: " + current.ric().name() + // - ", new name: " + policy.ric().name(), HttpStatus.CONFLICT); - logger.debug("Request rejected, {}", e.getMessage()); - return Mono.error(e); - } - return Mono.just("OK"); - } - - private Mono checkSupportedType(Ric ric, PolicyType type) { - if (!ric.isSupportingType(type.name())) { - logger.debug("Request rejected, type not supported, RIC: {}", ric); - RejectionException e = new RejectionException( - "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND); - return Mono.error(e); - } - return Mono.just("OK"); - } - - private Mono assertRicStateIdle(Ric ric) { - if (ric.getState() == Ric.RicState.AVAILABLE) { - return Mono.just("OK"); - } else { - logger.debug("Request rejected RIC not IDLE, ric: {}", ric); - RejectionException e = new RejectionException( - "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED); - return Mono.error(e); - } - } - - @GetMapping("/policies") - @ApiOperation(value = "Query policies") - @ApiResponses( - value = { - @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"), - @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)}) - public ResponseEntity getPolicies( // - @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") // - @RequestParam(name = "type", required = false) String type, // - @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") // - @RequestParam(name = "ric", required = false) String ric, // - @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") // - @RequestParam(name = "service", required = false) String service) // - { - if ((type != null && this.policyTypes.get(type) == null)) { - return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); - } - if ((ric != null && this.rics.get(ric) == null)) { - return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND); - } - - String filteredPolicies = policiesToJson(filter(type, ric, service)); - return new ResponseEntity<>(filteredPolicies, HttpStatus.OK); - } - - @GetMapping("/policy_ids") - @ApiOperation(value = "Query policies, only IDs returned") - @ApiResponses( - value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"), - @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)}) - public ResponseEntity getPolicyIds( // - @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") // - @RequestParam(name = "type", required = false) String type, // - @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") // - @RequestParam(name = "ric", required = false) String ric, // - @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") // - @RequestParam(name = "service", required = false) String service) // - { - if ((type != null && this.policyTypes.get(type) == null)) { - return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); - } - if ((ric != null && this.rics.get(ric) == null)) { - return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND); - } - - String policyIdsJson = toPolicyIdsJson(filter(type, ric, service)); - return new ResponseEntity<>(policyIdsJson, HttpStatus.OK); - } - - @GetMapping("/policy_status") - @ApiOperation(value = "Returns a policy status") // - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "Policy status", response = Object.class), // - @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} // - ) - public Mono> getPolicyStatus( // - @ApiParam(name = "id", required = true, value = "The ID of the policy.") @RequestParam( - name = "id", // - required = true) String id) { - try { - Policy policy = policies.getPolicy(id); - - return a1ClientFactory.createA1Client(policy.ric()) // - .flatMap(client -> client.getPolicyStatus(policy)) // - .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK))) - .onErrorResume(this::handleException); - } catch (ServiceException e) { - return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND)); - } - } - - private void keepServiceAlive(String name) { - Service s = this.services.get(name); - if (s != null) { - s.keepAlive(); - } - } - - private boolean include(String filter, String value) { - return filter == null || value.equals(filter); - } - - private Collection filter(Collection collection, String type, String ric, String service) { - if (type == null && ric == null && service == null) { - return collection; - } - List filtered = new ArrayList<>(); - for (Policy p : collection) { - if (include(type, p.type().name()) && include(ric, p.ric().name()) - && include(service, p.ownerServiceName())) { - filtered.add(p); - } - } - return filtered; - } - - private Collection filter(String type, String ric, String service) { - if (type != null) { - return filter(policies.getForType(type), null, ric, service); - } else if (service != null) { - return filter(policies.getForService(service), type, ric, null); - } else if (ric != null) { - return filter(policies.getForRic(ric), type, null, service); - } else { - return policies.getAll(); - } - } - - private String policiesToJson(Collection policies) { - List v = new ArrayList<>(policies.size()); - for (Policy p : policies) { - PolicyInfo policyInfo = new PolicyInfo(); - policyInfo.id = p.id(); - policyInfo.json = fromJson(p.json()); - policyInfo.ric = p.ric().name(); - policyInfo.type = p.type().name(); - policyInfo.service = p.ownerServiceName(); - policyInfo.lastModified = p.lastModified(); - if (!policyInfo.validate()) { - logger.error("BUG, all fields must be set"); - } - v.add(policyInfo); - } - return gson.toJson(v); - } - - private Object fromJson(String jsonStr) { - return gson.fromJson(jsonStr, Object.class); - } - - private String toPolicyTypeSchemasJson(Collection types) { - StringBuilder result = new StringBuilder(); - result.append("["); - boolean first = true; - for (PolicyType t : types) { - if (!first) { - result.append(","); - } - first = false; - result.append(t.schema()); - } - result.append("]"); - return result.toString(); - } - - private String toPolicyTypeIdsJson(Collection types) { - List v = new ArrayList<>(types.size()); - for (PolicyType t : types) { - v.add(t.name()); - } - return gson.toJson(v); - } - - private String toPolicyIdsJson(Collection policies) { - List v = new ArrayList<>(policies.size()); - for (Policy p : policies) { - v.add(p.id()); - } - return gson.toJson(v); - } - - private String getTimeStampUtc() { - return java.time.Instant.now().toString(); - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyInfo.java deleted file mode 100644 index 266a8449..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/PolicyInfo.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import org.immutables.gson.Gson; - -@Gson.TypeAdapters -@ApiModel(value = "PolicyInfo") -public class PolicyInfo { - - @ApiModelProperty(value = "identity of the policy") - public String id; - - @ApiModelProperty(value = "name of the policy type") - public String type; - - @ApiModelProperty(value = "identity of the target Near-RT RIC") - public String ric; - - @ApiModelProperty(value = "the configuration of the policy") - public Object json; - - @ApiModelProperty(value = "the name of the service owning the policy") - public String service; - - @ApiModelProperty(value = "timestamp, last modification time") - public String lastModified; - - PolicyInfo() { - } - - public boolean validate() { - return id != null && type != null && ric != null && json != null && service != null && lastModified != null; - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicInfo.java deleted file mode 100644 index 0b3b090a..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicInfo.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import java.util.Collection; - -import org.immutables.gson.Gson; - -@Gson.TypeAdapters -@ApiModel(value = "RicInfo") -class RicInfo { - @ApiModelProperty(value = "identity of the ric") - public final String ricName; - - @ApiModelProperty(value = "O1 identities for managed entities") - public final Collection managedElementIds; - - @ApiModelProperty(value = "supported policy types") - public final Collection policyTypes; - - @ApiModelProperty(value = "state info") - public final String state; - - RicInfo(String name, Collection managedElementIds, Collection policyTypes, String state) { - this.ricName = name; - this.managedElementIds = managedElementIds; - this.policyTypes = policyTypes; - this.state = state; - } -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicRepositoryController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicRepositoryController.java deleted file mode 100644 index 88c27a96..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/RicRepositoryController.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@Api(tags = "RIC Repository") -public class RicRepositoryController { - - @Autowired - private Rics rics; - - @Autowired - PolicyTypes types; - - private static Gson gson = new GsonBuilder() // - .serializeNulls() // - .create(); // - - /** - * Example: http://localhost:8081/rics?managedElementId=kista_1 - */ - @GetMapping("/ric") - @ApiOperation(value = "Returns the name of a RIC managing one Mananged Element") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "RIC is found", response = String.class), // - @ApiResponse(code = 404, message = "RIC is not found", response = String.class) // - }) - public ResponseEntity getRic( // - @ApiParam(name = "managedElementId", required = true, value = "The ID of the Managed Element") // - @RequestParam(name = "managedElementId", required = true) String managedElementId) { - Optional ric = this.rics.lookupRicForManagedElement(managedElementId); - - if (ric.isPresent()) { - return new ResponseEntity<>(ric.get().name(), HttpStatus.OK); - } else { - return new ResponseEntity<>("No RIC found", HttpStatus.NOT_FOUND); - } - } - - /** - * @return a Json array of all RIC data Example: http://localhost:8081/ric - */ - @GetMapping("/rics") - @ApiOperation(value = "Query Near-RT RIC information") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "OK", response = RicInfo.class, responseContainer = "List"), // - @ApiResponse(code = 404, message = "Policy type is not found", response = String.class)}) - public ResponseEntity getRics( // - @ApiParam(name = "policyType", required = false, value = "The name of the policy type") // - @RequestParam(name = "policyType", required = false) String supportingPolicyType) { - if ((supportingPolicyType != null) && (this.types.get(supportingPolicyType) == null)) { - return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); - } - - List result = new ArrayList<>(); - for (Ric ric : rics.getRics()) { - if (supportingPolicyType == null || ric.isSupportingType(supportingPolicyType)) { - result.add(new RicInfo(ric.name(), ric.getManagedElementIds(), ric.getSupportedPolicyTypeNames(), - ric.getState().toString())); - } - } - - return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK); - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceController.java deleted file mode 100644 index f06dd583..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceController.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -import java.net.MalformedURLException; -import java.net.URL; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collection; - -import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@Api(tags = "Service registry and supervision") -public class ServiceController { - - private final Services services; - private final Policies policies; - - private static Gson gson = new GsonBuilder() // - .create(); // - - @Autowired - ServiceController(Services services, Policies policies) { - this.services = services; - this.policies = policies; - } - - @GetMapping("/services") - @ApiOperation(value = "Returns service information") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "OK", response = ServiceStatus.class, responseContainer = "List"), // - @ApiResponse(code = 404, message = "Service is not found", response = String.class)}) - public ResponseEntity getServices(// - @ApiParam(name = "name", required = false, value = "The name of the service") // - @RequestParam(name = "name", required = false) String name) { - if (name != null && this.services.get(name) == null) { - return new ResponseEntity<>("Service not found", HttpStatus.NOT_FOUND); - } - - Collection servicesStatus = new ArrayList<>(); - for (Service s : this.services.getAll()) { - if (name == null || name.equals(s.getName())) { - servicesStatus.add(toServiceStatus(s)); - } - } - - String res = gson.toJson(servicesStatus); - return new ResponseEntity<>(res, HttpStatus.OK); - } - - private ServiceStatus toServiceStatus(Service s) { - return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(), - s.getCallbackUrl()); - } - - private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo) - throws ServiceException, MalformedURLException { - if (registrationInfo.serviceName.isEmpty()) { - throw new ServiceException("Missing mandatory parameter 'serviceName'"); - } - if (registrationInfo.keepAliveIntervalSeconds < 0) { - throw new ServiceException("Keepalive interval shoul be greater or equal to 0"); - } - if (!registrationInfo.callbackUrl.isEmpty()) { - new URL(registrationInfo.callbackUrl); - } - } - - @ApiOperation(value = "Register a service") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "Service updated", response = String.class), - @ApiResponse(code = 201, message = "Service created", response = String.class), // - @ApiResponse(code = 400, message = "The ServiceRegistrationInfo is not accepted", response = String.class)}) - @PutMapping("/service") - public ResponseEntity putService(// - @RequestBody ServiceRegistrationInfo registrationInfo) { - try { - validateRegistrationInfo(registrationInfo); - final boolean isCreate = this.services.get(registrationInfo.serviceName) == null; - this.services.put(toService(registrationInfo)); - return new ResponseEntity<>("OK", isCreate ? HttpStatus.CREATED : HttpStatus.OK); - } catch (Exception e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); - } - } - - @ApiOperation(value = "Delete a service") - @ApiResponses( - value = { // - @ApiResponse(code = 204, message = "OK"), - @ApiResponse(code = 404, message = "Service not found", response = String.class)}) - @DeleteMapping("/services") - public ResponseEntity deleteService(// - @ApiParam(name = "name", required = true, value = "The name of the service") // - @RequestParam(name = "name", required = true) String serviceName) { - try { - Service service = removeService(serviceName); - // Remove the policies from the repo and let the consistency monitoring - // do the rest. - removePolicies(service); - return new ResponseEntity<>("OK", HttpStatus.NO_CONTENT); - } catch (Exception e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); - } - } - - @ApiOperation(value = "Heartbeat from a serice") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "Service supervision timer refreshed, OK"), - @ApiResponse(code = 404, message = "The service is not found, needs re-registration")}) - @PutMapping("/services/keepalive") - public ResponseEntity keepAliveService(// - @ApiParam(name = "name", required = true, value = "The name of the service") // - @RequestParam(name = "name", required = true) String serviceName) { - try { - services.getService(serviceName).keepAlive(); - return new ResponseEntity<>("OK", HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); - } - } - - private Service removeService(String name) throws ServiceException { - Service service = this.services.getService(name); // Just to verify that it exists - this.services.remove(service.getName()); - return service; - } - - private void removePolicies(Service service) { - Collection policyList = this.policies.getForService(service.getName()); - for (Policy policy : policyList) { - this.policies.remove(policy); - } - } - - private Service toService(ServiceRegistrationInfo s) { - return new Service(s.serviceName, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl); - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceRegistrationInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceRegistrationInfo.java deleted file mode 100644 index 132c6276..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceRegistrationInfo.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import com.google.gson.annotations.SerializedName; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import org.immutables.gson.Gson; - -@Gson.TypeAdapters -@ApiModel(value = "ServiceRegistrationInfo") -public class ServiceRegistrationInfo { - - @ApiModelProperty(value = "identity of the service", required = true, allowEmptyValue = false) - @SerializedName(value = "serviceName", alternate = {"name"}) - - public String serviceName = ""; - - @ApiModelProperty( - value = "keep alive interval for the service. This is a heartbeat supervision of the service, " - + "which in regular intevals must invoke a 'keepAlive' REST call. " - + "When a service does not invoke this call within the given time, it is considered unavailble. " - + "An unavailable service will be automatically deregistered and its policies will be deleted. " - + "Value 0 means no timeout supervision.") - @SerializedName("keepAliveIntervalSeconds") - public long keepAliveIntervalSeconds = 0; - - @ApiModelProperty(value = "callback for notifying of RIC synchronization", required = false, allowEmptyValue = true) - @SerializedName("callbackUrl") - public String callbackUrl = ""; - - public ServiceRegistrationInfo() { - } - - public ServiceRegistrationInfo(String name, long keepAliveIntervalSeconds, String callbackUrl) { - this.serviceName = name; - this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; - this.callbackUrl = callbackUrl; - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceStatus.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceStatus.java deleted file mode 100644 index d9117099..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/ServiceStatus.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import org.immutables.gson.Gson; - -@Gson.TypeAdapters -@ApiModel(value = "ServiceStatus") -public class ServiceStatus { - - @ApiModelProperty(value = "identity of the service") - public final String serviceName; - - @ApiModelProperty(value = "policy keep alive timeout") - public final long keepAliveIntervalSeconds; - - @ApiModelProperty(value = "time since last invocation by the service") - public final long timeSinceLastActivitySeconds; - - @ApiModelProperty(value = "callback for notifying of RIC synchronization") - public String callbackUrl; - - ServiceStatus(String name, long keepAliveIntervalSeconds, long timeSincePingSeconds, String callbackUrl) { - this.serviceName = name; - this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; - this.timeSinceLastActivitySeconds = timeSincePingSeconds; - this.callbackUrl = callbackUrl; - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/StatusController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/StatusController.java deleted file mode 100644 index f43a96c2..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/StatusController.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; - -@RestController -@Api(tags = "Health check") -public class StatusController { - - @GetMapping("/status") - @ApiOperation(value = "Returns status and statistics of this service") - @ApiResponses( - value = { // - @ApiResponse(code = 200, message = "Service is living", response = String.class) // - }) - public Mono> getStatus() { - return Mono.just(new ResponseEntity<>("hunky dory", HttpStatus.OK)); - } - -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/VoidResponse.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/VoidResponse.java new file mode 100644 index 00000000..6ee656cc --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/VoidResponse.java @@ -0,0 +1,32 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers; + +import io.swagger.annotations.ApiModel; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "void", description = "Void/empty") +public class VoidResponse { + private VoidResponse() { + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/Consts.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/Consts.java new file mode 100644 index 00000000..cef31c30 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/Consts.java @@ -0,0 +1,29 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +public class Consts { + + public static final String V1_API_NAME = "A1 Policy Management Version 1.0"; + + private Consts() { + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyController.java new file mode 100644 index 00000000..2c8ad7f2 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyController.java @@ -0,0 +1,480 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import java.lang.invoke.MethodHandles; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import lombok.Getter; + +import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory; +import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse; +import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClientResponseException; +import reactor.core.publisher.Mono; + +@RestController +@Api(tags = Consts.V1_API_NAME) +public class PolicyController { + + public static class RejectionException extends Exception { + private static final long serialVersionUID = 1L; + @Getter + private final HttpStatus status; + + public RejectionException(String message, HttpStatus status) { + super(message); + this.status = status; + } + } + + @Autowired + private Rics rics; + @Autowired + private PolicyTypes policyTypes; + @Autowired + private Policies policies; + @Autowired + private A1ClientFactory a1ClientFactory; + @Autowired + private Services services; + + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static Gson gson = new GsonBuilder() // + .serializeNulls() // + .create(); // + + @GetMapping("/policy_schemas") + @ApiOperation(value = "Returns policy type schema definitions") + @ApiResponses( + value = { + @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), // + @ApiResponse(code = 404, message = "NearRT-RIC is not found", response = String.class)}) + public ResponseEntity getPolicySchemas( // + @ApiParam(name = "ric", required = false, value = "The name of the NearRT-RIC to get the definitions for.") // + @RequestParam(name = "ric", required = false) String ricName) { + if (ricName == null) { + Collection types = this.policyTypes.getAll(); + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } else { + try { + Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } catch (ServiceException e) { + return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); + } + } + } + + @GetMapping("/policy_schema") + @ApiOperation(value = "Returns one policy type schema definition") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy schema", response = Object.class), + @ApiResponse(code = 404, message = "The policy type is not found", response = String.class)}) + public ResponseEntity getPolicySchema( // + @ApiParam(name = "id", required = true, value = "The identity of the policy type to get the definition for.") // + @RequestParam(name = "id", required = true) String id) { + try { + PolicyType type = policyTypes.getType(id); + return new ResponseEntity<>(type.schema(), HttpStatus.OK); + } catch (ServiceException e) { + return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); + } + } + + @GetMapping("/policy_types") + @ApiOperation(value = "Query policy type names") + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "Policy type names", + response = String.class, + responseContainer = "List"), + @ApiResponse(code = 404, message = "NearRT-RIC is not found", response = String.class)}) + public ResponseEntity getPolicyTypes( // + @ApiParam(name = "ric", required = false, value = "The name of the NearRT-RIC to get types for.") // + @RequestParam(name = "ric", required = false) String ricName) { + if (ricName == null) { + Collection types = this.policyTypes.getAll(); + return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); + } else { + try { + Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); + return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); + } catch (ServiceException e) { + return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); + } + } + } + + @GetMapping("/policy") + @ApiOperation(value = "Returns a policy configuration") // + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy found", response = Object.class), // + @ApiResponse(code = 404, message = "Policy is not found")} // + ) + public ResponseEntity getPolicy( // + @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") // + @RequestParam(name = "id", required = true) String id) { + try { + Policy p = policies.getPolicy(id); + return new ResponseEntity<>(p.json(), HttpStatus.OK); + } catch (ServiceException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); + } + } + + @DeleteMapping("/policy") + @ApiOperation(value = "Delete a policy", response = Object.class) + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class), + @ApiResponse(code = 204, message = "Policy deleted", response = VoidResponse.class), + @ApiResponse(code = 404, message = "Policy is not found", response = String.class), + @ApiResponse(code = 423, message = "NearRT-RIC is not operational", response = String.class)}) + public Mono> deletePolicy( // + @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") // + @RequestParam(name = "id", required = true) String id) { + try { + Policy policy = policies.getPolicy(id); + keepServiceAlive(policy.ownerServiceId()); + Ric ric = policy.ric(); + return ric.getLock().lock(LockType.SHARED) // + .flatMap(notUsed -> assertRicStateIdle(ric)) // + .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) // + .doOnNext(notUsed -> policies.remove(policy)) // + .flatMap(client -> client.deletePolicy(policy)) // + .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // + .doOnError(notUsed -> ric.getLock().unlockBlocking()) // + .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT))) + .onErrorResume(this::handleException); + } catch (ServiceException e) { + return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + } + + @PutMapping(path = "/policy") + @ApiOperation(value = "Put a policy", response = String.class) + @ApiResponses( + value = { // + @ApiResponse(code = 201, message = "Policy created", response = VoidResponse.class), // + @ApiResponse(code = 200, message = "Policy updated", response = VoidResponse.class), // + @ApiResponse(code = 423, message = "NearRT-RIC is not operational", response = String.class), // + @ApiResponse(code = 404, message = "NearRT-RIC or policy type is not found", response = String.class) // + }) + public Mono> putPolicy( // + @ApiParam(name = "type", required = false, value = "The name of the policy type.") // + @RequestParam(name = "type", required = false, defaultValue = "") String typeName, // + @ApiParam(name = "id", required = true, value = "The identity of the policy instance.") // + @RequestParam(name = "id", required = true) String instanceId, // + @ApiParam(name = "ric", required = true, value = "The name of the NearRT-RIC where the policy will be " + // + "created.") // + @RequestParam(name = "ric", required = true) String ricName, // + @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") // + @RequestParam(name = "service", required = true) String service, // + @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " + // + "defaulted to false). A policy is transient if it will be forgotten when the service needs to " + // + "reconnect to the NearRT-RIC.") // + @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, // + @RequestBody Object jsonBody) { + + String jsonString = gson.toJson(jsonBody); + Ric ric = rics.get(ricName); + PolicyType type = policyTypes.get(typeName); + keepServiceAlive(service); + if (ric == null || type == null) { + return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + Policy policy = ImmutablePolicy.builder() // + .id(instanceId) // + .json(jsonString) // + .type(type) // + .ric(ric) // + .ownerServiceId(service) // + .lastModified(Instant.now()) // + .isTransient(isTransient) // + .build(); + + final boolean isCreate = this.policies.get(policy.id()) == null; + + return ric.getLock().lock(LockType.SHARED) // + .flatMap(notUsed -> assertRicStateIdle(ric)) // + .flatMap(notUsed -> checkSupportedType(ric, type)) // + .flatMap(notUsed -> validateModifiedPolicy(policy)) // + .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) // + .flatMap(client -> client.putPolicy(policy)) // + .doOnNext(notUsed -> policies.put(policy)) // + .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // + .doOnError(trowable -> ric.getLock().unlockBlocking()) // + .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) // + .onErrorResume(this::handleException); + } + + @SuppressWarnings({"unchecked"}) + private Mono> createResponseEntity(String message, HttpStatus status) { + ResponseEntity re = new ResponseEntity<>((T) message, status); + return Mono.just(re); + } + + private Mono> handleException(Throwable throwable) { + if (throwable instanceof WebClientResponseException) { + WebClientResponseException e = (WebClientResponseException) throwable; + return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); + } else if (throwable instanceof RejectionException) { + RejectionException e = (RejectionException) throwable; + return createResponseEntity(e.getMessage(), e.getStatus()); + } else { + return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + private Mono validateModifiedPolicy(Policy policy) { + // Check that ric is not updated + Policy current = this.policies.get(policy.id()); + if (current != null && !current.ric().id().equals(policy.ric().id())) { + RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + // + ", RIC name: " + current.ric().id() + // + ", new name: " + policy.ric().id(), HttpStatus.CONFLICT); + logger.debug("Request rejected, {}", e.getMessage()); + return Mono.error(e); + } + return Mono.just("OK"); + } + + private Mono checkSupportedType(Ric ric, PolicyType type) { + if (!ric.isSupportingType(type.id())) { + logger.debug("Request rejected, type not supported, RIC: {}", ric); + RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(), + HttpStatus.NOT_FOUND); + return Mono.error(e); + } + return Mono.just("OK"); + } + + private Mono assertRicStateIdle(Ric ric) { + if (ric.getState() == Ric.RicState.AVAILABLE) { + return Mono.just("OK"); + } else { + logger.debug("Request rejected RIC not IDLE, ric: {}", ric); + RejectionException e = new RejectionException( + "Ric is not operational, RIC name: " + ric.id() + ", state: " + ric.getState(), HttpStatus.LOCKED); + return Mono.error(e); + } + } + + @GetMapping("/policies") + @ApiOperation(value = "Query policies") + @ApiResponses( + value = { + @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"), + @ApiResponse(code = 404, message = "NearRT-RIC or type not found", response = String.class)}) + public ResponseEntity getPolicies( // + @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") // + @RequestParam(name = "type", required = false) String type, // + @ApiParam(name = "ric", required = false, value = "The name of the NearRT-RIC to get policies for.") // + @RequestParam(name = "ric", required = false) String ric, // + @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") // + @RequestParam(name = "service", required = false) String service) // + { + if ((type != null && this.policyTypes.get(type) == null)) { + return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); + } + if ((ric != null && this.rics.get(ric) == null)) { + return new ResponseEntity<>("NearRT-RIC not found", HttpStatus.NOT_FOUND); + } + + String filteredPolicies = policiesToJson(filter(type, ric, service)); + return new ResponseEntity<>(filteredPolicies, HttpStatus.OK); + } + + @GetMapping("/policy_ids") + @ApiOperation(value = "Query policies, only IDs returned") + @ApiResponses( + value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"), + @ApiResponse(code = 404, message = "NearRT-RIC or type not found", response = String.class)}) + public ResponseEntity getPolicyIds( // + @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") // + @RequestParam(name = "type", required = false) String type, // + @ApiParam(name = "ric", required = false, value = "The name of the NearRT-RIC to get policies for.") // + @RequestParam(name = "ric", required = false) String ric, // + @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") // + @RequestParam(name = "service", required = false) String service) // + { + if ((type != null && this.policyTypes.get(type) == null)) { + return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); + } + if ((ric != null && this.rics.get(ric) == null)) { + return new ResponseEntity<>("NearRT-RIC not found", HttpStatus.NOT_FOUND); + } + + String policyIdsJson = toPolicyIdsJson(filter(type, ric, service)); + return new ResponseEntity<>(policyIdsJson, HttpStatus.OK); + } + + @GetMapping("/policy_status") + @ApiOperation(value = "Returns a policy status") // + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy status", response = Object.class), // + @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} // + ) + public Mono> getPolicyStatus( // + @ApiParam(name = "id", required = true, value = "The identity of the policy.") @RequestParam( + name = "id", // + required = true) String id) { + try { + Policy policy = policies.getPolicy(id); + + return a1ClientFactory.createA1Client(policy.ric()) // + .flatMap(client -> client.getPolicyStatus(policy)) // + .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK))) + .onErrorResume(this::handleException); + } catch (ServiceException e) { + return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND)); + } + } + + private void keepServiceAlive(String name) { + Service s = this.services.get(name); + if (s != null) { + s.keepAlive(); + } + } + + private boolean include(String filter, String value) { + return filter == null || value.equals(filter); + } + + private Collection filter(Collection collection, String type, String ric, String service) { + if (type == null && ric == null && service == null) { + return collection; + } + List filtered = new ArrayList<>(); + for (Policy p : collection) { + if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) { + filtered.add(p); + } + } + return filtered; + } + + private Collection filter(String type, String ric, String service) { + if (type != null) { + return filter(policies.getForType(type), null, ric, service); + } else if (service != null) { + return filter(policies.getForService(service), type, ric, null); + } else if (ric != null) { + return filter(policies.getForRic(ric), type, null, service); + } else { + return policies.getAll(); + } + } + + private String policiesToJson(Collection policies) { + List v = new ArrayList<>(policies.size()); + for (Policy p : policies) { + PolicyInfo policyInfo = new PolicyInfo(); + policyInfo.id = p.id(); + policyInfo.json = fromJson(p.json()); + policyInfo.ric = p.ric().id(); + policyInfo.type = p.type().id(); + policyInfo.service = p.ownerServiceId(); + policyInfo.lastModified = p.lastModified().toString(); + if (!policyInfo.validate()) { + logger.error("BUG, all fields must be set"); + } + v.add(policyInfo); + } + return gson.toJson(v); + } + + private Object fromJson(String jsonStr) { + return gson.fromJson(jsonStr, Object.class); + } + + private String toPolicyTypeSchemasJson(Collection types) { + StringBuilder result = new StringBuilder(); + result.append("["); + boolean first = true; + for (PolicyType t : types) { + if (!first) { + result.append(","); + } + first = false; + result.append(t.schema()); + } + result.append("]"); + return result.toString(); + } + + private String toPolicyTypeIdsJson(Collection types) { + List v = new ArrayList<>(types.size()); + for (PolicyType t : types) { + v.add(t.id()); + } + return gson.toJson(v); + } + + private String toPolicyIdsJson(Collection policies) { + List v = new ArrayList<>(policies.size()); + for (Policy p : policies) { + v.add(p.id()); + } + return gson.toJson(v); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyInfo.java new file mode 100644 index 00000000..4cb91c0d --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyInfo.java @@ -0,0 +1,57 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "policy_info_v1") +public class PolicyInfo { + + @ApiModelProperty(value = "identity of the policy") + public String id; + + @ApiModelProperty(value = "name of the policy type") + public String type; + + @ApiModelProperty(value = "identity of the target NearRT-RIC") + public String ric; + + @ApiModelProperty(value = "the configuration of the policy") + public Object json; + + @ApiModelProperty(value = "the name of the service owning the policy") + public String service; + + @ApiModelProperty(value = "timestamp, last modification time") + public String lastModified; + + PolicyInfo() { + } + + public boolean validate() { + return id != null && type != null && ric != null && json != null && service != null && lastModified != null; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicInfo.java new file mode 100644 index 00000000..4257a263 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicInfo.java @@ -0,0 +1,51 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "ric_info_v1") +class RicInfo { + @ApiModelProperty(value = "identity of the NearRT-RIC") + public final String ricName; + + @ApiModelProperty(value = "O1 identities for managed entities") + public final Collection managedElementIds; + + @ApiModelProperty(value = "supported policy types") + public final Collection policyTypes; + + @ApiModelProperty(value = "state info") + public final String state; + + RicInfo(String name, Collection managedElementIds, Collection policyTypes, String state) { + this.ricName = name; + this.managedElementIds = managedElementIds; + this.policyTypes = policyTypes; + this.state = state; + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicRepositoryController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicRepositoryController.java new file mode 100644 index 00000000..5036356e --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/RicRepositoryController.java @@ -0,0 +1,109 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Api(tags = Consts.V1_API_NAME) +public class RicRepositoryController { + + @Autowired + private Rics rics; + + @Autowired + PolicyTypes types; + + private static Gson gson = new GsonBuilder() // + .serializeNulls() // + .create(); // + + /** + * Example: http://localhost:8081/rics?managedElementId=kista_1 + */ + @GetMapping("/ric") + @ApiOperation(value = "Returns the name of a RIC managing one Mananged Element") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "NearRT-RIC is found", response = String.class), // + @ApiResponse(code = 404, message = "NearRT-RIC is not found", response = String.class) // + }) + public ResponseEntity getRic( // + @ApiParam(name = "managedElementId", required = true, value = "The identity of the Managed Element") // + @RequestParam(name = "managedElementId", required = true) String managedElementId) { + Optional ric = this.rics.lookupRicForManagedElement(managedElementId); + + if (ric.isPresent()) { + return new ResponseEntity<>(ric.get().id(), HttpStatus.OK); + } else { + return new ResponseEntity<>("No RIC found", HttpStatus.NOT_FOUND); + } + } + + /** + * @return a Json array of all RIC data Example: http://localhost:8081/ric + */ + @GetMapping("/rics") + @ApiOperation(value = "Query NearRT-RIC information") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "OK", response = RicInfo.class, responseContainer = "List"), // + @ApiResponse(code = 404, message = "Policy type is not found", response = String.class)}) + public ResponseEntity getRics( // + @ApiParam(name = "policyType", required = false, value = "The name of the policy type") // + @RequestParam(name = "policyType", required = false) String supportingPolicyType) { + if ((supportingPolicyType != null) && (this.types.get(supportingPolicyType) == null)) { + return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); + } + + List result = new ArrayList<>(); + for (Ric ric : rics.getRics()) { + if (supportingPolicyType == null || ric.isSupportingType(supportingPolicyType)) { + result.add(new RicInfo(ric.id(), ric.getManagedElementIds(), ric.getSupportedPolicyTypeNames(), + ric.getState().toString())); + } + } + + return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceController.java new file mode 100644 index 00000000..bb85ad14 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceController.java @@ -0,0 +1,186 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import java.net.MalformedURLException; +import java.net.URL; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; + +import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse; +import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Api(tags = Consts.V1_API_NAME) +public class ServiceController { + + private final Services services; + private final Policies policies; + + private static Gson gson = new GsonBuilder() // + .create(); // + + @Autowired + ServiceController(Services services, Policies policies) { + this.services = services; + this.policies = policies; + } + + @GetMapping("/services") + @ApiOperation(value = "Returns service information") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "OK", response = ServiceStatus.class, responseContainer = "List"), // + @ApiResponse(code = 404, message = "Service is not found", response = String.class)}) + public ResponseEntity getServices(// + @ApiParam(name = "name", required = false, value = "The name of the service") // + @RequestParam(name = "name", required = false) String name) { + if (name != null && this.services.get(name) == null) { + return new ResponseEntity<>("Service not found", HttpStatus.NOT_FOUND); + } + + Collection servicesStatus = new ArrayList<>(); + for (Service s : this.services.getAll()) { + if (name == null || name.equals(s.getName())) { + servicesStatus.add(toServiceStatus(s)); + } + } + + String res = gson.toJson(servicesStatus); + return new ResponseEntity<>(res, HttpStatus.OK); + } + + private ServiceStatus toServiceStatus(Service s) { + return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(), + s.getCallbackUrl()); + } + + private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo) + throws ServiceException, MalformedURLException { + if (registrationInfo.serviceName.isEmpty()) { + throw new ServiceException("Missing mandatory parameter 'serviceName'"); + } + if (registrationInfo.keepAliveIntervalSeconds < 0) { + throw new ServiceException("Keepalive interval shoul be greater or equal to 0"); + } + if (!registrationInfo.callbackUrl.isEmpty()) { + new URL(registrationInfo.callbackUrl); + } + } + + @ApiOperation(value = "Register a service") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Service updated", response = String.class), + @ApiResponse(code = 201, message = "Service created", response = String.class), // + @ApiResponse(code = 400, message = "The ServiceRegistrationInfo is not accepted", response = String.class)}) + @PutMapping("/service") + public ResponseEntity putService(// + @RequestBody ServiceRegistrationInfo registrationInfo) { + try { + validateRegistrationInfo(registrationInfo); + final boolean isCreate = this.services.get(registrationInfo.serviceName) == null; + this.services.put(toService(registrationInfo)); + return new ResponseEntity<>("OK", isCreate ? HttpStatus.CREATED : HttpStatus.OK); + } catch (Exception e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } + } + + @ApiOperation(value = "Delete a service") + @ApiResponses( + value = { // + @ApiResponse(code = 204, message = "Service deleted"), + @ApiResponse(code = 204, message = "Not used", response = VoidResponse.class), + @ApiResponse(code = 404, message = "Service not found", response = String.class)}) + @DeleteMapping("/services") + public ResponseEntity deleteService(// + @ApiParam(name = "name", required = true, value = "The name of the service") // + @RequestParam(name = "name", required = true) String serviceName) { + try { + Service service = removeService(serviceName); + // Remove the policies from the repo and let the consistency monitoring + // do the rest. + removePolicies(service); + return new ResponseEntity<>("OK", HttpStatus.NO_CONTENT); + } catch (Exception e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); + } + } + + @ApiOperation(value = "Heartbeat from a serice") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Service supervision timer refreshed, OK"), + @ApiResponse(code = 404, message = "The service is not found, needs re-registration")}) + @PutMapping("/services/keepalive") + public ResponseEntity keepAliveService(// + @ApiParam(name = "name", required = true, value = "The name of the service") // + @RequestParam(name = "name", required = true) String serviceName) { + try { + services.getService(serviceName).keepAlive(); + return new ResponseEntity<>("OK", HttpStatus.OK); + } catch (ServiceException e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); + } + } + + private Service removeService(String name) throws ServiceException { + Service service = this.services.getService(name); // Just to verify that it exists + this.services.remove(service.getName()); + return service; + } + + private void removePolicies(Service service) { + Collection policyList = this.policies.getForService(service.getName()); + for (Policy policy : policyList) { + this.policies.remove(policy); + } + } + + private Service toService(ServiceRegistrationInfo s) { + return new Service(s.serviceName, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceRegistrationInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceRegistrationInfo.java new file mode 100644 index 00000000..89016919 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceRegistrationInfo.java @@ -0,0 +1,59 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "service_registration_info_v1") +public class ServiceRegistrationInfo { + + @SerializedName("serviceName") + public String serviceName = ""; + + @ApiModelProperty( + value = "keep alive interval for the service. This is a heartbeat supervision of the service, " + + "which in regular intevals must invoke a 'keepAlive' REST call. " + + "When a service does not invoke this call within the given time, it is considered unavailble. " + + "An unavailable service will be automatically deregistered and its policies will be deleted. " + + "Value 0 means no timeout supervision.") + @SerializedName("keepAliveIntervalSeconds") + public long keepAliveIntervalSeconds = 0; + + @ApiModelProperty(value = "callback for notifying of RIC synchronization", required = false, allowEmptyValue = true) + @SerializedName("callbackUrl") + public String callbackUrl = ""; + + public ServiceRegistrationInfo() { + } + + public ServiceRegistrationInfo(String name, long keepAliveIntervalSeconds, String callbackUrl) { + this.serviceName = name; + this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; + this.callbackUrl = callbackUrl; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceStatus.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceStatus.java new file mode 100644 index 00000000..8f6273f9 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/ServiceStatus.java @@ -0,0 +1,51 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "service_status_v1") +public class ServiceStatus { + + @ApiModelProperty(value = "identity of the service") + public final String serviceName; + + @ApiModelProperty(value = "policy keep alive timeout") + public final long keepAliveIntervalSeconds; + + @ApiModelProperty(value = "time since last invocation by the service") + public final long timeSinceLastActivitySeconds; + + @ApiModelProperty(value = "callback for notifying of RIC synchronization") + public String callbackUrl; + + ServiceStatus(String name, long keepAliveIntervalSeconds, long timeSincePingSeconds, String callbackUrl) { + this.serviceName = name; + this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; + this.timeSinceLastActivitySeconds = timeSincePingSeconds; + this.callbackUrl = callbackUrl; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/StatusController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/StatusController.java new file mode 100644 index 00000000..e520a282 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/StatusController.java @@ -0,0 +1,48 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v1; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +@RestController +@Api(tags = Consts.V1_API_NAME) +public class StatusController { + + @GetMapping("/status") + @ApiOperation(value = "Returns status and statistics of this service") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Service is living", response = String.class) // + }) + public Mono> getStatus() { + return Mono.just(new ResponseEntity<>("hunky dory", HttpStatus.OK)); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/Consts.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/Consts.java new file mode 100644 index 00000000..68c1d717 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/Consts.java @@ -0,0 +1,36 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +public class Consts { + public static final String RIC_ID_PARAM = "ric_id"; + public static final String POLICY_TYPE_ID_PARAM = "policytype_id"; + public static final String POLICY_ID_PARAM = "policy_id"; + public static final String SERVICE_ID_PARAM = "service_id"; + public static final String TRANSIENT_PARAM = "transient"; + public static final String MANAGED_ELEMENT_ID_PARAM = "managed_element_id"; + + public static final String V2_API_ROOT = "/v2"; + public static final String V2_API_NAME = "A1 Policy Management Version 2.0 (in progress)"; + + private Consts() { + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ErrorResponse.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ErrorResponse.java new file mode 100644 index 00000000..2ba63abc --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ErrorResponse.java @@ -0,0 +1,106 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import reactor.core.publisher.Mono; + +class ErrorResponse { + private static Gson gson = new GsonBuilder() // + .create(); // + + // Returned as body for all failed REST calls + @ApiModel(value = "error_information", description = "Problem as defined in https://tools.ietf.org/html/rfc7807") + public static class ErrorInfo { + @SerializedName("type") + private String type = "about:blank"; + + @SerializedName("title") + private String title = null; + + @SerializedName("status") + private final Integer status; + + @SerializedName("detail") + private String detail = null; + + @SerializedName("instance") + private String instance = null; + + public ErrorInfo(String detail, Integer status) { + this.detail = detail; + this.status = status; + } + + @ApiModelProperty( + example = "503", + value = "The HTTP status code generated by the origin server for this occurrence of the problem. ") + public Integer getStatus() { + return status; + } + + @ApiModelProperty( + example = "Policy type not found", + value = " A human-readable explanation specific to this occurrence of the problem.") + public String getDetail() { + return this.detail; + } + + } + + @ApiModelProperty(value = "message") + public final String message; + + ErrorResponse(String message) { + this.message = message; + } + + static Mono> createMono(String text, HttpStatus code) { + return Mono.just(create(text, code)); + } + + static Mono> createMono(Exception e, HttpStatus code) { + return createMono(e.toString(), code); + } + + static ResponseEntity create(String text, HttpStatus code) { + ErrorInfo p = new ErrorInfo(text, code.value()); + String json = gson.toJson(p); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON); + return new ResponseEntity<>(json, headers, code); + } + + static ResponseEntity create(Exception e, HttpStatus code) { + return create(e.toString(), code); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonObject.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonObject.java new file mode 100644 index 00000000..9290ca07 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonObject.java @@ -0,0 +1,30 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import io.swagger.annotations.ApiModel; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "json_object", description = "A JSON object. The schema is defined by the Policy Type") +class JsonObject { +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonSchema.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonSchema.java new file mode 100644 index 00000000..ff1b8edc --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/JsonSchema.java @@ -0,0 +1,30 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import io.swagger.annotations.ApiModel; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "json_schema", description = "A JSON schema following http://json-schema.org/draft-07/schema") +class JsonSchema { +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyController.java new file mode 100644 index 00000000..9bf6c4b5 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyController.java @@ -0,0 +1,516 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import java.lang.invoke.MethodHandles; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import lombok.Getter; + +import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory; +import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse; +import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClientResponseException; +import reactor.core.publisher.Mono; + +@RestController("PolicyControllerV2") +@Api(tags = Consts.V2_API_NAME) +public class PolicyController { + + public static class RejectionException extends Exception { + private static final long serialVersionUID = 1L; + + @Getter + private final HttpStatus status; + + public RejectionException(String message, HttpStatus status) { + super(message); + this.status = status; + } + } + + @Autowired + private Rics rics; + @Autowired + private PolicyTypes policyTypes; + @Autowired + private Policies policies; + @Autowired + private A1ClientFactory a1ClientFactory; + @Autowired + private Services services; + + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static Gson gson = new GsonBuilder() // + .serializeNulls() // + .create(); // + + @GetMapping(path = Consts.V2_API_ROOT + "/policy-schemas", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Returns policy type schema definitions") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy schemas", response = PolicySchemaList.class), // + @ApiResponse(code = 404, message = "NearRT-RIC is not found", response = ErrorResponse.ErrorInfo.class)}) + public ResponseEntity getPolicySchemas( // + @ApiParam( + name = Consts.RIC_ID_PARAM, + required = false, + value = "The identity of the NearRT-RIC to get the definitions for.") // + @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, + @ApiParam( + name = Consts.POLICY_TYPE_ID_PARAM, + required = true, + value = "The identity of the policy type to get the definition for. When this parameter is given, max one schema will be returned") // + @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId) { + try { + if (ricId == null && policyTypeId == null) { + Collection types = this.policyTypes.getAll(); + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } else if (ricId != null && policyTypeId != null) { + Collection types = new ArrayList<>(); + if (rics.getRic(ricId).isSupportingType(policyTypeId)) { + types.add(policyTypes.getType(policyTypeId)); + } + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } else if (ricId != null) { + Collection types = rics.getRic(ricId).getSupportedPolicyTypes(); + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } else { + Collection types = new ArrayList<>(); + types.add(policyTypes.getType(policyTypeId)); + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } + } catch (ServiceException e) { + return ErrorResponse.create(e, HttpStatus.NOT_FOUND); + } + } + + @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Query policy type identities", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiResponses( + value = {@ApiResponse(code = 200, message = "Policy type IDs", response = PolicyTypeIdList.class), + @ApiResponse(code = 404, message = "NearRT-RIC is not found", response = ErrorResponse.ErrorInfo.class)}) + public ResponseEntity getPolicyTypes( // + @ApiParam( + name = Consts.RIC_ID_PARAM, + required = false, + value = "The identity of the NearRT-RIC to get types for.") // + @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId) { + if (ricId == null) { + Collection types = this.policyTypes.getAll(); + return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); + } else { + try { + Collection types = rics.getRic(ricId).getSupportedPolicyTypes(); + return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); + } catch (ServiceException e) { + return ErrorResponse.create(e, HttpStatus.NOT_FOUND); + } + } + } + + @GetMapping(path = Consts.V2_API_ROOT + "/policy", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Returns a policy configuration") // + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy found", response = JsonObject.class), // + @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class)} // + ) + public ResponseEntity getPolicy( // + @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy instance.") // + @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String id) { + try { + Policy p = policies.getPolicy(id); + return new ResponseEntity<>(p.json(), HttpStatus.OK); + } catch (ServiceException e) { + return ErrorResponse.create(e, HttpStatus.NOT_FOUND); + } + } + + @DeleteMapping(Consts.V2_API_ROOT + "/policy") + @ApiOperation(value = "Delete a policy") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class), + @ApiResponse(code = 204, message = "Policy deleted", response = VoidResponse.class), + @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class), + @ApiResponse( + code = 423, + message = "NearRT-RIC is not operational", + response = ErrorResponse.ErrorInfo.class)}) + public Mono> deletePolicy( // + @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy instance.") // + @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String id) { + try { + Policy policy = policies.getPolicy(id); + keepServiceAlive(policy.ownerServiceId()); + Ric ric = policy.ric(); + return ric.getLock().lock(LockType.SHARED) // + .flatMap(notUsed -> assertRicStateIdle(ric)) // + .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) // + .doOnNext(notUsed -> policies.remove(policy)) // + .flatMap(client -> client.deletePolicy(policy)) // + .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // + .doOnError(notUsed -> ric.getLock().unlockBlocking()) // + .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT))) + .onErrorResume(this::handleException); + } catch (ServiceException e) { + return ErrorResponse.createMono(e, HttpStatus.NOT_FOUND); + } + } + + @PutMapping(path = Consts.V2_API_ROOT + "/policy", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Create or update a policy") + @ApiResponses( + value = { // + @ApiResponse(code = 201, message = "Policy created", response = VoidResponse.class), // + @ApiResponse(code = 200, message = "Policy updated", response = VoidResponse.class), // + @ApiResponse( + code = 423, + message = "NearRT-RIC is not operational", + response = ErrorResponse.ErrorInfo.class), // + @ApiResponse( + code = 404, + message = "NearRT-RIC or policy type is not found", + response = ErrorResponse.ErrorInfo.class) // + }) + public Mono> putPolicy( // + @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false, value = "The identity of the policy type.") // + @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false, defaultValue = "") String policyTypeId, // + @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy instance.") // + @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String instanceId, // + @ApiParam( + name = Consts.RIC_ID_PARAM, + required = true, + value = "The identity of the NearRT-RIC where the policy will be " + // + "created.") // + @RequestParam(name = Consts.RIC_ID_PARAM, required = true) String ricId, // + @ApiParam( + name = Consts.SERVICE_ID_PARAM, + required = true, + value = "The identity of the service creating the policy.") // + @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceId, // + @ApiParam( + name = Consts.TRANSIENT_PARAM, + required = false, + value = "If the policy is transient or not (boolean " + // + "defaulted to false). A policy is transient if it will not be recreated in the NearRT-RIC " + // + "when it has been lost (for instance due to a restart)") // + @RequestParam(name = Consts.TRANSIENT_PARAM, required = false, defaultValue = "false") boolean isTransient, // + @RequestBody Object jsonBody) { + + String jsonString = gson.toJson(jsonBody); + Ric ric = rics.get(ricId); + PolicyType type = policyTypes.get(policyTypeId); + keepServiceAlive(serviceId); + if (ric == null || type == null) { + return ErrorResponse.createMono("NearRT-RIC or policy type not found", HttpStatus.NOT_FOUND); + } + Policy policy = ImmutablePolicy.builder() // + .id(instanceId) // + .json(jsonString) // + .type(type) // + .ric(ric) // + .ownerServiceId(serviceId) // + .lastModified(Instant.now()) // + .isTransient(isTransient) // + .build(); + + final boolean isCreate = this.policies.get(policy.id()) == null; + + return ric.getLock().lock(LockType.SHARED) // + .flatMap(notUsed -> assertRicStateIdle(ric)) // + .flatMap(notUsed -> checkSupportedType(ric, type)) // + .flatMap(notUsed -> validateModifiedPolicy(policy)) // + .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) // + .flatMap(client -> client.putPolicy(policy)) // + .doOnNext(notUsed -> policies.put(policy)) // + .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // + .doOnError(trowable -> ric.getLock().unlockBlocking()) // + .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) // + .onErrorResume(this::handleException); + } + + private Mono> handleException(Throwable throwable) { + if (throwable instanceof WebClientResponseException) { + WebClientResponseException e = (WebClientResponseException) throwable; + return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode()); + } else if (throwable instanceof RejectionException) { + RejectionException e = (RejectionException) throwable; + return ErrorResponse.createMono(e.getMessage(), e.getStatus()); + } else { + return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + private Mono validateModifiedPolicy(Policy policy) { + // Check that ric is not updated + Policy current = this.policies.get(policy.id()); + if (current != null && !current.ric().id().equals(policy.ric().id())) { + RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + // + ", RIC ID: " + current.ric().id() + // + ", new ID: " + policy.ric().id(), HttpStatus.CONFLICT); + logger.debug("Request rejected, {}", e.getMessage()); + return Mono.error(e); + } + return Mono.just("{}"); + } + + private Mono checkSupportedType(Ric ric, PolicyType type) { + if (!ric.isSupportingType(type.id())) { + logger.debug("Request rejected, type not supported, RIC: {}", ric); + RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(), + HttpStatus.NOT_FOUND); + return Mono.error(e); + } + return Mono.just("{}"); + } + + private Mono assertRicStateIdle(Ric ric) { + if (ric.getState() == Ric.RicState.AVAILABLE) { + return Mono.just("{}"); + } else { + logger.debug("Request rejected RIC not IDLE, ric: {}", ric); + RejectionException e = new RejectionException( + "Ric is not operational, RIC name: " + ric.id() + ", state: " + ric.getState(), HttpStatus.LOCKED); + return Mono.error(e); + } + } + + @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation( + value = "Query policies", + notes = "If several query parameters are defined, the policies matching all conditions are returned") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policies", response = PolicyInfoList.class), + @ApiResponse( + code = 404, + message = "NearRT-RIC, policy type or service not found", + response = ErrorResponse.ErrorInfo.class)}) + public ResponseEntity getPolicies( // + @ApiParam( + name = Consts.POLICY_TYPE_ID_PARAM, + required = false, + value = "The identity of the policy type to get policies for.") // + @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String type, // + @ApiParam( + name = Consts.RIC_ID_PARAM, + required = false, + value = "The identity of the NearRT-RIC to get policies for.") // + @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, // + @ApiParam( + name = Consts.SERVICE_ID_PARAM, + required = false, + value = "The identity of the service to get policies for.") // + @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service) // + { + if ((type != null && this.policyTypes.get(type) == null)) { + return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND); + } + if ((ric != null && this.rics.get(ric) == null)) { + return ErrorResponse.create("NearRT-RIC not found", HttpStatus.NOT_FOUND); + } + + String filteredPolicies = policiesToJson(filter(type, ric, service)); + return new ResponseEntity<>(filteredPolicies, HttpStatus.OK); + } + + @GetMapping(path = Consts.V2_API_ROOT + "/policy-ids", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Query policies, only IDs returned") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy ids", response = PolicyIdList.class), + @ApiResponse( + code = 404, + message = "NearRT-RIC or type not found", + response = ErrorResponse.ErrorInfo.class)}) + public ResponseEntity getPolicyIds( // + @ApiParam( + name = Consts.POLICY_TYPE_ID_PARAM, + required = false, + value = "The identity of the policy type to get policies for.") // + @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, // + @ApiParam( + name = Consts.RIC_ID_PARAM, + required = false, + value = "The identity of the NearRT-RIC to get policies for.") // + @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, // + @ApiParam( + name = Consts.SERVICE_ID_PARAM, + required = false, + value = "The identity of the service to get policies for.") // + @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId) // + { + if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) { + return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND); + } + if ((ricId != null && this.rics.get(ricId) == null)) { + return ErrorResponse.create("NearRT-RIC not found", HttpStatus.NOT_FOUND); + } + + String policyIdsJson = toPolicyIdsJson(filter(policyTypeId, ricId, serviceId)); + return new ResponseEntity<>(policyIdsJson, HttpStatus.OK); + } + + @GetMapping(path = Consts.V2_API_ROOT + "/policy-status", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Returns a policy status") // + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Policy status", response = JsonObject.class), // + @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class)} // + ) + public Mono> getPolicyStatus( // + @ApiParam(name = Consts.POLICY_ID_PARAM, required = true, value = "The identity of the policy.") // + @RequestParam(name = Consts.POLICY_ID_PARAM, required = true) String policyId) { + try { + Policy policy = policies.getPolicy(policyId); + + return a1ClientFactory.createA1Client(policy.ric()) // + .flatMap(client -> client.getPolicyStatus(policy)) // + .flatMap(status -> Mono.just(new ResponseEntity<>((Object) status, HttpStatus.OK))) + .onErrorResume(this::handleException); + } catch (ServiceException e) { + return ErrorResponse.createMono(e, HttpStatus.NOT_FOUND); + } + } + + private void keepServiceAlive(String name) { + Service s = this.services.get(name); + if (s != null) { + s.keepAlive(); + } + } + + private boolean include(String filter, String value) { + return filter == null || value.equals(filter); + } + + private Collection filter(Collection collection, String type, String ric, String service) { + if (type == null && ric == null && service == null) { + return collection; + } + List filtered = new ArrayList<>(); + for (Policy p : collection) { + if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) { + filtered.add(p); + } + } + return filtered; + } + + private Collection filter(String type, String ric, String service) { + if (type != null) { + return filter(policies.getForType(type), null, ric, service); + } else if (service != null) { + return filter(policies.getForService(service), type, ric, null); + } else if (ric != null) { + return filter(policies.getForRic(ric), type, null, service); + } else { + return policies.getAll(); + } + } + + private String policiesToJson(Collection policies) { + List v = new ArrayList<>(policies.size()); + for (Policy p : policies) { + PolicyInfo policyInfo = new PolicyInfo(); + policyInfo.policyId = p.id(); + policyInfo.policyData = fromJson(p.json()); + policyInfo.ricId = p.ric().id(); + policyInfo.policyTypeId = p.type().id(); + policyInfo.serviceId = p.ownerServiceId(); + policyInfo.lastModified = p.lastModified().toString(); + if (!policyInfo.validate()) { + logger.error("BUG, all fields must be set"); + } + v.add(policyInfo); + } + PolicyInfoList list = new PolicyInfoList(v); + return gson.toJson(list); + } + + private Object fromJson(String jsonStr) { + return gson.fromJson(jsonStr, Object.class); + } + + private String toPolicyTypeSchemasJson(Collection types) { + + Collection schemas = new ArrayList<>(); + for (PolicyType t : types) { + schemas.add(t.schema()); + } + PolicySchemaList res = new PolicySchemaList(schemas); + return gson.toJson(res); + } + + private String toPolicyTypeIdsJson(Collection types) { + List v = new ArrayList<>(types.size()); + for (PolicyType t : types) { + v.add(t.id()); + } + PolicyTypeIdList ids = new PolicyTypeIdList(v); + return gson.toJson(ids); + } + + private String toPolicyIdsJson(Collection policies) { + List v = new ArrayList<>(policies.size()); + for (Policy p : policies) { + v.add(p.id()); + } + return gson.toJson(new PolicyIdList(v)); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyIdList.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyIdList.java new file mode 100644 index 00000000..329ce5f0 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyIdList.java @@ -0,0 +1,45 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "policy_id_list_v2", description = "A list of policy identities") +public class PolicyIdList { + + @ApiModelProperty(value = "Policy identities") + @SerializedName("policy_ids") + @JsonProperty("policy_ids") + public final Collection policyIds; + + public PolicyIdList(Collection ids) { + this.policyIds = ids; + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfo.java new file mode 100644 index 00000000..4ba3dc79 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfo.java @@ -0,0 +1,73 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "policy_info_v2", description = "Information for one A1-P Policy") +public class PolicyInfo { + + @ApiModelProperty(value = "identity of the policy") + @JsonProperty("policy_id") + @SerializedName("policy_id") + public String policyId; + + @ApiModelProperty(value = "name of the policy type") + @SerializedName("policy_type_id") + @JsonProperty("policy_type_id") + public String policyTypeId; + + @ApiModelProperty(value = "identity of the target NearRT-RIC") + @SerializedName("ric_id") + @JsonProperty("ric_id") + public String ricId; + + @ApiModelProperty(value = "the configuration of the policy") + @SerializedName("policy_data") + @JsonProperty("policy_data") + public Object policyData; + + @ApiModelProperty(value = "the name of the service owning the policy") + @SerializedName("service_id") + @JsonProperty("service_id") + public String serviceId; + + @ApiModelProperty(value = "timestamp, last modification time") + @SerializedName("last_modified") + @JsonProperty("last_modified") + public String lastModified; + + PolicyInfo() { + } + + public boolean validate() { + return policyId != null && policyTypeId != null && ricId != null && policyData != null && serviceId != null + && lastModified != null; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfoList.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfoList.java new file mode 100644 index 00000000..dde00a52 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyInfoList.java @@ -0,0 +1,46 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "policy_info_list_v2", description = "List of policy information") +public class PolicyInfoList { + + @ApiModelProperty(value = "List of policy information") + @SerializedName("policies") + @JsonProperty("policies") + public final Collection policies; + + public PolicyInfoList(Collection policies) { + this.policies = policies; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicySchemaList.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicySchemaList.java new file mode 100644 index 00000000..66296f50 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicySchemaList.java @@ -0,0 +1,53 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.ArrayList; +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "policy_schema_list_v2", description = "Policy type json schemas") +public class PolicySchemaList { + + @ApiModelProperty(value = "Policy type json schemas") + @SerializedName("policy_schemas") + @JsonProperty("policy_schemas") + public final Collection schemas; + + public PolicySchemaList(Collection schemasAsStrings) { + this.schemas = new ArrayList<>(); + for (String str : schemasAsStrings) { + JsonObject jsonObj = JsonParser.parseString(str).getAsJsonObject(); + this.schemas.add(jsonObj); + } + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyTypeIdList.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyTypeIdList.java new file mode 100644 index 00000000..5ecc7277 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyTypeIdList.java @@ -0,0 +1,45 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "policy_type_id_list_v2", description = "Information about policy types") +public class PolicyTypeIdList { + + @ApiModelProperty(value = "Policy type identities") + @SerializedName("policy_type_ids") + @JsonProperty("policy_type_ids") + public final Collection policyTypesIds; + + public PolicyTypeIdList(Collection ids) { + this.policyTypesIds = ids; + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfo.java new file mode 100644 index 00000000..63b4bd60 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfo.java @@ -0,0 +1,75 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "ric_info_v2", description = "Information for a NearRT-RIC") +public class RicInfo { + + @Gson.TypeAdapters + @ApiModel(value = "ric_state_v2", description = "Represents the states for a NearRT-RIC") + public enum RicState { + UNAVAILABLE, AVAILABLE, SYNCHRONIZING, CONSISTENCY_CHECK + } + + private static final String STATE_DESCRIPTION = "State for the NearRT-RIC, values: \n" + + "UNAVAILABLE: The NearRT-RIC is not avialable, information may be inconsistent \n" + + "AVAILABLE: The normal state. Policies can be configured. +\n" + + "SYNCHRONIZING: The Policy Management Service is synchronizing the view of the NearRT-RIC. Policies cannot be configured. \n" + + "CONSISTENCY_CHECK: A consistency check between the Policy Management Service and the NearRT-RIC. Policies cannot be configured."; + + @ApiModelProperty(value = "identity of the NearRT-RIC") + @SerializedName("ric_id") + @JsonProperty("ric_id") + public final String ricId; + + @ApiModelProperty(value = "O1 identities for managed entities") + @SerializedName("managed_element_ids") + @JsonProperty("managed_element_ids") + public final Collection managedElementIds; + + @ApiModelProperty(value = "supported policy types") + @SerializedName("policy_type_ids") + @JsonProperty("policy_type_ids") + public final Collection policyTypeIds; + + @ApiModelProperty(value = STATE_DESCRIPTION, name = "state") + @SerializedName("state") + @JsonProperty("state") + public final RicState state; + + RicInfo(String ricId, Collection managedElementIds, Collection policyTypes, RicState state) { + this.ricId = ricId; + this.managedElementIds = managedElementIds; + this.policyTypeIds = policyTypes; + this.state = state; + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfoList.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfoList.java new file mode 100644 index 00000000..7ca49be7 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicInfoList.java @@ -0,0 +1,46 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "ric_info_list_v2", description = "List of NearRT-RIC information") +public class RicInfoList { + + @ApiModelProperty(value = "List of NearRT-RIC information") + @SerializedName("rics") + @JsonProperty("rics") + public final Collection rics; + + public RicInfoList(Collection rics) { + this.rics = rics; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicRepositoryController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicRepositoryController.java new file mode 100644 index 00000000..a0987ada --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/RicRepositoryController.java @@ -0,0 +1,150 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController("RicRepositoryControllerV2") +@Api(tags = Consts.V2_API_NAME) +public class RicRepositoryController { + + @Autowired + private Rics rics; + + @Autowired + PolicyTypes types; + + private static Gson gson = new GsonBuilder() // + .serializeNulls() // + .create(); // + + /** + * Example: http://localhost:8081/v2/ric?managed_element_id=kista_1 + */ + @GetMapping(path = Consts.V2_API_ROOT + "/ric", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Returns info for the NearRT-RIC with the given identity or managing one Mananged Element") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "NearRT-RIC is found", response = RicInfo.class), // + @ApiResponse(code = 404, message = "NearRT-RIC is not found", response = ErrorResponse.ErrorInfo.class) // + }) + public ResponseEntity getRic( // + @ApiParam( + name = Consts.MANAGED_ELEMENT_ID_PARAM, + required = false, + value = "The identity of a Managed Element. If given, the NearRT-RIC managing the ME is returned.") // + @RequestParam(name = Consts.MANAGED_ELEMENT_ID_PARAM, required = false) String managedElementId, + @ApiParam( + name = Consts.RIC_ID_PARAM, + required = false, + value = "The identity of a NearRT-RIC to get information for.") // + @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId) { + try { + if (managedElementId != null && ricId != null) { + return ErrorResponse.create("Give one query parameter", HttpStatus.BAD_REQUEST); + } else if (managedElementId != null) { + Optional ric = this.rics.lookupRicForManagedElement(managedElementId); + if (ric.isPresent()) { + return new ResponseEntity<>(gson.toJson(toRicInfo(ric.get())), HttpStatus.OK); + } else { + return ErrorResponse.create("No NearRT-RIC managing the ME is found", HttpStatus.NOT_FOUND); + } + } else if (ricId != null) { + RicInfo info = toRicInfo(this.rics.getRic(ricId)); + return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK); + } else { + return ErrorResponse.create("Give one query parameter", HttpStatus.BAD_REQUEST); + } + } catch (ServiceException e) { + return ErrorResponse.create(e, HttpStatus.NOT_FOUND); + } + } + + /** + * @return a Json array of all RIC data Example: http://localhost:8081/v2/ric + */ + @GetMapping(path = Consts.V2_API_ROOT + "/rics", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Query NearRT-RIC information") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "OK", response = RicInfoList.class), // + @ApiResponse(code = 404, message = "Policy type is not found", response = ErrorResponse.ErrorInfo.class)}) + public ResponseEntity getRics( // + @ApiParam( + name = Consts.POLICY_TYPE_ID_PARAM, + required = false, + value = "The identity of a policy type. If given, all NearRT-RICs supporteing the policy type are returned") // + @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String supportingPolicyType) { + if ((supportingPolicyType != null) && (this.types.get(supportingPolicyType) == null)) { + return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND); + } + + List result = new ArrayList<>(); + for (Ric ric : rics.getRics()) { + if (supportingPolicyType == null || ric.isSupportingType(supportingPolicyType)) { + result.add(toRicInfo(ric)); + } + } + + return new ResponseEntity<>(gson.toJson(new RicInfoList(result)), HttpStatus.OK); + } + + private RicInfo.RicState toRicState(Ric.RicState state) { + if (state == Ric.RicState.AVAILABLE) { + return RicInfo.RicState.AVAILABLE; + } else if (state == Ric.RicState.CONSISTENCY_CHECK) { + return RicInfo.RicState.CONSISTENCY_CHECK; + } else if (state == Ric.RicState.SYNCHRONIZING) { + return RicInfo.RicState.SYNCHRONIZING; + } else if (state == Ric.RicState.UNAVAILABLE) { + return RicInfo.RicState.UNAVAILABLE; + } + return RicInfo.RicState.UNAVAILABLE; + } + + private RicInfo toRicInfo(Ric ric) { + return new RicInfo(ric.id(), ric.getManagedElementIds(), ric.getSupportedPolicyTypeNames(), + toRicState(ric.getState())); + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceController.java new file mode 100644 index 00000000..19d68161 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceController.java @@ -0,0 +1,194 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import java.net.MalformedURLException; +import java.net.URL; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; + +import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse; +import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController("ServiceControllerV2") +@Api(tags = Consts.V2_API_NAME) +public class ServiceController { + + private final Services services; + private final Policies policies; + + private static Gson gson = new GsonBuilder() // + .create(); // + + @Autowired + ServiceController(Services services, Policies policies) { + this.services = services; + this.policies = policies; + } + + @GetMapping(path = Consts.V2_API_ROOT + "/services", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Returns service information") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "OK", response = ServiceStatusList.class), // + @ApiResponse(code = 404, message = "Service is not found", response = ErrorResponse.ErrorInfo.class)}) + public ResponseEntity getServices(// + @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false, value = "The identity of the service") // + @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String name) { + if (name != null && this.services.get(name) == null) { + return ErrorResponse.create("Service type not found", HttpStatus.NOT_FOUND); + } + + Collection servicesStatus = new ArrayList<>(); + for (Service s : this.services.getAll()) { + if (name == null || name.equals(s.getName())) { + servicesStatus.add(toServiceStatus(s)); + } + } + + String res = gson.toJson(new ServiceStatusList(servicesStatus)); + return new ResponseEntity<>(res, HttpStatus.OK); + } + + private ServiceStatus toServiceStatus(Service s) { + return new ServiceStatus(s.getName(), s.getKeepAliveInterval().toSeconds(), s.timeSinceLastPing().toSeconds(), + s.getCallbackUrl()); + } + + private void validateRegistrationInfo(ServiceRegistrationInfo registrationInfo) + throws ServiceException, MalformedURLException { + if (registrationInfo.serviceId.isEmpty()) { + throw new ServiceException("Missing mandatory parameter 'serviceName'"); + } + if (registrationInfo.keepAliveIntervalSeconds < 0) { + throw new ServiceException("Keepalive interval shoul be greater or equal to 0"); + } + if (!registrationInfo.callbackUrl.isEmpty()) { + new URL(registrationInfo.callbackUrl); + } + } + + @ApiOperation(value = "Register a service") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Service updated"), + @ApiResponse(code = 201, message = "Service created"), // + @ApiResponse( + code = 400, + message = "The ServiceRegistrationInfo is not accepted", + response = ErrorResponse.ErrorInfo.class)}) + @PutMapping(Consts.V2_API_ROOT + "/services") + public ResponseEntity putService(// + @RequestBody ServiceRegistrationInfo registrationInfo) { + try { + validateRegistrationInfo(registrationInfo); + final boolean isCreate = this.services.get(registrationInfo.serviceId) == null; + this.services.put(toService(registrationInfo)); + return new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK); + } catch (Exception e) { + return ErrorResponse.create(e, HttpStatus.BAD_REQUEST); + } + } + + @ApiOperation(value = "Delete a service") + @ApiResponses( + value = { // + @ApiResponse(code = 204, message = "Service deleted"), + @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class), + @ApiResponse(code = 404, message = "Service not found", response = ErrorResponse.ErrorInfo.class)}) + @DeleteMapping(Consts.V2_API_ROOT + "/services") + public ResponseEntity deleteService(// + @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true, value = "The name of the service") // + @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceName) { + try { + Service service = removeService(serviceName); + // Remove the policies from the repo and let the consistency monitoring + // do the rest. + removePolicies(service); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } catch (ServiceException e) { + return ErrorResponse.create(e, HttpStatus.NOT_FOUND); + } + } + + @ApiOperation(value = "Heartbeat indicates that the service is running") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Service supervision timer refreshed, OK"), // + @ApiResponse( + code = 404, + message = "The service is not found, needs re-registration", + response = ErrorResponse.ErrorInfo.class)}) + + @PutMapping(Consts.V2_API_ROOT + "/services/keepalive") + public ResponseEntity keepAliveService(// + @ApiParam(name = Consts.SERVICE_ID_PARAM, required = true, value = "The identity of the service") // + @RequestParam(name = Consts.SERVICE_ID_PARAM, required = true) String serviceName) { + try { + services.getService(serviceName).keepAlive(); + return new ResponseEntity<>(HttpStatus.OK); + } catch (ServiceException e) { + return ErrorResponse.create(e, HttpStatus.NOT_FOUND); + } + } + + private Service removeService(String name) throws ServiceException { + Service service = this.services.getService(name); // Just to verify that it exists + this.services.remove(service.getName()); + return service; + } + + private void removePolicies(Service service) { + Collection policyList = this.policies.getForService(service.getName()); + for (Policy policy : policyList) { + this.policies.remove(policy); + } + } + + private Service toService(ServiceRegistrationInfo s) { + return new Service(s.serviceId, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceRegistrationInfo.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceRegistrationInfo.java new file mode 100644 index 00000000..30fcb7d6 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceRegistrationInfo.java @@ -0,0 +1,64 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "service_registration_info_v2", description = "Information for one service") +public class ServiceRegistrationInfo { + + @ApiModelProperty(value = "identity of the service", required = true, allowEmptyValue = false) + @SerializedName(value = "service_id") + @JsonProperty("service_id") + public String serviceId = ""; + + @ApiModelProperty( + value = "keep alive interval for the service. This is a heartbeat supervision of the service, " + + "which in regular intevals must invoke a 'keepAlive' REST call. " + + "When a service does not invoke this call within the given time, it is considered unavailble. " + + "An unavailable service will be automatically deregistered and its policies will be deleted. " + + "Value 0 means no timeout supervision.") + @SerializedName("keep_alive_interval_seconds") + @JsonProperty("keep_alive_interval_seconds") + public long keepAliveIntervalSeconds = 0; + + @ApiModelProperty(value = "callback for notifying of RIC synchronization", required = false, allowEmptyValue = true) + @SerializedName("callback_url") + @JsonProperty("callback_url") + public String callbackUrl = ""; + + public ServiceRegistrationInfo() { + } + + public ServiceRegistrationInfo(String id, long keepAliveIntervalSeconds, String callbackUrl) { + this.serviceId = id; + this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; + this.callbackUrl = callbackUrl; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatus.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatus.java new file mode 100644 index 00000000..221fef8d --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatus.java @@ -0,0 +1,62 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "service_status_v2") +public class ServiceStatus { + + @ApiModelProperty(value = "identity of the service") + @SerializedName("service_id") + @JsonProperty("service_id") + public final String serviceId; + + @ApiModelProperty(value = "policy keep alive timeout") + @SerializedName("keep_alive_interval_seconds") + @JsonProperty("keep_alive_interval_seconds") + public final long keepAliveIntervalSeconds; + + @ApiModelProperty(value = "time since last invocation by the service") + @SerializedName("time_since_last_activity_seconds") + @JsonProperty("time_since_last_activity_seconds") + public final long timeSinceLastActivitySeconds; + + @ApiModelProperty(value = "callback for notifying of RIC synchronization") + @SerializedName("callback_url") + @JsonProperty("callback_url") + public String callbackUrl; + + ServiceStatus(String id, long keepAliveIntervalSeconds, long timeSincePingSeconds, String callbackUrl) { + this.serviceId = id; + this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; + this.timeSinceLastActivitySeconds = timeSincePingSeconds; + this.callbackUrl = callbackUrl; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatusList.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatusList.java new file mode 100644 index 00000000..a7ffeca0 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ServiceStatusList.java @@ -0,0 +1,46 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.Collection; + +import org.immutables.gson.Gson; + +@Gson.TypeAdapters +@ApiModel(value = "service_list_v2", description = "List of service information") +public class ServiceStatusList { + + @ApiModelProperty(value = "List of service information") + @SerializedName("service_list") + @JsonProperty("service_list") + public final Collection statusList; + + public ServiceStatusList(Collection statuses) { + this.statusList = statuses; + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/StatusController.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/StatusController.java new file mode 100644 index 00000000..f47cdd5c --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/StatusController.java @@ -0,0 +1,64 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2019-2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.controllers.v2; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +import org.immutables.gson.Gson; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +@RestController("StatusControllerV2") +@Api(tags = Consts.V2_API_NAME) +public class StatusController { + + @Gson.TypeAdapters + @ApiModel(value = "status_info_v2") + class StatusInfo { + @ApiModelProperty(value = "status text") + public final String status; + + StatusInfo(String status) { + this.status = status; + } + } + + @GetMapping(path = Consts.V2_API_ROOT + "/status", produces = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "Returns status and statistics of this service") + @ApiResponses( + value = { // + @ApiResponse(code = 200, message = "Service is living", response = StatusInfo.class) // + }) + public Mono> getStatus() { + StatusInfo info = new StatusInfo("hunky dory"); + return Mono.just(new ResponseEntity<>(info, HttpStatus.OK)); + } + +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/dmaap/DmaapMessageConsumer.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/dmaap/DmaapMessageConsumer.java index 3063a5f5..37a092bb 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/dmaap/DmaapMessageConsumer.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/dmaap/DmaapMessageConsumer.java @@ -111,7 +111,8 @@ public class DmaapMessageConsumer { protected boolean isDmaapConfigured() { String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl(); String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl(); - return (!producerTopicUrl.isEmpty() && !consumerTopicUrl.isEmpty()); + return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty() + && !consumerTopicUrl.isEmpty()); } private static List parseMessages(String jsonString) { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policies.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policies.java index 162d05f4..4df2504b 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policies.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policies.java @@ -37,9 +37,9 @@ public class Policies { public synchronized void put(Policy policy) { policiesId.put(policy.id(), policy); - multiMapPut(policiesRic, policy.ric().name(), policy); - multiMapPut(policiesService, policy.ownerServiceName(), policy); - multiMapPut(policiesType, policy.type().name(), policy); + multiMapPut(policiesRic, policy.ric().id(), policy); + multiMapPut(policiesService, policy.ownerServiceId(), policy); + multiMapPut(policiesType, policy.type().id(), policy); } private void multiMapPut(Map> multiMap, String key, Policy value) { @@ -106,13 +106,13 @@ public class Policies { public synchronized void remove(Policy policy) { policiesId.remove(policy.id()); - multiMapRemove(policiesRic, policy.ric().name(), policy); - multiMapRemove(policiesService, policy.ownerServiceName(), policy); - multiMapRemove(policiesType, policy.type().name(), policy); + multiMapRemove(policiesRic, policy.ric().id(), policy); + multiMapRemove(policiesService, policy.ownerServiceId(), policy); + multiMapRemove(policiesType, policy.type().id(), policy); } - public synchronized void removePoliciesForRic(String ricName) { - Collection policiesForRic = getForRic(ricName); + public synchronized void removePoliciesForRic(String ricId) { + Collection policiesForRic = getForRic(ricId); for (Policy policy : policiesForRic) { remove(policy); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policy.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policy.java index 957b5f3e..752d8dac 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policy.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Policy.java @@ -20,6 +20,8 @@ package org.onap.ccsdk.oran.a1policymanagementservice.repository; +import java.time.Instant; + import org.immutables.gson.Gson; import org.immutables.value.Value; @@ -30,13 +32,13 @@ public interface Policy { public String json(); - public String ownerServiceName(); + public String ownerServiceId(); public Ric ric(); public PolicyType type(); - public String lastModified(); + public Instant lastModified(); public boolean isTransient(); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyType.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyType.java index 9524756f..f2c6254e 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyType.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyType.java @@ -26,7 +26,7 @@ import org.immutables.value.Value; @Value.Immutable @Gson.TypeAdapters public interface PolicyType { - public String name(); + public String id(); public String schema(); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyTypes.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyTypes.java index 9311e58e..db25d9cc 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyTypes.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/PolicyTypes.java @@ -43,7 +43,7 @@ public class PolicyTypes { } public synchronized void put(PolicyType type) { - types.put(type.name(), type); + types.put(type.id(), type); } public synchronized boolean contains(String policyType) { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Ric.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Ric.java index 14ac981f..154809de 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Ric.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Ric.java @@ -30,10 +30,9 @@ import lombok.Setter; import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client.A1ProtocolType; import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState; /** - * Represents the dynamic information about a Near-RT RIC. + * Holds information about a NearRT-RIC. */ public class Ric { @@ -57,8 +56,8 @@ public class Ric { this.ricConfig = ricConfig; } - public String name() { - return ricConfig.name(); + public String id() { + return ricConfig.ricId(); } public RicConfig getConfig() { @@ -111,7 +110,7 @@ public class Ric { * @param type the policy type to support. */ public synchronized void addSupportedPolicyType(PolicyType type) { - supportedPolicyTypes.put(type.name(), type); + supportedPolicyTypes.put(type.id(), type); } /** @@ -134,7 +133,7 @@ public class Ric { @Override public synchronized String toString() { - return Ric.class.getSimpleName() + ": " + "name: " + name() + ", state: " + state + ", baseUrl: " + return Ric.class.getSimpleName() + ": " + "name: " + id() + ", state: " + state + ", baseUrl: " + ricConfig.baseUrl() + ", managedNodes: " + ricConfig.managedElementIds(); } @@ -143,7 +142,7 @@ public class Ric { */ public enum RicState { /** - * The Policy Management Service's view of the Ric may be inconsistent. + * The Policy Management Service's view of the NearRT-RIC may be inconsistent. */ UNAVAILABLE, /** @@ -151,12 +150,13 @@ public class Ric { */ AVAILABLE, /** - * The Policy Management Service is synchronizing the view of the Ric. + * The Policy Management Service is synchronizing the view of the NearRT-RIC. */ SYNCHRONIZING, /** - * A consistency check between the Policy Management Service and the Ric is done + * A consistency check between the Policy Management Service and the NearRT-RIC + * is done */ CONSISTENCY_CHECK } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Rics.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Rics.java index d810dfa0..75c16da1 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Rics.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/Rics.java @@ -35,27 +35,27 @@ public class Rics { Map registeredRics = new HashMap<>(); public synchronized void put(Ric ric) { - registeredRics.put(ric.name(), ric); + registeredRics.put(ric.id(), ric); } public synchronized Collection getRics() { return new Vector<>(registeredRics.values()); } - public synchronized Ric getRic(String name) throws ServiceException { - Ric ric = registeredRics.get(name); + public synchronized Ric getRic(String ricId) throws ServiceException { + Ric ric = registeredRics.get(ricId); if (ric == null) { - throw new ServiceException("Could not find ric: " + name); + throw new ServiceException("Could not find ric: " + ricId); } return ric; } - public synchronized Ric get(String name) { - return registeredRics.get(name); + public synchronized Ric get(String ricId) { + return registeredRics.get(ricId); } - public synchronized void remove(String name) { - registeredRics.remove(name); + public synchronized void remove(String ricId) { + registeredRics.remove(ricId); } public synchronized int size() { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTask.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTask.java index f113da9e..57d6969f 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTask.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTask.java @@ -68,7 +68,8 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** - * Regularly refreshes the configuration from Consul or from a local configuration file. + * Regularly refreshes the configuration from Consul or from a local + * configuration file. */ @Component public class RefreshConfigTask { @@ -198,15 +199,15 @@ public class RefreshConfigTask { private void handleUpdatedRicConfig(RicConfigUpdate updatedInfo) { synchronized (this.rics) { - String ricName = updatedInfo.getRicConfig().name(); + String ricId = updatedInfo.getRicConfig().ricId(); RicConfigUpdate.Type event = updatedInfo.getType(); if (event == RicConfigUpdate.Type.ADDED) { addRic(updatedInfo.getRicConfig()); } else if (event == RicConfigUpdate.Type.REMOVED) { - rics.remove(ricName); - this.policies.removePoliciesForRic(ricName); + rics.remove(ricId); + this.policies.removePoliciesForRic(ricId); } else if (event == RicConfigUpdate.Type.CHANGED) { - Ric ric = this.rics.get(ricName); + Ric ric = this.rics.get(ricId); if (ric == null) { // Should not happen,just for robustness addRic(updatedInfo.getRicConfig()); diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSupervision.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSupervision.java index 832ec117..9bad36cc 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSupervision.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSupervision.java @@ -44,7 +44,7 @@ import reactor.core.publisher.Mono; /** * Regularly checks the existing rics towards the local repository to keep it - * consistent. When the policy types or instances in the Near-RT RIC is not + * consistent. When the policy types or instances in the NearRT-RIC is not * consistent, a synchronization is performed. */ @Component @@ -118,7 +118,7 @@ public class RicSupervision { } private void onRicCheckedError(Throwable t, RicData ricData) { - logger.debug("Ric: {} check stopped, exception: {}", ricData.ric.name(), t.getMessage()); + logger.debug("Ric: {} check stopped, exception: {}", ricData.ric.id(), t.getMessage()); if (t instanceof SynchStartedException) { // this is just a temporary state, ricData.ric.setState(RicState.AVAILABLE); @@ -129,7 +129,7 @@ public class RicSupervision { } private void onRicCheckedOk(RicData ricData) { - logger.debug("Ric: {} checked OK", ricData.ric.name()); + logger.debug("Ric: {} checked OK", ricData.ric.id()); ricData.ric.setState(RicState.AVAILABLE); ricData.ric.getLock().unlockBlocking(); } @@ -138,7 +138,7 @@ public class RicSupervision { private Mono setRicState(RicData ric) { synchronized (ric) { if (ric.ric.getState() == RicState.CONSISTENCY_CHECK) { - logger.debug("Ric: {} is already being checked", ric.ric.getConfig().name()); + logger.debug("Ric: {} is already being checked", ric.ric.getConfig().ricId()); return Mono.empty(); } ric.ric.setState(RicState.CONSISTENCY_CHECK); @@ -170,7 +170,7 @@ public class RicSupervision { private Mono validateInstances(Collection ricPolicies, RicData ric) { synchronized (this.policies) { - if (ricPolicies.size() != policies.getForRic(ric.ric.name()).size()) { + if (ricPolicies.size() != policies.getForRic(ric.ric.id()).size()) { return startSynchronization(ric); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSynchronizationTask.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSynchronizationTask.java index 1eefeee4..d8cd04e2 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSynchronizationTask.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RicSynchronizationTask.java @@ -43,12 +43,12 @@ import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; /** - * Synchronizes the content of a RIC with the content in the repository. This - * means: + * Synchronizes the content of a NearRT-RIC with the content in the repository. + * This means: *

* load all policy types *

- * send all policy instances to the RIC + * send all policy instances to the NearRT-RIC *

* if that fails remove all policy instances *

@@ -74,10 +74,10 @@ public class RicSynchronizationTask { } public void run(Ric ric) { - logger.debug("Handling ric: {}", ric.getConfig().name()); + logger.debug("Handling ric: {}", ric.getConfig().ricId()); if (ric.getState() == RicState.SYNCHRONIZING) { - logger.debug("Ric: {} is already being synchronized", ric.getConfig().name()); + logger.debug("Ric: {} is already being synchronized", ric.getConfig().ricId()); return; } @@ -89,7 +89,7 @@ public class RicSynchronizationTask { .subscribe(new BaseSubscriber() { @Override protected void hookOnError(Throwable throwable) { - logger.warn("Synchronization failure for ric: {}, reason: {}", ric.name(), throwable.getMessage()); + logger.warn("Synchronization failure for ric: {}, reason: {}", ric.id(), throwable.getMessage()); ric.setState(RicState.UNAVAILABLE); } @@ -109,7 +109,7 @@ public class RicSynchronizationTask { private Mono setRicState(Ric ric) { synchronized (ric) { if (ric.getState() == RicState.SYNCHRONIZING) { - logger.debug("Ric: {} is already being synchronized", ric.getConfig().name()); + logger.debug("Ric: {} is already being synchronized", ric.getConfig().ricId()); return Mono.empty(); } ric.setState(RicState.SYNCHRONIZING); @@ -126,9 +126,9 @@ public class RicSynchronizationTask { } private void onSynchronizationComplete(Ric ric) { - logger.debug("Synchronization completed for: {}", ric.name()); + logger.debug("Synchronization completed for: {}", ric.id()); ric.setState(RicState.AVAILABLE); - notifyAllServices("Synchronization completed for:" + ric.name()); + notifyAllServices("Synchronization completed for:" + ric.id()); } private void notifyAllServices(String body) { @@ -147,7 +147,7 @@ public class RicSynchronizationTask { } private Flux deleteAllPolicyInstances(Ric ric, Throwable t) { - logger.debug("Recreation of policies failed for ric: {}, reason: {}", ric.name(), t.getMessage()); + logger.debug("Recreation of policies failed for ric: {}, reason: {}", ric.id(), t.getMessage()); deleteAllPoliciesInRepository(ric); Flux synchronizedTypes = this.a1ClientFactory.createA1Client(ric) // @@ -167,7 +167,7 @@ public class RicSynchronizationTask { return a1Client.getPolicyTypeIdentities() // .doOnNext(x -> ric.clearSupportedPolicyTypes()) // .flatMapMany(Flux::fromIterable) // - .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().name(), typeId)) // + .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().ricId(), typeId)) // .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client), CONCURRENCY_RIC) // .doOnNext(ric::addSupportedPolicyType); // } @@ -181,19 +181,19 @@ public class RicSynchronizationTask { } private Mono createPolicyType(String policyTypeId, String schema) { - PolicyType pt = ImmutablePolicyType.builder().name(policyTypeId).schema(schema).build(); + PolicyType pt = ImmutablePolicyType.builder().id(policyTypeId).schema(schema).build(); policyTypes.put(pt); return Mono.just(pt); } private void deleteAllPoliciesInRepository(Ric ric) { - for (Policy policy : policies.getForRic(ric.name())) { + for (Policy policy : policies.getForRic(ric.id())) { this.policies.remove(policy); } } private Flux putPolicy(Policy policy, Ric ric, A1Client a1Client) { - logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name()); + logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().ricId()); return a1Client.putPolicy(policy) // .flatMapMany(notUsed -> Flux.just(policy)); } @@ -206,7 +206,7 @@ public class RicSynchronizationTask { } private Flux recreateAllPoliciesInRic(Ric ric, A1Client a1Client) { - return Flux.fromIterable(policies.getForRic(ric.name())) // + return Flux.fromIterable(policies.getForRic(ric.id())) // .filter(policy -> !checkTransient(policy)) // .flatMap(policy -> putPolicy(policy, ric, a1Client), CONCURRENCY_RIC); } diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/ServiceSupervision.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/ServiceSupervision.java index c066e12c..a46ff1f9 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/ServiceSupervision.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/ServiceSupervision.java @@ -96,7 +96,7 @@ public class ServiceSupervision { .doOnNext(notUsed -> policies.remove(policy)) // .flatMap(notUsed -> deletePolicyInRic(policy)) .doOnNext(notUsed -> logger.debug("Policy deleted due to service inactivity: {}, service: {}", policy.id(), - policy.ownerServiceName())) // + policy.ownerServiceId())) // .doOnNext(notUsed -> lock.unlockBlocking()) // .doOnError(throwable -> lock.unlockBlocking()) // .doOnError(throwable -> logger.debug("Failed to delete inactive policy: {}, reason: {}", policy.id(), @@ -117,7 +117,7 @@ public class ServiceSupervision { } private Mono handleDeleteFromRicFailure(Policy policy, Throwable e) { - logger.warn("Could not delete policy: {} from ric: {}. Cause: {}", policy.id(), policy.ric().name(), + logger.warn("Could not delete policy: {} from ric: {}. Cause: {}", policy.id(), policy.ric().id(), e.getMessage()); return Mono.empty(); } -- cgit 1.2.3-korg