3b0d12a40f1b8acea9d2845a4c61b42b50c41496
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2020-2023 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 import java.util.Set;
32
33 import lombok.Getter;
34
35 import org.json.JSONObject;
36 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig;
37 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
38 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
39 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.web.reactive.function.client.WebClientResponseException;
44
45 import reactor.core.publisher.Flux;
46 import reactor.core.publisher.Mono;
47
48 /**
49  * Client for accessing the A1 adapter in the CCSDK in ONAP.
50  */
51 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
52 public class CcsdkA1AdapterClient implements A1Client {
53
54     static final int CONCURRENCY_RIC = 1; // How many paralell requests that is sent to one NearRT RIC
55
56     @Getter
57     public static class AdapterRequest {
58         private String nearRtRicUrl = null;
59         private String body = null;
60
61         public AdapterRequest(String url, String body) {
62             this.nearRtRicUrl = url;
63             this.body = body;
64         }
65
66         public AdapterRequest() {}
67     }
68
69     @Getter
70     public static class AdapterOutput {
71         private String body = null;
72         private int httpStatus = 0;
73
74         public AdapterOutput(int status, String body) {
75             this.httpStatus = status;
76             this.body = body;
77         }
78
79         public AdapterOutput() {}
80     }
81
82     static com.google.gson.Gson gson = new GsonBuilder() //
83             .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) //
84             .create(); //
85
86     private static final String GET_POLICY_RPC = "getA1Policy";
87     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
88     private final AsyncRestClient restClient;
89     private final RicConfig ricConfig;
90     private final A1ProtocolType protocolType;
91
92     /**
93      * Constructor that creates the REST client to use.
94      *
95      * @param protocolType the southbound protocol of the controller. Supported
96      *        protocols are CCSDK_A1_ADAPTER_STD_V1_1,
97      *        CCSDK_A1_ADAPTER_OSC_V1 and
98      *        CCSDK_A1_ADAPTER_STD_V2_0_0 with
99      * @param ricConfig the configuration of the Near-RT RIC to communicate
100      *        with
101      * @param controllerConfig the configuration of the CCSDK A1 Adapter to use
102      *
103      * @throws IllegalArgumentException when the protocolType is wrong.
104      */
105     public CcsdkA1AdapterClient(A1ProtocolType protocolType, RicConfig ricConfig,
106             AsyncRestClientFactory restClientFactory) {
107         this(protocolType, ricConfig, restClientFactory
108                 .createRestClientNoHttpProxy(ricConfig.getControllerConfig().getBaseUrl() + "/rests/operations"));
109     }
110
111     /**
112      * Constructor where the REST client to use is provided.
113      *
114      * @param protocolType the southbound protocol of the controller. Supported
115      *        protocols are CCSDK_A1_ADAPTER_STD_V1_1,
116      *        CCSDK_A1_ADAPTER_OSC_V1 and
117      *        CCSDK_A1_ADAPTER_STD_V2_0_0 with
118      * @param ricConfig the configuration of the Near-RT RIC to communicate
119      *        with
120      * @param controllerConfig the configuration of the CCSDK A1 Adapter to use
121      * @param restClient the REST client to use
122      *
123      * @throws IllegalArgumentException when the protocolType is illegal.
124      */
125     CcsdkA1AdapterClient(A1ProtocolType protocolType, RicConfig ricConfig, AsyncRestClient restClient) {
126         if (A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1.equals(protocolType) //
127                 || A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1.equals(protocolType) //
128                 || A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0.equals(protocolType)) {
129             this.restClient = restClient;
130             this.ricConfig = ricConfig;
131             this.protocolType = protocolType;
132             logger.debug("CcsdkA1AdapterClient for ric: {}, a1Controller: {}", ricConfig.getRicId(),
133                     ricConfig.getControllerConfig());
134         } else {
135             logger.error("Not supported protocoltype: {}", protocolType);
136             throw new IllegalArgumentException("Not handeled protocolversion: " + protocolType);
137         }
138     }
139
140     @Override
141     public Mono<List<String>> getPolicyTypeIdentities() {
142         if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) {
143             return Mono.just(Arrays.asList(""));
144         } else {
145             return post(GET_POLICY_RPC, getUriBuilder().createPolicyTypesUri(), Optional.empty()) //
146                     .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString) //
147                     .collectList();
148         }
149     }
150
151     @Override
152     public Mono<List<String>> getPolicyIdentities() {
153         return getPolicyIds() //
154                 .collectList();
155     }
156
157     @Override
158     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
159         if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) {
160             return Mono.just("{}");
161         } else {
162             A1UriBuilder uri = this.getUriBuilder();
163             final String ricUrl = uri.createGetSchemaUri(policyTypeId);
164             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
165                     .flatMap(response -> extractCreateSchema(response, policyTypeId));
166         }
167     }
168
169     private Mono<String> extractCreateSchema(String controllerResponse, String policyTypeId) {
170         if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1) {
171             return OscA1Client.extractCreateSchema(controllerResponse, policyTypeId);
172         } else if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0) {
173             return StdA1ClientVersion2.extractPolicySchema(controllerResponse, policyTypeId);
174         } else {
175             return Mono.error(new ServiceException("Not supported " + this.protocolType));
176         }
177     }
178
179     @Override
180     public Mono<String> putPolicy(Policy policy) {
181         String ricUrl = getUriBuilder().createPutPolicyUri(policy.getType().getId(), policy.getId(),
182                 policy.getStatusNotificationUri());
183         return post("putA1Policy", ricUrl, Optional.of(policy.getJson()));
184     }
185
186     @Override
187     public Mono<String> deletePolicy(Policy policy) {
188         return deletePolicyById(policy.getType().getId(), policy.getId());
189     }
190
191     @Override
192     public Flux<String> deleteAllPolicies(Set<String> excludePolicyIds) {
193         if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) {
194             return getPolicyIds() //
195                     .filter(policyId -> !excludePolicyIds.contains(policyId)) //
196                     .flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); //
197         } else {
198             A1UriBuilder uriBuilder = this.getUriBuilder();
199             return getPolicyTypeIdentities() //
200                     .flatMapMany(Flux::fromIterable) //
201                     .flatMap(type -> deleteAllInstancesForType(uriBuilder, type, excludePolicyIds), CONCURRENCY_RIC);
202         }
203     }
204
205     private Flux<String> getInstancesForType(A1UriBuilder uriBuilder, String type) {
206         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty()) //
207                 .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString);
208     }
209
210     private Flux<String> deleteAllInstancesForType(A1UriBuilder uriBuilder, String type, Set<String> excludePolicyIds) {
211         return getInstancesForType(uriBuilder, type) //
212                 .filter(policyId -> !excludePolicyIds.contains(policyId)) //
213                 .flatMap(policyId -> deletePolicyById(type, policyId), CONCURRENCY_RIC);
214     }
215
216     @Override
217     public Mono<A1ProtocolType> getProtocolVersion() {
218         return tryStdProtocolVersion2() //
219                 .onErrorResume(t -> tryStdProtocolVersion1()) //
220                 .onErrorResume(t -> tryOscProtocolVersion());
221     }
222
223     @Override
224     public Mono<String> getPolicyStatus(Policy policy) {
225         String ricUrl = getUriBuilder().createGetPolicyStatusUri(policy.getType().getId(), policy.getId());
226         return post("getA1PolicyStatus", ricUrl, Optional.empty());
227
228     }
229
230     private A1UriBuilder getUriBuilder() {
231         if (protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) {
232             return new StdA1ClientVersion1.UriBuilder(ricConfig);
233         } else if (protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0) {
234             return new StdA1ClientVersion2.OranV2UriBuilder(ricConfig);
235         } else if (protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1) {
236             return new OscA1Client.UriBuilder(ricConfig);
237         }
238         logger.error("Not supported protocoltype: {}", protocolType);
239         throw new NullPointerException();
240     }
241
242     private Mono<A1ProtocolType> tryOscProtocolVersion() {
243         OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig);
244         return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) //
245                 .flatMap(x -> Mono.just(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1));
246     }
247
248     private Mono<A1ProtocolType> tryStdProtocolVersion1() {
249         StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig);
250         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(""), Optional.empty()) //
251                 .flatMap(x -> Mono.just(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1));
252     }
253
254     private Mono<A1ProtocolType> tryStdProtocolVersion2() {
255         StdA1ClientVersion2.OranV2UriBuilder uriBuilder = new StdA1ClientVersion2.OranV2UriBuilder(ricConfig);
256         return post(GET_POLICY_RPC, uriBuilder.createPolicyTypesUri(), Optional.empty()) //
257                 .flatMap(x -> Mono.just(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0));
258     }
259
260     private Flux<String> getPolicyIds() {
261         if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) {
262             StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig);
263             final String ricUrl = uri.createGetPolicyIdsUri("");
264             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
265                     .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString);
266         } else {
267             A1UriBuilder uri = this.getUriBuilder();
268             return getPolicyTypeIdentities() //
269                     .flatMapMany(Flux::fromIterable)
270                     .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
271                     .flatMap(A1AdapterJsonHelper::parseJsonArrayOfString);
272         }
273     }
274
275     private Mono<String> deletePolicyById(String type, String policyId) {
276         String ricUrl = getUriBuilder().createDeleteUri(type, policyId);
277         return post("deleteA1Policy", ricUrl, Optional.empty());
278     }
279
280     private Mono<String> post(String rpcName, String ricUrl, Optional<String> body) {
281         AdapterRequest inputParams = new AdapterRequest(ricUrl, body.isPresent() ? body.get() : null);
282
283         final String inputJsonString = A1AdapterJsonHelper.createInputJsonString(inputParams);
284         logger.debug("POST inputJsonString = {}", inputJsonString);
285         ControllerConfig controllerConfig = this.ricConfig.getControllerConfig();
286         return restClient
287                 .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, controllerConfig.getUserName(),
288                         controllerConfig.getPassword()) //
289                 .flatMap(resp -> extractResponseBody(resp, ricUrl));
290     }
291
292     private Mono<String> extractResponse(JSONObject responseOutput, String ricUrl) {
293         AdapterOutput output = gson.fromJson(responseOutput.toString(), AdapterOutput.class);
294
295         String body = output.body == null ? "" : output.body;
296         if (HttpStatus.valueOf(output.httpStatus).is2xxSuccessful()) {
297             return Mono.just(body);
298         } else {
299             logger.debug("Error response: {} {}, from: {}", output.httpStatus, body, ricUrl);
300             byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
301             HttpStatus httpStatus = HttpStatus.valueOf(output.httpStatus);
302             WebClientResponseException responseException = new WebClientResponseException(httpStatus.value(),
303                     httpStatus.getReasonPhrase(), null, responseBodyBytes, StandardCharsets.UTF_8, null);
304
305             return Mono.error(responseException);
306         }
307     }
308
309     private Mono<String> extractResponseBody(String responseStr, String ricUrl) {
310         return A1AdapterJsonHelper.getOutput(responseStr) //
311                 .flatMap(responseOutput -> extractResponse(responseOutput, ricUrl));
312     }
313
314     private String controllerUrl(String rpcName) {
315         return "/A1-ADAPTER-API:" + rpcName;
316     }
317 }