mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
fix(cloudformation): keep tags added outside the stack on EC2 VPCs, security groups and instances (#7534)
This commit is contained in:
1 parent
b35e51374c
commit
cfbf86b8a1
11 files changed
+428
-160
No files matched your search
+15
-76
@@ -1,9 +1,7 @@
|
||||
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.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
@@ -13,8 +11,6 @@ import io.github.hectorvent.floci.services.ec2.model.FlowLog;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -41,11 +37,7 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SNAPSHOT_ATTR = CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR;
|
||||
|
||||
/**
|
||||
* The tag keys the last deployment resolved and wrote, as a JSON array: the keys the stack owns.
|
||||
* Recorded rather than re-resolved from the previous template, because a key taken from a
|
||||
* parameter resolves to the new value on the next update.
|
||||
*/
|
||||
/** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */
|
||||
static final String TAG_KEYS_ATTR = "__FlociEc2FlowLogTagKeys";
|
||||
|
||||
private final FlowLogService flowLogService;
|
||||
@@ -86,12 +78,12 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner {
|
||||
requireUnchanged(existing, props, ctx);
|
||||
r.getAttributes().put("Id", existingId);
|
||||
// Only the keys the last deployment wrote are the stack's to remove.
|
||||
Set<String> owned = ownedTagKeys(r, ctx);
|
||||
Set<String> owned = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx);
|
||||
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {
|
||||
snapshotTags(r, region, existingId, owned, desiredTags, priorTagKeys);
|
||||
Ec2Tags.reconcileOwned(ec2Service, region, existingId, owned, desiredTags);
|
||||
});
|
||||
recordTagKeys(r, desiredTags);
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -111,8 +103,8 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("Id", flowLogId);
|
||||
// A tag write that still fails deletes the new log rather than leaving it outside the stack.
|
||||
CfnRollback.guarded(r, ctx, true, () -> flowLogService.deleteFlowLogs(region, List.of(flowLogId)),
|
||||
() -> { }, () -> Ec2Tags.reconcile(ec2Service, region, flowLogId, desiredTags));
|
||||
recordTagKeys(r, desiredTags);
|
||||
() -> { }, () -> Ec2Tags.reconcileOwned(ec2Service, region, flowLogId, Set.of(), desiredTags));
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags);
|
||||
if (ctx.isUpdate()) {
|
||||
// The stack's log was removed outside it, so a rollback deletes this one and names the
|
||||
// prior id again rather than keeping the failed update's log.
|
||||
@@ -143,95 +135,42 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner {
|
||||
JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR);
|
||||
if (snapshot != null && CfnRollback.undoCreatedByUpdate(resource, snapshot, SNAPSHOT_ATTR, "Id",
|
||||
(id, region) -> flowLogService.deleteFlowLogs(region, List.of(id)))) {
|
||||
restoreTagKeys(resource, snapshot);
|
||||
Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, snapshot);
|
||||
return true;
|
||||
}
|
||||
undoInPlace(resource);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Puts back the ownership record the snapshot carries, or its absence. */
|
||||
private static void restoreTagKeys(StackResource r, JsonNode snapshot) {
|
||||
String tagKeys = CfnRollback.snapshotText(snapshot, "tagKeys");
|
||||
if (tagKeys == null) {
|
||||
r.getAttributes().remove(TAG_KEYS_ATTR);
|
||||
} else {
|
||||
r.getAttributes().put(TAG_KEYS_ATTR, tagKeys);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys the last deployment recorded in {@link #TAG_KEYS_ATTR}. A log provisioned before
|
||||
* that was recorded falls back to the previous template's keys, resolved as well as they still
|
||||
* can be.
|
||||
*/
|
||||
private Set<String> ownedTagKeys(StackResource r, ProvisionContext ctx) {
|
||||
String recorded = r.getAttributes().get(TAG_KEYS_ATTR);
|
||||
if (recorded == null) {
|
||||
return ctx.resolveTags(ctx.priorProperties(), "Tags").keySet();
|
||||
}
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
try {
|
||||
MAPPER.readTree(recorded).forEach(key -> keys.add(key.asText()));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Unreadable tag keys on " + r.getLogicalId(), e);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static void recordTagKeys(StackResource r, Map<String, String> desiredTags) {
|
||||
ArrayNode keys = MAPPER.createArrayNode();
|
||||
desiredTags.keySet().forEach(keys::add);
|
||||
r.getAttributes().put(TAG_KEYS_ATTR, keys.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the values the touched keys (the owned ones and the declared ones) had before the
|
||||
* update changes them, with the ownership record it replaces, only when a value or the owned
|
||||
* key set is about to change, so an unchanged reuse leaves no snapshot. Tags outside that set
|
||||
* are never written, so they are not recorded either.
|
||||
* Records what the update is about to change on a reused log, only when a value or the owned key
|
||||
* set changes, so an unchanged reuse leaves no snapshot.
|
||||
*/
|
||||
private void snapshotTags(StackResource r, String region, String flowLogId, Set<String> owned,
|
||||
Map<String, String> desiredTags, String priorTagKeys) {
|
||||
Map<String, String> currentTags = Ec2Tags.current(ec2Service, region, flowLogId);
|
||||
Set<String> touched = new LinkedHashSet<>(owned);
|
||||
touched.addAll(desiredTags.keySet());
|
||||
// A change of ownership alone (taking over a key that already holds the declared value)
|
||||
// still needs the record put back, so it counts as a change too.
|
||||
boolean changes = !owned.equals(desiredTags.keySet())
|
||||
|| touched.stream().anyMatch(key -> desiredTags.containsKey(key)
|
||||
? !desiredTags.get(key).equals(currentTags.get(key))
|
||||
: currentTags.containsKey(key));
|
||||
if (!changes) {
|
||||
if (!Ec2Tags.changesOwned(owned, desiredTags, currentTags)) {
|
||||
return;
|
||||
}
|
||||
ObjectNode prior = MAPPER.createObjectNode();
|
||||
prior.put("region", region);
|
||||
prior.put("flowLogId", flowLogId);
|
||||
prior.put("tagKeys", priorTagKeys);
|
||||
touched.forEach(prior.putArray("touched")::add);
|
||||
ObjectNode tags = prior.putObject("tags");
|
||||
touched.stream().filter(currentTags::containsKey).forEach(key -> tags.put(key, currentTags.get(key)));
|
||||
Ec2Tags.snapshotOwned(prior, owned, desiredTags, currentTags, priorTagKeys);
|
||||
r.getAttributes().put(SNAPSHOT_ATTR, prior.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the touched keys of a reused log back from the snapshot: a key it had gets its value
|
||||
* again, and a key the update added is removed. The ownership record goes back too. The snapshot is removed only after the restore
|
||||
* succeeds, so a failed one keeps it for the rollback walker's retry.
|
||||
* Puts the touched keys of a reused log and its ownership record back from the snapshot. The
|
||||
* snapshot is removed only after the restore succeeds, so a failed one keeps it for the rollback
|
||||
* walker's retry.
|
||||
*/
|
||||
private void undoInPlace(StackResource r) {
|
||||
JsonNode prior = CfnRollback.updateSnapshot(r, SNAPSHOT_ATTR);
|
||||
if (prior == null) {
|
||||
return;
|
||||
}
|
||||
Set<String> touched = new LinkedHashSet<>();
|
||||
prior.path("touched").forEach(key -> touched.add(key.asText()));
|
||||
Map<String, String> priorTags = new LinkedHashMap<>();
|
||||
prior.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), f.getValue().asText()));
|
||||
Ec2Tags.reconcileOwned(ec2Service, prior.path("region").asText(), prior.path("flowLogId").asText(),
|
||||
touched, priorTags);
|
||||
restoreTagKeys(r, prior);
|
||||
Ec2Tags.restoreOwned(ec2Service, prior.path("region").asText(), prior.path("flowLogId").asText(), r,
|
||||
TAG_KEYS_ATTR, prior);
|
||||
r.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -50,6 +50,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
// The MetadataOptions members declared last time, the instance's own or its launch template's, so
|
||||
// an update can return the ones it no longer declares to their launch defaults.
|
||||
private static final String DECLARED_METADATA_OPTIONS_ATTR = "__FlociDeclaredMetadataOptions";
|
||||
// The tag keys the last deployment wrote, as Ec2Tags.recordKeys records them, so an update
|
||||
// removes only those and keeps a tag added outside the stack.
|
||||
static final String DECLARED_TAG_KEYS_ATTR = "__FlociDeclaredTagKeys";
|
||||
// The __FlociDeclared records as they stood before a replacing update, for rollbackUpdate to put
|
||||
// back with the instance it restores; ReplacementCleanup leaves __Floci attributes alone.
|
||||
private static final String PRIOR_DECLARATIONS_ATTR = "__FlociPriorDeclarations";
|
||||
@@ -155,7 +158,8 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
&& Ec2CfnMetadataOptions.changes(optionsBefore, metadataOptionsToApply);
|
||||
boolean otherChange = reconcileMutableProperties(region, prior, instanceType, securityGroupIds,
|
||||
userData, iamInstanceProfileArn, attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
|
||||
boolean tagsChanged = Ec2Tags.reconcile(ec2Service, region, prior.getInstanceId(), desiredTags);
|
||||
boolean tagsChanged = Ec2Tags.reconcileOwned(ec2Service, region, prior.getInstanceId(),
|
||||
Ec2Tags.ownedKeys(r, DECLARED_TAG_KEYS_ATTR, ctx), desiredTags);
|
||||
// Saved on every update that keeps the instance, also one that changes no EC2 setting but
|
||||
// only what is declared, so a rollback can always put the declarations back.
|
||||
r.getAttributes().put(PRIOR_IN_PLACE_ATTR, priorInPlaceUpdate(region,
|
||||
@@ -173,6 +177,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
|
||||
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
|
||||
putOrRemove(r, DECLARED_METADATA_OPTIONS_ATTR, Ec2CfnMetadataOptions.declaredMembers(metadataOptions));
|
||||
Ec2Tags.recordKeys(r, DECLARED_TAG_KEYS_ATTR, desiredTags);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
return;
|
||||
}
|
||||
@@ -216,6 +221,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
|
||||
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
|
||||
putOrRemove(r, DECLARED_METADATA_OPTIONS_ATTR, Ec2CfnMetadataOptions.declaredMembers(metadataOptions));
|
||||
Ec2Tags.recordKeys(r, DECLARED_TAG_KEYS_ATTR, desiredTags);
|
||||
// A createOnly change that landed a new instance id replaced the prior one: record it so
|
||||
// the stack cleans the displaced instance up after the update commits.
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
|
||||
+7
-6
@@ -47,6 +47,8 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
|
||||
// standalone SecurityGroupIngress/Egress resource owns.
|
||||
static final String INGRESS_RULES_ATTR = "__FlociSgIngressRules";
|
||||
static final String EGRESS_RULES_ATTR = "__FlociSgEgressRules";
|
||||
/** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */
|
||||
static final String TAG_KEYS_ATTR = "__FlociSgTagKeys";
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
@@ -110,7 +112,11 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
|
||||
EGRESS_RULES_ATTR,
|
||||
perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms),
|
||||
perms -> ec2Service.revokeSecurityGroupEgress(region, sg.getGroupId(), perms));
|
||||
Ec2Tags.reconcile(ec2Service, region, sg.getGroupId(), desiredTags);
|
||||
// AWS updates Tags in place and keeps a tag added outside the stack, so a reused group has
|
||||
// only the keys the last deployment wrote removed; a new group carries no tags yet.
|
||||
Set<String> ownedTags = reconciled != null ? Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx) : Set.of();
|
||||
Ec2Tags.reconcileOwned(ec2Service, region, sg.getGroupId(), ownedTags, desiredTags);
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -177,11 +183,6 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
|
||||
return new LinkedHashSet<>(Arrays.asList(stored.split("\n", -1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconciles the group's tags to the template on create and update: adds or overwrites the
|
||||
* declared tags and removes any the template dropped. AWS treats SecurityGroup Tags as an
|
||||
* in-place (no interruption) update.
|
||||
*/
|
||||
/**
|
||||
* Resolves a peer group's name to its id, the same lookup {@code Ec2Service} performs when it
|
||||
* stores an authorized rule. Group names are unique per VPC rather than per region, so the
|
||||
|
||||
+112
-33
@@ -1,23 +1,33 @@
|
||||
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.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner},
|
||||
* {@code Ec2SecurityGroupCfnProvisioner}, {@code Ec2VpcCfnProvisioner} and
|
||||
* {@code Ec2FlowLogCfnProvisioner}). They drive it from the desired tags resolved via
|
||||
* {@link ProvisionContext#resolveTags}; the reconcile itself is identical.
|
||||
* {@link ProvisionContext#resolveTags}; the reconcile itself is identical: an update changes only
|
||||
* the keys the stack owns, recorded by {@link #recordKeys}, and keeps a tag added outside the stack,
|
||||
* as AWS does.
|
||||
*/
|
||||
final class Ec2Tags {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private Ec2Tags() {
|
||||
}
|
||||
|
||||
@@ -30,8 +40,8 @@ final class Ec2Tags {
|
||||
|
||||
/**
|
||||
* The user tags EC2 currently holds for the resource, keyed by tag key in DescribeTags order.
|
||||
* Reserved {@code aws:} keys are never part of the user tag set, so neither {@link #reconcile}
|
||||
* nor a rollback snapshot taken from this map can try to write one.
|
||||
* Reserved {@code aws:} keys are never part of the user tag set, so neither
|
||||
* {@link #reconcileOwned} nor a rollback snapshot taken from this map can try to write one.
|
||||
*/
|
||||
static Map<String, String> current(Ec2Service ec2Service, String region, String resourceId) {
|
||||
Map<String, String> current = new LinkedHashMap<>();
|
||||
@@ -43,42 +53,18 @@ final class Ec2Tags {
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a resource's tags to {@code desired}: removes the keys AWS currently has that the
|
||||
* template no longer declares, then creates or overwrites the declared ones. Returns whether the
|
||||
* tags were anything other than {@code desired} before.
|
||||
*/
|
||||
static boolean reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
|
||||
List<Tag> add = validatedTags(desired);
|
||||
Map<String, String> current = current(ec2Service, region, resourceId);
|
||||
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
|
||||
boolean changed = !stale.isEmpty();
|
||||
for (Tag tag : add) {
|
||||
changed |= !current.containsKey(tag.getKey()) || !Objects.equals(tag.getValue(), current.get(tag.getKey()));
|
||||
}
|
||||
if (!stale.isEmpty()) {
|
||||
List<Tag> remove = new ArrayList<>();
|
||||
for (String key : stale) {
|
||||
remove.add(new Tag(key, current.get(key)));
|
||||
}
|
||||
ec2Service.deleteTags(region, List.of(resourceId), remove);
|
||||
}
|
||||
if (!add.isEmpty()) {
|
||||
ec2Service.createTags(region, List.of(resourceId), add);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the keys a template owns to {@code desired} and leaves every other tag alone, as AWS
|
||||
* keeps a tag added outside the stack: removes the {@code owned} keys {@code desired} no longer
|
||||
* declares, then creates or overwrites the declared ones. {@code owned} is the key set the
|
||||
* previous template declared, or the keys an update touched when a rollback restores them.
|
||||
* last deployment wrote, or the keys an update touched when a rollback restores them. Returns
|
||||
* whether any of those tags were anything other than {@code desired} before.
|
||||
*/
|
||||
static void reconcileOwned(Ec2Service ec2Service, String region, String resourceId, Set<String> owned,
|
||||
Map<String, String> desired) {
|
||||
static boolean reconcileOwned(Ec2Service ec2Service, String region, String resourceId, Set<String> owned,
|
||||
Map<String, String> desired) {
|
||||
List<Tag> add = validatedTags(desired);
|
||||
Map<String, String> current = current(ec2Service, region, resourceId);
|
||||
boolean changed = changesOwnedTags(owned, desired, current);
|
||||
List<Tag> remove = new ArrayList<>();
|
||||
for (String key : owned) {
|
||||
if (!desired.containsKey(key) && current.containsKey(key)) {
|
||||
@@ -91,5 +77,98 @@ final class Ec2Tags {
|
||||
if (!add.isEmpty()) {
|
||||
ec2Service.createTags(region, List.of(resourceId), add);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys the last deployment recorded in {@code recordAttr}. A resource provisioned before
|
||||
* that was recorded falls back to the previous template's keys, resolved as well as they still
|
||||
* can be. Recorded rather than re-resolved, because a key taken from a parameter resolves to the
|
||||
* new value on the next update.
|
||||
*/
|
||||
static Set<String> ownedKeys(StackResource r, String recordAttr, ProvisionContext ctx) {
|
||||
String recorded = r.getAttributes().get(recordAttr);
|
||||
if (recorded == null) {
|
||||
return ctx.resolveTags(ctx.priorProperties(), "Tags").keySet();
|
||||
}
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
try {
|
||||
MAPPER.readTree(recorded).forEach(key -> keys.add(key.asText()));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Unreadable tag keys on " + r.getLogicalId(), e);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the keys this deployment resolved and wrote, as a JSON array: the keys the stack owns.
|
||||
* An empty array is recorded too: re-resolving the previous template could read keys this
|
||||
* deployment never wrote (an {@code Fn::If} over the next update's conditions), so only a
|
||||
* resource provisioned before records were kept falls back to that.
|
||||
*/
|
||||
static void recordKeys(StackResource r, String recordAttr, Map<String, String> desired) {
|
||||
ArrayNode keys = MAPPER.createArrayNode();
|
||||
desired.keySet().forEach(keys::add);
|
||||
r.getAttributes().put(recordAttr, keys.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an update to {@code desired} changes a tag or the owned key set. A change of ownership
|
||||
* alone (taking over a key that already holds the declared value) still needs the record put
|
||||
* back, so it counts as a change too.
|
||||
*/
|
||||
static boolean changesOwned(Set<String> owned, Map<String, String> desired, Map<String, String> current) {
|
||||
return !owned.equals(desired.keySet()) || changesOwnedTags(owned, desired, current);
|
||||
}
|
||||
|
||||
private static boolean changesOwnedTags(Set<String> owned, Map<String, String> desired,
|
||||
Map<String, String> current) {
|
||||
return touched(owned, desired).stream().anyMatch(key -> desired.containsKey(key)
|
||||
? !desired.get(key).equals(current.get(key))
|
||||
: current.containsKey(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Records in {@code snapshot} what {@link #restoreOwned} needs: the keys an update touches (the
|
||||
* owned ones and the declared ones), the values they had, and the ownership record the update
|
||||
* replaces. Tags outside the touched set are never written, so they are not recorded either.
|
||||
*/
|
||||
static void snapshotOwned(ObjectNode snapshot, Set<String> owned, Map<String, String> desired,
|
||||
Map<String, String> current, String priorRecord) {
|
||||
Set<String> touched = touched(owned, desired);
|
||||
touched.forEach(snapshot.putArray("touched")::add);
|
||||
ObjectNode tags = snapshot.putObject("tags");
|
||||
touched.stream().filter(current::containsKey).forEach(key -> tags.put(key, current.get(key)));
|
||||
snapshot.put("tagKeys", priorRecord);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the touched keys back from a {@link #snapshotOwned} snapshot: a key the resource had gets
|
||||
* its value again, and a key the update added is removed. The ownership record goes back too.
|
||||
*/
|
||||
static void restoreOwned(Ec2Service ec2Service, String region, String resourceId, StackResource r,
|
||||
String recordAttr, JsonNode snapshot) {
|
||||
Set<String> touched = new LinkedHashSet<>();
|
||||
snapshot.path("touched").forEach(key -> touched.add(key.asText()));
|
||||
Map<String, String> priorTags = new LinkedHashMap<>();
|
||||
snapshot.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), f.getValue().asText()));
|
||||
reconcileOwned(ec2Service, region, resourceId, touched, priorTags);
|
||||
restoreRecord(r, recordAttr, snapshot);
|
||||
}
|
||||
|
||||
/** Puts back the ownership record a snapshot carries in {@code tagKeys}, or its absence. */
|
||||
static void restoreRecord(StackResource r, String recordAttr, JsonNode snapshot) {
|
||||
String tagKeys = CfnRollback.snapshotText(snapshot, "tagKeys");
|
||||
if (tagKeys == null) {
|
||||
r.getAttributes().remove(recordAttr);
|
||||
} else {
|
||||
r.getAttributes().put(recordAttr, tagKeys);
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> touched(Set<String> owned, Map<String, String> desired) {
|
||||
Set<String> touched = new LinkedHashSet<>(owned);
|
||||
touched.addAll(desired.keySet());
|
||||
return touched;
|
||||
}
|
||||
}
|
||||
+46
-21
@@ -14,7 +14,6 @@ import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -33,16 +32,17 @@ import java.util.stream.Collectors;
|
||||
* Ipv6CidrBlocks. List-valued attributes are comma-joined like the other provisioners' lists.
|
||||
*
|
||||
* <p>Tags are reconciled to the template's {@code Tags} the way {@link Ec2Tags} does for the
|
||||
* instance and security-group provisioners: a key the template dropped is deleted. Stack-level
|
||||
* instance and security-group provisioners: a key the last deployment wrote that the template
|
||||
* dropped is deleted, and a tag added outside the stack is kept, as on AWS. Stack-level
|
||||
* tags and the {@code aws:cloudformation:*} system tags are not applied here, matching every other
|
||||
* EC2 provisioner in this package.
|
||||
*
|
||||
* <p>A replacement leaves the displaced VPC to the {@link ReplacementCleanup} record: it is deleted
|
||||
* once the update commits, or the resource is pointed back at it when a later resource fails the
|
||||
* update and it rolls back. An in-place change to a reused VPC is snapshotted before it is written
|
||||
* (tenancy, the DNS attributes and the tag set), so the same rollback puts them back; a provision
|
||||
* that fails mid-way restores its own snapshot before the failure propagates. The stack delete
|
||||
* removes the VPC; it tolerates only {@code InvalidVpcID.NotFound}, so a VPC that still has
|
||||
* (tenancy, the DNS attributes and the tag keys it touches), so the same rollback puts them back; a
|
||||
* provision that fails mid-way restores its own snapshot before the failure propagates. The stack
|
||||
* delete removes the VPC; it tolerates only {@code InvalidVpcID.NotFound}, so a VPC that still has
|
||||
* dependents outside the stack fails the delete with {@code DependencyViolation}, as on AWS.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
@@ -53,9 +53,12 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
/**
|
||||
* What an in-place update changed on a reused VPC, recorded before the change so a stack
|
||||
* rollback can put it back. Internal, like the other {@code __Floci} attributes.
|
||||
* rollback can put it back, or, for a replacement, the tag-key record it replaced. Internal,
|
||||
* like the other {@code __Floci} attributes.
|
||||
*/
|
||||
static final String IN_PLACE_PRIOR_ATTR = "__FlociEc2VpcPrior";
|
||||
/** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */
|
||||
static final String TAG_KEYS_ATTR = "__FlociEc2VpcTagKeys";
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
@@ -85,6 +88,9 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
|
||||
Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, desiredTenancy, region);
|
||||
boolean reused = reconciled != null;
|
||||
// Only the keys the last deployment wrote are the stack's to remove; a new VPC has no tags.
|
||||
String priorTagKeys = r.getAttributes().get(TAG_KEYS_ATTR);
|
||||
Set<String> ownedTags = reused ? Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx) : Set.of();
|
||||
Vpc vpc = reused ? reconciled : ec2Service.createVpc(region, cidr, false, false, desiredTenancy);
|
||||
String vpcId = vpc.getVpcId();
|
||||
r.setPhysicalId(vpcId);
|
||||
@@ -92,15 +98,25 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
CfnRollback.guarded(r, ctx, !reused, () -> ec2Service.deleteVpc(region, vpcId), () -> undoInPlace(r), () -> {
|
||||
if (reused) {
|
||||
snapshotInPlace(r, vpc, desiredTenancy, dnsSupport, dnsHostnames, desiredTags, region);
|
||||
snapshotInPlace(r, vpc, desiredTenancy, dnsSupport, dnsHostnames, ownedTags, desiredTags,
|
||||
priorTagKeys, region);
|
||||
}
|
||||
if (reused && isDedicatedToDefault(vpc, desiredTenancy)) {
|
||||
ec2Service.modifyVpcTenancy(region, vpcId, desiredTenancy);
|
||||
}
|
||||
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", String.valueOf(dnsSupport));
|
||||
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", String.valueOf(dnsHostnames));
|
||||
Ec2Tags.reconcile(ec2Service, region, vpcId, desiredTags);
|
||||
Ec2Tags.reconcileOwned(ec2Service, region, vpcId, ownedTags, desiredTags);
|
||||
});
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags);
|
||||
if (!reused && ctx.isUpdate()) {
|
||||
// A replacement's rollback names the prior VPC again with its public attributes; the
|
||||
// tag-key record it owns goes back from here.
|
||||
ObjectNode replaced = MAPPER.createObjectNode();
|
||||
replaced.put("replaced", true);
|
||||
replaced.put("tagKeys", priorTagKeys);
|
||||
r.getAttributes().put(IN_PLACE_PRIOR_ATTR, replaced.toString());
|
||||
}
|
||||
|
||||
if (vpc.getCidrBlock() != null) {
|
||||
r.getAttributes().put("CidrBlock", vpc.getCidrBlock());
|
||||
@@ -158,6 +174,12 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
*/
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
JsonNode prior = CfnRollback.updateSnapshot(resource, IN_PLACE_PRIOR_ATTR);
|
||||
if (prior != null && prior.path("replaced").asBoolean(false)) {
|
||||
// Put back before the replacement's delete, which can throw after the prior VPC is named
|
||||
// again.
|
||||
Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, prior);
|
||||
}
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
|
||||
return true;
|
||||
@@ -176,17 +198,18 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
/**
|
||||
* Records what the update is about to change on a reused VPC, only when something differs: an
|
||||
* unchanged reuse leaves no snapshot and rolls back as complete. The tag set comes from
|
||||
* DescribeTags, the same source {@link Ec2Tags#reconcile} compares against.
|
||||
* unchanged reuse leaves no snapshot and rolls back as complete. The tags come from
|
||||
* DescribeTags, the same source {@link Ec2Tags#reconcileOwned} compares against.
|
||||
*/
|
||||
private void snapshotInPlace(StackResource r, Vpc vpc, String desiredTenancy, boolean dnsSupport,
|
||||
boolean dnsHostnames, Map<String, String> desiredTags, String region) {
|
||||
boolean dnsHostnames, Set<String> ownedTags, Map<String, String> desiredTags,
|
||||
String priorTagKeys, String region) {
|
||||
Map<String, String> currentTags = Ec2Tags.current(ec2Service, region, vpc.getVpcId());
|
||||
boolean tenancyChanges = isDedicatedToDefault(vpc, desiredTenancy);
|
||||
boolean changed = tenancyChanges
|
||||
|| vpc.isEnableDnsSupport() != dnsSupport
|
||||
|| vpc.isEnableDnsHostnames() != dnsHostnames
|
||||
|| !currentTags.equals(desiredTags);
|
||||
|| Ec2Tags.changesOwned(ownedTags, desiredTags, currentTags);
|
||||
if (!changed) {
|
||||
return;
|
||||
}
|
||||
@@ -198,16 +221,16 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
prior.put("enableDnsSupport", vpc.isEnableDnsSupport());
|
||||
prior.put("enableDnsHostnames", vpc.isEnableDnsHostnames());
|
||||
ObjectNode tags = prior.putObject("tags");
|
||||
currentTags.forEach(tags::put);
|
||||
Ec2Tags.snapshotOwned(prior, ownedTags, desiredTags, currentTags, priorTagKeys);
|
||||
r.getAttributes().put(IN_PLACE_PRIOR_ATTR, prior.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the DNS attributes and the tag set back, then the tenancy last. The only tenancy change
|
||||
* applied in place is {@code dedicated} to {@code default}, and EC2 refuses the reverse, so a
|
||||
* rollback of that change fails on the ModifyVpcTenancy call after everything else is restored
|
||||
* and the stack reports UPDATE_ROLLBACK_FAILED for the VPC rather than claiming it is back.
|
||||
* Puts the DNS attributes, the touched tag keys and their record back, then the tenancy last.
|
||||
* The only tenancy change applied in place is {@code dedicated} to {@code default}, and EC2
|
||||
* refuses the reverse, so a rollback of that change fails on the ModifyVpcTenancy call after
|
||||
* everything else is restored and the stack reports UPDATE_ROLLBACK_FAILED for the VPC rather
|
||||
* than claiming it is back.
|
||||
*/
|
||||
private void restoreInPlace(StackResource resource, String snapshot) {
|
||||
ObjectNode prior;
|
||||
@@ -216,13 +239,15 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Unreadable in-place snapshot on " + resource.getLogicalId(), e);
|
||||
}
|
||||
if (prior.path("replaced").asBoolean(false)) {
|
||||
Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, prior);
|
||||
return;
|
||||
}
|
||||
String region = prior.path("region").asText();
|
||||
String vpcId = prior.path("vpcId").asText();
|
||||
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", prior.path("enableDnsSupport").asText());
|
||||
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", prior.path("enableDnsHostnames").asText());
|
||||
Map<String, String> priorTags = new LinkedHashMap<>();
|
||||
prior.path("tags").fields().forEachRemaining(f -> priorTags.put(f.getKey(), f.getValue().asText()));
|
||||
Ec2Tags.reconcile(ec2Service, region, vpcId, priorTags);
|
||||
Ec2Tags.restoreOwned(ec2Service, region, vpcId, resource, TAG_KEYS_ATTR, prior);
|
||||
if (prior.hasNonNull("instanceTenancy")) {
|
||||
ec2Service.modifyVpcTenancy(region, vpcId, prior.get("instanceTenancy").asText());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user