Fix bug in SDNC, read controller info from yaml
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / clients / SdnrOnapA1Client.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 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 java.lang.invoke.MethodHandles;
24 import java.util.ArrayList;
25 import java.util.List;
26
27 import org.json.JSONArray;
28 import org.json.JSONException;
29 import org.json.JSONObject;
30 import org.oransc.policyagent.configuration.RicConfig;
31 import org.oransc.policyagent.repository.Policy;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 import reactor.core.publisher.Flux;
36 import reactor.core.publisher.Mono;
37
38 public class SdnrOnapA1Client implements A1Client {
39     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
40
41     private String a1ControllerBaseUrl;
42     private String a1ControllerUsername;
43     private String a1ControllerPassword;
44     private final RicConfig ricConfig;
45     private final AsyncRestClient restClient;
46
47     public SdnrOnapA1Client(RicConfig ricConfig, String baseUrl, String username, String password) {
48         this.ricConfig = ricConfig;
49         this.a1ControllerBaseUrl = baseUrl;
50         this.a1ControllerUsername = username;
51         this.a1ControllerPassword = password;
52         this.restClient = new AsyncRestClient(a1ControllerBaseUrl + "/restconf/operations");
53         logger.debug("SdnrOnapA1Client for ric: {}, a1ControllerBaseUrl: {}", this.ricConfig.name(),
54             a1ControllerBaseUrl);
55     }
56
57     @Override
58     public Mono<List<String>> getPolicyTypeIdentities() {
59         JSONObject paramsJson = new JSONObject();
60         paramsJson.put("near-rt-ric-id", ricConfig.baseUrl());
61         String inputJsonString = createInputJsonString(paramsJson);
62         logger.debug("POST getPolicyTypeIdentities inputJsonString = {}", inputJsonString);
63
64         return restClient
65             .postWithAuthHeader("/A1-ADAPTER-API:getPolicyTypes", inputJsonString, a1ControllerUsername,
66                 a1ControllerPassword) //
67             .flatMap(response -> getValueFromResponse(response, "policy-type-id-list")) //
68             .flatMap(this::parseJsonArrayOfString);
69     }
70
71     @Override
72     public Mono<List<String>> getPolicyIdentities() {
73         return getPolicyTypeIdentities() //
74             .flatMapMany(types -> Flux.fromIterable(types)) //
75             .flatMap(type -> getPolicyIdentities(type)) //
76             .flatMap(policyIds -> Flux.fromIterable(policyIds)) //
77             .collectList();
78     }
79
80     public Mono<List<String>> getPolicyIdentities(String policyTypeId) {
81         JSONObject paramsJson = new JSONObject();
82         paramsJson.put("near-rt-ric-id", ricConfig.baseUrl());
83         paramsJson.put("policy-type-id", policyTypeId);
84         String inputJsonString = createInputJsonString(paramsJson);
85         logger.debug("POST getPolicyIdentities inputJsonString = {}", inputJsonString);
86
87         return restClient
88             .postWithAuthHeader("/A1-ADAPTER-API:getPolicyInstances", inputJsonString, a1ControllerUsername,
89                 a1ControllerPassword) //
90             .flatMap(response -> getValueFromResponse(response, "policy-instance-id-list")) //
91             .flatMap(this::parseJsonArrayOfString);
92     }
93
94     @Override
95     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
96         JSONObject paramsJson = new JSONObject();
97         paramsJson.put("near-rt-ric-id", ricConfig.baseUrl());
98         paramsJson.put("policy-type-id", policyTypeId);
99         String inputJsonString = createInputJsonString(paramsJson);
100         logger.debug("POST getPolicyType inputJsonString = {}", inputJsonString);
101
102         return restClient
103             .postWithAuthHeader("/A1-ADAPTER-API:getPolicyType", inputJsonString, a1ControllerUsername,
104                 a1ControllerPassword) //
105             .flatMap(response -> getValueFromResponse(response, "policy-type")) //
106             .flatMap(this::extractPolicySchema);
107     }
108
109     @Override
110     public Mono<String> putPolicy(Policy policy) {
111         JSONObject paramsJson = new JSONObject();
112         paramsJson.put("near-rt-ric-id", ricConfig.baseUrl());
113         paramsJson.put("policy-instance-id", policy.id());
114         paramsJson.put("policy-type-id", policy.type().name());
115         paramsJson.put("policy-instance", policy.json());
116         paramsJson.put("properties", new JSONArray());
117         String inputJsonString = createInputJsonString(paramsJson);
118         logger.debug("POST putPolicy inputJsonString = {}", inputJsonString);
119
120         return restClient.postWithAuthHeader("/A1-ADAPTER-API:createPolicyInstance", inputJsonString,
121             a1ControllerUsername, a1ControllerPassword);
122     }
123
124     public Mono<String> deletePolicy(String policyTypeId, String policyId) {
125         JSONObject paramsJson = new JSONObject();
126         paramsJson.put("near-rt-ric-id", ricConfig.baseUrl());
127         paramsJson.put("policy-instance-id", policyId);
128         paramsJson.put("policy-type-id", policyTypeId);
129         String inputJsonString = createInputJsonString(paramsJson);
130         logger.debug("POST deletePolicy inputJsonString = {}", inputJsonString);
131
132         return restClient.postWithAuthHeader("/A1-ADAPTER-API:deletePolicyInstance", inputJsonString,
133             a1ControllerUsername, a1ControllerPassword);
134     }
135
136     @Override
137     public Mono<String> deletePolicy(Policy policy) {
138         return deletePolicy(policy.type().name(), policy.id());
139     }
140
141     @Override
142     public Flux<String> deleteAllPolicies() {
143         return getPolicyTypeIdentities() //
144             .flatMapMany(types -> Flux.fromIterable(types)) //
145             .flatMap(typeId -> deletePoliciesForType(typeId)); //
146     }
147
148     private Flux<String> deletePoliciesForType(String typeId) {
149         return getPolicyIdentities(typeId) //
150             .flatMapMany(policyIds -> Flux.fromIterable(policyIds)) //
151             .flatMap(policyId -> deletePolicy(typeId, policyId)); //
152     }
153
154     @Override
155     public Mono<A1ProtocolType> getProtocolVersion() {
156         return getPolicyTypeIdentities() //
157             .flatMap(x -> Mono.just(A1ProtocolType.SDNR_ONAP));
158     }
159
160     private String createInputJsonString(JSONObject paramsJson) {
161         JSONObject inputJson = new JSONObject();
162         inputJson.put("input", paramsJson);
163         return inputJson.toString();
164     }
165
166     private Mono<String> getValueFromResponse(String response, String key) {
167         logger.debug("A1 client: response = {}", response);
168         try {
169             JSONObject outputJson = new JSONObject(response);
170             JSONObject responseParams = outputJson.getJSONObject("output");
171             if (!responseParams.has(key)) {
172                 return Mono.just("");
173             }
174             String value = responseParams.get(key).toString();
175             return Mono.just(value);
176         } catch (JSONException ex) { // invalid json
177             return Mono.error(ex);
178         }
179     }
180
181     private Mono<List<String>> parseJsonArrayOfString(String inputString) {
182         try {
183             List<String> arrayList = new ArrayList<>();
184             if (inputString.isEmpty()) {
185                 return Mono.just(arrayList);
186             }
187             JSONArray jsonArray = new JSONArray(inputString);
188             for (int i = 0; i < jsonArray.length(); i++) {
189                 arrayList.add(jsonArray.getString(i));
190             }
191             logger.debug("A1 client: received list = {}", arrayList);
192             return Mono.just(arrayList);
193         } catch (JSONException ex) { // invalid json
194             return Mono.error(ex);
195         }
196     }
197
198     private Mono<String> extractPolicySchema(String inputString) {
199         try {
200             JSONObject jsonObject = new JSONObject(inputString);
201             JSONObject schemaObject = jsonObject.getJSONObject("policySchema");
202             String schemaString = schemaObject.toString();
203             return Mono.just(schemaString);
204         } catch (JSONException ex) { // invalid json
205             return Mono.error(ex);
206         }
207     }
208 }