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 logger.debug("Request rejected, {}", e.getMessage());
286 return Mono.error(e);
288 return Mono.just("OK");
291 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
292 if (!ric.isSupportingType(type.name())) {
293 logger.debug("Request rejected, type not supported, RIC: {}", ric);
294 RejectionException e = new RejectionException(
295 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
296 return Mono.error(e);
298 return Mono.just("OK");
301 private Mono<Object> assertRicStateIdle(Ric ric) {
302 if (ric.getState() == Ric.RicState.AVAILABLE) {
303 return Mono.just("OK");
305 logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
306 RejectionException e = new RejectionException(
307 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
308 return Mono.error(e);
312 @GetMapping("/policies")
313 @ApiOperation(value = "Query policies")
316 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
317 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
318 public ResponseEntity<String> getPolicies( //
319 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
320 @RequestParam(name = "type", required = false) String type, //
321 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
322 @RequestParam(name = "ric", required = false) String ric, //
323 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
324 @RequestParam(name = "service", required = false) String service) //
326 if ((type != null && this.policyTypes.get(type) == null)) {
327 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
329 if ((ric != null && this.rics.get(ric) == null)) {
330 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
333 String filteredPolicies = policiesToJson(filter(type, ric, service));
334 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
337 @GetMapping("/policy_ids")
338 @ApiOperation(value = "Query policies, only IDs returned")
340 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
341 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
342 public ResponseEntity<String> getPolicyIds( //
343 @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
344 @RequestParam(name = "type", required = false) String type, //
345 @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
346 @RequestParam(name = "ric", required = false) String ric, //
347 @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
348 @RequestParam(name = "service", required = false) String service) //
350 if ((type != null && this.policyTypes.get(type) == null)) {
351 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
353 if ((ric != null && this.rics.get(ric) == null)) {
354 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
357 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
358 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
361 @GetMapping("/policy_status")
362 @ApiOperation(value = "Returns a policy status") //
365 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
366 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
368 public Mono<ResponseEntity<String>> getPolicyStatus( //
369 @ApiParam(name = "id", required = true, value = "The ID of the policy.")@RequestParam(name = "id", //
370 required = true) String id) {
372 Policy policy = policies.getPolicy(id);
374 return a1ClientFactory.createA1Client(policy.ric()) //
375 .flatMap(client -> client.getPolicyStatus(policy)) //
376 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
377 .onErrorResume(this::handleException);
378 } catch (ServiceException e) {
379 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
383 private void keepServiceAlive(String name) {
384 Service s = this.services.get(name);
390 private boolean include(String filter, String value) {
391 return filter == null || value.equals(filter);
394 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
395 if (type == null && ric == null && service == null) {
398 List<Policy> filtered = new ArrayList<>();
399 for (Policy p : collection) {
400 if (include(type, p.type().name()) && include(ric, p.ric().name())
401 && include(service, p.ownerServiceName())) {
408 private Collection<Policy> filter(String type, String ric, String service) {
410 return filter(policies.getForType(type), null, ric, service);
411 } else if (service != null) {
412 return filter(policies.getForService(service), type, ric, null);
413 } else if (ric != null) {
414 return filter(policies.getForRic(ric), type, null, service);
416 return policies.getAll();
420 private String policiesToJson(Collection<Policy> policies) {
421 List<PolicyInfo> v = new ArrayList<>(policies.size());
422 for (Policy p : policies) {
423 PolicyInfo policyInfo = new PolicyInfo();
424 policyInfo.id = p.id();
425 policyInfo.json = fromJson(p.json());
426 policyInfo.ric = p.ric().name();
427 policyInfo.type = p.type().name();
428 policyInfo.service = p.ownerServiceName();
429 policyInfo.lastModified = p.lastModified();
430 if (!policyInfo.validate()) {
431 logger.error("BUG, all fields must be set");
435 return gson.toJson(v);
438 private Object fromJson(String jsonStr) {
439 return gson.fromJson(jsonStr, Object.class);
442 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
443 StringBuilder result = new StringBuilder();
445 boolean first = true;
446 for (PolicyType t : types) {
451 result.append(t.schema());
454 return result.toString();
457 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
458 List<String> v = new ArrayList<>(types.size());
459 for (PolicyType t : types) {
462 return gson.toJson(v);
465 private String toPolicyIdsJson(Collection<Policy> policies) {
466 List<String> v = new ArrayList<>(policies.size());
467 for (Policy p : policies) {
470 return gson.toJson(v);
473 private String getTimeStampUtc() {
474 return java.time.Instant.now().toString();