mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): settle interrupted lifecycle states and prune terminated instances (#8779)
* fix(ec2): settle interrupted lifecycle states and prune terminated instances * fix(ec2): address review findings on lifecycle recovery and pruning * test(ec2): use Awaitility in the EC2 lifecycle tests
This commit is contained in:
1 parent
39cdaa5075
commit
90b6d46317
8 files changed
+1187
-54
No files matched your search
@@ -17,6 +17,7 @@ import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLiveness;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
@@ -144,6 +145,8 @@ public class Ec2ContainerManager {
|
||||
|
||||
static int containerBridgeIpAttempts = 30;
|
||||
static long containerBridgeIpPollMillis = 500;
|
||||
private static final int PERSIST_ATTEMPTS = 5;
|
||||
private static final long PERSIST_RETRY_MILLIS = 100;
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
@@ -164,6 +167,13 @@ public class Ec2ContainerManager {
|
||||
private final ExecutorService executor;
|
||||
private final Semaphore metadataSetupSlots = new Semaphore(METADATA_SETUP_CONCURRENCY);
|
||||
private final Map<String, CompletableFuture<Void>> lifecycleOperations = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Writes an instance back to the store. The state changes made here run on executor threads
|
||||
* after the request that started them has returned, so nothing else would persist them: the
|
||||
* stored record would keep the state that request wrote, and a process stopped before the next
|
||||
* write would restore it as {@code pending} or {@code shutting-down} for good.
|
||||
*/
|
||||
private volatile Consumer<Instance> persister = instance -> { };
|
||||
/** Instances whose service-network lookup failed and is retried on the next address read. */
|
||||
private final Set<String> serviceNetworkRetries = ConcurrentHashMap.newKeySet();
|
||||
/** The latest service-network lookup started per instance; only that one may publish. */
|
||||
@@ -583,6 +593,7 @@ public class Ec2ContainerManager {
|
||||
failLaunch(instance, leasedPrivateIp);
|
||||
return;
|
||||
}
|
||||
persist(instance);
|
||||
|
||||
LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})",
|
||||
instanceId, containerId, String.valueOf(sshHostPort));
|
||||
@@ -818,6 +829,60 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
}
|
||||
|
||||
void setPersister(Consumer<Instance> persister) {
|
||||
this.persister = persister;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the instance's current state, and narrows the window in which an older state can be
|
||||
* the last one the store commits. A store may take its snapshot of the instance before it
|
||||
* commits it, as the write-ahead log does, so a slow writer can commit an older state after a
|
||||
* newer one. When the state moved on while a write was in flight the instance is written
|
||||
* again, without a lock around the store.
|
||||
*
|
||||
* <p>This is a mitigation, not an ordering guarantee. The check and the corrective write are not
|
||||
* atomic with the store's commit, and they cover only the writes made here: those the request
|
||||
* threads make through the service are not covered.
|
||||
*
|
||||
* <p>A write that fails is retried a few times before it is reported.
|
||||
*/
|
||||
private void persist(Instance instance) {
|
||||
for (int attempt = 1; attempt <= PERSIST_ATTEMPTS; attempt++) {
|
||||
String writing = stateName(instance);
|
||||
try {
|
||||
persister.accept(instance);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not persist the state of EC2 instance {0} (attempt {1} of {2})",
|
||||
instance.getInstanceId(), attempt, PERSIST_ATTEMPTS);
|
||||
if (!pause(PERSIST_RETRY_MILLIS)) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (writing.equals(stateName(instance))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
LOG.errorv("Could not confirm that the current state of EC2 instance {0} reached the store; "
|
||||
+ "a later write or the next start will correct it", instance.getInstanceId());
|
||||
}
|
||||
|
||||
private static String stateName(Instance instance) {
|
||||
InstanceState state = instance.getState();
|
||||
return state == null ? "" : state.getName();
|
||||
}
|
||||
|
||||
/** Sleeps; false when the thread was interrupted, which also restores its interrupt flag. */
|
||||
private static boolean pause(long millis) {
|
||||
try {
|
||||
Thread.sleep(millis);
|
||||
return true;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void failLaunch(Instance instance) {
|
||||
failLaunch(instance, instance.getPrivateIpAddress());
|
||||
}
|
||||
@@ -844,7 +909,7 @@ public class Ec2ContainerManager {
|
||||
&& instance.getDockerContainerId() == null
|
||||
&& instance.getSshHostPort() <= 0
|
||||
&& (instance.getContainerBridgeIp() == null || instance.getContainerBridgeIp().isBlank());
|
||||
instance.setState(InstanceState.terminated());
|
||||
instance.markTerminated(System.currentTimeMillis());
|
||||
containerId = instance.getDockerContainerId();
|
||||
sshHostPort = instance.getSshHostPort();
|
||||
containerIp = instance.getContainerBridgeIp();
|
||||
@@ -855,6 +920,7 @@ public class Ec2ContainerManager {
|
||||
serviceNetworkRetries.remove(instance.getInstanceId());
|
||||
serviceNetworkLookups.remove(instance.getInstanceId());
|
||||
}
|
||||
persist(instance);
|
||||
if (alreadyCleaned) {
|
||||
return;
|
||||
}
|
||||
@@ -911,7 +977,7 @@ public class Ec2ContainerManager {
|
||||
if ("running".equals(state)) {
|
||||
return false;
|
||||
}
|
||||
instance.setState(InstanceState.terminated());
|
||||
instance.markTerminated(System.currentTimeMillis());
|
||||
}
|
||||
failLaunch(instance);
|
||||
return true;
|
||||
@@ -995,6 +1061,7 @@ public class Ec2ContainerManager {
|
||||
*/
|
||||
private void markContainerlessRunning(Instance instance) {
|
||||
if (markRunning(instance)) {
|
||||
persist(instance);
|
||||
LOG.infov("EC2 instance {0} is running without a backing container (no Docker daemon reachable)",
|
||||
instance.getInstanceId());
|
||||
}
|
||||
@@ -1069,7 +1136,9 @@ public class Ec2ContainerManager {
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error stopping EC2 container {0}: {1}", containerId, e.getMessage());
|
||||
}
|
||||
instance.compareAndSetState(stopping, InstanceState.stopped());
|
||||
if (instance.compareAndSetState(stopping, InstanceState.stopped())) {
|
||||
persist(instance);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1151,13 +1220,17 @@ public class Ec2ContainerManager {
|
||||
setUpMetadataEndpoint = namespace == null;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
instance.compareAndSetState(pending, InstanceState.stopped());
|
||||
if (instance.compareAndSetState(pending, InstanceState.stopped())) {
|
||||
persist(instance);
|
||||
}
|
||||
rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration);
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error starting EC2 container {0}: {1}", containerId, e.getMessage());
|
||||
instance.compareAndSetState(pending, InstanceState.stopped());
|
||||
if (instance.compareAndSetState(pending, InstanceState.stopped())) {
|
||||
persist(instance);
|
||||
}
|
||||
rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration);
|
||||
return;
|
||||
}
|
||||
@@ -1166,6 +1239,7 @@ public class Ec2ContainerManager {
|
||||
rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration);
|
||||
return;
|
||||
}
|
||||
persist(instance);
|
||||
if (postStart != null) {
|
||||
try {
|
||||
postStart.run();
|
||||
@@ -1618,6 +1692,11 @@ public class Ec2ContainerManager {
|
||||
* removal itself failed would attempt work Docker is bound to refuse with no later retry
|
||||
* behind it. A skip is logged. Anything the callback throws is logged and swallowed rather
|
||||
* than killing the executor task.
|
||||
*
|
||||
* <p>Every release of the teardown is best effort and independent of the container removal, so
|
||||
* one that fails neither skips the removal nor keeps the instance from terminating. The
|
||||
* instance ends {@code terminated} even when Docker refuses the removal; the callback is then
|
||||
* skipped, and the container is collected on the next start.
|
||||
*/
|
||||
public void terminate(Instance instance, Runnable afterTeardown) {
|
||||
String containerId;
|
||||
@@ -1639,47 +1718,36 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
executor.submit(() -> {
|
||||
// The post-teardown hook's only precondition; see the Javadoc above for why.
|
||||
boolean containerGone = false;
|
||||
boolean containerGone = containerId == null;
|
||||
try {
|
||||
portForwardManager.unpublishAll(instance);
|
||||
if (containerId == null) {
|
||||
// Nothing was ever launched, so there is no container to hold the image.
|
||||
containerGone = true;
|
||||
}
|
||||
cleanupStep(instance, "port forwards", () -> portForwardManager.unpublishAll(instance));
|
||||
if (containerId != null) {
|
||||
try {
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
containerGone = true;
|
||||
} catch (NotFoundException e) {
|
||||
// already gone
|
||||
containerGone = true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage());
|
||||
}
|
||||
try {
|
||||
// iptables/veth teardown lags behind container removal; prevents port-reuse conflicts.
|
||||
Thread.sleep(500);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
containerGone = removeContainer(containerId);
|
||||
// iptables/veth teardown lags behind container removal; prevents port-reuse conflicts.
|
||||
pause(500);
|
||||
}
|
||||
if (firewallManager != null && firewallManager.enabled() && firewallEniId != null) {
|
||||
firewallManager.unregister(firewallEniId);
|
||||
cleanupStep(instance, "firewall registration", () -> firewallManager.unregister(firewallEniId));
|
||||
}
|
||||
if (sshHostPort > 0) {
|
||||
portAllocator.release(sshHostPort);
|
||||
cleanupStep(instance, "SSH host port", () -> portAllocator.release(sshHostPort));
|
||||
}
|
||||
metadataServer.unregisterContainer(containerIp, instance);
|
||||
metadataServer.unregisterContainer(imdsSourceIp, instance);
|
||||
metadataServer.unregisterInstance(instance);
|
||||
cleanupStep(instance, "metadata registrations", () -> {
|
||||
metadataServer.unregisterContainer(containerIp, instance);
|
||||
metadataServer.unregisterContainer(imdsSourceIp, instance);
|
||||
metadataServer.unregisterInstance(instance);
|
||||
});
|
||||
// Give the address back only now that the container is gone: releasing it while
|
||||
// Docker still holds the endpoint would hand the same IP to the next launch and
|
||||
// have Docker refuse it.
|
||||
vpcNetworkManager.releasePrivateIp(instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(),
|
||||
instance.getPrivateIpAddress());
|
||||
instance.setState(InstanceState.terminated());
|
||||
instance.setTerminatedAt(System.currentTimeMillis());
|
||||
cleanupStep(instance, "private address", () -> vpcNetworkManager.releasePrivateIp(
|
||||
instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(),
|
||||
instance.getPrivateIpAddress()));
|
||||
} finally {
|
||||
// Whatever the teardown managed, the instance must not stay shutting-down: nothing
|
||||
// else would ever finish it, and a leftover container is collected on the next start.
|
||||
instance.markTerminated(System.currentTimeMillis());
|
||||
persist(instance);
|
||||
if (afterTeardown != null && containerGone) {
|
||||
try {
|
||||
afterTeardown.run();
|
||||
@@ -1696,6 +1764,48 @@ public class Ec2ContainerManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true when the container is gone, including when it was already absent
|
||||
*/
|
||||
private boolean removeContainer(String containerId) {
|
||||
try {
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
return true;
|
||||
} catch (NotFoundException e) {
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one best-effort release during teardown. Each release is independent of the others, and
|
||||
* above all of the container removal, so one that fails is logged and the rest still run.
|
||||
*/
|
||||
private void cleanupStep(Instance instance, String step, Runnable release) {
|
||||
try {
|
||||
release.run();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not release the {0} of EC2 instance {1} during termination; "
|
||||
+ "continuing with the rest", step, instance.getInstanceId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops an instance's container for startup recovery and reports whether it is confirmed
|
||||
* stopped or gone. A Docker error while stopping, or while checking afterwards, is not
|
||||
* confirmation: the container may still be running.
|
||||
*/
|
||||
boolean stopAndConfirm(Instance instance) {
|
||||
String containerId = instance.getDockerContainerId();
|
||||
if (containerId == null) {
|
||||
return true;
|
||||
}
|
||||
stopForShutdown(instance);
|
||||
return lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reboots an instance via docker restart.
|
||||
*/
|
||||
|
||||
@@ -157,6 +157,7 @@ import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
@@ -175,6 +176,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(Ec2Service.class);
|
||||
|
||||
/** How long a terminated instance stays listed, as EC2 keeps one visible for about an hour. */
|
||||
static final Duration TERMINATED_INSTANCE_RETENTION = Duration.ofHours(1);
|
||||
|
||||
/**
|
||||
* The availability zones every region is modelled with. DescribeAvailabilityZones publishes
|
||||
* exactly these, the seeded default subnets sit in them, and CreateSubnet refuses a zone id
|
||||
@@ -1083,13 +1087,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
@PostConstruct
|
||||
void restoreMetadataRegistrations() {
|
||||
migrateTagsToRegionKeys();
|
||||
Consumer<Instance> persister = inst -> {
|
||||
if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) {
|
||||
putInstanceForOwner(key(inst.getRegion(), inst.getInstanceId()), inst);
|
||||
}
|
||||
};
|
||||
if (portForwardManager != null) {
|
||||
portForwardManager.setPersister(inst -> {
|
||||
if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) {
|
||||
putInstanceForOwner(key(inst.getRegion(), inst.getInstanceId()), inst);
|
||||
}
|
||||
});
|
||||
portForwardManager.setPersister(persister);
|
||||
}
|
||||
if (containerManager != null) {
|
||||
containerManager.setPersister(persister);
|
||||
}
|
||||
stampUntimedTerminatedRecords();
|
||||
if (config.services().ec2().mock()) {
|
||||
return;
|
||||
}
|
||||
@@ -1097,10 +1106,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
restoreVpcNetworks();
|
||||
|
||||
int restored = 0;
|
||||
Set<String> registered = new HashSet<>();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Instance> entry : entriesOfEveryAccount(instances)) {
|
||||
if (needsMetadataRegistration(entry.value())
|
||||
&& RequestScopes.callAs(entry.accountId(), entry.value().getRegion(), () -> restoreInstance(entry))) {
|
||||
restored++;
|
||||
registered.add(entry.accountId() + "/" + entry.key());
|
||||
}
|
||||
}
|
||||
if (restored > 0) {
|
||||
@@ -1109,12 +1120,135 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (volumeBlockDeviceManager != null && volumeBlockDeviceManager.isAvailable()) {
|
||||
restoreAttachedVolumesOnStartup();
|
||||
}
|
||||
resumeInterruptedLifecycles(registered);
|
||||
|
||||
// Runs after the restore loop, so anything legitimately revived above is already
|
||||
// accounted for and only genuine leftovers are left to collect.
|
||||
containerManager.reconcileOrphanedContainers(this::instanceContainerStillWanted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the retention clock of terminated records that have none. Records written before
|
||||
* every terminal path stamped {@code terminatedAt} (a launch that failed, for one) carry zero,
|
||||
* which {@link #pruneTerminatedInstances(Instant)} reads as "not yet expired" for ever.
|
||||
*/
|
||||
private void stampUntimedTerminatedRecords() {
|
||||
long now = System.currentTimeMillis();
|
||||
int stamped = 0;
|
||||
for (AccountAwareStorageBackend.AccountEntry<Instance> entry : entriesOfEveryAccount(instances)) {
|
||||
Instance instance = entry.value();
|
||||
if (instance != null && instance.getState() != null
|
||||
&& "terminated".equals(instance.getState().getName()) && instance.getTerminatedAt() <= 0) {
|
||||
instance.markTerminated(now);
|
||||
putForOwner(instances, entry, instance);
|
||||
stamped++;
|
||||
}
|
||||
}
|
||||
if (stamped > 0) {
|
||||
LOG.infov("Started the retention clock of {0} terminated EC2 instance(s) recorded without one",
|
||||
stamped);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles instances a previous run left mid-transition. The thread that would have finished
|
||||
* each of them died with that run, so without this a record stays {@code pending},
|
||||
* {@code stopping} or {@code shutting-down} for good, whatever its container is doing.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code shutting-down}: the termination is finished, container and all.</li>
|
||||
* <li>{@code pending} with no container: the launch never produced one, so it ends as a
|
||||
* failed launch does.</li>
|
||||
* <li>{@code pending} with a container: running if the container is, which is what the
|
||||
* restore loop just re-registered, otherwise the container is stopped and the record
|
||||
* settles as stopped. The container is never discarded, because the record may be a
|
||||
* stopped instance that was being started.</li>
|
||||
* <li>{@code stopping}: the container is stopped and the record settles as stopped.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>A record settles as stopped only when Docker confirms its container stopped or gone. When
|
||||
* it cannot (Docker unreachable, for one) the record keeps its state and the next start tries
|
||||
* again, because writing {@code stopped} for a container that may be running would be wrong.
|
||||
*
|
||||
* @param registered the accounts and keys whose running container the restore loop registered
|
||||
*/
|
||||
private void resumeInterruptedLifecycles(Set<String> registered) {
|
||||
List<String> unsettled = new ArrayList<>();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Instance> entry : entriesOfEveryAccount(instances)) {
|
||||
Instance instance = entry.value();
|
||||
if (instance == null || instance.getState() == null) {
|
||||
continue;
|
||||
}
|
||||
boolean containerRegistered = registered.contains(entry.accountId() + "/" + entry.key());
|
||||
// One instance that cannot be settled must neither stop the others being settled nor
|
||||
// stop Floci starting, so a failure is kept apart and reported below.
|
||||
try {
|
||||
boolean settled = RequestScopes.callAs(entry.accountId(), instance.getRegion(),
|
||||
() -> resumeInterruptedLifecycle(entry, containerRegistered));
|
||||
if (!settled) {
|
||||
unsettled.add(instance.getInstanceId());
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not settle EC2 instance {0} left in state {1} by a previous run",
|
||||
instance.getInstanceId(), instance.getState().getName());
|
||||
unsettled.add(instance.getInstanceId());
|
||||
}
|
||||
}
|
||||
if (!unsettled.isEmpty()) {
|
||||
LOG.errorv("{0} EC2 instance(s) left mid-transition by a previous run could not be settled and "
|
||||
+ "keep their state until the next start: {1}", unsettled.size(), unsettled);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return false when the instance could not be settled and was left as it was
|
||||
*/
|
||||
private boolean resumeInterruptedLifecycle(AccountAwareStorageBackend.AccountEntry<Instance> entry,
|
||||
boolean containerRegistered) {
|
||||
Instance instance = entry.value();
|
||||
String state = instance.getState().getName();
|
||||
boolean hasContainer = instance.getDockerContainerId() != null;
|
||||
if ("shutting-down".equals(state) || ("pending".equals(state) && !hasContainer)) {
|
||||
LOG.infov("Finishing the termination of EC2 instance {0} left {1} by a previous run",
|
||||
instance.getInstanceId(), state);
|
||||
finishTermination(entry);
|
||||
} else if ("pending".equals(state)) {
|
||||
if (!containerRegistered && !containerManager.stopAndConfirm(instance)) {
|
||||
LOG.warnv("The container of EC2 instance {0}, left pending by a previous run, could not be "
|
||||
+ "confirmed stopped, so the instance stays pending", instance.getInstanceId());
|
||||
return false;
|
||||
}
|
||||
instance.setState(containerRegistered ? InstanceState.running() : InstanceState.stopped());
|
||||
putForOwner(instances, entry, instance);
|
||||
LOG.infov("EC2 instance {0} left pending by a previous run is now {1}", instance.getInstanceId(),
|
||||
instance.getState().getName());
|
||||
} else if ("stopping".equals(state)) {
|
||||
if (hasContainer && !containerManager.stopAndConfirm(instance)) {
|
||||
LOG.warnv("The container of EC2 instance {0}, left stopping by a previous run, could not be "
|
||||
+ "confirmed stopped, so the instance stays stopping", instance.getInstanceId());
|
||||
return false;
|
||||
}
|
||||
instance.setState(InstanceState.stopped());
|
||||
putForOwner(instances, entry, instance);
|
||||
LOG.infov("EC2 instance {0} left stopping by a previous run is now stopped", instance.getInstanceId());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void finishTermination(AccountAwareStorageBackend.AccountEntry<Instance> entry) {
|
||||
Instance instance = entry.value();
|
||||
String region = instance.getRegion();
|
||||
String owner = entry.accountId();
|
||||
containerManager.terminate(instance, () -> RequestScopes.runAs(owner,
|
||||
() -> reclaimCapturesPinnedBy(region, instance, Set.of(instance.getInstanceId()))));
|
||||
detachAttachedVolumesOnTermination(region, instance);
|
||||
releaseStandaloneInterfacesOnTermination(region, instance);
|
||||
putForOwner(instances, entry, instance);
|
||||
synchronized (capacityReservationLock) {
|
||||
reconcileCapacityMembership(region);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs as the instance's own account, so the security groups, prefix lists and port-forward
|
||||
* writes it resolves along the way come from that account rather than the default one.
|
||||
@@ -5369,11 +5503,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (config.services().ec2().mock()) {
|
||||
// Under the instance's lock, so a concurrent Elastic IP write sees the new state.
|
||||
synchronized (inst) {
|
||||
inst.setState(InstanceState.terminated());
|
||||
inst.markTerminated(System.currentTimeMillis());
|
||||
// Termination also disassociates an Elastic IP, so nothing public is left.
|
||||
clearPublicAddress(inst);
|
||||
}
|
||||
inst.setTerminatedAt(System.currentTimeMillis());
|
||||
} else {
|
||||
// Also attempt the reclaim once this container is really gone. The synchronous
|
||||
// attempt below runs while teardown is still scheduled, so for a batch whose
|
||||
@@ -5707,21 +5840,62 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes terminated instances older than 1 hour. Called periodically by lifecycle. */
|
||||
public void pruneTerminatedInstances() {
|
||||
long cutoff = System.currentTimeMillis() - 3_600_000L;
|
||||
for (String storeKey : new ArrayList<>(instances.keys())) {
|
||||
Instance inst = instances.get(storeKey).orElse(null);
|
||||
if (inst != null
|
||||
&& "terminated".equals(inst.getState().getName())
|
||||
&& inst.getTerminatedAt() > 0
|
||||
&& inst.getTerminatedAt() < cutoff) {
|
||||
instances.delete(storeKey);
|
||||
if (inst.getRegion() != null) {
|
||||
removeTags(inst.getRegion(), inst.getInstanceId());
|
||||
pruneTerminatedInstances(Instant.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes terminated instances older than {@link #TERMINATED_INSTANCE_RETENTION}, of every
|
||||
* account, with their tags. {@link Ec2TerminatedInstanceScheduler} calls it on a timer.
|
||||
*
|
||||
* <p>Whatever termination left attached is released first: a launch that failed ends
|
||||
* terminated without TerminateInstances having run, so its volumes and interfaces are settled
|
||||
* here rather than left pointing at a record that no longer exists.
|
||||
*/
|
||||
public void pruneTerminatedInstances(Instant now) {
|
||||
long cutoff = now.minus(TERMINATED_INSTANCE_RETENTION).toEpochMilli();
|
||||
List<String> failed = new ArrayList<>();
|
||||
RuntimeException failure = null;
|
||||
for (AccountAwareStorageBackend.AccountEntry<Instance> entry : entriesOfEveryAccount(instances)) {
|
||||
Instance inst = entry.value();
|
||||
if (inst == null || inst.getState() == null
|
||||
|| !"terminated".equals(inst.getState().getName())
|
||||
|| inst.getTerminatedAt() <= 0
|
||||
|| inst.getTerminatedAt() >= cutoff) {
|
||||
continue;
|
||||
}
|
||||
// A record that cannot be removed must not keep the others from expiring, so every
|
||||
// failure is collected and reported once the sweep has been through all of them.
|
||||
try {
|
||||
RequestScopes.runAs(entry.accountId(), inst.getRegion(), () -> pruneTerminatedInstance(entry));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove terminated EC2 instance {0}", inst.getInstanceId());
|
||||
failed.add(inst.getInstanceId());
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
} else {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw new IllegalStateException("Could not remove " + failed.size()
|
||||
+ " expired terminated EC2 instance(s), they are tried again on the next sweep: " + failed,
|
||||
failure);
|
||||
}
|
||||
}
|
||||
|
||||
void pruneTerminatedInstance(AccountAwareStorageBackend.AccountEntry<Instance> entry) {
|
||||
Instance inst = entry.value();
|
||||
String region = inst.getRegion();
|
||||
if (region != null) {
|
||||
detachAttachedVolumesOnTermination(region, inst);
|
||||
releaseStandaloneInterfacesOnTermination(region, inst);
|
||||
}
|
||||
deleteForOwner(instances, entry);
|
||||
if (region != null) {
|
||||
removeTags(entry.accountId(), region, inst.getInstanceId());
|
||||
}
|
||||
}
|
||||
|
||||
public List<Instance> describeInstanceStatus(String region, List<String> instanceIds) {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.SweepScheduler;
|
||||
import io.floci.aws.core.common.SweepWorker;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
/** Removes terminated EC2 instances once they have been listed for the retention period. */
|
||||
@ApplicationScoped
|
||||
public class Ec2TerminatedInstanceScheduler extends SweepScheduler {
|
||||
private static final long SWEEP_INTERVAL_SECONDS = 60;
|
||||
|
||||
@Inject
|
||||
public Ec2TerminatedInstanceScheduler(Ec2Service service, EmulatorConfig config) {
|
||||
super(new SweepWorker("ec2-terminated-instance-pruning", config.services().ec2().enabled(),
|
||||
SWEEP_INTERVAL_SECONDS, false, service::pruneTerminatedInstances));
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,17 @@ public class Instance {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the instance to {@code terminated} and starts its retention clock. The clock starts
|
||||
* once: terminating an already terminated record never extends how long it stays listed.
|
||||
*/
|
||||
public synchronized void markTerminated(long nowMillis) {
|
||||
state = InstanceState.terminated();
|
||||
if (terminatedAt <= 0) {
|
||||
terminatedAt = nowMillis;
|
||||
}
|
||||
}
|
||||
|
||||
public String getStateTransitionReason() { return stateTransitionReason; }
|
||||
public void setStateTransitionReason(String stateTransitionReason) { this.stateTransitionReason = stateTransitionReason; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user