Search in sources :

Example 6 with Msg

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

the class PolicyCrudService method setEnabledStateForPolicies.

@Operation(summary = "Enable/disable policies identified by list of uuid in body")
@Parameter(name = "uuids", schema = @Schema(type = SchemaType.ARRAY, implementation = UUID.class))
@APIResponse(responseCode = "200", description = "Policy updated", content = @Content(schema = @Schema(type = SchemaType.ARRAY, implementation = UUID.class)))
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@POST
@Path("/ids/enabled")
@Transactional
public Response setEnabledStateForPolicies(@QueryParam("enabled") boolean shouldBeEnabled, @NotEmpty List<UUID> uuids) {
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_UPDATE_POLICY)).build();
    }
    List<UUID> changed = new ArrayList<>(uuids.size());
    try {
        for (UUID uuid : uuids) {
            Policy storedPolicy = Policy.findById(user.getAccount(), uuid);
            boolean wasChanged = false;
            if (storedPolicy != null) {
                try {
                    if (shouldBeEnabled) {
                        engine.enableTrigger(storedPolicy.id, user.getAccount());
                    } else {
                        engine.disableTrigger(storedPolicy.id, user.getAccount());
                    }
                    wasChanged = true;
                } catch (Exception e) {
                    log.warning("Changing state in engine failed: " + e.getMessage());
                }
                if (wasChanged) {
                    storedPolicy.isEnabled = shouldBeEnabled;
                    storedPolicy.setMtimeToNow();
                    storedPolicy.persist();
                    changed.add(uuid);
                }
            }
        }
        return Response.ok(changed).build();
    } catch (Throwable e) {
        log.severe("Enabling failed: " + e.getMessage());
        return Response.serverError().build();
    }
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) ArrayList(java.util.ArrayList) 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) 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 7 with Msg

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

the class PolicyCrudService method getPolicyIdsForCustomer.

@Operation(summary = "Return all policy ids for a given account after applying the filters")
@GET
@Path("/ids")
@Parameters({ @Parameter(name = "filter[name]", in = ParameterIn.QUERY, description = "Filtering policies by the 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 filter", schema = @Schema(type = SchemaType.STRING, enumeration = { "equal", "like", "ilike", "not_equal" }, defaultValue = "equal")), @Parameter(name = "filter[description]", in = ParameterIn.QUERY, description = "Filtering policies by the description depending on the Filter operator used.", schema = @Schema(type = SchemaType.STRING)), @Parameter(name = "filter:op[description]", in = ParameterIn.QUERY, description = "Operations used with the filter", schema = @Schema(type = SchemaType.STRING, enumeration = { "equal", "like", "ilike", "not_equal" }, defaultValue = "equal")), @Parameter(name = "filter[is_enabled]", in = ParameterIn.QUERY, description = "Filtering policies by the is_enabled field." + "Defaults to true if no operand is given.", schema = @Schema(type = SchemaType.STRING, defaultValue = "true", enumeration = { "true", "false" })) })
@APIResponse(responseCode = "400", description = "Bad parameter for sorting was passed")
@APIResponse(responseCode = "404", description = "No policies found for customer")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@APIResponse(responseCode = "200", description = "PolicyIds found", content = @Content(schema = @Schema(type = SchemaType.ARRAY, implementation = UUID.class)))
public Response getPolicyIdsForCustomer() {
    if (!user.canReadPolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_RETRIEVE_POLICIES)).build();
    }
    List<UUID> uuids;
    try {
        Pager pager = PagingUtils.extractPager(uriInfo);
        uuids = Policy.getPolicyIdsForCustomer(entityManager, user.getAccount(), pager);
    } catch (IllegalArgumentException iae) {
        return Response.status(400, iae.getLocalizedMessage()).build();
    }
    return Response.ok(uuids).build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Pager(com.redhat.cloud.policies.app.model.pager.Pager) UUID(java.util.UUID) 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 8 with Msg

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

the class PolicyCrudService method getPolicy.

@Operation(summary = "Retrieve a single policy for a customer by its id")
@GET
@Path("/{id}")
@APIResponse(responseCode = "200", description = "Policy found", content = @Content(schema = @Schema(implementation = Policy.class)))
@APIResponse(responseCode = "404", description = "Policy not found")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action", content = @Content(schema = @Schema(implementation = Msg.class)))
@Parameter(name = "id", description = "UUID of the policy")
public Response getPolicy(@PathParam("id") UUID policyId) {
    if (!user.canReadPolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_RETRIEVE_POLICIES)).build();
    }
    Policy policy = Policy.findById(user.getAccount(), policyId);
    ResponseBuilder builder;
    if (policy == null) {
        builder = Response.status(Response.Status.NOT_FOUND);
    } else {
        Long lastTriggerTime = policiesHistoryRepository.getLastTriggerTime(user.getAccount(), policy.id);
        if (lastTriggerTime != null) {
            policy.setLastTriggered(lastTriggerTime);
        }
        builder = Response.ok(policy);
        EntityTag etag = new EntityTag(String.valueOf(policy.hashCode()));
        builder.header("ETag", etag);
    }
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) GET(javax.ws.rs.GET) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 9 with Msg

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

the class AdminService method syncToEngine.

@Path("/sync")
@POST
@Transactional
public Response syncToEngine(@QueryParam("token") String token) {
    boolean validToken = StuffHolder.getInstance().compareToken(token);
    if (!validToken) {
        return Response.status(Response.Status.FORBIDDEN).entity("You don't have permission for this").build();
    }
    final int[] count = { 0 };
    try (Stream<Policy> policies = Policy.streamAll()) {
        policies.forEach(p -> {
            FullTrigger fullTrigger;
            try {
                fullTrigger = engine.fetchTrigger(p.id, p.customerid);
            } catch (NotFoundException nfe) {
                fullTrigger = null;
            }
            if (fullTrigger == null) {
                // Engine does not have the trigger
                log.info("Trigger " + p.id + " not found, syncing");
                FullTrigger ft = new FullTrigger(p);
                engine.storeTrigger(ft, false, p.customerid);
                log.info("   done");
                count[0]++;
            } else {
                log.info("Trigger " + p.id + " already in engine, skipping");
            }
        });
    }
    String s = "Stored " + count[0] + " triggers";
    log.info(s);
    return Response.ok().entity(new Msg(s)).build();
}
Also used : Policy(com.redhat.cloud.policies.app.model.Policy) Msg(com.redhat.cloud.policies.app.model.Msg) NotFoundException(javax.ws.rs.NotFoundException) FullTrigger(com.redhat.cloud.policies.app.model.engine.FullTrigger) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Transactional(javax.transaction.Transactional)

Example 10 with Msg

use of com.redhat.cloud.policies.app.model.Msg 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)

Aggregations

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