28c278436a0eaba16d07e4757ee55a0f40d901dd
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2020 Nordix Foundation. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.clients;
22
23 import com.google.gson.FieldNamingPolicy;
24 import com.google.gson.GsonBuilder;
25
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;
31
32 import org.immutables.value.Value;
33 import org.json.JSONObject;
34 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig;
35 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
36 import org.onap.ccsdk.oran.a1policymanagementservice.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;
41
42 import reactor.core.publisher.Flux;
43 import reactor.core.publisher.Mono;
44
45 /**
46  * Client for accessing the A1 adapter in the SDNC controller in OSC.
47  */
48 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
49 public class SdncOscA1Client implements A1Client {
50
51     static final int CONCURRENCY_RIC = 1; // How many paralell requests that is sent to one NearRT RIC
52
53     @Value.Immutable
54     @org.immutables.gson.Gson.TypeAdapters
55     public interface AdapterRequest {
56         public String nearRtRicUrl();
57
58         public Optional<String> body();
59     }
60
61     @Value.Immutable
62     @org.immutables.gson.Gson.TypeAdapters
63     public interface AdapterOutput {
64         public Optional<String> body();
65
66         public int httpStatus();
67     }
68
69     static com.google.gson.Gson gson = new GsonBuilder() //
70             .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) //
71             .create(); //
72
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;
79
80     /**
81      * Constructor that creates the REST client to use.
82      *
83      * @param protocolType the southbound protocol of the controller. Supported
84      *        protocols are SDNC_OSC_STD_V1_1, SDNC_OSC_OSC_V1 and
85      *        SDNC_OSC_STD_V2_0_0 with
86      * @param ricConfig the configuration of the Near-RT RIC to communicate
87      *        with
88      * @param controllerConfig the configuration of the SDNC controller to use
89      *
90      * @throws IllegalArgumentException when the protocolType is wrong.
91      */
92     public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig,
93             AsyncRestClientFactory restClientFactory) {
94         this(protocolType, ricConfig, controllerConfig,
95                 restClientFactory.createRestClient(controllerConfig.baseUrl() + "/restconf/operations"));
96     }
97
98     /**
99      * Constructor where the REST client to use is provided.
100      *
101      * @param protocolType the southbound protocol of the controller. Supported
102      *        protocols are SDNC_OSC_STD_V1_1, SDNC_OSC_OSC_V1 and
103      *        SDNC_OSC_STD_V2_0_0 with
104      * @param ricConfig the configuration of the Near-RT RIC to communicate
105      *        with
106      * @param controllerConfig the configuration of the SDNC controller to use
107      * @param restClient the REST client to use
108      *
109      * @throws IllegalArgumentException when the protocolType is illegal.
110      */
111     public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig,
112             AsyncRestClient restClient) {
113         if (A1ProtocolType.SDNC_OSC_STD_V1_1.equals(protocolType) //
114                 || A1ProtocolType.SDNC_OSC_OSC_V1.equals(protocolType) //
115                 || A1ProtocolType.SDNC_OSC_STD_V2_0_0.equals(protocolType)) {
116             this.restClient = restClient;
117             this.ricConfig = ricConfig;
118             this.protocolType = protocolType;
119             this.controllerConfig = controllerConfig;
120             logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.ricId(), controllerConfig);
121         } else {
122             throw new IllegalArgumentException("Not handeled protocolversion: " + protocolType);
123         }
124
125     }
126
127     @Override
128     public Mono<List<String>> getPolicyTypeIdentities() {
129         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
130             return Mono.just(Arrays.asList(""));
131         } else {
132             return post(GET_POLICY_RPC, getUriBuilder().createPolicyTypesUri(), Optional.empty()) //
133                     .flatMapMany(SdncJsonHelper::parseJsonArrayOfString) //
134                     .collectList();
135         }
136
137     }
138
139     @Override
140     public Mono<List<String>> getPolicyIdentities() {
141         return getPolicyIds() //
142                 .collectList();
143     }
144
145     @Override
146     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
147         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
148             return Mono.just("{}");
149         } else {
150             A1UriBuilder uri = this.getUriBuilder();
151             final String ricUrl = uri.createGetSchemaUri(policyTypeId);
152             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
153                     .flatMap(response -> extractCreateSchema(response, policyTypeId));
154         }
155     }
156
157     private Mono<String> extractCreateSchema(String controllerResponse, String policyTypeId) {
158         if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
159             return OscA1Client.extractCreateSchema(controllerResponse, policyTypeId);
160         } else if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V2_0_0) {
161             return StdA1ClientVersion2.extractPolicySchema(controllerResponse, policyTypeId);
162         } else {
163             throw new NullPointerException("Not supported");
164         }
165     }
166
167     @Override
168     public Mono<String> putPolicy(Policy policy) {
169         String ricUrl = getUriBuilder().createPutPolicyUri(policy.type().id(), policy.id());
170         return post("putA1Policy", ricUrl, Optional.of(policy.json()));
171     }
172
173     @Override
174     public Mono<String> deletePolicy(Policy policy) {
175         return deletePolicyById(policy.type().id(), policy.id());
176     }
177
178     @Override
179     public Flux<String> deleteAllPolicies() {
180         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
181             return getPolicyIds() //
182                     .flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); //
183         } else {
184             A1UriBuilder uriBuilder = this.getUriBuilder();
185             return getPolicyTypeIdentities() //
186                     .flatMapMany(Flux::fromIterable) //
187                     .flatMap(type -> deleteAllInstancesForType(uriBuilder, type), CONCURRENCY_RIC);
188         }
189     }
190
191     private Flux<String> getInstancesForType(A1UriBuilder uriBuilder, String type) {
192         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty()) //
193                 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
194     }
195
196     private Flux<String> deleteAllInstancesForType(A1UriBuilder uriBuilder, String type) {
197         return getInstancesForType(uriBuilder, type) //
198                 .flatMap(instance -> deletePolicyById(type, instance), CONCURRENCY_RIC);
199     }
200
201     @Override
202     public Mono<A1ProtocolType> getProtocolVersion() {
203         return tryStdProtocolVersion2() //
204                 .onErrorResume(t -> tryStdProtocolVersion1()) //
205                 .onErrorResume(t -> tryOscProtocolVersion());
206     }
207
208     @Override
209     public Mono<String> getPolicyStatus(Policy policy) {
210         String ricUrl = getUriBuilder().createGetPolicyStatusUri(policy.type().id(), policy.id());
211         return post("getA1PolicyStatus", ricUrl, Optional.empty());
212
213     }
214
215     private A1UriBuilder getUriBuilder() {
216         if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
217             return new StdA1ClientVersion1.UriBuilder(ricConfig);
218         } else if (protocolType == A1ProtocolType.SDNC_OSC_STD_V2_0_0) {
219             return new StdA1ClientVersion2.UriBuilder(ricConfig);
220         } else if (protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
221             return new OscA1Client.UriBuilder(ricConfig);
222         }
223         throw new NullPointerException();
224     }
225
226     private Mono<A1ProtocolType> tryOscProtocolVersion() {
227         OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig);
228         return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) //
229                 .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_OSC_V1));
230     }
231
232     private Mono<A1ProtocolType> tryStdProtocolVersion1() {
233         StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig);
234         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(""), Optional.empty()) //
235                 .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V1_1));
236     }
237
238     private Mono<A1ProtocolType> tryStdProtocolVersion2() {
239         StdA1ClientVersion2.UriBuilder uriBuilder = new StdA1ClientVersion2.UriBuilder(ricConfig);
240         return post(GET_POLICY_RPC, uriBuilder.createPolicyTypesUri(), Optional.empty()) //
241                 .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V2_0_0));
242     }
243
244     private Flux<String> getPolicyIds() {
245         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
246             StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig);
247             final String ricUrl = uri.createGetPolicyIdsUri("");
248             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
249                     .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
250         } else {
251             A1UriBuilder uri = this.getUriBuilder();
252             return getPolicyTypeIdentities() //
253                     .flatMapMany(Flux::fromIterable)
254                     .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
255                     .flatMap(SdncJsonHelper::parseJsonArrayOfString);
256         }
257     }
258
259     private Mono<String> deletePolicyById(String type, String policyId) {
260         String ricUrl = getUriBuilder().createDeleteUri(type, policyId);
261         return post("deleteA1Policy", ricUrl, Optional.empty());
262     }
263
264     private Mono<String> post(String rpcName, String ricUrl, Optional<String> body) {
265         AdapterRequest inputParams = ImmutableAdapterRequest.builder() //
266                 .nearRtRicUrl(ricUrl) //
267                 .body(body) //
268                 .build();
269         final String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
270         logger.debug("POST inputJsonString = {}", inputJsonString);
271
272         return restClient
273                 .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, this.controllerConfig.userName(),
274                         this.controllerConfig.password()) //
275                 .flatMap(this::extractResponseBody);
276     }
277
278     private Mono<String> extractResponse(JSONObject responseOutput) {
279         AdapterOutput output = gson.fromJson(responseOutput.toString(), ImmutableAdapterOutput.class);
280         Optional<String> optionalBody = output.body();
281         String body = optionalBody.isPresent() ? optionalBody.get() : "";
282         if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) {
283             return Mono.just(body);
284         } else {
285             logger.debug("Error response: {} {}", output.httpStatus(), body);
286             byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
287             HttpStatus httpStatus = HttpStatus.valueOf(output.httpStatus());
288             WebClientResponseException responseException = new WebClientResponseException(httpStatus.value(),
289                     httpStatus.getReasonPhrase(), null, responseBodyBytes, StandardCharsets.UTF_8, null);
290
291             return Mono.error(responseException);
292         }
293     }
294
295     private Mono<String> extractResponseBody(String responseStr) {
296         return SdncJsonHelper.getOutput(responseStr) //
297                 .flatMap(this::extractResponse);
298     }
299
300     private String controllerUrl(String rpcName) {
301         return "/A1-ADAPTER-API:" + rpcName;
302     }
303 }