Search in sources :

Example 11 with Policy

use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method getTriggerHistoryForPolicy.

@Operation(summary = "Retrieve the trigger history of a single policy")
@APIResponse(responseCode = "200", description = "History could be retrieved", content = @Content(schema = @Schema(implementation = PagedResponseOfHistoryItem.class)), headers = @Header(name = "TotalCount", description = "Total number of items found", schema = @Schema(type = SchemaType.INTEGER)))
@APIResponse(responseCode = "400", description = "Bad parameters passed")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@APIResponse(responseCode = "404", description = "Policy not found")
@APIResponse(responseCode = "500", description = "Retrieval of History failed")
@Parameters({ @Parameter(name = "offset", in = ParameterIn.QUERY, description = "Page number, starts 0, if not specified uses 0.", schema = @Schema(type = SchemaType.INTEGER)), @Parameter(name = "limit", in = ParameterIn.QUERY, description = "Number of items per page, if not specified uses 50. Maximum value is 200.", schema = @Schema(type = SchemaType.INTEGER)), @Parameter(name = "filter[name]", in = ParameterIn.QUERY, description = "Filtering history entries by the host name depending on the Filter operator used.", schema = @Schema(type = SchemaType.STRING)), @Parameter(name = "filter:op[name]", in = ParameterIn.QUERY, description = "Operations used with the name filter", schema = @Schema(type = SchemaType.STRING, enumeration = { "equal", "like", "not_equal" }, defaultValue = "equal")), @Parameter(name = "filter[id]", in = ParameterIn.QUERY, description = "Filtering history entries by the id depending on the Filter operator used.", schema = @Schema(type = SchemaType.STRING)), @Parameter(name = "filter:op[id]", in = ParameterIn.QUERY, description = "Operations used with the name filter", schema = @Schema(type = SchemaType.STRING, enumeration = { "equal", "not_equal", "like" }, defaultValue = "equal")), @Parameter(name = "sortColumn", in = ParameterIn.QUERY, description = "Column to sort the results by", schema = @Schema(type = SchemaType.STRING, enumeration = { "hostName", CTIME_STRING }, defaultValue = CTIME_STRING)), @Parameter(name = "sortDirection", in = ParameterIn.QUERY, description = "Sort direction used", schema = @Schema(type = SchemaType.STRING, enumeration = { "asc", "desc" })), @Parameter(name = "id", description = "UUID of the policy") })
@GET
@Path("/{id}/history/trigger")
public Response getTriggerHistoryForPolicy(@PathParam("id") UUID policyId) {
    if (!user.canReadPolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg("Missing permissions to retrieve the policy history")).build();
    }
    ResponseBuilder builder;
    Policy policy = Policy.findById(user.getAccount(), policyId);
    if (policy == null) {
        builder = Response.status(Response.Status.NOT_FOUND);
    } else {
        try {
            Pager pager = PagingUtils.extractPager(uriInfo);
            builder = buildHistoryResponse(policyId, pager);
        } catch (IllegalArgumentException iae) {
            tracer.activeSpan().setTag(ERROR_STRING, true);
            builder = Response.status(400, iae.getMessage());
        } catch (Exception e) {
            tracer.activeSpan().setTag(ERROR_STRING, true);
            String msg = "Retrieval of history failed with: " + e.getMessage();
            log.warning(msg);
            builder = Response.serverError().entity(msg);
        }
    }
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) Pager(com.redhat.cloud.policies.app.model.pager.Pager) JsonString(javax.json.JsonString) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) NotFoundException(javax.ws.rs.NotFoundException) PersistenceException(javax.persistence.PersistenceException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SystemException(javax.transaction.SystemException) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Parameters(org.eclipse.microprofile.openapi.annotations.parameters.Parameters) GET(javax.ws.rs.GET) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 12 with Policy

use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method deletePolicy.

@Operation(summary = "Delete a single policy for a customer by its id")
@DELETE
@Path("/{id}")
@APIResponse(responseCode = "200", description = "Policy deleted")
@APIResponse(responseCode = "404", description = "Policy not found")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@Parameter(name = "id", description = "UUID of the policy")
@Transactional
public Response deletePolicy(@PathParam("id") UUID policyId) {
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg("Missing permissions to delete policy")).build();
    }
    Policy policy = Policy.findById(user.getAccount(), policyId);
    ResponseBuilder builder = Response.ok();
    if (policy == null) {
        builder = Response.status(Response.Status.NOT_FOUND);
    } else {
        boolean deletedOnEngine = false;
        try {
            engine.deleteTrigger(policy.id, user.getAccount());
            deletedOnEngine = true;
        } catch (NotFoundException nfe) {
            // Engine does not have it - we can delete anyway
            deletedOnEngine = true;
        } catch (Exception e) {
            log.warning("Deletion on engine failed because of " + e.getMessage());
            builder = Response.serverError().entity(new Msg(e.getMessage()));
        }
        if (deletedOnEngine) {
            policy.delete(policy);
            builder = Response.ok(policy);
        }
    }
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) NotFoundException(javax.ws.rs.NotFoundException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) NotFoundException(javax.ws.rs.NotFoundException) PersistenceException(javax.persistence.PersistenceException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SystemException(javax.transaction.SystemException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Example 13 with Policy

use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method setEnabledStateForPolicy.

@Operation(summary = "Enable/disable a policy")
@Parameter(name = "id", description = "ID of the Policy")
@Parameter(name = "enabled", schema = @Schema(type = SchemaType.BOOLEAN, defaultValue = "false"), description = "Should the policy be enabled (true) or disabled (false, default)")
@APIResponse(responseCode = "200", description = "Policy updated")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@APIResponse(responseCode = "404", description = "Policy not found")
@APIResponse(responseCode = "500", description = "Updating failed")
@POST
@Path("/{id:[0-9a-fA-F-]+}/enabled")
@Transactional
public Response setEnabledStateForPolicy(@PathParam("id") UUID policyId, @QueryParam("enabled") boolean shouldBeEnabled) {
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_UPDATE_POLICY)).build();
    }
    Policy storedPolicy = Policy.findById(user.getAccount(), policyId);
    ResponseBuilder builder;
    if (storedPolicy == null) {
        builder = Response.status(404, "Original policy not found");
    } else {
        try {
            if (shouldBeEnabled) {
                engine.enableTrigger(storedPolicy.id, user.getAccount());
            } else {
                engine.disableTrigger(storedPolicy.id, user.getAccount());
            }
            storedPolicy.isEnabled = shouldBeEnabled;
            storedPolicy.setMtimeToNow();
            storedPolicy.persist();
            builder = Response.ok();
        } catch (NotFoundException nfe) {
            builder = Response.status(404, "Policy not found in engine");
            log.warning("Enable/Disable failed, policy [" + storedPolicy.id + "] not found in engine");
        } catch (Exception e) {
            builder = Response.status(500, "Update failed: " + e.getMessage());
        }
    }
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) NotFoundException(javax.ws.rs.NotFoundException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) NotFoundException(javax.ws.rs.NotFoundException) PersistenceException(javax.persistence.PersistenceException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SystemException(javax.transaction.SystemException) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) POST(javax.ws.rs.POST) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Example 14 with Policy

