X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=blobdiff_plain;f=policy-agent%2Fsrc%2Fmain%2Fjava%2Forg%2Foransc%2Fpolicyagent%2Fcontrollers%2FPolicyController.java;h=49d7702833e0d5ffd1d2c4d46d9ccd2022b9fd46;hb=ba50f8809edc7d49a74021e25b4094f4c3174b26;hp=1af607f46c9101c962e4d40068792a0d627224d0;hpb=6a8a0d5350a77b6d1e4a8f95c0fe8fbfeef77339;p=nonrtric.git diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java index 1af607f4..49d77028 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java @@ -28,12 +28,14 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import lombok.Getter; + import org.oransc.policyagent.clients.A1ClientFactory; -import org.oransc.policyagent.configuration.ApplicationConfig; import org.oransc.policyagent.exceptions.ServiceException; import org.oransc.policyagent.repository.ImmutablePolicy; import org.oransc.policyagent.repository.Lock.LockType; @@ -43,6 +45,10 @@ import org.oransc.policyagent.repository.PolicyType; import org.oransc.policyagent.repository.PolicyTypes; import org.oransc.policyagent.repository.Ric; import org.oransc.policyagent.repository.Rics; +import org.oransc.policyagent.repository.Service; +import org.oransc.policyagent.repository.Services; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -52,30 +58,40 @@ import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClientResponseException; import reactor.core.publisher.Mono; @RestController @Api(tags = "A1 Policy Management") public class PolicyController { - private final Rics rics; - private final PolicyTypes policyTypes; - private final Policies policies; - private final A1ClientFactory a1ClientFactory; + public static class RejectionException extends Exception { + private static final long serialVersionUID = 1L; + @Getter + private final HttpStatus status; + + public RejectionException(String message, HttpStatus status) { + super(message); + this.status = status; + } + } + + @Autowired + private Rics rics; + @Autowired + private PolicyTypes policyTypes; + @Autowired + private Policies policies; + @Autowired + private A1ClientFactory a1ClientFactory; + @Autowired + private Services services; + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static Gson gson = new GsonBuilder() // .serializeNulls() // .create(); // - @Autowired - PolicyController(ApplicationConfig config, PolicyTypes types, Policies policies, Rics rics, - A1ClientFactory a1ClientFactory) { - this.policyTypes = types; - this.policies = policies; - this.rics = rics; - this.a1ClientFactory = a1ClientFactory; - } - @GetMapping("/policy_schemas") @ApiOperation(value = "Returns policy type schema definitions") @ApiResponses( @@ -83,17 +99,15 @@ public class PolicyController { @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), // @ApiResponse(code = 404, message = "RIC is not found", response = String.class)}) public ResponseEntity getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) { - synchronized (this.policyTypes) { - if (ricName == null) { - Collection types = this.policyTypes.getAll(); + if (ricName == null) { + Collection types = this.policyTypes.getAll(); + return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); + } else { + try { + Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); - } else { - try { - Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); - return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); - } + } catch (ServiceException e) { + return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); } } } @@ -124,17 +138,15 @@ public class PolicyController { responseContainer = "List"), @ApiResponse(code = 404, message = "RIC is not found", response = String.class)}) public ResponseEntity getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) { - synchronized (this.policyTypes) { - if (ricName == null) { - Collection types = this.policyTypes.getAll(); + if (ricName == null) { + Collection types = this.policyTypes.getAll(); + return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); + } else { + try { + Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); - } else { - try { - Collection types = rics.getRic(ricName).getSupportedPolicyTypes(); - return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK); - } catch (ServiceException e) { - return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); - } + } catch (ServiceException e) { + return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND); } } } @@ -147,9 +159,9 @@ public class PolicyController { @ApiResponse(code = 404, message = "Policy is not found")} // ) public ResponseEntity getPolicy( // - @RequestParam(name = "instance", required = true) String instance) { + @RequestParam(name = "id", required = true) String id) { try { - Policy p = policies.getPolicy(instance); + Policy p = policies.getPolicy(id); return new ResponseEntity<>(p.json(), HttpStatus.OK); } catch (ServiceException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); @@ -162,22 +174,23 @@ public class PolicyController { value = { // @ApiResponse(code = 204, message = "Policy deleted", response = Object.class), @ApiResponse(code = 404, message = "Policy is not found", response = String.class), - @ApiResponse(code = 423, message = "RIC is locked", response = String.class)}) + @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)}) public Mono> deletePolicy( // - @RequestParam(name = "instance", required = true) String id) { - Policy policy = policies.get(id); - if (policy != null && policy.ric().getState() == Ric.RicState.IDLE) { + @RequestParam(name = "id", required = true) String id) { + try { + Policy policy = policies.getPolicy(id); + keepServiceAlive(policy.ownerServiceName()); Ric ric = policy.ric(); - return ric.getLock().lock(LockType.SHARED) // // - .flatMap(lock -> a1ClientFactory.createA1Client(policy.ric())) // + return ric.getLock().lock(LockType.SHARED) // + .flatMap(notUsed -> assertRicStateIdle(ric)) // + .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) // .doOnNext(notUsed -> policies.remove(policy)) // .flatMap(client -> client.deletePolicy(policy)) // .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // .doOnError(notUsed -> ric.getLock().unlockBlocking()) // - .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT))); - } else if (policy != null) { - return Mono.just(new ResponseEntity<>("Busy, recovering", HttpStatus.LOCKED)); - } else { + .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT))) + .onErrorResume(this::handleException); + } catch (ServiceException e) { return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } } @@ -186,59 +199,100 @@ public class PolicyController { @ApiOperation(value = "Put a policy", response = String.class) @ApiResponses( value = { // - @ApiResponse(code = 201, message = "Policy created"), // - @ApiResponse(code = 200, message = "Policy updated"), // - @ApiResponse(code = 423, message = "RIC is locked", response = String.class), // - @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class), // - @ApiResponse(code = 405, message = "Change is not allowed", response = String.class)}) + @ApiResponse(code = 201, message = "Policy created", response = Object.class), // + @ApiResponse(code = 200, message = "Policy updated", response = Object.class), // + @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), // + @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) // + }) public Mono> putPolicy( // - @RequestParam(name = "type", required = true) String typeName, // - @RequestParam(name = "instance", required = true) String instanceId, // + @RequestParam(name = "type", required = false, defaultValue = "") String typeName, // + @RequestParam(name = "id", required = true) String instanceId, // @RequestParam(name = "ric", required = true) String ricName, // @RequestParam(name = "service", required = true) String service, // + @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, // @RequestBody Object jsonBody) { String jsonString = gson.toJson(jsonBody); Ric ric = rics.get(ricName); PolicyType type = policyTypes.get(typeName); - if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) { - Policy policy = ImmutablePolicy.builder() // - .id(instanceId) // - .json(jsonString) // - .type(type) // - .ric(ric) // - .ownerServiceName(service) // - .lastModified(getTimeStampUtc()) // - .build(); - - final boolean isCreate = this.policies.get(policy.id()) == null; - - return ric.getLock().lock(LockType.SHARED) // - .flatMap(p -> validateModifiedPolicy(policy)) // - .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) // - .flatMap(client -> client.putPolicy(policy)) // - .doOnNext(notUsed -> policies.put(policy)) // - .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // - .doOnError(t -> ric.getLock().unlockBlocking()) // - .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) // - .onErrorResume(t -> Mono.just(new ResponseEntity<>(t.getMessage(), HttpStatus.METHOD_NOT_ALLOWED))); + keepServiceAlive(service); + if (ric == null || type == null) { + return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } + Policy policy = ImmutablePolicy.builder() // + .id(instanceId) // + .json(jsonString) // + .type(type) // + .ric(ric) // + .ownerServiceName(service) // + .lastModified(getTimeStampUtc()) // + .isTransient(isTransient) // + .build(); + + final boolean isCreate = this.policies.get(policy.id()) == null; + + return ric.getLock().lock(LockType.SHARED) // + .flatMap(notUsed -> assertRicStateIdle(ric)) // + .flatMap(notUsed -> checkSupportedType(ric, type)) // + .flatMap(notUsed -> validateModifiedPolicy(policy)) // + .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) // + .flatMap(client -> client.putPolicy(policy)) // + .doOnNext(notUsed -> policies.put(policy)) // + .doOnNext(notUsed -> ric.getLock().unlockBlocking()) // + .doOnError(trowable -> ric.getLock().unlockBlocking()) // + .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) // + .onErrorResume(this::handleException); + } + + @SuppressWarnings({"unchecked"}) + private Mono> createResponseEntity(String message, HttpStatus status) { + ResponseEntity re = new ResponseEntity<>((T) message, status); + return Mono.just(re); + } - return ric == null || type == null ? Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)) - : Mono.just(new ResponseEntity<>(HttpStatus.LOCKED)); // Recovering + private Mono> handleException(Throwable throwable) { + if (throwable instanceof WebClientResponseException) { + WebClientResponseException e = (WebClientResponseException) throwable; + return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); + } else if (throwable instanceof RejectionException) { + RejectionException e = (RejectionException) throwable; + return createResponseEntity(e.getMessage(), e.getStatus()); + } else { + return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } private Mono validateModifiedPolicy(Policy policy) { // Check that ric is not updated Policy current = this.policies.get(policy.id()); if (current != null && !current.ric().name().equals(policy.ric().name())) { - return Mono.error(new Exception("Policy cannot change RIC, policyId: " + current.id() + // + RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + // ", RIC name: " + current.ric().name() + // - ", new name: " + policy.ric().name())); + ", new name: " + policy.ric().name(), HttpStatus.CONFLICT); + return Mono.error(e); + } + return Mono.just("OK"); + } + + private Mono checkSupportedType(Ric ric, PolicyType type) { + if (!ric.isSupportingType(type.name())) { + RejectionException e = new RejectionException( + "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND); + return Mono.error(e); } return Mono.just("OK"); } + private Mono assertRicStateIdle(Ric ric) { + if (ric.getState() == Ric.RicState.AVAILABLE) { + return Mono.just("OK"); + } else { + RejectionException e = new RejectionException( + "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED); + return Mono.error(e); + } + } + @GetMapping("/policies") @ApiOperation(value = "Query policies") @ApiResponses( @@ -256,29 +310,30 @@ public class PolicyController { if ((ric != null && this.rics.get(ric) == null)) { return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND); } - synchronized (policies) { - Collection result = null; - - if (type != null) { - result = policies.getForType(type); - result = filter(result, null, ric, service); - } else if (service != null) { - result = policies.getForService(service); - result = filter(result, type, ric, null); - } else if (ric != null) { - result = filter(policies.getForRic(ric), type, null, service); - } else { - result = policies.getAll(); - } - String policiesJson; - try { - policiesJson = policiesToJson(result); - } catch (ServiceException e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - return new ResponseEntity<>(policiesJson, HttpStatus.OK); + String filteredPolicies = policiesToJson(filter(type, ric, service)); + return new ResponseEntity<>(filteredPolicies, HttpStatus.OK); + } + + @GetMapping("/policy_ids") + @ApiOperation(value = "Query policies, only IDs returned") + @ApiResponses( + value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"), + @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)}) + public ResponseEntity getPolicyIds( // + @RequestParam(name = "type", required = false) String type, // + @RequestParam(name = "ric", required = false) String ric, // + @RequestParam(name = "service", required = false) String service) // + { + if ((type != null && this.policyTypes.get(type) == null)) { + return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND); } + if ((ric != null && this.rics.get(ric) == null)) { + return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND); + } + + String policyIdsJson = toPolicyIdsJson(filter(type, ric, service)); + return new ResponseEntity<>(policyIdsJson, HttpStatus.OK); } @GetMapping("/policy_status") @@ -289,18 +344,26 @@ public class PolicyController { @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} // ) public Mono> getPolicyStatus( // - @RequestParam(name = "instance", required = true) String instance) { + @RequestParam(name = "id", required = true) String id) { try { - Policy policy = policies.getPolicy(instance); + Policy policy = policies.getPolicy(id); return a1ClientFactory.createA1Client(policy.ric()) // .flatMap(client -> client.getPolicyStatus(policy)) // - .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK))); + .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK))) + .onErrorResume(this::handleException); } catch (ServiceException e) { return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND)); } } + private void keepServiceAlive(String name) { + Service s = this.services.get(name); + if (s != null) { + s.keepAlive(); + } + } + private boolean include(String filter, String value) { return filter == null || value.equals(filter); } @@ -319,7 +382,19 @@ public class PolicyController { return filtered; } - private String policiesToJson(Collection policies) throws ServiceException { + private Collection filter(String type, String ric, String service) { + if (type != null) { + return filter(policies.getForType(type), null, ric, service); + } else if (service != null) { + return filter(policies.getForService(service), type, ric, null); + } else if (ric != null) { + return filter(policies.getForRic(ric), type, null, service); + } else { + return policies.getAll(); + } + } + + private String policiesToJson(Collection policies) { List v = new ArrayList<>(policies.size()); for (Policy p : policies) { PolicyInfo policyInfo = new PolicyInfo(); @@ -330,7 +405,7 @@ public class PolicyController { policyInfo.service = p.ownerServiceName(); policyInfo.lastModified = p.lastModified(); if (!policyInfo.validate()) { - throw new ServiceException("BUG, all fields must be set"); + logger.error("BUG, all fields must be set"); } v.add(policyInfo); } @@ -364,6 +439,14 @@ public class PolicyController { return gson.toJson(v); } + private String toPolicyIdsJson(Collection policies) { + List v = new ArrayList<>(policies.size()); + for (Policy p : policies) { + v.add(p.id()); + } + return gson.toJson(v); + } + private String getTimeStampUtc() { return java.time.Instant.now().toString(); }