Merge "Bugfix"
[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     @Value.Immutable
52     @org.immutables.gson.Gson.TypeAdapters
53     public interface AdapterRequest {
54         public String nearRtRicUrl();
55
56         public Optional<String> body();
57     }
58
59     @Value.Immutable
60     @org.immutables.gson.Gson.TypeAdapters
61     public interface AdapterOutput {
62         public Optional<String> body();
63
64         public int httpStatus();
65     }
66
67     static com.google.gson.Gson gson = new GsonBuilder() //
68         .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) //
69         .create(); //
70
71     private static final String GET_POLICY_RPC = "getA1Policy";
72     private static final String UNHANDELED_PROTOCOL = "Bug, unhandeled protocoltype: ";
73     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
74     private final ControllerConfig controllerConfig;
75     private final AsyncRestClient restClient;
76     private final RicConfig ricConfig;
77     private final A1ProtocolType protocolType;
78
79     /**
80      * Constructor
81      * 
82      * @param protocolType the southbound protocol of the controller. Supported
83      *        protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1
84      * @param ricConfig
85      * @param controllerBaseUrl the base URL of the SDNC controller
86      * @param username username to accesss the SDNC controller
87      * @param password password to accesss the SDNC controller
88      */
89     public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig) {
90         this(protocolType, ricConfig, controllerConfig,
91             new AsyncRestClient(controllerConfig.baseUrl() + "/restconf/operations"));
92         logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.name(), controllerConfig);
93     }
94
95     public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig,
96         AsyncRestClient restClient) {
97         this.restClient = restClient;
98         this.ricConfig = ricConfig;
99         this.protocolType = protocolType;
100         this.controllerConfig = controllerConfig;
101     }
102
103     @Override
104     public Mono<List<String>> getPolicyTypeIdentities() {
105         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
106             return Mono.just(Arrays.asList(""));
107         } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
108             OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
109             final String ricUrl = uri.createPolicyTypesUri();
110             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
111                 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString) //
112                 .collectList();
113         }
114         throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
115     }
116
117     @Override
118     public Mono<List<String>> getPolicyIdentities() {
119         return getPolicyIds() //
120             .collectList();
121     }
122
123     @Override
124     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
125         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
126             return Mono.just("{}");
127         } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
128             OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
129             final String ricUrl = uri.createGetSchemaUri(policyTypeId);
130             return post(GET_POLICY_RPC, ricUrl, Optional.empty());
131         }
132         throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
133     }
134
135     @Override
136     public Mono<String> putPolicy(Policy policy) {
137         final String ricUrl = getUriBuilder().createPutPolicyUri(policy.type().name(), policy.id());
138         return post("putA1Policy", ricUrl, Optional.of(policy.json()));
139     }
140
141     @Override
142     public Mono<String> deletePolicy(Policy policy) {
143         return deletePolicyById(policy.type().name(), policy.id());
144     }
145
146     @Override
147     public Flux<String> deleteAllPolicies() {
148         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
149             return getPolicyIds() //
150                 .flatMap(policyId -> deletePolicyById("", policyId)); //
151         } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
152             OscA1Client.UriBuilder uriBuilder = new OscA1Client.UriBuilder(ricConfig);
153             return getPolicyTypeIdentities() //
154                 .flatMapMany(Flux::fromIterable)
155                 .flatMap(type -> post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty())) //
156                 .flatMap(SdncJsonHelper::parseJsonArrayOfString);
157         }
158         throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
159     }
160
161     @Override
162     public Mono<A1ProtocolType> getProtocolVersion() {
163         return tryStdProtocolVersion() //
164             .onErrorResume(t -> tryOscProtocolVersion());
165     }
166
167     @Override
168     public Mono<String> getPolicyStatus(Policy policy) {
169         final String ricUrl = getUriBuilder().createGetPolicyStatusUri(policy.type().name(), policy.id());
170         return post("getA1PolicyStatus", ricUrl, Optional.empty());
171     }
172
173     private A1UriBuilder getUriBuilder() {
174         if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
175             return new StdA1ClientVersion1.UriBuilder(ricConfig);
176         } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
177             return new OscA1Client.UriBuilder(ricConfig);
178         }
179         throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
180     }
181
182     private Mono<A1ProtocolType> tryOscProtocolVersion() {
183         OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig);
184         return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) //
185             .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_OSC_V1));
186     }
187
188     private Mono<A1ProtocolType> tryStdProtocolVersion() {
189         StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig);
190         return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(), Optional.empty()) //
191             .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V1_1));
192     }
193
194     private Flux<String> getPolicyIds() {
195         if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
196             StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig);
197             final String ricUrl = uri.createGetPolicyIdsUri();
198             return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
199                 .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
200         } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
201             OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
202             return getPolicyTypeIdentities() //
203                 .flatMapMany(Flux::fromIterable)
204                 .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
205                 .flatMap(SdncJsonHelper::parseJsonArrayOfString);
206         }
207         throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
208     }
209
210     private Mono<String> deletePolicyById(String type, String policyId) {
211         final String ricUrl = getUriBuilder().createDeleteUri(type, policyId);
212         return post("deleteA1Policy", ricUrl, Optional.empty());
213     }
214
215     private Mono<String> post(String rpcName, String ricUrl, Optional<String> body) {
216         AdapterRequest inputParams = ImmutableAdapterRequest.builder() //
217             .nearRtRicUrl(ricUrl) //
218             .body(body) //
219             .build();
220         final String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
221         logger.debug("POST inputJsonString = {}", inputJsonString);
222
223         return restClient
224             .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, this.controllerConfig.userName(),
225                 this.controllerConfig.password()) //
226             .flatMap(this::extractResponseBody);
227     }
228
229     private Mono<String> extractResponse(JSONObject responseOutput) {
230         AdapterOutput output = gson.fromJson(responseOutput.toString(), ImmutableAdapterOutput.class);
231         Optional<String> optionalBody = output.body();
232         String body = optionalBody.isPresent() ? optionalBody.get() : "";
233         if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) {
234             return Mono.just(body);
235         } else {
236             logger.debug("Error response: {} {}", output.httpStatus(), body);
237             byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
238             WebClientResponseException e = new WebClientResponseException(output.httpStatus(), "statusText", null,
239                 responseBodyBytes, StandardCharsets.UTF_8, null);
240
241             return Mono.error(e);
242         }
243     }
244
245     private Mono<String> extractResponseBody(String responseStr) {
246         return SdncJsonHelper.getOutput(responseStr) //
247             .flatMap(this::extractResponse);
248     }
249
250     private String controllerUrl(String rpcName) {
251         return "/A1-ADAPTER-API:" + rpcName;
252     }
253 }