use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method deletePolicies.

@Operation(summary = "Delete policies for a customer by the ids passed in the body. Result will be a list of deleted UUIDs")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@APIResponse(responseCode = "200", description = "Policies deleted", content = @Content(schema = @Schema(type = SchemaType.ARRAY, implementation = UUID.class)))
@DELETE
@Path("/ids")
@Transactional
public Response deletePolicies(List<UUID> uuids) {
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg("Missing permissions to delete policy")).build();
    }
    List<UUID> deleted = new ArrayList<>(uuids.size());
    for (UUID uuid : uuids) {
        Policy policy = Policy.findById(user.getAccount(), uuid);
        if (policy == null) {
            // Nothing to do for us
            deleted.add(uuid);
        } else {
            boolean deletedOnEngine = false;
            try {
                engine.deleteTrigger(policy.id, user.getAccount());
                deletedOnEngine = true;
            } catch (NotFoundException nfe) {
                // Engine does not have it - we can delete anyway
                deletedOnEngine = true;
            } catch (Exception e) {
                log.warning("Deletion on engine failed because of " + e.getMessage());
            }
            if (deletedOnEngine) {
                policy.delete();
                deleted.add(uuid);
            }
        }
    }
    return Response.ok(deleted).build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) ArrayList(java.util.ArrayList) NotFoundException(javax.ws.rs.NotFoundException) UUID(java.util.UUID) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) NotFoundException(javax.ws.rs.NotFoundException) PersistenceException(javax.persistence.PersistenceException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SystemException(javax.transaction.SystemException) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) DELETE(javax.ws.rs.DELETE) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Example 15 with Policy

