Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/services/cloudformation.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ cross-resource references.
| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) |
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) |
| Redshift Serverless | `Namespace` (ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |
| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
| Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` |
Expand Down
4 changes: 2 additions & 2 deletions docs/services/ec2.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ Floci seeds the following resources on first use in each region so Terraform, th
|--------|-------------|
| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. |
| DescribeVpcs | Lists or returns stored VPCs. |
| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, or an attached internet gateway. Instances, NAT gateways and other subnet-resident resources are not checked. |
| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, an attached internet gateway, a transit gateway attachment, or anything still holding a network interface in one of its subnets: an instance that is not terminated, a NAT gateway that is not deleted, a standalone network interface, or an interface endpoint. |
| ModifyVpcAttribute | Updates supported VPC attributes. |
| DescribeVpcAttribute | Returns a supported VPC attribute. |
| DescribeVpcEndpointServices | Lists common AWS interface endpoint services and S3 (gateway and interface) in every availability zone, named per partition (see [Partitions](../configuration/partitions.md)). A `ServiceName` filter is echoed back as asked. |
Expand All @@ -247,7 +247,7 @@ gateway lifecycles.
|--------|-------------|
| CreateSubnet | Creates a subnet in a VPC. |
| DescribeSubnets | Lists or returns stored subnets. |
| DeleteSubnet | Deletes a subnet from the local EC2 store. |
| DeleteSubnet | Deletes a subnet from the local EC2 store. Fails with `DependencyViolation` while the subnet still has a transit gateway attachment or anything holding a network interface in it: an instance that is not terminated, a NAT gateway that is not deleted, a standalone network interface, or an interface endpoint. |
| ModifySubnetAttribute | Updates supported subnet attributes. |

### Security Groups
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
private static final String DECLARED_IAM_PROFILE_ATTR = "__FlociDeclaredIamInstanceProfile";

private final Ec2Service ec2Service;
/** How long {@link #delete} waits for a terminated instance; package-visible so tests can shorten it. */
long terminateTimeoutMillis = 90_000L;
long terminatePollMillis = 250L;

@Inject
public Ec2InstanceCfnProvisioner(Ec2Service ec2Service) {
Expand Down Expand Up @@ -393,11 +396,63 @@ public boolean rollbackUpdate(StackResource resource) {
return ReplacementCleanup.rollback(resource, this::delete);
}

/**
* Terminates the instance and waits until EC2 reports it {@code terminated} (or gone). With
* real containers the instance sits in {@code shutting-down} until the container manager's
* executor finishes, and a subnet or VPC delete that follows in the same stack delete refuses
* a resident that is still shutting down. In mock mode the terminate is synchronous, so the
* first describe already sees {@code terminated}.
*/
@Override
public void delete(String resourceType, String physicalId, String region) {
// Tolerate an instance already terminated out of band, so DeleteStack does not fail on it.
CfnDeletes.safeDelete("EC2 instance", physicalId,
() -> ec2Service.terminateInstances(region, List.of(physicalId)),
"InvalidInstanceID.NotFound");
awaitTerminated(region, physicalId);
}

private void awaitTerminated(String region, String instanceId) {
long deadline = System.currentTimeMillis() + terminateTimeoutMillis;
while (true) {
if (isTerminatedOrGone(region, instanceId)) {
return;
}
if (System.currentTimeMillis() >= deadline) {
throw new AwsException("ValidationError", "Instance " + instanceId
+ " did not reach terminated within " + (terminateTimeoutMillis / 1000) + "s", 400);
}
try {
Thread.sleep(terminatePollMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AwsException("ValidationError",
"Interrupted while waiting for instance " + instanceId + " to terminate", 400);
}
}
}

private boolean isTerminatedOrGone(String region, String instanceId) {
List<Reservation> reservations;
try {
reservations = ec2Service.describeInstances(region, List.of(instanceId), null);
} catch (AwsException e) {
if ("InvalidInstanceID.NotFound".equals(e.getErrorCode())) {
return true;
}
throw e;
}
if (reservations == null) {
return true;
}
for (Reservation reservation : reservations) {
for (Instance instance : reservation.getInstances()) {
if (instanceId.equals(instance.getInstanceId())) {
InstanceState state = instance.getState();
return state != null && "terminated".equals(state.getName());
}
}
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,21 +122,20 @@ public void clearUpdate(StackResource resource) {
/**
* A replacement is undone through the cleanup record: the displaced entity was never touched.
* A reused entity that an update changed in place (tags, a subnet's MapPublicIpOnLaunch, a
* route's target) is put back from the snapshot taken before the change. Without either, the
* update changed nothing about the entity. A provision that fails mid-way restores its own
* snapshot before the failure propagates (see {@link #guarded}), so the previous metadata the
* engine restores for that resource matches the entity again.
* route's target) is put back from the snapshot taken before the change; the snapshot is
* removed only after the restore succeeds, so a restore that throws keeps it for a
* ContinueUpdateRollback retry. Without either, the update changed nothing about the entity.
* A provision that fails mid-way restores its own snapshot before the failure propagates (see
* {@link #guarded}), so the previous metadata the engine restores for that resource matches
* the entity again.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
return true;
}
String snapshot = resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
restoreInPlace(resource, snapshot);
}
undoInPlace(resource);
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
import java.util.Map;

/**
* Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner} and
* {@code Ec2SecurityGroupCfnProvisioner}). Both drive it from the desired tags resolved via
* {@link ProvisionContext#resolveTags}; the reconcile itself is identical.
* Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner},
* {@code Ec2SecurityGroupCfnProvisioner} and {@code Ec2VpcCfnProvisioner}). They drive it from the
* desired tags resolved via {@link ProvisionContext#resolveTags}; the reconcile itself is identical.
*/
final class Ec2Tags {

Expand All @@ -26,17 +26,27 @@ static List<Tag> validatedTags(Map<String, String> desired) {
}

/**
* 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.
* 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.
*/
static void reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
List<Tag> add = validatedTags(desired);
static Map<String, String> current(Ec2Service ec2Service, String region, String resourceId) {
Map<String, String> current = new LinkedHashMap<>();
for (Map<String, String> entry : ec2Service.describeTags(region, Map.of("resource-id", List.of(resourceId)))) {
if (!Ec2Service.isAwsTagKey(entry.get("key"))) {
current.put(entry.get("key"), entry.get("value"));
}
}
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.
*/
static void 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);
if (!stale.isEmpty()) {
List<Tag> remove = new ArrayList<>();
Expand Down
Loading
Loading