diff --git a/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java b/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java index 49538f95f2..f91ed68bb7 100644 --- a/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java +++ b/src/main/java/io/floci/aws/services/ec2/VpcContainerLeases.java @@ -7,12 +7,18 @@ import io.floci.aws.services.ec2.model.Subnet; import io.floci.aws.services.ec2.net.Cidr4; import org.jboss.logging.Logger; +import java.time.Duration; import java.util.Collection; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; @@ -25,8 +31,10 @@ import java.util.function.Supplier; * *

Leases live in memory: a container kept running across a restart takes its address back with * {@link #reclaim}. A container Docker could not be shown to be gone keeps its address, and is looked at again - * whenever the service is asked whether it holds a subnet or VPC. Without Docker-backed VPC networks, or for a subnet - * EC2 does not know, a container keeps the network it was created on. + * whenever the service is asked whether it holds a subnet or VPC: in the background, waited for up to + * {@link #RECHECK_WAIT}, so a healthy daemon's answer counts for the DeleteSubnet or DeleteVpc that asked, while a + * slow one costs that call at most the wait and a later one sees the address given back. Without + * Docker-backed VPC networks, or for a subnet EC2 does not know, a container keeps the network it was created on. */ public final class VpcContainerLeases { @@ -39,6 +47,13 @@ public final class VpcContainerLeases { private final Map leases = new ConcurrentHashMap<>(); /** Containers whose removal Docker did not confirm, whose addresses wait for another look. */ private final Set unconfirmed = ConcurrentHashMap.newKeySet(); + /** The background look at {@link #unconfirmed} running or last run, so asking again starts no second one. */ + private final AtomicReference> recheck = new AtomicReference<>(); + /** How long a dependency check waits for that look before it answers from memory. */ + private final Duration recheckWait; + + /** The longest a DeleteSubnet or DeleteVpc waits on Docker for an unconfirmed removal. */ + static final Duration RECHECK_WAIT = Duration.ofSeconds(2); /** * @param ec2 EC2, which leases the addresses; null leaves every container on its own network @@ -46,9 +61,14 @@ public final class VpcContainerLeases { * @param docker the Docker client that says whether a container is gone */ public VpcContainerLeases(Ec2Service ec2, String owner, Supplier docker) { + this(ec2, owner, docker, RECHECK_WAIT); + } + + VpcContainerLeases(Ec2Service ec2, String owner, Supplier docker, Duration recheckWait) { this.ec2 = ec2; this.owner = owner; this.docker = docker; + this.recheckWait = recheckWait; } /** An address a container holds in a subnet of a VPC, for the account and Region that own them. */ @@ -175,25 +195,79 @@ public final class VpcContainerLeases { return Optional.ofNullable(containerId == null ? null : leases.get(containerId)); } - /** Whether a live container of the account holds an address in the subnet. */ + /** + * Whether a live container of the account holds an address in the subnet, from memory. A container whose removal + * was not confirmed still counts until a background look, waited for up to {@link #RECHECK_WAIT}, finds it gone. + */ public boolean holdsSubnet(String accountId, String region, String subnetId) { - recheckUnconfirmed(); + awaitRecheck(); return leases.values().stream().anyMatch(lease -> lease.accountId().equals(accountId) && lease.region().equals(region) && lease.subnetId().equals(subnetId)); } - /** Whether a live container of the account is on the VPC's network. */ + /** Whether a live container of the account is on the VPC's network, from memory, as {@link #holdsSubnet}. */ public boolean holdsVpc(String accountId, String region, String vpcId) { - recheckUnconfirmed(); + awaitRecheck(); return leases.values().stream().anyMatch(lease -> lease.accountId().equals(accountId) && lease.region().equals(region) && lease.vpcId().equals(vpcId)); } - /** Gives back the addresses of containers whose removal was not confirmed and that Docker no longer has. */ - private void recheckUnconfirmed() { - for (String containerId : List.copyOf(unconfirmed)) { - releaseIfGone(containerId); + /** Starts or joins the background look, and waits for it up to {@link #recheckWait}. */ + private void awaitRecheck() { + CompletableFuture pass = recheckUnconfirmedInBackground(); + if (pass == null) { + return; } + try { + pass.get(recheckWait.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException expected) { + // Docker is slow: answer from memory, the look carries on and a later question sees its result. + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (ExecutionException e) { + LOG.debugv(e, "{0} lease recheck failed", owner); + } + } + + /** + * Gives back, on a virtual thread, the addresses of containers whose removal was not confirmed and that Docker no + * longer has, or returns the look already running; null when nothing waits for one. One look runs at a time, so a + * daemon that does not answer holds one thread, not one per question. A look takes up a container that became + * unconfirmed while it ran, and one container's failure does not stop it looking at the others. + */ + private CompletableFuture recheckUnconfirmedInBackground() { + if (unconfirmed.isEmpty()) { + return null; + } + CompletableFuture running = recheck.get(); + if (running != null && !running.isDone()) { + return running; + } + CompletableFuture pass = new CompletableFuture<>(); + if (!recheck.compareAndSet(running, pass)) { + return recheck.get(); + } + Thread.ofVirtual().name("vpc-lease-recheck").start(() -> { + try { + Set looked = new HashSet<>(); + List next = List.copyOf(unconfirmed); + while (!next.isEmpty()) { + for (String containerId : next) { + looked.add(containerId); + try { + releaseIfGone(containerId); + } catch (RuntimeException e) { + LOG.warnv("{0} container {1}: could not give its VPC address back ({2})", owner, + containerId, e.getMessage()); + } + } + next = unconfirmed.stream().filter(id -> !looked.contains(id)).toList(); + } + } finally { + pass.complete(null); + } + }); + return pass; } private String vpcOf(String region, String subnetId) { diff --git a/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java b/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java index a961240588..e0cd734f92 100644 --- a/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java +++ b/src/test/java/io/floci/aws/services/ec2/VpcContainerLeasesTest.java @@ -6,12 +6,18 @@ import com.github.dockerjava.api.exception.NotFoundException; import io.floci.aws.services.ec2.model.Subnet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -21,8 +27,10 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -71,7 +79,7 @@ class VpcContainerLeasesTest { } @Test - void anAddressDockerCouldNotConfirmFreeIsGivenBackOnceTheContainerIsGone() { + void anAddressDockerCouldNotConfirmFreeIsGivenBackOnceTheContainerIsGone() throws Exception { when(ec2.attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "10.0.1.20")) .thenReturn(Optional.of("10.0.1.20")); assertEquals("10.0.1.20", leases.join(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "r1") @@ -91,7 +99,131 @@ class VpcContainerLeasesTest { assertTrue(leases.holdsVpc(ACCOUNT, REGION, "vpc-1"), "a container still present keeps the address"); inspect.set(new NotFoundException("gone")); - assertFalse(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1")); - verify(ec2).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + await("the address should be given back once a background look finds the container gone") + .atMost(Duration.ofSeconds(5)).until(() -> !leases.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + verify(ec2, timeout(5_000)).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + } + + // Catches: DeleteSubnet and DeleteVpc waiting on a daemon that does not answer, because the + // dependency check inspected each unconfirmed container on the request thread. + @Test + @Timeout(30) + void aDaemonThatDoesNotAnswerLeavesTheDependencyCheckAnsweringFromMemory() throws Exception { + leases = new VpcContainerLeases(ec2, "Test resource", () -> docker, Duration.ofMillis(50)); + when(ec2.attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "10.0.1.20")) + .thenReturn(Optional.of("10.0.1.20")); + leases.join(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "r1"); + CountDownLatch daemonAnswers = new CountDownLatch(1); + AtomicInteger inspects = new AtomicInteger(); + // The removal's own look fails at once; every later one hangs until the daemon answers. + when(docker.inspectContainerCmd("c1").exec()).thenAnswer(invocation -> { + if (inspects.getAndIncrement() == 0) { + throw new IllegalStateException("daemon down"); + } + daemonAnswers.await(); + throw new NotFoundException("gone"); + }); + leases.releaseIfGone("c1"); + try { + long start = System.nanoTime(); + for (int i = 0; i < 5; i++) { + assertTrue(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"), "still held until Docker answers"); + assertTrue(leases.holdsVpc(ACCOUNT, REGION, "vpc-1")); + } + long tookMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + assertTrue(tookMillis < 3_000, "each check should wait at most the recheck wait, took " + tookMillis + " ms"); + // The look is still blocked in Docker, so each of the ten checks could only join it: one more + // inspect after the removal's own means none of them started a second look. + await("one background look should be running").atMost(Duration.ofSeconds(5)) + .until(() -> inspects.get() >= 2); + assertEquals(2, inspects.get(), "asking again while a look runs starts no second one"); + } finally { + daemonAnswers.countDown(); + } + + await("the address should be given back once Docker says the container is gone") + .atMost(Duration.ofSeconds(5)).until(() -> !leases.holdsSubnet(ACCOUNT, REGION, "subnet-1")); + } + + // Catches: the first DeleteSubnet after an unconfirmed removal getting DependencyViolation even + // though a healthy daemon would say at once that the container is gone (a console asks once). + @Test + void aHealthyDaemonsAnswerCountsForTheCheckThatAsked() { + join("c1", "10.0.1.20"); + AtomicReference inspect = new AtomicReference<>(new IllegalStateException("daemon down")); + when(docker.inspectContainerCmd("c1").exec()).thenAnswer(invocation -> { + throw inspect.get(); + }); + leases.releaseIfGone("c1"); + inspect.set(new NotFoundException("gone")); + + assertFalse(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"), "the first check should see the address free"); + } + + // Catches: one container whose address could not be given back stopping the look before the others. + @Test + void oneFailedReleaseDoesNotStopTheOthers() { + when(ec2.allocateVpcPrivateIp(ACCOUNT, REGION, "subnet-1")) + .thenReturn(Optional.of("10.0.1.20"), Optional.of("10.0.1.21")); + join("c1", "10.0.1.20"); + join("c2", "10.0.1.21"); + AtomicReference inspect = new AtomicReference<>(new IllegalStateException("daemon down")); + when(docker.inspectContainerCmd(anyString()).exec()).thenAnswer(invocation -> { + throw inspect.get(); + }); + leases.releaseIfGone("c1"); + leases.releaseIfGone("c2"); + inspect.set(new NotFoundException("gone")); + doThrow(new IllegalStateException("EC2 refused")).when(ec2) + .releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.20"); + + leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"); + + verify(ec2, timeout(5_000)).releaseVpcPrivateIp(ACCOUNT, REGION, "subnet-1", "10.0.1.21"); + assertTrue(leases.lease("c2").isEmpty(), "the second container's address should be given back"); + } + + // Catches: a removal that went unconfirmed while a look was running waiting for the next question. + @Test + @Timeout(30) + void aLookTakesUpAContainerThatBecameUnconfirmedWhileItRan() throws Exception { + when(ec2.allocateVpcPrivateIp(ACCOUNT, REGION, "subnet-1")) + .thenReturn(Optional.of("10.0.1.20"), Optional.of("10.0.1.21")); + join("c1", "10.0.1.20"); + join("c2", "10.0.1.21"); + CountDownLatch firstLookStarted = new CountDownLatch(1); + CountDownLatch daemonAnswers = new CountDownLatch(1); + AtomicInteger c1Looks = new AtomicInteger(); + when(docker.inspectContainerCmd("c1").exec()).thenAnswer(invocation -> { + if (c1Looks.getAndIncrement() == 0) { + throw new IllegalStateException("daemon down"); + } + firstLookStarted.countDown(); + daemonAnswers.await(); + throw new NotFoundException("gone"); + }); + AtomicInteger c2Looks = new AtomicInteger(); + when(docker.inspectContainerCmd("c2").exec()).thenAnswer(invocation -> { + if (c2Looks.getAndIncrement() == 0) { + throw new IllegalStateException("daemon down"); + } + throw new NotFoundException("gone"); + }); + leases.releaseIfGone("c1"); + leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"); + assertTrue(firstLookStarted.await(5, TimeUnit.SECONDS)); + + leases.releaseIfGone("c2"); + daemonAnswers.countDown(); + + await("the running look should also take up c2").atMost(Duration.ofSeconds(5)) + .until(() -> leases.lease("c2").isEmpty()); + } + + private void join(String containerId, String address) { + when(ec2.attachContainerToVpc(ACCOUNT, REGION, "vpc-1", "subnet-1", containerId, address)) + .thenReturn(Optional.of(address)); + assertEquals(address, leases.join(ACCOUNT, REGION, "vpc-1", "subnet-1", containerId, "r-" + containerId) + .orElseThrow().address()); } }