use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method updatePolicy.

@Operation(summary = "Update a single policy for a customer by its id")
@PUT
@Path("/{policyId}")
@APIResponse(responseCode = "200", description = "Policy updated or policy validated", content = @Content(schema = @Schema(implementation = Policy.class)))
@APIResponse(responseCode = "400", description = "Invalid or no policy provided")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@APIResponse(responseCode = "404", description = "Policy did not exist - did you store it before?")
@APIResponse(responseCode = "409", description = "Persisting failed", content = @Content(schema = @Schema(implementation = Msg.class)))
@Transactional
public Response updatePolicy(@QueryParam("dry") boolean dryRun, @PathParam("policyId") UUID policyId, @NotNull @Valid Policy policy) {
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_UPDATE_POLICY)).build();
    }
    Policy storedPolicy = Policy.findById(user.getAccount(), policyId);
    ResponseBuilder builder;
    if (storedPolicy == null) {
        builder = Response.status(404, "Original policy not found");
    } else {
        if (!policy.id.equals(policyId)) {
            builder = Response.status(400, "Invalid policy");
        } else {
            Response invalidNameResponse = isNameUnique(policy);
            if (invalidNameResponse != null) {
                return invalidNameResponse;
            }
            try {
                FullTrigger trigger = new FullTrigger(policy);
                engine.updateTrigger(policy.id, trigger, true, user.getAccount());
            } catch (Exception e) {
                return Response.status(400, e.getMessage()).entity(getEngineExceptionMsg(e)).build();
            }
            if (dryRun) {
                return Response.status(200).entity(new Msg("Policy validated")).build();
            }
            // so we need to first poll from it.
            try {
                FullTrigger existingTrigger;
                try {
                    existingTrigger = engine.fetchTrigger(storedPolicy.id, user.getAccount());
                } catch (Exception e) {
                    return Response.status(400, e.getMessage()).entity(getEngineExceptionMsg(e)).build();
                }
                storedPolicy.populateFrom(policy);
                storedPolicy.customerid = user.getAccount();
                storedPolicy.setMtimeToNow();
                existingTrigger.updateFromPolicy(storedPolicy);
                try {
                    engine.updateTrigger(storedPolicy.id, existingTrigger, false, user.getAccount());
                } catch (Exception e) {
                    transactionManager.setRollbackOnly();
                    return Response.status(400, e.getMessage()).entity(getEngineExceptionMsg(e)).build();
                }
            } catch (Throwable t) {
                try {
                    transactionManager.setRollbackOnly();
                } catch (SystemException ex) {
                    throw new RuntimeException(ex);
                }
                return getResponseSavingPolicyThrowable(t);
            }
            builder = Response.ok(storedPolicy);
        }
    }
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) SystemException(javax.transaction.SystemException) FullTrigger(com.redhat.cloud.policies.app.model.engine.FullTrigger) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) NotFoundException(javax.ws.rs.NotFoundException) PersistenceException(javax.persistence.PersistenceException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SystemException(javax.transaction.SystemException) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Operation(org.eclipse.microprofile.openapi.annotations.Operation) PUT(javax.ws.rs.PUT) Transactional(javax.transaction.Transactional)

Aggregations

Policy (com.redhat.cloud.policies.app.model.Policy)21 Msg (com.redhat.cloud.policies.app.model.Msg)11 FullTrigger (com.redhat.cloud.policies.app.model.engine.FullTrigger)11 Path (javax.ws.rs.Path)11 Operation (org.eclipse.microprofile.openapi.annotations.Operation)9 APIResponse (org.eclipse.microprofile.openapi.annotations.responses.APIResponse)9 NotFoundException (javax.ws.rs.NotFoundException)8 Test (org.junit.jupiter.api.Test)8 Transactional (javax.transaction.Transactional)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 ConnectException (java.net.ConnectException)6 PersistenceException (javax.persistence.PersistenceException)6 SystemException (javax.transaction.SystemException)6 ProcessingException (javax.ws.rs.ProcessingException)6 WebApplicationException (javax.ws.rs.WebApplicationException)6 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)6 POST (javax.ws.rs.POST)5 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)5 Parameter (org.eclipse.microprofile.openapi.annotations.parameters.Parameter)5 GET (javax.ws.rs.GET)4