diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 9a940e6e00..246bee34a1 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -343,7 +343,15 @@ public class ContainerLifecycleManager { labels.put(CREATE_ATTEMPT_LABEL, createAttemptId); createCmd.withLabels(labels); - String containerId = createWithConflictRecovery(createCmd, spec, createAttemptId); + String containerId; + try { + containerId = createWithConflictRecovery(createCmd, spec, createAttemptId); + } catch (DockerException e) { + if (ContainerRejectedException.isRejection(e)) { + throw new ContainerRejectedException(e); + } + throw e; + } LOG.infov("Created container {0} (name={1}, not yet started)", containerId, spec.name()); return containerId; } diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerRejectedException.java b/src/main/java/io/floci/aws/core/common/docker/ContainerRejectedException.java new file mode 100644 index 0000000000..3a7369c46a --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerRejectedException.java @@ -0,0 +1,26 @@ +package io.floci.aws.core.common.docker; + +import com.github.dockerjava.api.exception.DockerException; + +/** + * The Docker daemon refused to create a container with a client error, such as an authorization + * plugin denying a host config option. Repeating the same create gets the same answer, so a + * service reports it as a non-retryable error instead of {@code InternalFailure}. + */ +public class ContainerRejectedException extends RuntimeException { + + public ContainerRejectedException(DockerException cause) { + super("Docker rejected the container create: " + cause.getMessage(), cause); + } + + /** + * Whether the daemon answered a create with a client error that a retry would get again. A + * name conflict and a missing object keep their own types, since callers recover from or + * report them, and a timeout (408) or throttling (429) stays retryable. + */ + static boolean isRejection(DockerException e) { + int status = e.getHttpStatus(); + return status >= 400 && status < 500 + && status != 404 && status != 408 && status != 409 && status != 429; + } +} diff --git a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java index 7436cb911a..066a0a4045 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.AwsQueryResponse; import io.floci.aws.core.common.AwsRegionFacts; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.XmlBuilder; +import io.floci.aws.core.common.docker.ContainerRejectedException; import io.floci.aws.services.docdb.DocDbQueryHandler; import io.floci.aws.services.neptune.NeptuneQueryHandler; import io.floci.aws.services.rds.export.RdsExportTaskService; @@ -232,6 +233,10 @@ public class RdsQueryHandler { }; } catch (AwsException e) { return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus()); + } catch (ContainerRejectedException e) { + // A 500 makes SDKs retry the same rejected create for minutes. + LOG.warnv("RDS {0} failed: {1}", action, e.getMessage()); + return AwsQueryResponse.error("InsufficientDBInstanceCapacity", e.getMessage(), AwsNamespaces.RDS, 400); } catch (Exception e) { LOG.errorv(e, "Unexpected error in RDS {0}", action); return AwsQueryResponse.error("InternalFailure", diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java index 939fe91897..fb6a14886b 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ServiceCallAuthorizer; +import io.floci.aws.core.common.docker.ContainerRejectedException; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -534,7 +535,7 @@ public class RedshiftService implements ManagedSecretRotator { clusters.put(identifier, cluster); } clusters.flush(); - throw new AwsException("InternalFailure", "Failed to start container: " + e.getMessage(), 500); + throw clusterStartFailure("Failed to start container: ", e); } clusters.put(identifier, cluster); @@ -2711,7 +2712,7 @@ public class RedshiftService implements ManagedSecretRotator { } catch (Exception e) { rollbackSnapshotRestore(cluster, proxyPort); emitClusterRestoreFailure(clusterIdentifier, snapshotIdentifier); - throw new AwsException("InternalFailure", "Failed to restore cluster from snapshot: " + e.getMessage(), 500); + throw clusterStartFailure("Failed to restore cluster from snapshot: ", e); } storeCluster(cluster); @@ -4153,6 +4154,14 @@ public class RedshiftService implements ManagedSecretRotator { private static final String CLUSTER_DB_NAME = "dev"; + private static AwsException clusterStartFailure(String context, Exception e) { + if (e instanceof ContainerRejectedException) { + // A 500 makes SDKs retry the same rejected create for minutes. + return new AwsException("InsufficientClusterCapacity", e.getMessage(), 400); + } + return new AwsException("InternalFailure", context + e.getMessage(), 500); + } + private int allocateProxyPort() { int base = config.services().redshift().proxyBasePort(); int max = config.services().redshift().proxyMaxPort(); diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerCreateRejectionTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerCreateRejectionTest.java new file mode 100644 index 0000000000..1e2134a056 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerCreateRejectionTest.java @@ -0,0 +1,119 @@ +package io.floci.aws.core.common.docker; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.exception.BadRequestException; +import com.github.dockerjava.api.exception.DockerException; +import com.github.dockerjava.api.exception.InternalServerErrorException; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.lambda.launcher.ImageCacheService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A daemon that refuses a create with a client error, such as an authorization plugin denying + * {@code HostConfig.Mounts}, refuses every retry of it too. The create reports that as a + * {@link ContainerRejectedException} so services can answer with a non-retryable error. + */ +@ExtendWith(MockitoExtension.class) +class ContainerLifecycleManagerCreateRejectionTest { + + @Mock + DockerClient dockerClient; + + @Mock + ImageCacheService imageCacheService; + + @Mock + ContainerDetector containerDetector; + + @Mock + EmulatorConfig config; + + @Mock + EmulatorConfig.DockerConfig dockerConfig; + + @Mock + EmulatorConfig.TlsConfig tlsConfig; + + @BeforeEach + void setUp() { + lenient().when(config.docker()).thenReturn(dockerConfig); + lenient().when(config.tls()).thenReturn(tlsConfig); + lenient().when(imageCacheService.ensureImageExists("busybox:stable")).thenReturn("busybox:stable"); + lenient().when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty()); + } + + @Test + void createReportsAnAuthorizationPluginDenialAsARejection() { + DockerException denied = new DockerException( + "{\"message\":\"authorization denied by plugin: --mounts is not allowed\"}", 403); + failCreateWith(denied); + + ContainerRejectedException rejected = assertThrows(ContainerRejectedException.class, + () -> manager().create(spec())); + + assertSame(denied, rejected.getCause()); + assertTrue(rejected.getMessage().contains("--mounts is not allowed"), rejected.getMessage()); + } + + @Test + void createReportsABadRequestAsARejection() { + failCreateWith(new BadRequestException("invalid mount config")); + + assertThrows(ContainerRejectedException.class, () -> manager().create(spec())); + } + + @ParameterizedTest + @ValueSource(ints = {408, 429}) + void createKeepsATimeoutOrThrottlingRetryable(int status) { + DockerException temporary = new DockerException("try again later", status); + failCreateWith(temporary); + + assertSame(temporary, assertThrows(DockerException.class, () -> manager().create(spec()))); + } + + @Test + void createKeepsADaemonErrorRetryable() { + InternalServerErrorException daemonError = new InternalServerErrorException("daemon failure"); + failCreateWith(daemonError); + + assertSame(daemonError, assertThrows(InternalServerErrorException.class, + () -> manager().create(spec()))); + } + + private void failCreateWith(DockerException failure) { + CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF); + when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd); + when(createCmd.exec()).thenThrow(failure); + } + + private static ContainerSpec spec() { + return new ContainerSpec( + "busybox:stable", "emulator-fixed-name", List.of(), null, null, null, Map.of(), + List.of(), null, List.of(), List.of(), List.of(), Map.of(), null, false, null, + List.of(), null, null, List.of()); + } + + private ContainerLifecycleManager manager() { + return new ContainerLifecycleManager( + dockerClient, imageCacheService, containerDetector, config); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java index e28b28c387..64325fcaee 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java @@ -1,7 +1,9 @@ package io.floci.aws.services.rds; +import com.github.dockerjava.api.exception.DockerException; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.docker.ContainerRejectedException; import io.floci.aws.services.docdb.DocDbQueryHandler; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.neptune.NeptuneQueryHandler; @@ -933,6 +935,26 @@ class RdsQueryHandlerTest { assertFalse(body.contains("")); } + @Test + void createDbClusterAnswersADockerRejectionWithANonRetryableCapacityError() { + when(service.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(), + any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(), + any(), anyBoolean())) + .thenThrow(new ContainerRejectedException( + new DockerException("authorization denied by plugin: --mounts is not allowed", 403))); + + MultivaluedMap p = params(); + p.add("DBClusterIdentifier", "mycluster"); + p.add("Engine", "aurora-postgresql"); + p.add("MasterUsername", "admin"); + Response response = handler.handle("CreateDBCluster", p); + + assertEquals(400, response.getStatus()); + String body = (String) response.getEntity(); + assertTrue(body.contains("InsufficientDBInstanceCapacity")); + assertTrue(body.contains("--mounts is not allowed")); + } + @Test void createDbClusterDeletesTheClusterWhenItsRolesAreRefused() { DbCluster cluster = makeCluster("mycluster"); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java index cc17a12f7c..50345c0a70 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.redshift; import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.exception.DockerException; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; @@ -8,6 +9,7 @@ import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ServiceCallAuthorizer; +import io.floci.aws.core.common.docker.ContainerRejectedException; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -955,6 +957,19 @@ class RedshiftServiceTest { verify(clusterBackend, never()).put(any(), any()); } + @Test + void createClusterAnswersADockerRejectionWithANonRetryableCapacityError() { + when(cm.start("111111111111", "c1", "admin", "pw")).thenThrow(new ContainerRejectedException( + new DockerException("authorization denied by plugin: --mounts is not allowed", 403))); + + AwsException ex = assertThrows(AwsException.class, () -> service.createCluster("c1", "dc2.large", + "admin", "pw", null, List.of(), List.of(), null)); + + assertEquals("InsufficientClusterCapacity", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + assertTrue(ex.getMessage().contains("--mounts is not allowed")); + } + @Test void createClusterStoresDefaultRoleAndConfiguresProxy() { String role = "arn:aws:iam::111111111111:role/copy";