diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index ea3acfe042..1c4382ff82 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -51,6 +51,13 @@ public class CloudFormationTemplateEngine { String resolve(String stackName, String outputName, String region, String roleArn); } + /** + * Internal attribute on a stub whose type is served by a provisioner whose service is turned + * off. The template engine reads it to refuse {@code Fn::GetAtt} on an attribute the stub + * does not have, instead of publishing the unresolved placeholder. + */ + public static final String SERVICE_DISABLED_ATTR = "__FlociServiceDisabled"; + private final String accountId; private final String region; private final String stackName; @@ -798,6 +805,11 @@ public class CloudFormationTemplateEngine { if (attrs != null && attrs.containsKey(attrName) && !attrName.startsWith("__Floci")) { return attrs.get(attrName); } + if (attrs != null && attrs.containsKey(SERVICE_DISABLED_ATTR)) { + throw new AwsException("ValidationError", "Template error: " + logicalId + + " was stubbed because its service is disabled, so attribute " + attrName + + " is unavailable.", 400); + } LOG.warnv("Unresolved GetAtt: {0}.{1}", logicalId, attrName); unresolvedIntrinsics.add("Fn::GetAtt " + logicalId + "." + attrName); return logicalId + "." + attrName; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java index 89cb7768ce..369e514c1e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java @@ -110,27 +110,45 @@ public class CfnResourceDispatcher { if (arn != null && arn.startsWith(STUB_ARN_PREFIX)) { resource.getAttributes().remove("Arn"); } + // The service is back on, so the real resource has every attribute it declares. + resource.getAttributes().remove(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR); + } else if (registry.isServiceDisabled(resourceType) && existingPhysicalId != null + && !isStub(existingPhysicalId, resource.getAttributes())) { + // A real resource a stack created while the service was on. Stubbing it would + // replace its physical id and the stack would lose the entity, so refuse instead. + throw new AwsException("ValidationError", "The service for " + resourceType + + " is disabled, so the existing resource " + existingPhysicalId + + " cannot be updated.", 400); } else if (!stubUnsupportedResourceTypesAllowed()) { // Before the physical id below is assigned, so the Cloud Control path sees a // resource with none and reports this message rather than a success. On the stack // path the catch below turns it into CREATE_FAILED with the same sentence, which // rolls the stack back. - throw new AwsException("ValidationError", unsupportedResourceTypeMessage(resourceType), 400); + throw new AwsException("ValidationError", unavailableResourceTypeMessage(resourceType), 400); } else { // Warn, not debug, and a status reason on the resource: the stub reports // CREATE_COMPLETE while creating nothing, so without both the stack is // indistinguishable from one where every resource was really provisioned. The // reason reaches DescribeStackEvents through the event CloudFormationService // already builds from it. - LOG.warnv("Stubbing unsupported resource type {0} ({1}): nothing is created " - + "for it. Set floci.services.cloudformation." - + "allow-stub-unsupported-resource-types=false to fail the " - + "stack instead.", - resourceType, logicalId); - resource.setStatusReason(unsupportedResourceTypeMessage(resourceType) + if (registry.isServiceDisabled(resourceType)) { + LOG.warnv("Stubbing resource type {0} ({1}): its service is disabled, so nothing " + + "is created for it. {2}", + resourceType, logicalId, enableServiceHint(resourceType)); + } else { + LOG.warnv("Stubbing unsupported resource type {0} ({1}): nothing is created " + + "for it. Set floci.services.cloudformation." + + "allow-stub-unsupported-resource-types=false to fail the " + + "stack instead.", + resourceType, logicalId); + } + resource.setStatusReason(unavailableResourceTypeMessage(resourceType) + " It was stubbed and nothing was created for it."); resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8)); resource.getAttributes().put("Arn", STUB_ARN_PREFIX + logicalId); + if (registry.isServiceDisabled(resourceType)) { + resource.getAttributes().put(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true"); + } } resource.setStatus("CREATE_COMPLETE"); } catch (Exception e) { @@ -173,6 +191,21 @@ public class CfnResourceDispatcher { return config == null || config.services().cloudformation().allowStubUnsupportedResourceTypes(); } + /** What Floci says about a resource type it will not provision: unsupported, or its service is off. */ + private String unavailableResourceTypeMessage(String resourceType) { + if (!registry.isServiceDisabled(resourceType)) { + return unsupportedResourceTypeMessage(resourceType); + } + return "Resource type " + resourceType + " is not provisioned because its Floci service is disabled. " + + enableServiceHint(resourceType); + } + + private String enableServiceHint(String resourceType) { + String flag = registry.serviceEnabledFlag(resourceType); + return flag == null ? "Enable the service to provision it." + : "Set " + flag + "=true to provision it."; + } + /** The one sentence Floci says about a resource type it has no provisioner for. */ private static String unsupportedResourceTypeMessage(String resourceType) { return "Resource type " + resourceType + " is not supported by Floci."; @@ -219,6 +252,12 @@ public class CfnResourceDispatcher { owner.delete(resource, region); return; } + if (registry.isServiceDisabled(resourceType) + && !isStub(resource.getPhysicalId(), resource.getAttributes())) { + // Completing this delete would drop the stack's record of an entity still there. + throw new AwsException("ValidationError", "The service for " + resourceType + + " is disabled, so " + resource.getPhysicalId() + " cannot be deleted.", 400); + } delete(resourceType, resource.getPhysicalId(), region); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java index a554a5046d..87ca06c1fa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java @@ -23,6 +23,19 @@ public interface CfnResourceProvisioner { void provision(StackResource resource, JsonNode properties, ProvisionContext ctx); + /** + * True when the service this provisioner wraps is turned off. {@link CloudFormationResourceRegistry} + * then serves none of its types, so the dispatcher stubs them instead of provisioning them. + */ + default boolean serviceDisabled() { + return false; + } + + /** The config property that turns this provisioner's service on, named in messages about it being off. */ + default String serviceEnabledFlag() { + return null; + } + /** Most implementations delegate to {@code service.deleteX(physicalId, region)}. */ default void delete(String resourceType, String physicalId, String region) { // no-op by default: some resource types have no backing delete diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java index 390e0b88ef..ed711fe8b9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java @@ -44,6 +44,29 @@ public class CloudFormationResourceRegistry { } public Optional forType(String resourceType) { + CfnResourceProvisioner provisioner = lookup(resourceType); + if (provisioner != null && provisioner.serviceDisabled()) { + return Optional.empty(); + } + return Optional.ofNullable(provisioner); + } + + /** + * Whether a provisioner exists for {@code resourceType} but its service is turned off, so + * {@link #forType} serves nothing for it: the type is stubbed, not unsupported. + */ + public boolean isServiceDisabled(String resourceType) { + CfnResourceProvisioner provisioner = lookup(resourceType); + return provisioner != null && provisioner.serviceDisabled(); + } + + /** The config property that enables the disabled service behind {@code resourceType}, or null. */ + public String serviceEnabledFlag(String resourceType) { + CfnResourceProvisioner provisioner = lookup(resourceType); + return provisioner == null ? null : provisioner.serviceEnabledFlag(); + } + + private CfnResourceProvisioner lookup(String resourceType) { CfnResourceProvisioner provisioner = byType.get(resourceType); if (provisioner == null && resourceType != null && resourceType.startsWith("Custom::")) { // Custom::* is a dynamic, unenumerable prefix, so it cannot be a registered key. An @@ -51,7 +74,7 @@ public class CloudFormationResourceRegistry { // above); only otherwise-unmatched Custom:: types fall through to the generic handler. provisioner = byType.get(CUSTOM_RESOURCE_TYPE); } - return Optional.ofNullable(provisioner); + return provisioner; } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java index 98683198d1..af69bd630d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcrCfnProvisioner.java @@ -39,6 +39,16 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { return Set.of("AWS::ECR::Repository"); } + @Override + public boolean serviceDisabled() { + return ecrService.isDisabled(); + } + + @Override + public String serviceEnabledFlag() { + return "floci.services.ecr.enabled"; + } + @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { // CDK bootstrap requires lower-case repository names; CFN-generated suffixes can include diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java index 790ff96816..33c1ce17ae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java @@ -132,6 +132,10 @@ public class EcrService implements ResourceProvider { this.registryManager.setReconcileHook(this::reconcileFromCatalog); } + public boolean isDisabled() { + return !config.services().ecr().enabled(); + } + // ============================================================ // Pull through cache rules // ============================================================ diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java index bb90d819be..0501429a92 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java @@ -124,6 +124,9 @@ public class EcrRegistryManager { if (image == null) { return null; } + if (!config.services().ecr().enabled()) { + return image; + } Matcher m = AWS_ECR_URI.matcher(image); if (!m.matches()) { return image; @@ -272,6 +275,9 @@ public class EcrRegistryManager { * @return true when the registry container is running */ public boolean tryEnsureStarted() { + if (!config.services().ecr().enabled()) { + return false; + } try { ensureStarted(); } catch (RuntimeException e) { @@ -294,6 +300,9 @@ public class EcrRegistryManager { * thread-safe. Throws if Docker is unreachable. */ public synchronized void ensureStarted() { + if (!config.services().ecr().enabled()) { + throw new IllegalStateException("ECR is disabled, the backing registry is not started"); + } if (started) { ContainerPresence presence = lifecycleManager.presenceOf(containerId); if (presence == ContainerPresence.RUNNING || presence == ContainerPresence.UNKNOWN) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java index 7dd0ca6fa1..e0b5fc9bd5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -17,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -30,6 +32,31 @@ class CloudFormationTemplateEngineTest { (Function) name -> null); } + private CloudFormationTemplateEngine engineWithAttributes(Map> attributes) { + return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack", + "stack/id", Map.of(), Map.of(), attributes, Map.of(), Map.of(), mapper, + (Function) name -> null); + } + + @Test + void getAttOnAMissingAttributeOfAStubbedDisabledServiceIsRefused() { + CloudFormationTemplateEngine e = engineWithAttributes(Map.of("Repo", Map.of( + "Arn", "arn:aws:stub:::Repo", CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true"))); + + AwsException failure = assertThrows(AwsException.class, + () -> e.resolve(json("{\"Fn::GetAtt\": [\"Repo\", \"RepositoryUri\"]}"))); + + assertEquals("ValidationError", failure.getErrorCode()); + assertEquals("arn:aws:stub:::Repo", e.resolve(json("{\"Fn::GetAtt\": [\"Repo\", \"Arn\"]}"))); + } + + @Test + void getAttOnAMissingAttributeOfAnOrdinaryStubStillResolvesToThePlaceholder() { + CloudFormationTemplateEngine e = engineWithAttributes(Map.of("Thing", Map.of("Arn", "arn:aws:stub:::Thing"))); + + assertEquals("Thing.Missing", e.resolve(json("{\"Fn::GetAtt\": [\"Thing\", \"Missing\"]}"))); + } + private JsonNode json(String s) { try { return mapper.readTree(s); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java index 9dfc15ebfd..c7a3867a04 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; +import io.github.hectorvent.floci.services.ecr.EcrService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -131,6 +132,54 @@ class CloudFormationUnsupportedResourceTypeTest { "expected the skipped delete to be reported at warn, got: " + rendered(logged)); } + private static final String ECR_TYPE = "AWS::ECR::Repository"; + private static final String ECR_DISABLED_HINT = + "Resource type AWS::ECR::Repository is not provisioned because its Floci service is disabled. " + + "Set floci.services.ecr.enabled=true to provision it."; + + @Test + void disabledEcrIsStubbedWithADisabledReasonAndWarningNamingItsFlag() { + CfnResourceDispatcher ecrDisabled = ecrDisabledDispatcher(true); + List logged = new CopyOnWriteArrayList<>(); + + StackResource resource = whileCapturingProvisionerLogs(logged, () -> ecrDisabled + .provision("Repo", ECR_TYPE, props(), engine(), REGION, ACCOUNT_ID, STACK_NAME)); + + assertEquals("CREATE_COMPLETE", resource.getStatus()); + assertEquals(ECR_DISABLED_HINT + " It was stubbed and nothing was created for it.", + resource.getStatusReason()); + assertTrue(logged.stream().anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue() + && ("Stubbing resource type AWS::ECR::Repository (Repo): its service is disabled, " + + "so nothing is created for it. Set floci.services.ecr.enabled=true to provision it.") + .equals(formatted(r))), + "expected the disabled-service warning, got: " + rendered(logged)); + assertTrue(logged.stream().noneMatch(r -> formatted(r).contains("allow-stub-unsupported-resource-types")), + "the warning must not blame the unsupported-type flag: " + rendered(logged)); + } + + @Test + void disabledEcrFailsWithTheDisabledReasonWhenTheStubIsDisallowed() { + StackResource resource = ecrDisabledDispatcher(false) + .provision("Repo", ECR_TYPE, props(), engine(), REGION, ACCOUNT_ID, STACK_NAME); + + assertEquals("CREATE_FAILED", resource.getStatus()); + assertEquals(ECR_DISABLED_HINT, resource.getStatusReason()); + assertNull(resource.getPhysicalId()); + } + + private CfnResourceDispatcher ecrDisabledDispatcher(boolean stubAllowed) { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.CloudFormationServiceConfig cloudformation = + mock(EmulatorConfig.CloudFormationServiceConfig.class); + when(config.services()).thenReturn(services); + when(services.cloudformation()).thenReturn(cloudformation); + when(cloudformation.allowStubUnsupportedResourceTypes()).thenReturn(stubAllowed); + EcrService ecr = mock(EcrService.class); + when(ecr.isDisabled()).thenReturn(true); + return CfnProvisionerFixture.builder().objectMapper(mapper).config(config).ecr(ecr).build(); + } + private CfnResourceDispatcher provisionerWithStubAllowed(boolean allowed) { EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java index b5d4a856ee..f239070512 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java @@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import org.junit.jupiter.api.Test; @@ -13,12 +15,15 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -162,6 +167,22 @@ class CfnResourceDispatcherTest { assertEquals("CREATE_COMPLETE", resource.getStatus()); } + @Test + void aProvisionerThatMigratesAStubOfADisabledServiceDropsTheDisabledMarker() { + when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> { + resource.setPhysicalId("dash-real"); + resource.getAttributes().put("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/dash-real"); + }))); + + StackResource resource = dispatcher.provision("Dash", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack", "Dash-1a2b3c4d", + Map.of("Arn", "arn:aws:stub:::Dash", CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true")); + + assertFalse(resource.getAttributes().containsKey(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR), + "the real resource must not keep refusing its own attributes"); + assertEquals("dash-real", resource.getPhysicalId()); + } + @Test void aProvisionerThatMigratesAStubAndWritesOtherAttributesStillDropsTheStubArn() { when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> @@ -226,6 +247,167 @@ class CfnResourceDispatcherTest { "thing-1".equals(r.getPhysicalId()) && "r".equals(r.getAttributes().get("Role"))), any()); } + /** + * A provisioner whose service is turned off serves none of its types: the dispatcher stubs + * the resource instead of provisioning it, so a disabled service is never reached. + */ + @Test + void aProvisionerWhoseServiceIsDisabledIsStubbedNotProvisioned() { + DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE); + CfnResourceDispatcher routed = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry( + List.of(disabled)), dynamicReferences, null); + + StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack"); + + assertFalse(disabled.provisioned, "a disabled service must not be provisioned"); + assertEquals("CREATE_COMPLETE", resource.getStatus()); + assertEquals("arn:aws:stub:::Thing", resource.getAttributes().get("Arn")); + } + + @Test + void deletingAResourceOfADisabledServiceReachesNoProvisioner() { + DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE); + CfnResourceDispatcher routed = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry( + List.of(disabled)), dynamicReferences, null); + + routed.delete(TYPE, "thing-1", "us-east-1"); + + assertFalse(disabled.deleted, "a disabled service must not be deleted from"); + } + + @Test + void aStubbedResourceOfADisabledServiceIsMarkedSoItsMissingAttributesAreRefused() { + CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE)); + + StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack"); + + assertEquals("true", resource.getAttributes().get(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR)); + } + + @Test + void updatingARealResourceWhileItsServiceIsDisabledFailsAndKeepsItsPhysicalId() { + DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE); + CfnResourceDispatcher routed = disabledDispatcher(disabled); + + StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack", "real-repo", + Map.of("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/real-repo")); + + assertEquals("CREATE_FAILED", resource.getStatus()); + assertEquals("real-repo", resource.getPhysicalId()); + assertFalse(resource.getAttributes().containsKey(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR)); + assertFalse(disabled.provisioned); + } + + @Test + void updatingAStubWhileItsServiceIsDisabledStaysStubbed() { + CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE)); + + StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack", "Thing-1a2b3c4d", + Map.of("Arn", "arn:aws:stub:::Thing", CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true")); + + assertEquals("CREATE_COMPLETE", resource.getStatus()); + assertEquals("arn:aws:stub:::Thing", resource.getAttributes().get("Arn")); + } + + @Test + void deletingARealResourceWhileItsServiceIsDisabledFailsInsteadOfDroppingIt() { + DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE); + CfnResourceDispatcher routed = disabledDispatcher(disabled); + StackResource real = new StackResource(); + real.setResourceType(TYPE); + real.setPhysicalId("real-repo"); + real.setAttributes(Map.of("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/real-repo")); + + AwsException failure = assertThrows(AwsException.class, () -> routed.delete(real, "us-east-1")); + + assertEquals(400, failure.getHttpStatus()); + assertFalse(disabled.deleted); + } + + @Test + void deletingAStubWhileItsServiceIsDisabledSucceeds() { + CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE)); + StackResource stub = new StackResource(); + stub.setResourceType(TYPE); + stub.setPhysicalId("Thing-1a2b3c4d"); + stub.setAttributes(Map.of("Arn", "arn:aws:stub:::Thing", + CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true")); + + assertDoesNotThrow(() -> routed.delete(stub, "us-east-1")); + } + + @Test + void aStubbedResourceOfADisabledServiceSaysTheServiceIsDisabledAndNamesItsFlag() { + CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE)); + + StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack"); + + assertEquals("Resource type " + TYPE + " is not provisioned because its Floci service is disabled. " + + "Set floci.services.thing.enabled=true to provision it. " + + "It was stubbed and nothing was created for it.", resource.getStatusReason()); + } + + @Test + void aDisabledServiceFailsWithTheDisabledMessageWhenStubbingIsOff() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().cloudformation().allowStubUnsupportedResourceTypes()).thenReturn(false); + CfnResourceDispatcher strict = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry( + List.of(new DisabledServiceProvisioner(TYPE))), dynamicReferences, config); + + StackResource resource = strict.provision("Thing", TYPE, mapper.createObjectNode(), null, + "us-east-1", "000000000000", "my-stack"); + + assertEquals("CREATE_FAILED", resource.getStatus()); + assertEquals("Resource type " + TYPE + " is not provisioned because its Floci service is disabled. " + + "Set floci.services.thing.enabled=true to provision it.", resource.getStatusReason()); + } + + private CfnResourceDispatcher disabledDispatcher(DisabledServiceProvisioner disabled) { + return new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(List.of(disabled)), + dynamicReferences, null); + } + + /** A provisioner whose service is disabled, recording whether it was ever asked to act. */ + private static final class DisabledServiceProvisioner implements CfnResourceProvisioner { + private final String type; + private boolean provisioned; + private boolean deleted; + + private DisabledServiceProvisioner(String type) { + this.type = type; + } + + @Override + public Set resourceTypes() { + return Set.of(type); + } + + @Override + public boolean serviceDisabled() { + return true; + } + + @Override + public String serviceEnabledFlag() { + return "floci.services.thing.enabled"; + } + + @Override + public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) { + provisioned = true; + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + deleted = true; + } + } + /** A provisioner that serves {@code type} and does nothing, for routing through a real registry. */ private static CfnResourceProvisioner serving(String type) { return new CfnResourceProvisioner() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java index d2ad4adf15..07d0728e68 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -211,6 +212,16 @@ class LeafCfnProvisionerTest { return repository; } + @Test + void servesNothingWhileTheEcrServiceIsDisabled() { + assertFalse(provisioner.serviceDisabled()); + + when(ecr.isDisabled()).thenReturn(true); + + assertTrue(provisioner.serviceDisabled()); + assertEquals("floci.services.ecr.enabled", provisioner.serviceEnabledFlag()); + } + @Test void refIsTheRepositoryNameAndGetAttExposesArnAndUri() { when(ecr.createRepository(eq("app"), any(), any(), any(), any(), any(), any(), eq(REGION))) diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java index 86ae3074b4..a7eca691b1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java @@ -125,6 +125,7 @@ class EcrRegistryManagerTest { when(ecr.registryMaxPort()).thenReturn(MAX_PORT); when(ecr.dockerNetwork()).thenReturn(Optional.empty()); when(ecr.preferLocalImages()).thenReturn(true); + when(ecr.enabled()).thenReturn(true); manager = new EcrRegistryManager(containerBuilder, lifecycleManager, logStreamer, containerDetector, currentContainerNetworkResolver, portAllocator, config, regionResolver); @@ -216,6 +217,37 @@ class EcrRegistryManagerTest { assertFalse(manager.isStarted()); } + @Test + void tryEnsureStarted_ecrDisabled_reportsUnavailableWithoutCreatingTheContainer() { + when(ecr.enabled()).thenReturn(false); + + assertFalse(manager.tryEnsureStarted()); + + assertFalse(manager.isStarted()); + verify(lifecycleManager, never()).findByName(anyString()); + verify(lifecycleManager, never()).createAndStart(any()); + } + + @Test + void ensureStarted_ecrDisabled_refusesWithoutCreatingTheContainer() { + when(ecr.enabled()).thenReturn(false); + + assertThrows(IllegalStateException.class, () -> manager.ensureStarted()); + + verify(lifecycleManager, never()).createAndStart(any()); + } + + @Test + void rewriteImageUri_ecrDisabled_returnsAwsEcrUriUnchangedWithoutStartingRegistry() { + when(ecr.enabled()).thenReturn(false); + + String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE); + + assertEquals(AWS_ECR_IMAGE, rewritten); + verify(lifecycleManager, never()).findByName(anyString()); + verify(lifecycleManager, never()).createAndStart(any()); + } + @Test void tryEnsureStarted_reportsSuccessOnceTheRegistryStarts() { when(lifecycleManager.createAndStart(any())) diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java index d529d5e6cf..2993a3deef 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java @@ -109,6 +109,7 @@ class EcrRegistryPortConflictDockerIntegrationTest { // Empty host-persistent-path selects a named volume, which memory mode removes on shutdown. when(config.storage().hostPersistentPath()).thenReturn(""); when(config.storage().mode()).thenReturn("memory"); + when(config.services().ecr().enabled()).thenReturn(true); when(config.services().ecr().registryContainerName()).thenReturn("ecr-registry"); when(config.services().ecr().registryImage()).thenReturn(TestImages.REGISTRY); when(config.services().ecr().registryBasePort()).thenReturn(basePort);