2763ab9b6a92813f38bdb88e557ada489874107d
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / clients / SdncOscA1Client.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
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.oransc.policyagent.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.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;
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 may 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 protocols are SDNC_OSC_STD_V1_1 and
84      *        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
87      *
88      * @throws IllegalArgumentException when the protocolType is wrong.
89      */
90     public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig) {
91         this(protocolType, ricConfig, controllerConfig,
92             new AsyncRestClient(controllerConfig.baseUrl() + "/restconf/operations"));
93         logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.name(), controllerConfig);
94     }
95
96     /**
97      * Constructor where the REST client to use is provided.
98      *
99      * @param protocolType the southbound protocol of the controller. Supported protocols are SDNC_OSC_STD_V1_1 and
100      *        SDNC_OSC_OSC_V1
101      * @param ricConfig the configuration of the Ric to communicate with
102      * @param controllerConfig the configuration of the SDNC controller to use
103      * @param restClient the REST client to use
104      *
105      * @throws IllegalArgumentException when the protocolType is wrong.
106      */
107     public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig,
108         AsyncRestClient restClient) {
109         if (!(A1ProtocolType.SDNC_OSC_STD_V1_1.equals(protocolType)
110             || A1ProtocolType.SDNC_OSC_OSC_V1.equals(protocolType))) {
111             throw new IllegalArgumentException("Protocol type must be " + A1ProtocolType.SDNC_OSC_STD_V1_1 + " or "
112                 + A1ProtocolType.SDNC_OSC_OSC_V1 + ", was: " + protocolType);
113         }
114         this.restClient = restClient;
115         this.ricConfig = ricConfig;
116         this.protocolType = protocolType;
117         this.controllerConfig = controllerConfig;
118     }
119
120     @Override
121     public Mono<List<String>> getPolicyTypeIdentities() {
122         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
123             return Mono.just(Arrays.asList(""));
124         } else {
125             OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
126             final String ricUrl = uri.createPolicyTypesUri();
127             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
128                 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString) //
129                 .collectList();
130         }
131
132     }
133
134     @Override
135     public Mono<List<String>> getPolicyIdentities() {
136         return getPolicyIds() //
137             .collectList();
138     }
139
140     @Override
141     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
142         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
143             return Mono.just("{}");
144         } else {
145             OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
146             final String ricUrl = uri.createGetSchemaUri(policyTypeId);
147             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
148                 .flatMap(response -> OscA1Client.extractCreateSchema(response, policyTypeId));
149         }
150     }
151
152     @Override
153     public Mono<String> putPolicy(Policy policy) {
154         return getUriBuilder() //
155             .flatMap(builder -> {
156                 String ricUrl = builder.createPutPolicyUri(policy.type().name(), policy.id());
157                 return post("putA1Policy", ricUrl, Optional.of(policy.json()));
158             });
159     }
160
161     @Override
162     public Mono<String> deletePolicy(Policy policy) {
163         return deletePolicyById(policy.type().name(), policy.id());
164     }
165
166     @Override
167     public Flux<String> deleteAllPolicies() {
168         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
169             return getPolicyIds() //
170                 .flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); //
171         } else {
172             OscA1Client.UriBuilder uriBuilder = new OscA1Client.UriBuilder(ricConfig);
173             return getPolicyTypeIdentities() //
174                 .flatMapMany(Flux::fromIterable) //
175                 .flatMap(type -> oscDeleteInstancesForType(uriBuilder, type), CONCURRENCY_RIC);
176         }
177     }
178
179     private Flux<String> oscGetInstancesForType(OscA1Client.UriBuilder uriBuilder, String type) {
180         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty()) //
181             .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
182     }
183
184     private Flux<String> oscDeleteInstancesForType(OscA1Client.UriBuilder uriBuilder, String type) {
185         return oscGetInstancesForType(uriBuilder, type) //
186             .flatMap(instance -> deletePolicyById(type, instance), CONCURRENCY_RIC);
187     }
188
189     @Override
190     public Mono<A1ProtocolType> getProtocolVersion() {
191         return tryStdProtocolVersion() //
192             .onErrorResume(t -> tryOscProtocolVersion());
193     }
194
195     @Override
196     public Mono<String> getPolicyStatus(Policy policy) {
197         return getUriBuilder() //
198             .flatMap(builder -> {
199                 String ricUrl = builder.createGetPolicyStatusUri(policy.type().name(), policy.id());
200                 return post("getA1PolicyStatus", ricUrl, Optional.empty());
201             });
202     }
203
204     private Mono<A1UriBuilder> getUriBuilder() {
205         if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
206             return Mono.just(new StdA1ClientVersion1.UriBuilder(ricConfig));
207         } else {
208             return Mono.just(new OscA1Client.UriBuilder(ricConfig));
209         }
210     }
211
212     private Mono<A1ProtocolType> tryOscProtocolVersion() {
213         OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig);
214         return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) //
215             .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_OSC_V1));
216     }
217
218     private Mono<A1ProtocolType> tryStdProtocolVersion() {
219         StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig);
220         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(), Optional.empty()) //
221             .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V1_1));
222     }
223
224     private Flux<String> getPolicyIds() {
225         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
226             StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig);
227             final String ricUrl = uri.createGetPolicyIdsUri();
228             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
229                 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
230         } else {
231             OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
232             return getPolicyTypeIdentities() //
233                 .flatMapMany(Flux::fromIterable)
234                 .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
235                 .flatMap(SdncJsonHelper::parseJsonArrayOfString);
236         }
237     }
238
239     private Mono<String> deletePolicyById(String type, String policyId) {
240         return getUriBuilder() //
241             .flatMap(builder -> {
242                 String ricUrl = builder.createDeleteUri(type, policyId);
243                 return post("deleteA1Policy", ricUrl, Optional.empty());
244             });
245     }
246
247     private Mono<String> post(String rpcName, String ricUrl, Optional<String> body) {
248         AdapterRequest inputParams = ImmutableAdapterRequest.builder() //
249             .nearRtRicUrl(ricUrl) //
250             .body(body) //
251             .build();
252         final String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
253         logger.debug("POST inputJsonString = {}", inputJsonString);
254
255         return restClient
256             .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, this.controllerConfig.userName(),
257                 this.controllerConfig.password()) //
258             .flatMap(this::extractResponseBody);
259     }
260
261     private Mono<String> extractResponse(JSONObject responseOutput) {
262         AdapterOutput output = gson.fromJson(responseOutput.toString(), ImmutableAdapterOutput.class);
263         Optional<String> optionalBody = output.body();
264         String body = optionalBody.isPresent() ? optionalBody.get() : "";
265         if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) {
266             return Mono.just(body);
267         } else {
268             logger.debug("Error response: {} {}", output.httpStatus(), body);
269             byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
270             WebClientResponseException responseException = new WebClientResponseException(output.httpStatus(),
271                 "statusText", null, responseBodyBytes, StandardCharsets.UTF_8, null);
272
273             return Mono.error(responseException);
274         }
275     }
276
277     private Mono<String> extractResponseBody(String responseStr) {
278         return SdncJsonHelper.getOutput(responseStr) //
279             .flatMap(this::extractResponse);
280     }
281
282     private String controllerUrl(String rpcName) {
283         return "/A1-ADAPTER-API:" + rpcName;
284     }
285 }