2 * ========================LICENSE_START=================================
5 * Copyright (C) 2020 Nordix Foundation
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.oransc.policyagent.clients;
23 import com.google.gson.FieldNamingPolicy;
24 import com.google.gson.GsonBuilder;
26 import java.lang.invoke.MethodHandles;
27 import java.nio.charset.StandardCharsets;
28 import java.util.Arrays;
29 import java.util.List;
30 import java.util.Optional;
32 import org.immutables.value.Value;
33 import org.json.JSONObject;
34 import org.oransc.policyagent.configuration.ControllerConfig;
35 import org.oransc.policyagent.configuration.RicConfig;
36 import org.oransc.policyagent.repository.Policy;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.web.reactive.function.client.WebClientResponseException;
42 import reactor.core.publisher.Flux;
43 import reactor.core.publisher.Mono;
46 * Client for accessing the A1 adapter in the SDNC controller in OSC.
48 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
49 public class SdncOscA1Client implements A1Client {
51 static final int CONCURRENCY_RIC = 1; // How may paralell requests that is sent to one NearRT RIC
54 @org.immutables.gson.Gson.TypeAdapters
55 public interface AdapterRequest {
56 public String nearRtRicUrl();
58 public Optional<String> body();
62 @org.immutables.gson.Gson.TypeAdapters
63 public interface AdapterOutput {
64 public Optional<String> body();
66 public int httpStatus();
69 static com.google.gson.Gson gson = new GsonBuilder() //
70 .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) //
73 private static final String GET_POLICY_RPC = "getA1Policy";
74 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
75 private final ControllerConfig controllerConfig;
76 private final AsyncRestClient restClient;
77 private final RicConfig ricConfig;
78 private final A1ProtocolType protocolType;
81 * Constructor that creates the REST client to use.
83 * @param protocolType the southbound protocol of the controller. Supported
84 * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1
85 * @param ricConfig the configuration of the Ric to communicate with
86 * @param controllerConfig the configuration of the SDNC controller to use
88 public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig) {
89 this(protocolType, ricConfig, controllerConfig,
90 new AsyncRestClient(controllerConfig.baseUrl() + "/restconf/operations"));
91 logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.name(), controllerConfig);
95 * Constructor where the REST client to use is provided.
97 * @param protocolType the southbound protocol of the controller. Supported
98 * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1
99 * @param ricConfig the configuration of the Ric to communicate with
100 * @param controllerConfig the configuration of the SDNC controller to use
101 * @param restClient the REST client to use
103 public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig,
104 AsyncRestClient restClient) {
105 this.restClient = restClient;
106 this.ricConfig = ricConfig;
107 this.protocolType = protocolType;
108 this.controllerConfig = controllerConfig;
112 public Mono<List<String>> getPolicyTypeIdentities() {
113 if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
114 return Mono.just(Arrays.asList(""));
115 } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
116 OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
117 final String ricUrl = uri.createPolicyTypesUri();
118 return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
119 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString) //
122 return Mono.error(createIllegalProtocolException());
127 private Exception createIllegalProtocolException() {
128 return new NullPointerException("Bug, unhandeled protocoltype: " + this.protocolType);
132 public Mono<List<String>> getPolicyIdentities() {
133 return getPolicyIds() //
138 public Mono<String> getPolicyTypeSchema(String policyTypeId) {
139 if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
140 return Mono.just("{}");
141 } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
142 OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
143 final String ricUrl = uri.createGetSchemaUri(policyTypeId);
144 return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
145 .flatMap(response -> OscA1Client.extractCreateSchema(response, policyTypeId));
147 return Mono.error(createIllegalProtocolException());
152 public Mono<String> putPolicy(Policy policy) {
153 return getUriBuilder() //
154 .flatMap(builder -> {
155 String ricUrl = builder.createPutPolicyUri(policy.type().name(), policy.id());
156 return post("putA1Policy", ricUrl, Optional.of(policy.json()));
161 public Mono<String> deletePolicy(Policy policy) {
162 return deletePolicyById(policy.type().name(), policy.id());
166 public Flux<String> deleteAllPolicies() {
167 if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
168 return getPolicyIds() //
169 .flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); //
170 } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
171 OscA1Client.UriBuilder uriBuilder = new OscA1Client.UriBuilder(ricConfig);
172 return getPolicyTypeIdentities() //
173 .flatMapMany(Flux::fromIterable) //
174 .flatMap(type -> oscDeleteInstancesForType(uriBuilder, type), CONCURRENCY_RIC);
176 return Flux.error(createIllegalProtocolException());
180 private Flux<String> oscGetInstancesForType(OscA1Client.UriBuilder uriBuilder, String type) {
181 return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty()) //
182 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
185 private Flux<String> oscDeleteInstancesForType(OscA1Client.UriBuilder uriBuilder, String type) {
186 return oscGetInstancesForType(uriBuilder, type) //
187 .flatMap(instance -> deletePolicyById(type, instance), CONCURRENCY_RIC);
191 public Mono<A1ProtocolType> getProtocolVersion() {
192 return tryStdProtocolVersion() //
193 .onErrorResume(t -> tryOscProtocolVersion());
197 public Mono<String> getPolicyStatus(Policy policy) {
198 return getUriBuilder() //
199 .flatMap(builder -> {
200 String ricUrl = builder.createGetPolicyStatusUri(policy.type().name(), policy.id());
201 return post("getA1PolicyStatus", ricUrl, Optional.empty());
205 private Mono<A1UriBuilder> getUriBuilder() {
206 if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
207 return Mono.just(new StdA1ClientVersion1.UriBuilder(ricConfig));
208 } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
209 return Mono.just(new OscA1Client.UriBuilder(ricConfig));
211 return Mono.error(createIllegalProtocolException());
215 private Mono<A1ProtocolType> tryOscProtocolVersion() {
216 OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig);
217 return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) //
218 .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_OSC_V1));
221 private Mono<A1ProtocolType> tryStdProtocolVersion() {
222 StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig);
223 return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(), Optional.empty()) //
224 .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V1_1));
227 private Flux<String> getPolicyIds() {
228 if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
229 StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig);
230 final String ricUrl = uri.createGetPolicyIdsUri();
231 return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
232 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
233 } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
234 OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
235 return getPolicyTypeIdentities() //
236 .flatMapMany(Flux::fromIterable)
237 .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
238 .flatMap(SdncJsonHelper::parseJsonArrayOfString);
240 return Flux.error(createIllegalProtocolException());
244 private Mono<String> deletePolicyById(String type, String policyId) {
245 return getUriBuilder() //
246 .flatMap(builder -> {
247 String ricUrl = builder.createDeleteUri(type, policyId);
248 return post("deleteA1Policy", ricUrl, Optional.empty());
252 private Mono<String> post(String rpcName, String ricUrl, Optional<String> body) {
253 AdapterRequest inputParams = ImmutableAdapterRequest.builder() //
254 .nearRtRicUrl(ricUrl) //
257 final String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
258 logger.debug("POST inputJsonString = {}", inputJsonString);
261 .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, this.controllerConfig.userName(),
262 this.controllerConfig.password()) //
263 .flatMap(this::extractResponseBody);
266 private Mono<String> extractResponse(JSONObject responseOutput) {
267 AdapterOutput output = gson.fromJson(responseOutput.toString(), ImmutableAdapterOutput.class);
268 Optional<String> optionalBody = output.body();
269 String body = optionalBody.isPresent() ? optionalBody.get() : "";
270 if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) {
271 return Mono.just(body);
273 logger.debug("Error response: {} {}", output.httpStatus(), body);
274 byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
275 WebClientResponseException e = new WebClientResponseException(output.httpStatus(), "statusText", null,
276 responseBodyBytes, StandardCharsets.UTF_8, null);
278 return Mono.error(e);
282 private Mono<String> extractResponseBody(String responseStr) {
283 return SdncJsonHelper.getOutput(responseStr) //
284 .flatMap(this::extractResponse);
287 private String controllerUrl(String rpcName) {
288 return "/A1-ADAPTER-API:" + rpcName;