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(@ApiParam(name = "ric", required = false, value = "The name of " +//
103 "the Near-RT RIC to get the definitions for.")@RequestParam(name = "ric", required = false) String ricName) {
104 if (ricName == null) {
105 Collection<PolicyType> types = this.policyTypes.getAll();
106 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
109 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
110 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
111 } catch (ServiceException e) {
112 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
117 @GetMapping("/policy_schema")
118 @ApiOperation(value = "Returns one policy type schema definition")
121 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
122 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
123 public ResponseEntity<String> getPolicySchema(@ApiParam(name = "id", required = true, value = "The ID of the " +//
124 "policy type to get the definition for.")@RequestParam(name = "id", required = true) String id) {
126 PolicyType type = policyTypes.getType(id);
127 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
128 } catch (ServiceException e) {
129 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
133 @GetMapping("/policy_types")
134 @ApiOperation(value = "Query policy type names")
139 message = "Policy type names",
140 response = String.class,
141 responseContainer = "List"),
142 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
143 public ResponseEntity<String> getPolicyTypes(@ApiParam(name = "ric", required = false, value = "The name of " +//
144 "the Near-RT RIC to get types for.")@RequestParam(name = "ric", required = false) String ricName) {
145 if (ricName == null) {
146 Collection<PolicyType> types = this.policyTypes.getAll();
147 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
150 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
151 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
152 } catch (ServiceException e) {
153 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
158 @GetMapping("/policy")
159 @ApiOperation(value = "Returns a policy configuration") //
162 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
163 @ApiResponse(code = 404, message = "Policy is not found")} //
165 public ResponseEntity<String> getPolicy( //
166 @ApiParam(name = "id", required = true, value = "The ID of the policy instance.")@RequestParam(name = "id", //
167 required = true) String id) {
169 Policy p = policies.getPolicy(id);
170 return new ResponseEntity<>(p.json(), HttpStatus.OK);
171 } catch (ServiceException e) {
172 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
176 @DeleteMapping("/policy")
177 @ApiOperation(value = "Delete a policy", response = Object.class)
180 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
181 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
182 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
183 public Mono<ResponseEntity<Object>> deletePolicy( //
184 @ApiParam(name = "id", required = true, value = "The ID of the policy instance.")@RequestParam(name = "id", //
185 required = true) String id) {
187 Policy policy = policies.getPolicy(id);
188 keepServiceAlive(policy.ownerServiceName());
189 Ric ric = policy.ric();
190 return ric.getLock().lock(LockType.SHARED) //
191 .flatMap(notUsed -> assertRicStateIdle(ric)) //
192 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
193 .doOnNext(notUsed -> policies.remove(policy)) //
194 .flatMap(client -> client.deletePolicy(policy)) //
195 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
196 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
197 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
198 .onErrorResume(this::handleException);
199 } catch (ServiceException e) {
200 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
204 @PutMapping(path = "/policy")
205 @ApiOperation(value = "Put a policy", response = String.class)
208 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
209 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
210 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
211 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
213 public Mono<ResponseEntity<Object>> putPolicy( //
214 @ApiParam(name = "type", required = false, value = "The name of the policy type.") //
215 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
216 @ApiParam(name = "id", required = true, value = "The ID of the policy instance.")@RequestParam(name = "id", //
217 required = true) String instanceId, //
218 @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " +//
219 "created.")@RequestParam(name = "ric", required = true) String ricName, //
220 @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") //
221 @RequestParam(name = "service", required = true) String service, //
222 @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " +//
223 "defaulted to false). A policy is transient if it will be forgotten when the service needs to " +//
224 "reconnect to the Near-RT RIC.")@RequestParam(name = "transient", required = false, //
225 defaultValue = "false") boolean isTransient, //
226 @RequestBody Object jsonBody) {
228 String jsonString = gson.toJson(jsonBody);
229 Ric ric = rics.get(ricName);
230 PolicyType type = policyTypes.get(typeName);
231 keepServiceAlive(service);
232 if (ric == null || type == null) {
233 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
235 Policy policy = ImmutablePolicy.builder() //
240 .ownerServiceName(service) //
241 .lastModified(getTimeStampUtc()) //
242 .isTransient(isTransient) //
245 final boolean isCreate = this.policies.get(policy.id()) == null;
247 return ric.getLock().lock(LockType.SHARED) //
248 .flatMap(notUsed -> assertRicStateIdle(ric)) //
249 .flatMap(notUsed -> checkSupportedType(ric, type)) //
250 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
251 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
252 .flatMap(client -> client.putPolicy(policy)) //
253 .doOnNext(notUsed -> policies.put(policy)) //
254 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
255 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
256 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
257 .onErrorResume(this::handleException);
260 @SuppressWarnings({"unchecked"})
261 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
262 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
263 return Mono.just(re);
266 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
267 if (throwable instanceof WebClientResponseException) {
268 WebClientResponseException e = (WebClientResponseException) throwable;
269 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
270 } else if (throwable instanceof RejectionException) {
271 RejectionException e = (RejectionException) throwable;
272 return createResponseEntity(e.getMessage(), e.getStatus());
274 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
278 private Mono<Object> validateModifiedPolicy(Policy policy) {
279 // Check that ric is not updated
280 Policy current = this.policies.get(policy.id());
281 if (current != null && !current.ric().name().equals(policy.ric().name())) {
282 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
283 ", RIC name: " + current.ric().name() + //
284 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
285 return Mono.error(e);
287 return Mono.just("OK");
290 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
291 if (!ric.isSupportingType(type.name())) {
292 RejectionException e = new RejectionException(
293 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
294 return Mono.error(e);
296 return Mono.just("OK");
299 private Mono<Object> assertRicStateIdle(Ric ric) {
300 if (ric.getState() == Ric.RicState.AVAILABLE) {
301 return Mono.just("OK");
303 RejectionException e = new RejectionException(
304 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
305 return Mono.error(e);
309 @GetMapping("/policies")
310 @ApiOperation(value = "Query policies")
313 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
314 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
315 public ResponseEntity<String> getPolicies( //
316 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
317 @RequestParam(name = "type", required = false) String type, //
318 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
319 @RequestParam(name = "ric", required = false) String ric, //
320 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
321 @RequestParam(name = "service", required = false) String service) //
323 if ((type != null && this.policyTypes.get(type) == null)) {
324 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
326 if ((ric != null && this.rics.get(ric) == null)) {
327 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
330 String filteredPolicies = policiesToJson(filter(type, ric, service));
331 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
334 @GetMapping("/policy_ids")
335 @ApiOperation(value = "Query policies, only IDs returned")
337 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
338 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
339 public ResponseEntity<String> getPolicyIds( //
340 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
341 @RequestParam(name = "type", required = false) String type, //
342 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
343 @RequestParam(name = "ric", required = false) String ric, //
344 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
345 @RequestParam(name = "service", required = false) String service) //
347 if ((type != null && this.policyTypes.get(type) == null)) {
348 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
350 if ((ric != null && this.rics.get(ric) == null)) {
351 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
354 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
355 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
358 @GetMapping("/policy_status")
359 @ApiOperation(value = "Returns a policy status") //
362 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
363 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
365 public Mono<ResponseEntity<String>> getPolicyStatus( //
366 @ApiParam(name = "id", required = true, value = "The ID of the policy.")@RequestParam(name = "id", //
367 required = true) String id) {
369 Policy policy = policies.getPolicy(id);
371 return a1ClientFactory.createA1Client(policy.ric()) //
372 .flatMap(client -> client.getPolicyStatus(policy)) //
373 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
374 .onErrorResume(this::handleException);
375 } catch (ServiceException e) {
376 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
380 private void keepServiceAlive(String name) {
381 Service s = this.services.get(name);
387 private boolean include(String filter, String value) {
388 return filter == null || value.equals(filter);
391 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
392 if (type == null && ric == null && service == null) {
395 List<Policy> filtered = new ArrayList<>();
396 for (Policy p : collection) {
397 if (include(type, p.type().name()) && include(ric, p.ric().name())
398 && include(service, p.ownerServiceName())) {
405 private Collection<Policy> filter(String type, String ric, String service) {
407 return filter(policies.getForType(type), null, ric, service);
408 } else if (service != null) {
409 return filter(policies.getForService(service), type, ric, null);
410 } else if (ric != null) {
411 return filter(policies.getForRic(ric), type, null, service);
413 return policies.getAll();
417 private String policiesToJson(Collection<Policy> policies) {
418 List<PolicyInfo> v = new ArrayList<>(policies.size());
419 for (Policy p : policies) {
420 PolicyInfo policyInfo = new PolicyInfo();
421 policyInfo.id = p.id();
422 policyInfo.json = fromJson(p.json());
423 policyInfo.ric = p.ric().name();
424 policyInfo.type = p.type().name();
425 policyInfo.service = p.ownerServiceName();
426 policyInfo.lastModified = p.lastModified();
427 if (!policyInfo.validate()) {
428 logger.error("BUG, all fields must be set");
432 return gson.toJson(v);
435 private Object fromJson(String jsonStr) {
436 return gson.fromJson(jsonStr, Object.class);
439 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
440 StringBuilder result = new StringBuilder();
442 boolean first = true;
443 for (PolicyType t : types) {
448 result.append(t.schema());
451 return result.toString();
454 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
455 List<String> v = new ArrayList<>(types.size());
456 for (PolicyType t : types) {
459 return gson.toJson(v);
462 private String toPolicyIdsJson(Collection<Policy> policies) {
463 List<String> v = new ArrayList<>(policies.size());
464 for (Policy p : policies) {
467 return gson.toJson(v);
470 private String getTimeStampUtc() {
471 return java.time.Instant.now().toString();