mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision Scheduler schedules (#4834)
* feat(cloudformation): provision Scheduler schedules * fix(cloudformation): track schedule move destination ownership * fix(cloudformation): preserve failed schedule deletion cleanup * fix(cloudformation): guard Scheduler schedule cleanup ownership * fix(cloudformation): verify Scheduler ownership before replacement * fix(cloudformation): omit conditional Scheduler properties * fix(cloudformation): share optional resolution and delete cleanup hooks * fix(cloudformation): address Scheduler schedules by group and name * fix(cloudformation): reject malformed Scheduler cleanup entries * fix(cloudformation): align Scheduler replacement cleanup with main
This commit is contained in:
1 parent
3ec1466014
commit
f6c8ebd5a0
10 files changed
+2789
-1
No files matched your search
@@ -178,7 +178,7 @@ cross-resource references.
|
||||
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) |
|
||||
| EventBridge Scheduler | `ScheduleGroup` |
|
||||
| EventBridge Scheduler | `Schedule`, `ScheduleGroup` |
|
||||
| Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported), `User` (management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user) |
|
||||
| Backup | `BackupVault` |
|
||||
| GuardDuty | `MalwareProtectionPlan` (management plane only: no scan runs, so the plan stays ACTIVE; Ref returns the plan id; a BucketName change is rejected) |
|
||||
@@ -212,6 +212,33 @@ Set `floci.services.cloudformation.allow-stub-unsupported-resource-types` to `fa
|
||||
resource instead: it reaches `CREATE_FAILED` and the stack rolls back. Use it in a pipeline that
|
||||
must not pass over a resource it never got.
|
||||
|
||||
## EventBridge Scheduler Schedules
|
||||
|
||||
`AWS::Scheduler::Schedule` creates a real schedule. `Ref` returns its name and `Fn::GetAtt Arn`
|
||||
returns its ARN. A group move preserves the name, removes the old group address, and restores the
|
||||
original configuration if the stack update rolls back.
|
||||
|
||||
`Fn::If` values that select `AWS::NoValue` omit optional schedule properties and nested target
|
||||
or time-window fields. `ScheduleExpression`, `Target`, `FlexibleTimeWindow`, and their required
|
||||
fields still must be present and valid.
|
||||
|
||||
Floci uses its main engine's bounded replacement-cleanup policy for committed updates and
|
||||
`DeleteStack`: each displaced address has up to three cleanup attempts, and exhausted entries are
|
||||
dropped. A failed cleanup leaves the first stack deletion in `DELETE_FAILED`, even if the current
|
||||
schedule was deleted; a later retry does not retry the dropped addresses. Schedules left after
|
||||
exhausted cleanup require manual deletion through the Scheduler API. A failed current-schedule
|
||||
delete preserves pending recovery state for a later deletion retry. This is Floci's shared cleanup
|
||||
policy, not a claim that AWS guarantees three attempts for `DeleteStack`.
|
||||
`UpdateReplacePolicy: Retain` keeps a name replacement's old schedule, but does not keep a group
|
||||
move's old address or an orphan created by a failed update.
|
||||
|
||||
Schedules are addressed by group and name, as in the Scheduler API. If another client removes a
|
||||
managed schedule and recreates the same address, an in-place stack update applies the template to
|
||||
the current schedule there. Stack deletion and replacement cleanup delete the current schedule
|
||||
at a tracked address, and rollback restores its saved configuration at that address.
|
||||
A historical cleanup entry with attempts remaining can still affect a new occupant of its
|
||||
address. Dropping exhausted debt prevents later retries, but does not establish resource ownership.
|
||||
|
||||
## EventBridge Event Buses
|
||||
|
||||
`AWS::Events::EventBus` creates a real custom EventBridge bus. `Name` is required, `Ref` returns
|
||||
|
||||
@@ -120,6 +120,38 @@ and `Message`, Step Functions `stateMachineArn` and `input`, EventBridge
|
||||
launch type, group, and network configuration. Non-JSON input of a universal
|
||||
target is encoded as a JSON string field.
|
||||
|
||||
## CloudFormation
|
||||
|
||||
`AWS::Scheduler::Schedule` creates a real schedule. `Ref` returns its name and
|
||||
`Fn::GetAtt Arn` returns its Scheduler ARN. An omitted `Name` is generated once
|
||||
and kept on updates. Expression, state, dates, timezone, time window, KMS key and
|
||||
target changes update the schedule in place. A `Name` change creates a replacement;
|
||||
`GroupName` changes keep the same `Ref` and move the schedule to the requested group.
|
||||
The group must already exist or be declared as an `AWS::Scheduler::ScheduleGroup`.
|
||||
|
||||
The displaced schedule stays until the stack update commits, then is deleted.
|
||||
`UpdateReplacePolicy: Retain` keeps a schedule displaced by a name replacement;
|
||||
it does not retain the old address of a group move. A failed stack update restores
|
||||
the original schedule configuration and removes a replacement or group-move destination.
|
||||
During a group move the old schedule is disabled before creating the destination,
|
||||
so the stored schedules are not both enabled. A rollback disables the destination
|
||||
before restoring the original state. A name replacement can briefly leave both
|
||||
schedules enabled until commit, following the existing replacement lifecycle.
|
||||
|
||||
If restoring a failed update also fails, the original configuration snapshot is
|
||||
kept. A later schedule update retries that restoration before taking a new snapshot
|
||||
or applying its desired configuration. If Floci skips the failed schedule during an
|
||||
otherwise unrelated stack update, cleanup preserves the snapshot and leaves the
|
||||
stack in `UPDATE_COMPLETE_CLEANUP_IN_PROGRESS` with an explicit reason. Further
|
||||
updates are blocked, and `DeleteStack` is the available recovery path. This is a
|
||||
Floci recovery limitation; AWS requires `ContinueUpdateRollback` to complete a failed
|
||||
rollback before accepting another stack update.
|
||||
|
||||
Target parameters are limited to those the Scheduler API currently models:
|
||||
retry/dead-letter configuration, SQS, ECS and EventBridge parameters. Kinesis and
|
||||
SageMaker pipeline parameters are rejected instead of silently discarded.
|
||||
Invocation support and time-window limitations are the same as the Scheduler API.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
+457
@@ -0,0 +1,457 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.json.JsonMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.FlexibleTimeWindow;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.Schedule;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.ScheduleRequest;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.Target;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** Provisions schedules through the same Scheduler service used by its REST API. */
|
||||
@ApplicationScoped
|
||||
public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String TYPE = "AWS::Scheduler::Schedule";
|
||||
private static final Logger LOG = Logger.getLogger(SchedulerScheduleCfnProvisioner.class);
|
||||
private static final String GROUP_ATTR = "FlociSchedulerGroupName";
|
||||
private static final String NAME_MODE_ATTR = "FlociSchedulerNameMode";
|
||||
private static final String NAME_REPLACEMENT_ATTR = "__FlociSchedulerNameReplacement";
|
||||
private static final String SNAPSHOT_ATTR = "__FlociSchedulerUpdateSnapshot";
|
||||
private static final ObjectMapper MAPPER = JsonMapper.builder()
|
||||
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
|
||||
.addModule(new JavaTimeModule())
|
||||
.build();
|
||||
|
||||
private final SchedulerService schedulerService;
|
||||
|
||||
@Inject
|
||||
public SchedulerScheduleCfnProvisioner(SchedulerService schedulerService) {
|
||||
this.schedulerService = schedulerService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
|
||||
readCleanup(resource);
|
||||
if (ctx.isUpdate() && resource.getAttributes().containsKey(SNAPSHOT_ATTR)) {
|
||||
try {
|
||||
rollbackUpdate(resource);
|
||||
ctx = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(), ctx.stackName(),
|
||||
resource.getPhysicalId(), ctx.progress(), ctx.priorProperties());
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
|
||||
} catch (RuntimeException failure) {
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, failure.getMessage());
|
||||
throw new IllegalStateException("Could not finish the previous schedule update rollback", failure);
|
||||
}
|
||||
}
|
||||
Map<String, String> attributesBefore = Map.copyOf(resource.getAttributes());
|
||||
String explicitName = optional(props, "Name", ctx);
|
||||
if (explicitName != null && explicitName.isBlank()) {
|
||||
throw validation("Name must not be blank");
|
||||
}
|
||||
boolean named = explicitName != null && !explicitName.isBlank();
|
||||
boolean removedName = ctx.isUpdate() && !named
|
||||
&& "explicit".equals(attributesBefore.get(NAME_MODE_ATTR));
|
||||
String name = removedName ? ctx.generatePhysicalName(resource.getLogicalId(), 64, false)
|
||||
: ctx.stablePhysicalName(explicitName, resource.getLogicalId(), 64, false);
|
||||
String explicitGroup = optional(props, "GroupName", ctx);
|
||||
if (explicitGroup != null && explicitGroup.isBlank()) {
|
||||
throw validation("GroupName must not be blank");
|
||||
}
|
||||
String group = explicitGroup == null ? "default" : explicitGroup;
|
||||
ScheduleRequest request = request(props, name, group, ctx);
|
||||
String priorGroup = attributesBefore.getOrDefault(GROUP_ATTR, "default");
|
||||
boolean sameAddress = ctx.reusesPriorEntity(name) && priorGroup.equals(group);
|
||||
boolean groupMove = ctx.reusesPriorEntity(name) && !priorGroup.equals(group);
|
||||
|
||||
Schedule schedule;
|
||||
ObjectNode moveSnapshot = null;
|
||||
if (sameAddress) {
|
||||
Schedule current = schedulerService.getSchedule(name, group, ctx.region());
|
||||
snapshot(resource, current, ctx.region(), null, null);
|
||||
try {
|
||||
schedule = schedulerService.updateSchedule(request, ctx.region());
|
||||
} catch (RuntimeException failure) {
|
||||
restoreAfterFailure(resource, failure);
|
||||
throw failure;
|
||||
}
|
||||
} else if (groupMove) {
|
||||
Schedule current = schedulerService.getSchedule(name, priorGroup, ctx.region());
|
||||
moveSnapshot = snapshot(resource, current, ctx.region(), name, group);
|
||||
ScheduleRequest paused = requestFrom(current);
|
||||
paused.setState("DISABLED");
|
||||
try {
|
||||
// Keep a moving schedule from firing at both addresses while the stack update
|
||||
// waits for its other resources. The original is restored if creation fails.
|
||||
schedulerService.updateSchedule(paused, ctx.region());
|
||||
schedule = schedulerService.createSchedule(request, ctx.region());
|
||||
} catch (RuntimeException failure) {
|
||||
restoreAfterFailure(resource, failure);
|
||||
throw failure;
|
||||
}
|
||||
} else {
|
||||
schedule = schedulerService.createSchedule(request, ctx.region());
|
||||
}
|
||||
if (!sameAddress) {
|
||||
retireDisplaced(resource, address(schedule.getGroupName(), schedule.getName()));
|
||||
}
|
||||
resource.setPhysicalId(schedule.getName());
|
||||
resource.getAttributes().put("Arn", schedule.getArn());
|
||||
resource.getAttributes().put(GROUP_ATTR, schedule.getGroupName());
|
||||
resource.getAttributes().put(NAME_MODE_ATTR, named ? "explicit" : "generated");
|
||||
resource.getAttributes().put(NAME_REPLACEMENT_ATTR,
|
||||
Boolean.toString(ctx.isUpdate() && !ctx.priorPhysicalId().equals(name)));
|
||||
|
||||
// Ref is the name, but deletion needs both name and group. The cleanup helper's private
|
||||
// identity includes the group so a group move with an unchanged Ref is still tracked.
|
||||
ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(),
|
||||
ctx.stackName(), ctx.isUpdate() ? address(priorGroup, ctx.priorPhysicalId()) : null, ctx.progress(),
|
||||
ctx.priorProperties());
|
||||
ReplacementCleanup.record(cleanupResource(resource), cleanupContext, attributesBefore);
|
||||
if (moveSnapshot != null) {
|
||||
moveSnapshot.put("destinationCreated", true);
|
||||
resource.getAttributes().put(SNAPSHOT_ATTR, moveSnapshot.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectNode snapshot(StackResource resource, Schedule current, String region,
|
||||
String destinationName, String destinationGroup) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode().put("region", region);
|
||||
snapshot.set("request", MAPPER.valueToTree(requestFrom(current)));
|
||||
if (destinationName != null) {
|
||||
snapshot.put("destinationName", destinationName);
|
||||
snapshot.put("destinationGroup", destinationGroup);
|
||||
snapshot.put("destinationCreated", false);
|
||||
}
|
||||
resource.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString());
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static ScheduleRequest request(JsonNode props, String name, String group, ProvisionContext ctx) {
|
||||
ScheduleRequest request = new ScheduleRequest();
|
||||
request.setName(name);
|
||||
request.setGroupName(group);
|
||||
String expression = optional(props, "ScheduleExpression", ctx);
|
||||
if (expression == null || expression.isBlank()) {
|
||||
throw validation("requires ScheduleExpression");
|
||||
}
|
||||
request.setScheduleExpression(expression);
|
||||
request.setFlexibleTimeWindow(requiredObject(props, "FlexibleTimeWindow", FlexibleTimeWindow.class, ctx));
|
||||
request.setTarget(requiredObject(props, "Target", Target.class, ctx));
|
||||
request.setDescription(optional(props, "Description", ctx));
|
||||
request.setScheduleExpressionTimezone(optional(props, "ScheduleExpressionTimezone", ctx));
|
||||
String state = optional(props, "State", ctx);
|
||||
if (state != null && !Set.of("ENABLED", "DISABLED").contains(state)) {
|
||||
throw validation("State must be ENABLED or DISABLED");
|
||||
}
|
||||
request.setState(state);
|
||||
request.setKmsKeyArn(optional(props, "KmsKeyArn", ctx));
|
||||
request.setStartDate(date(props, "StartDate", ctx));
|
||||
request.setEndDate(date(props, "EndDate", ctx));
|
||||
return request;
|
||||
}
|
||||
|
||||
private static <T> T requiredObject(JsonNode props, String property, Class<T> type, ProvisionContext ctx) {
|
||||
JsonNode resolved = props == null ? null : ctx.engine().resolveNodeOmittingNoValue(props.get(property));
|
||||
if (resolved == null || !resolved.isObject()) {
|
||||
throw validation("requires an object for " + property);
|
||||
}
|
||||
try {
|
||||
return MAPPER.treeToValue(resolved, type);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw validation("has invalid or unsupported " + property + " properties: " + e.getOriginalMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static String optional(JsonNode props, String property, ProvisionContext ctx) {
|
||||
JsonNode resolved = props == null ? null : ctx.engine().resolveNodeOmittingNoValue(props.get(property));
|
||||
if (resolved == null || resolved.isNull() || resolved.isMissingNode()) {
|
||||
return null;
|
||||
}
|
||||
if (!resolved.isValueNode()) {
|
||||
throw validation("requires a scalar for " + property);
|
||||
}
|
||||
return resolved.asText();
|
||||
}
|
||||
|
||||
private static Instant date(JsonNode props, String property, ProvisionContext ctx) {
|
||||
String value = optional(props, property, ctx);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Instant.parse(value);
|
||||
} catch (DateTimeParseException e) {
|
||||
throw validation(property + " must be a UTC date-time");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationError", TYPE + " " + message, 400);
|
||||
}
|
||||
|
||||
private static ScheduleRequest requestFrom(Schedule schedule) {
|
||||
ScheduleRequest request = new ScheduleRequest();
|
||||
request.setName(schedule.getName());
|
||||
request.setGroupName(schedule.getGroupName());
|
||||
request.setScheduleExpression(schedule.getScheduleExpression());
|
||||
request.setScheduleExpressionTimezone(schedule.getScheduleExpressionTimezone());
|
||||
request.setFlexibleTimeWindow(schedule.getFlexibleTimeWindow());
|
||||
request.setTarget(schedule.getTarget());
|
||||
request.setDescription(schedule.getDescription());
|
||||
request.setState(schedule.getState());
|
||||
request.setActionAfterCompletion(schedule.getActionAfterCompletion());
|
||||
request.setKmsKeyArn(schedule.getKmsKeyArn());
|
||||
request.setStartDate(schedule.getStartDate());
|
||||
request.setEndDate(schedule.getEndDate());
|
||||
return request;
|
||||
}
|
||||
|
||||
private void restoreAfterFailure(StackResource resource, RuntimeException failure) {
|
||||
try {
|
||||
rollbackUpdate(resource);
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
|
||||
} catch (RuntimeException restoreFailure) {
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, restoreFailure.getMessage());
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
deleteAddress(address(resource.getAttributes().getOrDefault(GROUP_ATTR, "default"),
|
||||
resource.getPhysicalId()), region);
|
||||
UpdateCleanupResult result = ReplacementCleanup.complete(cleanupResource(resource),
|
||||
(type, id, cleanupRegion) -> deleteAddress(id, cleanupRegion));
|
||||
if (result.applicable() && !result.complete()) {
|
||||
throw new IllegalStateException(result.failureReason());
|
||||
}
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
private void deleteAddress(String physicalId, String region) {
|
||||
int separator = physicalId.indexOf('/');
|
||||
String group = physicalId.substring(0, separator);
|
||||
String name = physicalId.substring(separator + 1);
|
||||
CfnDeletes.safeDelete("Scheduler schedule", physicalId,
|
||||
() -> schedulerService.deleteSchedule(name, group, region), "ResourceNotFoundException");
|
||||
}
|
||||
|
||||
private static String address(String group, String name) {
|
||||
return group + "/" + name;
|
||||
}
|
||||
|
||||
private static StackResource cleanupResource(StackResource resource) {
|
||||
StackResource cleanup = new StackResource();
|
||||
cleanup.setLogicalId(resource.getLogicalId());
|
||||
cleanup.setResourceType(resource.getResourceType());
|
||||
cleanup.setPhysicalId(address(resource.getAttributes().getOrDefault(GROUP_ATTR, "default"),
|
||||
resource.getPhysicalId()));
|
||||
cleanup.setAttributes(resource.getAttributes());
|
||||
// GroupName is mutable on CloudFormation. Retain applies to a name replacement only,
|
||||
// otherwise a group move would leave the old schedule firing indefinitely.
|
||||
if (Boolean.parseBoolean(resource.getAttributes().get(NAME_REPLACEMENT_ATTR))) {
|
||||
cleanup.setUpdateReplacePolicy(resource.getUpdateReplacePolicy());
|
||||
}
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(cleanupResource(resource));
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
if ("UPDATE_FAILED".equals(resource.getStatus()) && retainsFailedUpdateState(resource)) {
|
||||
throw new IllegalStateException("Schedule rollback is still pending; its original configuration "
|
||||
+ "cannot be discarded by another resource's update cleanup");
|
||||
}
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
UpdateCleanupResult result = ReplacementCleanup.complete(cleanupResource(resource),
|
||||
(type, id, region) -> deleteAddress(id, region));
|
||||
if (!result.applicable() || result.complete()) {
|
||||
resource.getAttributes().remove(NAME_REPLACEMENT_ATTR);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
|
||||
UpdateCleanupResult result = ReplacementCleanup.complete(cleanupResource(resource),
|
||||
(type, id, region) -> deleteAddress(id, region));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDeleteCleanup(StackResource resource) {
|
||||
ReplacementCleanup.clear(resource);
|
||||
if (!ReplacementCleanup.hasReplacement(resource)) {
|
||||
resource.getAttributes().remove(NAME_REPLACEMENT_ATTR);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
resource.getAttributes().remove(NAME_REPLACEMENT_ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
|
||||
ObjectNode source = readCleanup(attempted);
|
||||
if (source != null) {
|
||||
String currentAddress = cleanupResource(previous).getPhysicalId();
|
||||
for (JsonNode entry : source.path("displaced")) {
|
||||
String physicalId = entry.path("physicalId").asText();
|
||||
if (physicalId.equals(currentAddress)) {
|
||||
continue;
|
||||
}
|
||||
// The attempted update can recreate an address whose earlier cleanup was exhausted.
|
||||
// Preserve that attempt's current retry record when the engine restores the old resource.
|
||||
retireDisplaced(previous, physicalId);
|
||||
}
|
||||
}
|
||||
ReplacementCleanup.mergeDisplaced(cleanupResource(previous), cleanupResource(attempted));
|
||||
}
|
||||
|
||||
private static ObjectNode readCleanup(StackResource resource) {
|
||||
String raw = resource.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode node = MAPPER.readTree(raw);
|
||||
if (!node.isObject() || (node.has("displaced") && !node.path("displaced").isArray())) {
|
||||
throw new IllegalStateException("Invalid schedule replacement cleanup");
|
||||
}
|
||||
for (JsonNode entry : node.path("displaced")) {
|
||||
if (!entry.isObject()) {
|
||||
throw new IllegalStateException("Invalid schedule replacement cleanup");
|
||||
}
|
||||
}
|
||||
return (ObjectNode) node;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Could not read schedule replacement cleanup", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void retireDisplaced(StackResource resource, String physicalId) {
|
||||
ObjectNode cleanup = readCleanup(resource);
|
||||
if (cleanup == null) {
|
||||
return;
|
||||
}
|
||||
ArrayNode remaining = MAPPER.createArrayNode();
|
||||
for (JsonNode entry : cleanup.path("displaced")) {
|
||||
if (!physicalId.equals(entry.path("physicalId").asText())) {
|
||||
remaining.add(entry);
|
||||
}
|
||||
}
|
||||
cleanup.set("displaced", remaining);
|
||||
if (remaining.isEmpty() && !cleanup.has("priorPhysicalId")) {
|
||||
resource.getAttributes().remove(CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
} else {
|
||||
resource.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, cleanup.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
JsonNode snapshot = readSnapshot(resource);
|
||||
if (snapshot != null && snapshot.path("destinationCreated").asBoolean(false)) {
|
||||
// Disable the move's destination before restoring an enabled original, even if deleting
|
||||
// the destination fails. The cleanup helper retains that disabled orphan's address.
|
||||
pauseDestination(snapshot);
|
||||
}
|
||||
StackResource cleanup = cleanupResource(resource);
|
||||
RuntimeException cleanupFailure = null;
|
||||
try {
|
||||
ReplacementCleanup.rollback(cleanup, (type, id, region) -> deleteAddress(id, region));
|
||||
} catch (RuntimeException failure) {
|
||||
cleanupFailure = failure;
|
||||
} finally {
|
||||
String restoredAddress = cleanup.getPhysicalId();
|
||||
resource.setPhysicalId(restoredAddress.substring(restoredAddress.indexOf('/') + 1));
|
||||
}
|
||||
if (snapshot != null) {
|
||||
try {
|
||||
ScheduleRequest request = MAPPER.treeToValue(snapshot.get("request"), ScheduleRequest.class);
|
||||
schedulerService.updateSchedule(request, snapshot.path("region").asText());
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
} catch (JsonProcessingException | RuntimeException restoreFailure) {
|
||||
if (cleanupFailure != null && cleanupFailure != restoreFailure) {
|
||||
restoreFailure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
throw new IllegalStateException("Could not restore schedule update snapshot", restoreFailure);
|
||||
}
|
||||
}
|
||||
if (cleanupFailure != null) {
|
||||
throw cleanupFailure;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return resource.getAttributes().containsKey(SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
private static JsonNode readSnapshot(StackResource resource) {
|
||||
String raw = resource.getAttributes().get(SNAPSHOT_ATTR);
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readTree(raw);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Could not read schedule update snapshot", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void pauseDestination(JsonNode snapshot) {
|
||||
String name = snapshot.path("destinationName").asText();
|
||||
String group = snapshot.path("destinationGroup").asText();
|
||||
String region = snapshot.path("region").asText();
|
||||
try {
|
||||
ScheduleRequest request = requestFrom(schedulerService.getSchedule(name, group, region));
|
||||
request.setState("DISABLED");
|
||||
schedulerService.updateSchedule(request, region);
|
||||
} catch (AwsException e) {
|
||||
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Schedule move destination {0}/{1} already gone during rollback", group, name);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+2
@@ -97,6 +97,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftC
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftServerlessCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleGroupCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretTargetAttachmentCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretsManagerCfnProvisioner;
|
||||
@@ -463,6 +464,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (schedulerService != null) {
|
||||
discovered.add(new SchedulerScheduleGroupCfnProvisioner(schedulerService));
|
||||
discovered.add(new SchedulerScheduleCfnProvisioner(schedulerService));
|
||||
}
|
||||
if (transferService != null) {
|
||||
discovered.add(new TransferCfnProvisioner(transferService));
|
||||
|
||||
+10
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudForm
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -61,6 +62,15 @@ class CfnProvisionerFixtureTest {
|
||||
assertTrue(serves(fixture, "AWS::Logs::LogGroup"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulerWiresBothSchedulesAndGroups() {
|
||||
CfnProvisionerFixture.Builder fixture = CfnProvisionerFixture.builder()
|
||||
.scheduler(mock(SchedulerService.class));
|
||||
|
||||
assertTrue(serves(fixture, "AWS::Scheduler::Schedule"));
|
||||
assertTrue(serves(fixture, "AWS::Scheduler::ScheduleGroup"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedServiceIsNotWired() {
|
||||
CfnProvisionerFixture.Builder fixture = CfnProvisionerFixture.builder()
|
||||
|
||||
+1090
File diff suppressed because it is too large.
Load diff
+21
@@ -190,6 +190,27 @@ class ReplacementCleanupTest {
|
||||
assertFalse(ReplacementCleanup.hasReplacement(previous));
|
||||
}
|
||||
|
||||
@Test
|
||||
void committedUpdateStillStopsAfterThreeFailuresAndAbandonsTheExhaustedEntity() {
|
||||
StackResource r = resource("subnet-prior");
|
||||
List<String> attempted = new ArrayList<>();
|
||||
ReplacementCleanup.recordOrphan(r, "subnet-replacement", r.getResourceType(), "us-east-1");
|
||||
ReplacementCleanup.Deleter unavailable = (type, id, region) -> {
|
||||
attempted.add(id);
|
||||
throw new IllegalStateException("still in use");
|
||||
};
|
||||
|
||||
for (int attempt = 1; attempt <= 4; attempt++) {
|
||||
UpdateCleanupResult result = ReplacementCleanup.complete(r, unavailable);
|
||||
assertFalse(result.complete());
|
||||
assertEquals(Math.min(attempt, 3), result.attempts());
|
||||
}
|
||||
assertEquals(3, attempted.size());
|
||||
ReplacementCleanup.clear(r);
|
||||
assertFalse(ReplacementCleanup.hasReplacement(r));
|
||||
assertFalse(ReplacementCleanup.complete(r, unavailable).applicable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergingNothingLeavesTheTargetUntouched() {
|
||||
StackResource previous = resource("subnet-prior");
|
||||
|
||||
+1048
File diff suppressed because it is too large.
Load diff
+100
@@ -0,0 +1,100 @@
|
||||
package io.github.hectorvent.floci.services.scheduler;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.FlexibleTimeWindow;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.Schedule;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.ScheduleRequest;
|
||||
import io.github.hectorvent.floci.services.scheduler.model.Target;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class SchedulerAddressTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void updateAndDeleteAddressTheRecreatedSchedule() throws Exception {
|
||||
SchedulerService service = service(new InMemoryStorage<>());
|
||||
Schedule original = service.createSchedule(request("schedule", "default", "first"), REGION);
|
||||
service.deleteSchedule("schedule", "default", REGION);
|
||||
Schedule recreated = service.createSchedule(request("schedule", "default", "external"), REGION);
|
||||
assertEquals(original.getArn(), recreated.getArn());
|
||||
|
||||
Schedule updated = service.updateSchedule(request("schedule", "default", "template"), REGION);
|
||||
|
||||
assertEquals(recreated.getArn(), updated.getArn());
|
||||
assertEquals(recreated.getCreationDate(), updated.getCreationDate());
|
||||
assertEquals("template", service.getSchedule("schedule", "default", REGION).getTarget().getInput());
|
||||
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
Schedule restored = mapper.readValue(mapper.writeValueAsString(updated), Schedule.class);
|
||||
assertEquals(updated.getArn(), restored.getArn());
|
||||
assertEquals(updated.getCreationDate(), restored.getCreationDate());
|
||||
assertEquals("template", restored.getTarget().getInput());
|
||||
service.deleteSchedule("schedule", "default", REGION);
|
||||
AwsException missing = assertThrows(AwsException.class, () -> service.getSchedule("schedule", "default", REGION));
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameNameInAnotherGroupIsUnaffectedByUpdateAndDeletion() {
|
||||
SchedulerService service = service(new InMemoryStorage<>());
|
||||
service.createScheduleGroup("other", Map.of(), REGION);
|
||||
service.createSchedule(request("same", "default", "default"), REGION);
|
||||
service.createSchedule(request("same", "other", "other"), REGION);
|
||||
|
||||
service.updateSchedule(request("same", "default", "changed"), REGION);
|
||||
service.deleteSchedule("same", "default", REGION);
|
||||
|
||||
assertEquals("other", service.getSchedule("same", "other", REGION).getTarget().getInput());
|
||||
service.deleteSchedule("same", "other", REGION);
|
||||
assertThrows(AwsException.class, () -> service.getSchedule("same", "other", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPersistedScheduleCanBeUpdatedAndDeletedByItsAddress() throws Exception {
|
||||
InMemoryStorage<String, Schedule> store = new InMemoryStorage<>();
|
||||
Schedule persisted = new ObjectMapper().readValue("""
|
||||
{"name":"persisted","groupName":"default","state":"DISABLED",
|
||||
"arn":"arn:aws:scheduler:us-east-1:000000000000:schedule/default/persisted"}
|
||||
""", Schedule.class);
|
||||
store.put("schedule:" + REGION + ":default:persisted", persisted);
|
||||
SchedulerService service = service(store);
|
||||
|
||||
Schedule updated = service.updateSchedule(request("persisted", "default", "updated"), REGION);
|
||||
|
||||
assertEquals(persisted.getArn(), updated.getArn());
|
||||
assertEquals("updated", service.getSchedule("persisted", "default", REGION).getTarget().getInput());
|
||||
service.deleteSchedule("persisted", "default", REGION);
|
||||
assertThrows(AwsException.class, () -> service.getSchedule("persisted", "default", REGION));
|
||||
}
|
||||
|
||||
private static SchedulerService service(InMemoryStorage<String, Schedule> store) {
|
||||
return new SchedulerService(new InMemoryStorage<>(), store,
|
||||
new RegionResolver(REGION, "000000000000"));
|
||||
}
|
||||
|
||||
private static ScheduleRequest request(String name, String group, String input) {
|
||||
ScheduleRequest request = new ScheduleRequest();
|
||||
request.setName(name);
|
||||
request.setGroupName(group);
|
||||
request.setScheduleExpression("rate(5 minutes)");
|
||||
request.setState("DISABLED");
|
||||
FlexibleTimeWindow window = new FlexibleTimeWindow();
|
||||
window.setMode("OFF");
|
||||
request.setFlexibleTimeWindow(window);
|
||||
Target target = new Target();
|
||||
target.setArn("arn:aws:sqs:us-east-1:000000000000:queue");
|
||||
target.setRoleArn("arn:aws:iam::000000000000:role/scheduler");
|
||||
target.setInput(input);
|
||||
request.setTarget(target);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,7 @@ AWS::SNS::TopicPolicy SnsCfnProvisioner
|
||||
AWS::SQS::Queue SqsCfnProvisioner
|
||||
AWS::SQS::QueuePolicy SqsCfnProvisioner
|
||||
AWS::SSM::Parameter SsmCfnProvisioner
|
||||
AWS::Scheduler::Schedule SchedulerScheduleCfnProvisioner
|
||||
AWS::Scheduler::ScheduleGroup SchedulerScheduleGroupCfnProvisioner
|
||||
AWS::SecretsManager::Secret SecretsManagerCfnProvisioner
|
||||
AWS::SecretsManager::SecretTargetAttachment SecretTargetAttachmentCfnProvisioner
|
||||
|
||||
|
Reference in new issue
Block a user