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();
}
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);
}
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);
}
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();
}
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();
}
Aggregations