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