Search in sources :

Example 1 with FullTrigger

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

the class PolicyCrudService method storePolicy.

@Operation(summary = "Validate (and possibly persist) a passed policy for the given account")
@Parameter(name = "alsoStore", description = "If passed and set to true, the passed policy is also persisted (if it is valid)")
@APIResponses({ @APIResponse(responseCode = "500", description = "Internal error"), @APIResponse(responseCode = "400", description = "No policy provided or policy validation failed", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "409", description = "Persisting failed", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "403", description = "Individual permissions missing to complete action"), @APIResponse(responseCode = "201", description = "Policy persisted", content = @Content(schema = @Schema(implementation = Policy.class))), @APIResponse(responseCode = "200", description = "Policy validated") })
@POST
@Path("/")
@Transactional
public Response storePolicy(@QueryParam("alsoStore") boolean alsoStore, @NotNull @Valid Policy policy) {
    if (!user.canReadPolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_VERIFY_POLICY)).build();
    }
    // We use the indirection, so that for testing we can produce known UUIDs
    policy.id = uuidHelper.getUUID();
    policy.customerid = user.getAccount();
    Response invalidNameResponse = isNameUnique(policy);
    if (invalidNameResponse != null) {
        return invalidNameResponse;
    }
    try {
        FullTrigger trigger = new FullTrigger(policy, true);
        engine.storeTrigger(trigger, true, user.getAccount());
    } catch (Exception e) {
        return Response.status(400, e.getMessage()).entity(getEngineExceptionMsg(e)).build();
    }
    if (!alsoStore) {
        return Response.status(200).entity(new Msg("Policy validated")).build();
    }
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg("Missing permissions to store policy")).build();
    }
    // Basic validation was successful, so try to persist.
    // This may still fail du to unique name violation, so
    // we need to check for that.
    UUID id;
    try {
        FullTrigger trigger = new FullTrigger(policy);
        try {
            engine.storeTrigger(trigger, false, user.getAccount());
            id = policy.store(user.getAccount(), policy);
        } catch (Exception e) {
            Msg engineExceptionMsg = getEngineExceptionMsg(e);
            log.warning("Storing policy in engine failed: " + engineExceptionMsg.msg);
            return Response.status(400, e.getMessage()).entity(engineExceptionMsg).build();
        }
    } catch (Throwable t) {
        return getResponseSavingPolicyThrowable(t);
    }
    // Policy is persisted. Return its location.
    URI location = UriBuilder.fromResource(PolicyCrudService.class).path(PolicyCrudService.class, "getPolicy").build(id);
    ResponseBuilder builder = Response.created(location).entity(policy);
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) FullTrigger(com.redhat.cloud.policies.app.model.engine.FullTrigger) UUID(java.util.UUID) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URI(java.net.URI) 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) POST(javax.ws.rs.POST) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Example 2 with FullTrigger

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

the class FullTriggerHandlingTest method testSetup.

@Test
void testSetup() {
    Policy p = createPolicy();
    FullTrigger ft = new FullTrigger(p);
    assertFalse(ft.trigger.enabled);
    assertEquals("hula", ft.trigger.name);
    assertEquals(1, ft.conditions.size());
    assertEquals("bla", ft.conditions.get(0).expression);
    assertEquals(1, ft.trigger.actions.size());
    assertEquals("notification", ft.trigger.actions.iterator().next().actionPlugin);
    assertEquals("hula", ft.trigger.name);
    assertEquals("some text", ft.trigger.description);
}
Also used : Policy(com.redhat.cloud.policies.app.model.Policy) FullTrigger(com.redhat.cloud.policies.app.model.engine.FullTrigger) Test(org.junit.jupiter.api.Test)

Example 3 with FullTrigger

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

the class FullTriggerHandlingTest method testActionUpdate1.

@Test
void testActionUpdate1() {
    Policy p = createPolicy();
    FullTrigger ft = new FullTrigger(p);
    p.actions = "notification";
    ft.updateFromPolicy(p);
    assertEquals(1, ft.trigger.actions.size());
    assertEquals("notification", ft.trigger.actions.iterator().next().actionPlugin);
}
Also used : Policy(com.redhat.cloud.policies.app.model.Policy) FullTrigger(com.redhat.cloud.policies.app.model.engine.FullTrigger) Test(org.junit.jupiter.api.Test)

Example 4 with FullTrigger

use of com.redhat.cloud.policies.app.model.engine.FullTrigger 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 5 with FullTrigger

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

FullTrigger (com.redhat.cloud.policies.app.model.engine.FullTrigger)12 Policy (com.redhat.cloud.policies.app.model.Policy)10 Test (org.junit.jupiter.api.Test)8 Msg (com.redhat.cloud.policies.app.model.Msg)3 Transactional (javax.transaction.Transactional)3 NotFoundException (javax.ws.rs.NotFoundException)3 Path (javax.ws.rs.Path)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ConnectException (java.net.ConnectException)2 PersistenceException (javax.persistence.PersistenceException)2 SystemException (javax.transaction.SystemException)2 POST (javax.ws.rs.POST)2 ProcessingException (javax.ws.rs.ProcessingException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)2 Operation (org.eclipse.microprofile.openapi.annotations.Operation)2 APIResponse (org.eclipse.microprofile.openapi.annotations.responses.APIResponse)2 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)2 Trigger (com.redhat.cloud.policies.app.model.engine.Trigger)1 URI (java.net.URI)1