2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oransc.policyagent.controllers;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
26 import io.swagger.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import io.swagger.annotations.ApiResponse;
29 import io.swagger.annotations.ApiResponses;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.List;
37 import org.oransc.policyagent.clients.A1ClientFactory;
38 import org.oransc.policyagent.exceptions.ServiceException;
39 import org.oransc.policyagent.repository.ImmutablePolicy;
40 import org.oransc.policyagent.repository.Lock.LockType;
41 import org.oransc.policyagent.repository.Policies;
42 import org.oransc.policyagent.repository.Policy;
43 import org.oransc.policyagent.repository.PolicyType;
44 import org.oransc.policyagent.repository.PolicyTypes;
45 import org.oransc.policyagent.repository.Ric;
46 import org.oransc.policyagent.repository.Rics;
47 import org.oransc.policyagent.repository.Service;
48 import org.oransc.policyagent.repository.Services;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.http.HttpStatus;
51 import org.springframework.http.ResponseEntity;
52 import org.springframework.web.bind.annotation.DeleteMapping;
53 import org.springframework.web.bind.annotation.GetMapping;
54 import org.springframework.web.bind.annotation.PutMapping;
55 import org.springframework.web.bind.annotation.RequestBody;
56 import org.springframework.web.bind.annotation.RequestParam;
57 import org.springframework.web.bind.annotation.RestController;
58 import org.springframework.web.reactive.function.client.WebClientResponseException;
59 import reactor.core.publisher.Mono;
62 @Api(tags = "A1 Policy Management")
63 public class PolicyController {
65 public static class RejectionException extends Exception {
66 private static final long serialVersionUID = 1L;
68 private final HttpStatus status;
70 public RejectionException(String message, HttpStatus status) {
79 private PolicyTypes policyTypes;
81 private Policies policies;
83 private A1ClientFactory a1ClientFactory;
85 private Services services;
87 private static Gson gson = new GsonBuilder() //
91 @GetMapping("/policy_schemas")
92 @ApiOperation(value = "Returns policy type schema definitions")
95 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
96 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
97 public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
98 if (ricName == null) {
99 Collection<PolicyType> types = this.policyTypes.getAll();
100 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
103 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
104 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
105 } catch (ServiceException e) {
106 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
111 @GetMapping("/policy_schema")
112 @ApiOperation(value = "Returns one policy type schema definition")
115 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
116 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
117 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
119 PolicyType type = policyTypes.getType(id);
120 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
121 } catch (ServiceException e) {
122 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
126 @GetMapping("/policy_types")
127 @ApiOperation(value = "Query policy type names")
132 message = "Policy type names",
133 response = String.class,
134 responseContainer = "List"),
135 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
136 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
137 if (ricName == null) {
138 Collection<PolicyType> types = this.policyTypes.getAll();
139 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
142 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
143 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
144 } catch (ServiceException e) {
145 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
150 @GetMapping("/policy")
151 @ApiOperation(value = "Returns a policy configuration") //
154 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
155 @ApiResponse(code = 404, message = "Policy is not found")} //
157 public ResponseEntity<String> getPolicy( //
158 @RequestParam(name = "id", required = true) String id) {
160 Policy p = policies.getPolicy(id);
161 return new ResponseEntity<>(p.json(), HttpStatus.OK);
162 } catch (ServiceException e) {
163 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
167 @DeleteMapping("/policy")
168 @ApiOperation(value = "Delete a policy", response = Object.class)
171 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
172 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
173 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
174 public Mono<ResponseEntity<Object>> deletePolicy( //
175 @RequestParam(name = "id", required = true) String id) {
177 Policy policy = policies.getPolicy(id);
178 keepServiceAlive(policy.ownerServiceName());
179 Ric ric = policy.ric();
180 return ric.getLock().lock(LockType.SHARED) //
181 .flatMap(notUsed -> assertRicStateIdle(ric)) //
182 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
183 .doOnNext(notUsed -> policies.remove(policy)) //
184 .flatMap(client -> client.deletePolicy(policy)) //
185 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
186 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
187 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
188 .onErrorResume(this::handleException);
189 } catch (ServiceException e) {
190 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
194 @PutMapping(path = "/policy")
195 @ApiOperation(value = "Put a policy", response = String.class)
198 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
199 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
200 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
201 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
203 public Mono<ResponseEntity<Object>> putPolicy( //
204 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
205 @RequestParam(name = "id", required = true) String instanceId, //
206 @RequestParam(name = "ric", required = true) String ricName, //
207 @RequestParam(name = "service", required = true) String service, //
208 @RequestBody Object jsonBody) {
210 String jsonString = gson.toJson(jsonBody);
211 Ric ric = rics.get(ricName);
212 PolicyType type = policyTypes.get(typeName);
213 keepServiceAlive(service);
214 if (ric == null || type == null) {
215 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
217 Policy policy = ImmutablePolicy.builder() //
222 .ownerServiceName(service) //
223 .lastModified(getTimeStampUtc()) //
226 final boolean isCreate = this.policies.get(policy.id()) == null;
228 return ric.getLock().lock(LockType.SHARED) //
229 .flatMap(notUsed -> assertRicStateIdle(ric)) //
230 .flatMap(notUsed -> checkSupportedType(ric, type)) //
231 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
232 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
233 .flatMap(client -> client.putPolicy(policy)) //
234 .doOnNext(notUsed -> policies.put(policy)) //
235 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
236 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
237 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
238 .onErrorResume(this::handleException);
241 @SuppressWarnings({"unchecked"})
242 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
243 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
244 return Mono.just(re);
247 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
248 if (throwable instanceof WebClientResponseException) {
249 WebClientResponseException e = (WebClientResponseException) throwable;
250 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
251 } else if (throwable instanceof RejectionException) {
252 RejectionException e = (RejectionException) throwable;
253 return createResponseEntity(e.getMessage(), e.getStatus());
255 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
259 private Mono<Object> validateModifiedPolicy(Policy policy) {
260 // Check that ric is not updated
261 Policy current = this.policies.get(policy.id());
262 if (current != null && !current.ric().name().equals(policy.ric().name())) {
263 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
264 ", RIC name: " + current.ric().name() + //
265 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
266 return Mono.error(e);
268 return Mono.just("OK");
271 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
272 if (!ric.isSupportingType(type.name())) {
273 RejectionException e = new RejectionException(
274 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
275 return Mono.error(e);
277 return Mono.just("OK");
280 private Mono<Object> assertRicStateIdle(Ric ric) {
281 if (ric.getState() == Ric.RicState.AVAILABLE) {
282 return Mono.just("OK");
284 RejectionException e = new RejectionException(
285 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
286 return Mono.error(e);
290 @GetMapping("/policies")
291 @ApiOperation(value = "Query policies")
294 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
295 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
296 public ResponseEntity<String> getPolicies( //
297 @RequestParam(name = "type", required = false) String type, //
298 @RequestParam(name = "ric", required = false) String ric, //
299 @RequestParam(name = "service", required = false) String service) //
301 if ((type != null && this.policyTypes.get(type) == null)) {
302 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
304 if ((ric != null && this.rics.get(ric) == null)) {
305 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
308 String filteredPolicies = policiesToJson(filter(type, ric, service));
309 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
312 @GetMapping("/policy_ids")
313 @ApiOperation(value = "Query policies, only IDs returned")
315 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
316 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
317 public ResponseEntity<String> getPolicyIds( //
318 @RequestParam(name = "type", required = false) String type, //
319 @RequestParam(name = "ric", required = false) String ric, //
320 @RequestParam(name = "service", required = false) String service) //
322 if ((type != null && this.policyTypes.get(type) == null)) {
323 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
325 if ((ric != null && this.rics.get(ric) == null)) {
326 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
329 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
330 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
333 @GetMapping("/policy_status")
334 @ApiOperation(value = "Returns a policy status") //
337 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
338 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
340 public Mono<ResponseEntity<String>> getPolicyStatus( //
341 @RequestParam(name = "id", required = true) String id) {
343 Policy policy = policies.getPolicy(id);
345 return a1ClientFactory.createA1Client(policy.ric()) //
346 .flatMap(client -> client.getPolicyStatus(policy)) //
347 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
348 .onErrorResume(this::handleException);
349 } catch (ServiceException e) {
350 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
354 private void keepServiceAlive(String name) {
355 Service s = this.services.get(name);
361 private boolean include(String filter, String value) {
362 return filter == null || value.equals(filter);
365 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
366 if (type == null && ric == null && service == null) {
369 List<Policy> filtered = new ArrayList<>();
370 for (Policy p : collection) {
371 if (include(type, p.type().name()) && include(ric, p.ric().name())
372 && include(service, p.ownerServiceName())) {
379 private Collection<Policy> filter(String type, String ric, String service) {
381 return filter(policies.getForType(type), null, ric, service);
382 } else if (service != null) {
383 return filter(policies.getForService(service), type, ric, null);
384 } else if (ric != null) {
385 return filter(policies.getForRic(ric), type, null, service);
387 return policies.getAll();
391 private String policiesToJson(Collection<Policy> policies) {
392 List<PolicyInfo> v = new ArrayList<>(policies.size());
393 for (Policy p : policies) {
394 PolicyInfo policyInfo = new PolicyInfo();
395 policyInfo.id = p.id();
396 policyInfo.json = fromJson(p.json());
397 policyInfo.ric = p.ric().name();
398 policyInfo.type = p.type().name();
399 policyInfo.service = p.ownerServiceName();
400 policyInfo.lastModified = p.lastModified();
401 if (!policyInfo.validate()) {
402 throw new NullPointerException("BUG, all fields must be set");
406 return gson.toJson(v);
409 private Object fromJson(String jsonStr) {
410 return gson.fromJson(jsonStr, Object.class);
413 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
414 StringBuilder result = new StringBuilder();
416 boolean first = true;
417 for (PolicyType t : types) {
422 result.append(t.schema());
425 return result.toString();
428 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
429 List<String> v = new ArrayList<>(types.size());
430 for (PolicyType t : types) {
433 return gson.toJson(v);
436 private String toPolicyIdsJson(Collection<Policy> policies) {
437 List<String> v = new ArrayList<>(policies.size());
438 for (Policy p : policies) {
441 return gson.toJson(v);
444 private String getTimeStampUtc() {
445 return java.time.Instant.now().toString();