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