mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(mwaa): re-claim kept containers' VPC addresses safely at startup (#9472)
MwaaService re-claimed the VPC addresses that Airflow containers kept across a restart hold when the service was first used, in its @PostConstruct, and the Docker lookup there caught only a missing container. Since #9466 startup calls the service to restore the environments, so a Docker daemon that did not answer, with an environment in a subnet, stopped Floci from starting. The re-claim now runs when the startup restore begins, on the starting thread, before startup goes on, so EC2 hands none of those addresses to an instance. Each environment is re-claimed on its own: a Docker error is logged and stops neither startup nor any other environment. That environment's restore tries again before taking its containers over, and fails, leaving it UNAVAILABLE, when it cannot either, rather than taking a container over with an address EC2 may hand out. The container is found under its current name or the one before the floci-aws- prefix, as the takeover finds it. Part of #5664.
This commit is contained in:
1 parent
fbd71963e8
commit
5610fd44bd
4 files changed
+140
-23
No files matched your search
@@ -721,27 +721,27 @@ public class MwaaEnvironmentManager {
|
||||
/**
|
||||
* Re-claims the VPC address an environment's Airflow container still holds after Floci restarts, when it was
|
||||
* kept running ({@code keep-running-on-shutdown}): the address leases are in memory, so without this EC2 could
|
||||
* hand the same address to an instance and Docker would refuse it. The container is found by its name.
|
||||
* hand the same address to an instance and Docker would refuse it. The container is found by its name, current or
|
||||
* from before the {@code floci-aws-} prefix; none of either name means none outlived the restart. A Docker that
|
||||
* cannot say throws.
|
||||
*/
|
||||
void reclaimVpcAddress(Environment environment) {
|
||||
String subnetId = firstSubnet(environment);
|
||||
if (ec2Service == null || subnetId == null) {
|
||||
return;
|
||||
}
|
||||
String containerId;
|
||||
Collection<ContainerNetwork> networks;
|
||||
try {
|
||||
InspectContainerResponse inspect = lifecycleManager.getDockerClient()
|
||||
.inspectContainerCmd(airflowContainerName(environment)).exec();
|
||||
containerId = inspect.getId();
|
||||
networks = inspect.getNetworkSettings() == null || inspect.getNetworkSettings().getNetworks() == null
|
||||
? List.of() : inspect.getNetworkSettings().getNetworks().values();
|
||||
} catch (NotFoundException expected) {
|
||||
// The container did not outlive the restart, so there is no address to re-claim.
|
||||
return;
|
||||
for (String name : namesOf(airflowContainerName(environment))) {
|
||||
Optional<InspectContainerResponse> kept = inspectNamed(name);
|
||||
if (kept.isPresent()) {
|
||||
InspectContainerResponse inspect = kept.get();
|
||||
Collection<ContainerNetwork> networks = inspect.getNetworkSettings() == null
|
||||
|| inspect.getNetworkSettings().getNetworks() == null
|
||||
? List.of() : inspect.getNetworkSettings().getNetworks().values();
|
||||
vpcLeases.reclaim(environmentAccount(environment), regionOf(environment), subnetId, inspect.getId(),
|
||||
networks.stream().map(ContainerNetwork::getIpAddress).toList(), environment.getName());
|
||||
return;
|
||||
}
|
||||
}
|
||||
vpcLeases.reclaim(environmentAccount(environment), regionOf(environment), subnetId, containerId,
|
||||
networks.stream().map(ContainerNetwork::getIpAddress).toList(), environment.getName());
|
||||
}
|
||||
|
||||
/** Whether a live Airflow container of the account holds an address in the subnet. */
|
||||
|
||||
@@ -161,9 +161,6 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
if (!config.services().mwaa().mock()) {
|
||||
startReadinessPoller();
|
||||
startDagSyncPoller();
|
||||
for (Environment environment : allEnvironments()) {
|
||||
environmentManager.reclaimVpcAddress(environment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,9 +257,10 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
if (config.services().mwaa().mock() || !(storage instanceof AccountAwareStorageBackend<Environment> aware)) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
Set<String> unreclaimed = reclaimVpcAddresses();
|
||||
List<RestoringEnvironment> pending = new ArrayList<>();
|
||||
for (StoredEnvironment stored : storedEnvironments(aware)) {
|
||||
RestoringEnvironment restoring = prepareRestore(stored);
|
||||
RestoringEnvironment restoring = prepareRestore(stored, unreclaimed);
|
||||
if (restoring != null) {
|
||||
pending.add(restoring);
|
||||
}
|
||||
@@ -298,6 +296,26 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the containers that outlived Floci back the VPC addresses they hold, before startup goes on, so EC2 hands
|
||||
* none of them to an instance: their leases were in memory. Each environment on its own, so one Docker cannot
|
||||
* answer for stops neither startup nor any other; it is returned, by its restoring key, for its restore to try
|
||||
* again before taking its containers over.
|
||||
*/
|
||||
private Set<String> reclaimVpcAddresses() {
|
||||
Set<String> failures = new HashSet<>();
|
||||
for (Environment environment : allEnvironments()) {
|
||||
try {
|
||||
environmentManager.reclaimVpcAddress(environment);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not re-claim the VPC address of MWAA environment {0}''s Airflow container: {1}",
|
||||
environment.getName(), e.getMessage());
|
||||
failures.add(restoringKey(environment));
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
/** Every stored environment once, by the account, Region and name it belongs to, legacy keys included. */
|
||||
private Set<StoredEnvironment> storedEnvironments(AccountAwareStorageBackend<Environment> aware) {
|
||||
Set<StoredEnvironment> stored = new LinkedHashSet<>();
|
||||
@@ -312,7 +330,7 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
* Marks an environment the restore brings back, under its lock, and holds its proxy port for it; null for one it
|
||||
* leaves as it is.
|
||||
*/
|
||||
private RestoringEnvironment prepareRestore(StoredEnvironment stored) {
|
||||
private RestoringEnvironment prepareRestore(StoredEnvironment stored, Set<String> unreclaimed) {
|
||||
String key = environmentKey(stored.region(), stored.name());
|
||||
synchronized (storedEnvironmentLock(stored.accountId(), key)) {
|
||||
// Read as DescribeEnvironment reads it, which moves a record stored under a legacy key onto its key.
|
||||
@@ -328,7 +346,8 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
}
|
||||
environment.setAccountId(stored.accountId());
|
||||
RestoringEnvironment restoring = new RestoringEnvironment(stored.accountId(), key, stored.region(),
|
||||
environment, status == EnvironmentStatus.CREATING);
|
||||
environment, status == EnvironmentStatus.CREATING,
|
||||
unreclaimed.contains(restoringKey(stored.accountId(), key)));
|
||||
restoringEnvironments.add(restoring.lockKey());
|
||||
// One still DELETING was deleted during a restore Floci did not live to finish, or during its shutdown:
|
||||
// the delete stands.
|
||||
@@ -433,6 +452,11 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
*/
|
||||
private void startContainers(RestoringEnvironment restoring) {
|
||||
Environment environment = restoring.environment();
|
||||
if (restoring.unreclaimed()) {
|
||||
// Once more: a restore that cannot re-claim it either fails, rather than taking a container over with an
|
||||
// address EC2 may hand out.
|
||||
environmentManager.reclaimVpcAddress(environment);
|
||||
}
|
||||
if (environmentManager.adoptRunningEnvironment(environment)) {
|
||||
keepSecrets(restoring);
|
||||
return;
|
||||
@@ -572,11 +596,11 @@ public class MwaaService implements TagHandler, VpcDependencyProvider {
|
||||
}
|
||||
|
||||
/**
|
||||
* An environment the restore brings back, with the account, storage key and Region it is stored under, and
|
||||
* whether it was still being created.
|
||||
* An environment the restore brings back, with the account, storage key and Region it is stored under, whether it
|
||||
* was still being created, and whether the VPC address its kept container holds could not be re-claimed at startup.
|
||||
*/
|
||||
private record RestoringEnvironment(String accountId, String key, String region, Environment environment,
|
||||
boolean creating) {
|
||||
boolean creating, boolean unreclaimed) {
|
||||
String lockKey() {
|
||||
return restoringKey(accountId, key);
|
||||
}
|
||||
|
||||
@@ -261,6 +261,36 @@ class MwaaEnvironmentManagerTest {
|
||||
assertTrue(manager.holdsSubnet("000000000000", "us-east-1", "subnet-a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerAnOlderFlociNamedReclaimsItsVpcAddressAndADockerThatCannotSayThrows() {
|
||||
subnetInVpc("subnet-a", "vpc-1");
|
||||
Environment environment = environmentInSubnets("subnet-a");
|
||||
environment.setArn("arn:aws:airflow:us-east-1:000000000000:environment/vpc-env");
|
||||
DockerClient dockerClient = Mockito.mock(DockerClient.class);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
String current = manager.airflowContainerName(environment);
|
||||
String legacy = ContainerStorageHelper.legacyDockerName(config, current);
|
||||
InspectContainerCmd missing = Mockito.mock(InspectContainerCmd.class);
|
||||
when(missing.exec()).thenThrow(new NotFoundException("No such container: " + current));
|
||||
InspectContainerCmd kept = Mockito.mock(InspectContainerCmd.class);
|
||||
InspectContainerResponse response = Mockito.mock(InspectContainerResponse.class);
|
||||
NetworkSettings settings = Mockito.mock(NetworkSettings.class);
|
||||
when(dockerClient.inspectContainerCmd(current)).thenReturn(missing);
|
||||
when(dockerClient.inspectContainerCmd(legacy)).thenReturn(kept);
|
||||
when(kept.exec()).thenReturn(response);
|
||||
when(response.getId()).thenReturn("legacy-container-id");
|
||||
when(response.getNetworkSettings()).thenReturn(settings);
|
||||
when(settings.getNetworks()).thenReturn(Map.of(
|
||||
"floci-vpc-1", new ContainerNetwork().withIpv4Address("172.31.0.31")));
|
||||
when(ec2Service.reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-a", "172.31.0.31")).thenReturn(true);
|
||||
|
||||
manager.reclaimVpcAddress(environment);
|
||||
|
||||
verify(ec2Service).reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-a", "172.31.0.31");
|
||||
when(dockerClient.inspectContainerCmd(current)).thenThrow(new IllegalStateException("daemon unreachable"));
|
||||
assertThrows(IllegalStateException.class, () -> manager.reclaimVpcAddress(environment));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEnvironmentOutsideAnyVpcEc2KnowsStaysOnItsOwnNetwork() {
|
||||
airflowContainerStarts();
|
||||
|
||||
@@ -1058,6 +1058,69 @@ class MwaaServiceTest {
|
||||
.orElseThrow().getDbPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theVpcAddressesAreReclaimedOnTheStartingThreadBeforeTheRestoreGoesOn() {
|
||||
Environment first = storedEnvironment("reclaim-a-env", EnvironmentStatus.AVAILABLE);
|
||||
storedSecrets(first);
|
||||
Environment second = storedEnvironment("reclaim-b-env", EnvironmentStatus.CREATE_FAILED);
|
||||
Thread starting = Thread.currentThread();
|
||||
List<Thread> reclaimedOn = new ArrayList<>();
|
||||
Mockito.doAnswer(invocation -> {
|
||||
reclaimedOn.add(Thread.currentThread());
|
||||
return null;
|
||||
}).when(environmentManager).reclaimVpcAddress(any());
|
||||
|
||||
realModeService.restorePersistedRuntime().join();
|
||||
|
||||
assertEquals(List.of(starting, starting), reclaimedOn);
|
||||
verify(environmentManager).reclaimVpcAddress(first);
|
||||
verify(environmentManager).reclaimVpcAddress(second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReclaimThatFailedAtStartupIsTriedAgainBeforeTheTakeover() {
|
||||
Environment stored = storedEnvironment("reclaim-retried-env", EnvironmentStatus.AVAILABLE);
|
||||
storedSecrets(stored);
|
||||
Mockito.doThrow(new IllegalStateException("daemon unreachable")).doNothing()
|
||||
.when(environmentManager).reclaimVpcAddress(stored);
|
||||
|
||||
realModeService.restorePersistedRuntime().join();
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(environmentManager);
|
||||
inOrder.verify(environmentManager, Mockito.times(2)).reclaimVpcAddress(stored);
|
||||
inOrder.verify(environmentManager).adoptRunningEnvironment(stored);
|
||||
assertEquals(EnvironmentStatus.MAINTENANCE, stored("reclaim-retried-env").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEnvironmentWhoseAddressCannotBeReclaimedIsUnavailableAndTheOthersRestore() {
|
||||
Environment unreclaimable = storedEnvironment("unreclaimable-env", EnvironmentStatus.AVAILABLE);
|
||||
storedSecrets(unreclaimable);
|
||||
Environment other = storedEnvironment("reclaimable-env", EnvironmentStatus.AVAILABLE);
|
||||
storedSecrets(other);
|
||||
Mockito.doThrow(new IllegalStateException("daemon unreachable"))
|
||||
.when(environmentManager).reclaimVpcAddress(unreclaimable);
|
||||
|
||||
assertThrows(CompletionException.class, () -> realModeService.restorePersistedRuntime().join());
|
||||
|
||||
assertEquals(EnvironmentStatus.UNAVAILABLE, stored("unreclaimable-env").getStatus());
|
||||
verify(environmentManager, Mockito.never()).adoptRunningEnvironment(unreclaimable);
|
||||
verify(environmentManager).restartEnvironment(eq(other), any(), any(), any());
|
||||
assertEquals(EnvironmentStatus.MAINTENANCE, stored("reclaimable-env").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startingTheServiceAsksNothingOfDocker() {
|
||||
storedEnvironment("untouched-env", EnvironmentStatus.AVAILABLE);
|
||||
|
||||
realModeService.init();
|
||||
try {
|
||||
verify(environmentManager, Mockito.never()).reclaimVpcAddress(any());
|
||||
} finally {
|
||||
realModeService.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreInstallsTheRequirementsInTheNewContainerAsCreateDoesAndTheFirstSyncDoesNotAgain() {
|
||||
byte[] requirements = "boto3==1.35.0\n".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
Reference in new issue
Block a user