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.ApiParam;
29 import io.swagger.annotations.ApiResponse;
30 import io.swagger.annotations.ApiResponses;
32 import java.lang.invoke.MethodHandles;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
39 import org.oransc.policyagent.clients.A1ClientFactory;
40 import org.oransc.policyagent.exceptions.ServiceException;
41 import org.oransc.policyagent.repository.ImmutablePolicy;
42 import org.oransc.policyagent.repository.Lock.LockType;
43 import org.oransc.policyagent.repository.Policies;
44 import org.oransc.policyagent.repository.Policy;
45 import org.oransc.policyagent.repository.PolicyType;
46 import org.oransc.policyagent.repository.PolicyTypes;
47 import org.oransc.policyagent.repository.Ric;
48 import org.oransc.policyagent.repository.Rics;
49 import org.oransc.policyagent.repository.Service;
50 import org.oransc.policyagent.repository.Services;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.HttpStatus;
55 import org.springframework.http.ResponseEntity;
56 import org.springframework.web.bind.annotation.DeleteMapping;
57 import org.springframework.web.bind.annotation.GetMapping;
58 import org.springframework.web.bind.annotation.PutMapping;
59 import org.springframework.web.bind.annotation.RequestBody;
60 import org.springframework.web.bind.annotation.RequestParam;
61 import org.springframework.web.bind.annotation.RestController;
62 import org.springframework.web.reactive.function.client.WebClientResponseException;
63 import reactor.core.publisher.Mono;
66 @Api(tags = "A1 Policy Management")
67 public class PolicyController {
69 public static class RejectionException extends Exception {
70 private static final long serialVersionUID = 1L;
72 private final HttpStatus status;
74 public RejectionException(String message, HttpStatus status) {
83 private PolicyTypes policyTypes;
85 private Policies policies;
87 private A1ClientFactory a1ClientFactory;
89 private Services services;
91 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
92 private static Gson gson = new GsonBuilder() //
96 @GetMapping("/policy_schemas")
97 @ApiOperation(value = "Returns policy type schema definitions")
100 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
101 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
102 public ResponseEntity<String> getPolicySchemas( //
103 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get the definitions for.") //
104 @RequestParam(name = "ric", required = false) String ricName) {
105 if (ricName == null) {
106 Collection<PolicyType> types = this.policyTypes.getAll();
107 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
110 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
111 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
112 } catch (ServiceException e) {
113 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
118 @GetMapping("/policy_schema")
119 @ApiOperation(value = "Returns one policy type schema definition")
122 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
123 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
124 public ResponseEntity<String> getPolicySchema( //
125 @ApiParam(name = "id", required = true, value = "The ID of the policy type to get the definition for.") //
126 @RequestParam(name = "id", required = true) String id) {
128 PolicyType type = policyTypes.getType(id);
129 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
130 } catch (ServiceException e) {
131 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
135 @GetMapping("/policy_types")
136 @ApiOperation(value = "Query policy type names")
141 message = "Policy type names",
142 response = String.class,
143 responseContainer = "List"),
144 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
145 public ResponseEntity<String> getPolicyTypes( //
146 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get types for.") //
147 @RequestParam(name = "ric", required = false) String ricName) {
148 if (ricName == null) {
149 Collection<PolicyType> types = this.policyTypes.getAll();
150 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
153 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
154 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
155 } catch (ServiceException e) {
156 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
161 @GetMapping("/policy")
162 @ApiOperation(value = "Returns a policy configuration") //
165 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
166 @ApiResponse(code = 404, message = "Policy is not found")} //
168 public ResponseEntity<String> getPolicy( //
169 @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") //
170 @RequestParam(name = "id", required = true) String id) {
172 Policy p = policies.getPolicy(id);
173 return new ResponseEntity<>(p.json(), HttpStatus.OK);
174 } catch (ServiceException e) {
175 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
179 @DeleteMapping("/policy")
180 @ApiOperation(value = "Delete a policy", response = Object.class)
183 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
184 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
185 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
186 public Mono<ResponseEntity<Object>> deletePolicy( //
187 @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") //
188 @RequestParam(name = "id", required = true) String id) {
190 Policy policy = policies.getPolicy(id);
191 keepServiceAlive(policy.ownerServiceName());
192 Ric ric = policy.ric();
193 return ric.getLock().lock(LockType.SHARED) //
194 .flatMap(notUsed -> assertRicStateIdle(ric)) //
195 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
196 .doOnNext(notUsed -> policies.remove(policy)) //
197 .flatMap(client -> client.deletePolicy(policy)) //
198 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
199 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
200 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
201 .onErrorResume(this::handleException);
202 } catch (ServiceException e) {
203 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
207 @PutMapping(path = "/policy")
208 @ApiOperation(value = "Put a policy", response = String.class)
211 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
212 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
213 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
214 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
216 public Mono<ResponseEntity<Object>> putPolicy( //
217 @ApiParam(name = "type", required = false, value = "The name of the policy type.") //
218 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
219 @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") //
220 @RequestParam(name = "id", required = true) String instanceId, //
221 @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " + //
223 @RequestParam(name = "ric", required = true) String ricName, //
224 @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") //
225 @RequestParam(name = "service", required = true) String service, //
226 @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " + //
227 "defaulted to false). A policy is transient if it will be forgotten when the service needs to " + //
228 "reconnect to the Near-RT RIC.") //
229 @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
230 @RequestBody Object jsonBody) {
232 String jsonString = gson.toJson(jsonBody);
233 Ric ric = rics.get(ricName);
234 PolicyType type = policyTypes.get(typeName);
235 keepServiceAlive(service);
236 if (ric == null || type == null) {
237 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
239 Policy policy = ImmutablePolicy.builder() //
244 .ownerServiceName(service) //
245 .lastModified(getTimeStampUtc()) //
246 .isTransient(isTransient) //
249 final boolean isCreate = this.policies.get(policy.id()) == null;
251 return ric.getLock().lock(LockType.SHARED) //
252 .flatMap(notUsed -> assertRicStateIdle(ric)) //
253 .flatMap(notUsed -> checkSupportedType(ric, type)) //
254 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
255 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
256 .flatMap(client -> client.putPolicy(policy)) //
257 .doOnNext(notUsed -> policies.put(policy)) //
258 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
259 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
260 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
261 .onErrorResume(this::handleException);
264 @SuppressWarnings({"unchecked"})
265 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
266 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
267 return Mono.just(re);
270 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
271 if (throwable instanceof WebClientResponseException) {
272 WebClientResponseException e = (WebClientResponseException) throwable;
273 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
274 } else if (throwable instanceof RejectionException) {
275 RejectionException e = (RejectionException) throwable;
276 return createResponseEntity(e.getMessage(), e.getStatus());
278 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
282 private Mono<Object> validateModifiedPolicy(Policy policy) {
283 // Check that ric is not updated
284 Policy current = this.policies.get(policy.id());
285 if (current != null && !current.ric().name().equals(policy.ric().name())) {
286 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
287 ", RIC name: " + current.ric().name() + //
288 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
289 logger.debug("Request rejected, {}", e.getMessage());
290 return Mono.error(e);
292 return Mono.just("OK");
295 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
296 if (!ric.isSupportingType(type.name())) {
297 logger.debug("Request rejected, type not supported, RIC: {}", ric);
298 RejectionException e = new RejectionException(
299 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
300 return Mono.error(e);
302 return Mono.just("OK");
305 private Mono<Object> assertRicStateIdle(Ric ric) {
306 if (ric.getState() == Ric.RicState.AVAILABLE) {
307 return Mono.just("OK");
309 logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
310 RejectionException e = new RejectionException(
311 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
312 return Mono.error(e);
316 @GetMapping("/policies")
317 @ApiOperation(value = "Query policies")
320 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
321 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
322 public ResponseEntity<String> getPolicies( //
323 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
324 @RequestParam(name = "type", required = false) String type, //
325 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
326 @RequestParam(name = "ric", required = false) String ric, //
327 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
328 @RequestParam(name = "service", required = false) String service) //
330 if ((type != null && this.policyTypes.get(type) == null)) {
331 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
333 if ((ric != null && this.rics.get(ric) == null)) {
334 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
337 String filteredPolicies = policiesToJson(filter(type, ric, service));
338 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
341 @GetMapping("/policy_ids")
342 @ApiOperation(value = "Query policies, only IDs returned")
344 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
345 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
346 public ResponseEntity<String> getPolicyIds( //
347 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
348 @RequestParam(name = "type", required = false) String type, //
349 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
350 @RequestParam(name = "ric", required = false) String ric, //
351 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
352 @RequestParam(name = "service", required = false) String service) //
354 if ((type != null && this.policyTypes.get(type) == null)) {
355 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
357 if ((ric != null && this.rics.get(ric) == null)) {
358 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
361 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
362 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
365 @GetMapping("/policy_status")
366 @ApiOperation(value = "Returns a policy status") //
369 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
370 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
372 public Mono<ResponseEntity<String>> getPolicyStatus( //
373 @ApiParam(name = "id", required = true, value = "The ID of the policy.") @RequestParam(
375 required = true) String id) {
377 Policy policy = policies.getPolicy(id);
379 return a1ClientFactory.createA1Client(policy.ric()) //
380 .flatMap(client -> client.getPolicyStatus(policy)) //
381 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
382 .onErrorResume(this::handleException);
383 } catch (ServiceException e) {
384 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
388 private void keepServiceAlive(String name) {
389 Service s = this.services.get(name);
395 private boolean include(String filter, String value) {
396 return filter == null || value.equals(filter);
399 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
400 if (type == null && ric == null && service == null) {
403 List<Policy> filtered = new ArrayList<>();
404 for (Policy p : collection) {
405 if (include(type, p.type().name()) && include(ric, p.ric().name())
406 && include(service, p.ownerServiceName())) {
413 private Collection<Policy> filter(String type, String ric, String service) {
415 return filter(policies.getForType(type), null, ric, service);
416 } else if (service != null) {
417 return filter(policies.getForService(service), type, ric, null);
418 } else if (ric != null) {
419 return filter(policies.getForRic(ric), type, null, service);
421 return policies.getAll();
425 private String policiesToJson(Collection<Policy> policies) {
426 List<PolicyInfo> v = new ArrayList<>(policies.size());
427 for (Policy p : policies) {
428 PolicyInfo policyInfo = new PolicyInfo();
429 policyInfo.id = p.id();
430 policyInfo.json = fromJson(p.json());
431 policyInfo.ric = p.ric().name();
432 policyInfo.type = p.type().name();
433 policyInfo.service = p.ownerServiceName();
434 policyInfo.lastModified = p.lastModified();
435 if (!policyInfo.validate()) {
436 logger.error("BUG, all fields must be set");
440 return gson.toJson(v);
443 private Object fromJson(String jsonStr) {
444 return gson.fromJson(jsonStr, Object.class);
447 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
448 StringBuilder result = new StringBuilder();
450 boolean first = true;
451 for (PolicyType t : types) {
456 result.append(t.schema());
459 return result.toString();
462 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
463 List<String> v = new ArrayList<>(types.size());
464 for (PolicyType t : types) {
467 return gson.toJson(v);
470 private String toPolicyIdsJson(Collection<Policy> policies) {
471 List<String> v = new ArrayList<>(policies.size());
472 for (Policy p : policies) {
475 return gson.toJson(v);
478 private String getTimeStampUtc() {
479 return java.time.Instant.now().toString();