mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): clear dropped ECS service settings (#7780)
An update that drops DeploymentConfiguration from an AWS::ECS::Service now clears it. A dropped CapacityProviderStrategy or ServiceRegistries keeps the stored value, and a declared empty list clears either. A failed stabilisation puts the prior values back, and a deployment configuration the service did not have is put back as none. Signed-off-by: Oleksandr Nikolaichuk <sekator778@gmail.com>
This commit is contained in:
1 parent
c1599bd03f
commit
7ca797ff22
8 files changed
+918
-17
No files matched your search
@@ -734,13 +734,18 @@ regenerates it from AWS's published schemas, and `cfn-schema-drift.yml` compares
|
||||
A property the previous template declared and the new template drops is cleared on `UpdateStack`,
|
||||
goes back to its create default, or is kept, on the AppSync resources, the EC2 networking types
|
||||
(`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`), an
|
||||
`AWS::ApiGatewayV2::Stage` and an `AWS::EC2::Instance`. Kept: required members
|
||||
`AWS::ApiGatewayV2::Stage`, an `AWS::EC2::Instance` and an `AWS::ECS::Service`. Kept: required members
|
||||
(`AuthenticationType`, `Type`, a function's `DataSourceName`), a data source's and a function's `Name`,
|
||||
an API key's `Expires`, a GraphQL API's `ApiType` and `Visibility`, a UNIT resolver's `DataSourceName`,
|
||||
a `NatGateway`'s `PrivateIpAddress`, a `PrefixList`'s `MaxEntries`, a `Stage`'s `StageName` and an
|
||||
`Instance`'s `SecurityGroupIds`, `NetworkInterfaces` and `LaunchTemplate`. A dropped `LaunchTemplate` keeps
|
||||
the instance, but the instance type and the `MetadataOptions` members the template supplied go back to
|
||||
their defaults, and the instance profile it supplied is disassociated. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is
|
||||
their defaults, and the instance profile it supplied is disassociated. A service's `TaskDefinition`,
|
||||
`NetworkConfiguration`, `ServiceName`, `LaunchType`, `LoadBalancers`, `CapacityProviderStrategy` and
|
||||
`ServiceRegistries` are kept, and its `DesiredCount` goes back to 1. A service's dropped
|
||||
`DeploymentConfiguration` is cleared. An empty `CapacityProviderStrategy` or `ServiceRegistries` in the
|
||||
template clears it; a failed stabilisation puts the prior values back, and a deployment configuration
|
||||
the service did not have goes back to none. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is
|
||||
cleared: a running instance is stopped for the rewrite and started again, and a stopped one stays stopped.
|
||||
An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName` fails. Create-only members are
|
||||
not cleared either.
|
||||
|
||||
+38
-14
@@ -304,6 +304,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
List<Map<String, Object>> serviceRegistries =
|
||||
parseServiceRegistries(props != null ? props.get("ServiceRegistries") : null, ctx);
|
||||
|
||||
Set<String> dropped = ctx.droppedProperties(props);
|
||||
String priorName = r.getAttributes().get("Name");
|
||||
String serviceName = ctx.resolveOptional(props, "ServiceName");
|
||||
if (serviceName == null || serviceName.isBlank()) {
|
||||
@@ -317,6 +318,9 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
boolean inPlace = ctx.isUpdate() && serviceName.equals(priorName)
|
||||
&& clusterName(clusterRef).equals(clusterOfServiceArn(ctx.priorPhysicalId()));
|
||||
UpdateServiceRequest restore;
|
||||
boolean clearDeploymentConfiguration = false;
|
||||
boolean restoreDeploymentConfiguration = false;
|
||||
Map<String, Object> priorDeploymentConfiguration = null;
|
||||
if (inPlace) {
|
||||
UpdateServiceRequest update = new UpdateServiceRequest();
|
||||
update.setCluster(clusterRef);
|
||||
@@ -325,10 +329,17 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
update.setDesiredCount(desiredCount);
|
||||
update.setNetworkConfiguration(networkConfiguration);
|
||||
update.setDeploymentConfiguration(deploymentConfiguration);
|
||||
// A dropped strategy or registries stay null, so the stored value stays; only a declared empty list clears it.
|
||||
update.setCapacityProviderStrategy(capacityProviderStrategy);
|
||||
update.setServiceRegistries(serviceRegistries);
|
||||
clearDeploymentConfiguration = deploymentConfiguration == null
|
||||
&& dropped.contains("DeploymentConfiguration");
|
||||
// Built before updateService, which changes this same model in place.
|
||||
restore = restoreRequest(update, ecsService.serviceByArn(ctx.priorPhysicalId()));
|
||||
EcsServiceModel prior = ecsService.serviceByArn(ctx.priorPhysicalId());
|
||||
restore = restoreRequest(update, prior);
|
||||
priorDeploymentConfiguration = prior == null ? null : prior.getDeploymentConfiguration();
|
||||
restoreDeploymentConfiguration = prior != null
|
||||
&& (deploymentConfiguration != null || clearDeploymentConfiguration);
|
||||
svc = ecsService.updateService(update, ctx.region());
|
||||
} else {
|
||||
CreateServiceRequest create = new CreateServiceRequest();
|
||||
@@ -340,7 +351,8 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
create.setLoadBalancers(loadBalancers);
|
||||
create.setNetworkConfiguration(networkConfiguration);
|
||||
create.setDeploymentConfiguration(deploymentConfiguration);
|
||||
create.setCapacityProviderStrategy(capacityProviderStrategy);
|
||||
create.setCapacityProviderStrategy(
|
||||
capacityProviderStrategy != null && capacityProviderStrategy.isEmpty() ? null : capacityProviderStrategy);
|
||||
create.setServiceRegistries(serviceRegistries);
|
||||
restore = null;
|
||||
svc = ecsService.createService(create, ctx.region());
|
||||
@@ -350,11 +362,25 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("Name", svc.getServiceName());
|
||||
r.getAttributes().put("ServiceArn", svc.getServiceArn());
|
||||
if (inPlace) {
|
||||
String service = serviceName;
|
||||
boolean clearedDeploymentConfiguration = clearDeploymentConfiguration;
|
||||
boolean restoredDeploymentConfiguration = restoreDeploymentConfiguration;
|
||||
Map<String, Object> priorConfiguration = priorDeploymentConfiguration;
|
||||
try {
|
||||
if (clearedDeploymentConfiguration) {
|
||||
ecsService.replaceServiceDeploymentConfiguration(clusterRef, service, null, ctx.region());
|
||||
}
|
||||
ecsService.awaitServiceStable(svc);
|
||||
} catch (RuntimeException failure) {
|
||||
restoreInPlace(r, failure, () -> ecsService.awaitServiceStable(
|
||||
ecsService.updateService(restore, ctx.region())));
|
||||
restoreInPlace(r, failure, () -> {
|
||||
EcsServiceModel restored = ecsService.updateService(restore, ctx.region());
|
||||
// After updateService, so the exact prior value, none included, is what stays.
|
||||
if (restoredDeploymentConfiguration) {
|
||||
ecsService.replaceServiceDeploymentConfiguration(
|
||||
clusterRef, service, priorConfiguration, ctx.region());
|
||||
}
|
||||
ecsService.awaitServiceStable(restored);
|
||||
});
|
||||
throw failure;
|
||||
}
|
||||
} else {
|
||||
@@ -364,11 +390,12 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
/**
|
||||
* The update that puts {@code prior} back on what {@code update} changed: its task definition,
|
||||
* desired count and network configuration, and each setting the update declared. A deployment
|
||||
* configuration, capacity provider strategy or service registries the service did not have are
|
||||
* put back empty, so a registry the update added is deregistered; a setting the update left
|
||||
* unchanged is left unchanged again, so the restore rolls no deployment for registries nobody
|
||||
* touched.
|
||||
* desired count and network configuration, and each setting the update declared. A capacity
|
||||
* provider strategy or service registries the service did not have are put back empty, so a
|
||||
* registry the update added is deregistered; a setting the update left unchanged is left
|
||||
* unchanged again, so the restore rolls no deployment for registries nobody touched. The
|
||||
* deployment configuration is not here: updateService cannot put back none, so the caller
|
||||
* restores it exactly through replaceServiceDeploymentConfiguration.
|
||||
*/
|
||||
private static UpdateServiceRequest restoreRequest(UpdateServiceRequest update, EcsServiceModel prior) {
|
||||
UpdateServiceRequest restore = new UpdateServiceRequest();
|
||||
@@ -380,9 +407,6 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
restore.setTaskDefinition(prior.getTaskDefinition());
|
||||
restore.setDesiredCount(prior.getDesiredCount());
|
||||
restore.setNetworkConfiguration(prior.getNetworkConfiguration());
|
||||
if (update.getDeploymentConfiguration() != null) {
|
||||
restore.setDeploymentConfiguration(Objects.requireNonNullElse(prior.getDeploymentConfiguration(), Map.of()));
|
||||
}
|
||||
if (update.getCapacityProviderStrategy() != null) {
|
||||
restore.setCapacityProviderStrategy(Objects.requireNonNullElse(prior.getCapacityProviderStrategy(), List.of()));
|
||||
}
|
||||
@@ -749,7 +773,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** As the ECS handler reads it: an empty strategy is none. */
|
||||
/** An empty list stays empty: an update clears the strategy with it, a create treats it as none. */
|
||||
private static List<CapacityProviderStrategyItem> parseCapacityProviderStrategy(JsonNode node,
|
||||
ProvisionContext ctx) {
|
||||
JsonNode resolved = ctx.engine().resolveNode(node);
|
||||
@@ -764,7 +788,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
item.path("Weight").asInt(0), item.path("Base").asInt(0)));
|
||||
}
|
||||
}
|
||||
return result.isEmpty() ? null : result;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2945,6 +2945,34 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return updateService(request, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the deployment configuration exactly as given, null included, and starts no deployment.
|
||||
* UpdateService keeps a configuration the request leaves out, so it cannot remove one that
|
||||
* CloudFormation dropped.
|
||||
*/
|
||||
public EcsServiceModel replaceServiceDeploymentConfiguration(String clusterRef, String serviceName,
|
||||
Map<String, Object> deploymentConfiguration,
|
||||
String region) {
|
||||
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
|
||||
String name = extractServiceName(serviceName);
|
||||
String key = serviceKey(region, cluster.getClusterName(), name);
|
||||
synchronized (serviceLock(key)) {
|
||||
EcsServiceModel svc = services.get(key);
|
||||
if (svc == null) {
|
||||
throw new AwsException("ServiceNotFoundException", "Service " + name + " not found.", 404);
|
||||
}
|
||||
synchronized (svc) {
|
||||
if ("INACTIVE".equals(svc.getStatus())) {
|
||||
throw new AwsException("ServiceNotActiveException",
|
||||
"Service " + name + " is not active.", 400);
|
||||
}
|
||||
svc.setDeploymentConfiguration(deploymentConfiguration);
|
||||
services.put(key, svc);
|
||||
return svc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public EcsServiceModel updateService(UpdateServiceRequest request, String region) {
|
||||
EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region);
|
||||
|
||||
|
||||
+246
@@ -12,10 +12,14 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.floci.aws.testing.CfnRequests.cfn;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@@ -100,6 +104,62 @@ class CloudFormationEcsForwardedSettingsIntegrationTest {
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGISTRIES_SETTING =
|
||||
"\"ServiceRegistries\": [{\"RegistryArn\": {\"Fn::GetAtt\": [\"Registry\", \"Arn\"]}}]";
|
||||
private static final String STRATEGY_SETTING =
|
||||
"\"CapacityProviderStrategy\": [{\"CapacityProvider\": \"FARGATE\", \"Weight\": 2}]";
|
||||
private static final String DEPLOYMENT_SETTING =
|
||||
"\"DeploymentConfiguration\": {\"MaximumPercent\": 150, \"MinimumHealthyPercent\": 0}";
|
||||
private static final String NO_VALUE_DEPLOYMENT_SETTING = "\"DeploymentConfiguration\": "
|
||||
+ "{\"Fn::If\": [\"Never\", {\"MaximumPercent\": 150}, {\"Ref\": \"AWS::NoValue\"}]}";
|
||||
private static final String NO_VALUE_REGISTRIES_SETTING = "\"ServiceRegistries\": "
|
||||
+ "{\"Fn::If\": [\"Never\", [{\"RegistryArn\": {\"Fn::GetAtt\": [\"Registry\", \"Arn\"]}}], {\"Ref\": \"AWS::NoValue\"}]}";
|
||||
private static final String NO_VALUE_STRATEGY_SETTING = "\"CapacityProviderStrategy\": "
|
||||
+ "{\"Fn::If\": [\"Never\", [{\"CapacityProvider\": \"FARGATE\", \"Weight\": 2}], {\"Ref\": \"AWS::NoValue\"}]}";
|
||||
private static final String OUTSIDE_REGISTRY_ARN = "arn:aws:servicediscovery:us-east-1:000000000000:service/srv-9";
|
||||
|
||||
/** A service that declares only the settings spliced into %4$s, so a test controls which of the three it declares. */
|
||||
private static final String SERVICE_TEMPLATE = """
|
||||
{
|
||||
"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
|
||||
"Resources": {
|
||||
"Namespace": {
|
||||
"Type": "AWS::ServiceDiscovery::HttpNamespace",
|
||||
"Properties": {"Name": "%1$s"}
|
||||
},
|
||||
"Registry": {
|
||||
"Type": "AWS::ServiceDiscovery::Service",
|
||||
"Properties": {"Name": "app", "NamespaceId": {"Ref": "Namespace"}}
|
||||
},
|
||||
"Cluster": {
|
||||
"Type": "AWS::ECS::Cluster",
|
||||
"Properties": {"ClusterName": "%1$s"}
|
||||
},
|
||||
"TaskDef": {
|
||||
"Type": "AWS::ECS::TaskDefinition",
|
||||
"Properties": {
|
||||
"Family": "%1$s-td",
|
||||
"Cpu": "256",
|
||||
"Memory": "512",
|
||||
"NetworkMode": "awsvpc",
|
||||
"RequiresCompatibilities": ["FARGATE"],
|
||||
"ContainerDefinitions": [{"Name": "app", "Image": "app:v1"}]
|
||||
}
|
||||
},
|
||||
"Service": {
|
||||
"Type": "AWS::ECS::Service",
|
||||
"Properties": {
|
||||
"ServiceName": "%1$s-svc",
|
||||
"Cluster": {"Ref": "Cluster"},
|
||||
"TaskDefinition": {"Ref": "TaskDef"},
|
||||
"DesiredCount": %3$d,
|
||||
"NetworkConfiguration": {"AwsvpcConfiguration": {"Subnets": ["%2$s"]}}%4$s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@@ -154,6 +214,192 @@ class CloudFormationEcsForwardedSettingsIntegrationTest {
|
||||
.body("services[0].serviceRegistries[0].registryArn", containsString(":servicediscovery:us-east-1:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_droppedServiceRegistries_keepTheStoredRegistries() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, REGISTRIES_SETTING, STRATEGY_SETTING, DEPLOYMENT_SETTING);
|
||||
describeService(name).body("services[0].serviceRegistries[0].registryArn", containsString(":servicediscovery:"));
|
||||
|
||||
updateServiceStack(name, 1, STRATEGY_SETTING, DEPLOYMENT_SETTING);
|
||||
|
||||
describeService(name)
|
||||
.body("services[0].serviceRegistries[0].registryArn", containsString(":servicediscovery:"))
|
||||
.body("services[0].capacityProviderStrategy[0].weight", equalTo(2))
|
||||
.body("services[0].deploymentConfiguration.maximumPercent", equalTo(150));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_droppedCapacityProviderStrategy_keepTheStoredStrategy() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, REGISTRIES_SETTING, STRATEGY_SETTING, DEPLOYMENT_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, REGISTRIES_SETTING, DEPLOYMENT_SETTING);
|
||||
|
||||
describeService(name)
|
||||
.body("services[0].capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE"))
|
||||
.body("services[0].capacityProviderStrategy[0].weight", equalTo(2))
|
||||
.body("services[0].serviceRegistries[0].registryArn", containsString(":servicediscovery:"))
|
||||
.body("services[0].deploymentConfiguration.maximumPercent", equalTo(150));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_droppedDeploymentConfiguration_isReadBackAsNeverSet() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, REGISTRIES_SETTING, STRATEGY_SETTING, DEPLOYMENT_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, REGISTRIES_SETTING, STRATEGY_SETTING);
|
||||
|
||||
describeService(name)
|
||||
.body("services[0]", not(hasKey("deploymentConfiguration")))
|
||||
.body("services[0].capacityProviderStrategy[0].weight", equalTo(2))
|
||||
.body("services[0].serviceRegistries[0].registryArn", containsString(":servicediscovery:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_deploymentConfigurationChosenAsNoValue_isReadBackAsNeverSet() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, DEPLOYMENT_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, NO_VALUE_DEPLOYMENT_SETTING);
|
||||
|
||||
describeService(name).body("services[0]", not(hasKey("deploymentConfiguration")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_serviceRegistriesChosenAsNoValue_keepTheStoredRegistries() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, REGISTRIES_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, NO_VALUE_REGISTRIES_SETTING);
|
||||
|
||||
describeService(name).body("services[0].serviceRegistries[0].registryArn", containsString(":servicediscovery:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_capacityProviderStrategyChosenAsNoValue_keepTheStoredStrategy() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, STRATEGY_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, NO_VALUE_STRATEGY_SETTING);
|
||||
|
||||
describeService(name)
|
||||
.body("services[0].capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE"))
|
||||
.body("services[0].capacityProviderStrategy[0].weight", equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_strategyDeclaredDirectlyAsNoValue_keepsTheStoredStrategy() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, STRATEGY_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, "\"CapacityProviderStrategy\": {\"Ref\": \"AWS::NoValue\"}");
|
||||
|
||||
describeService(name).body("services[0].capacityProviderStrategy[0].weight", equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_emptyStrategyAndEmptyRegistries_clearBoth() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, REGISTRIES_SETTING, STRATEGY_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, "\"ServiceRegistries\": []", "\"CapacityProviderStrategy\": []");
|
||||
|
||||
describeService(name)
|
||||
.body("services[0].serviceRegistries", nullValue())
|
||||
.body("services[0].capacityProviderStrategy", nullValue())
|
||||
.body("services[0].launchType", equalTo("FARGATE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_emptyDeploymentConfiguration_isStoredAsGivenAndClearedWhenDroppedLater() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, DEPLOYMENT_SETTING);
|
||||
|
||||
updateServiceStack(name, 1, "\"DeploymentConfiguration\": {}");
|
||||
describeService(name).body("services[0].deploymentConfiguration", equalTo(Map.of()));
|
||||
|
||||
updateServiceStack(name, 1);
|
||||
describeService(name).body("services[0]", not(hasKey("deploymentConfiguration")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_settingsSetThroughTheApi_surviveAnUpdateThatStillDoesNotDeclareThem() {
|
||||
String name = stackName();
|
||||
createServiceStack(name);
|
||||
ecs("UpdateService", """
|
||||
{"cluster": "%1$s", "service": "%1$s-svc",
|
||||
"deploymentConfiguration": {"maximumPercent": 111},
|
||||
"capacityProviderStrategy": [{"capacityProvider": "FARGATE_SPOT", "weight": 1}],
|
||||
"serviceRegistries": [{"registryArn": "%2$s"}]}
|
||||
""".formatted(name, OUTSIDE_REGISTRY_ARN));
|
||||
|
||||
updateServiceStack(name, 2);
|
||||
|
||||
describeService(name)
|
||||
.body("services[0].desiredCount", equalTo(2))
|
||||
.body("services[0].deploymentConfiguration.maximumPercent", equalTo(111))
|
||||
.body("services[0].capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE_SPOT"))
|
||||
.body("services[0].serviceRegistries[0].registryArn", equalTo(OUTSIDE_REGISTRY_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_droppingOneSetting_leavesASettingSetThroughTheApiAlone() {
|
||||
String name = stackName();
|
||||
createServiceStack(name, DEPLOYMENT_SETTING);
|
||||
ecs("UpdateService", """
|
||||
{"cluster": "%1$s", "service": "%1$s-svc",
|
||||
"capacityProviderStrategy": [{"capacityProvider": "FARGATE_SPOT", "weight": 1}]}
|
||||
""".formatted(name));
|
||||
|
||||
updateServiceStack(name, 1);
|
||||
|
||||
describeService(name)
|
||||
.body("services[0]", not(hasKey("deploymentConfiguration")))
|
||||
.body("services[0].capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE_SPOT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_droppedDesiredCount_setsTheDesiredCountToOne() {
|
||||
String name = stackName();
|
||||
submitService("CreateStack", name, 3);
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
|
||||
describeService(name).body("services[0].desiredCount", equalTo(3));
|
||||
|
||||
submitTemplate("UpdateStack", name, serviceTemplate(name, 0).replace("\"DesiredCount\": 0,", ""));
|
||||
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
|
||||
|
||||
describeService(name).body("services[0].desiredCount", equalTo(1));
|
||||
}
|
||||
|
||||
private void createServiceStack(String name, String... settings) {
|
||||
submitService("CreateStack", name, 1, settings);
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
|
||||
}
|
||||
|
||||
private void updateServiceStack(String name, int desiredCount, String... settings) {
|
||||
submitService("UpdateStack", name, desiredCount, settings);
|
||||
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
|
||||
}
|
||||
|
||||
/** Submits SERVICE_TEMPLATE whose service declares exactly {@code settings} besides its fixed properties. */
|
||||
private static void submitService(String action, String stackName, int desiredCount, String... settings) {
|
||||
submitTemplate(action, stackName, serviceTemplate(stackName, desiredCount, settings));
|
||||
}
|
||||
|
||||
private static String serviceTemplate(String stackName, int desiredCount, String... settings) {
|
||||
String declared = List.of(settings).stream().map(setting -> ", " + setting).collect(Collectors.joining());
|
||||
return SERVICE_TEMPLATE.formatted(stackName, Ec2Service.defaultSubnetId("us-east-1", "a"), desiredCount, declared);
|
||||
}
|
||||
|
||||
private static void submitTemplate(String action, String stackName, String template) {
|
||||
cfn(action, stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_healthCheckWithoutACommand_failsAsRegisterTaskDefinitionDoes() {
|
||||
String name = stackName();
|
||||
|
||||
+19
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
@@ -16,7 +17,9 @@ import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.everyItem;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
@@ -213,6 +216,22 @@ class CloudFormationEcsServiceStableIntegrationTest {
|
||||
equalTo(List.of(subnet)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStack_ecsServiceThatCannotStabilize_isReadBackWithoutTheDeploymentConfigurationItNeverHad() {
|
||||
String name = "cfn-stable-dc-" + Long.toString(System.nanoTime(), 36);
|
||||
String subnet = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
stackCall("CreateStack", name, AWSVPC_TEMPLATE.formatted(name, 1, subnet));
|
||||
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
|
||||
|
||||
stackCall("UpdateStack", name, AWSVPC_TEMPLATE.formatted(name, 1, "subnet-does-not-exist")
|
||||
.replace("\"LaunchType\": \"FARGATE\",",
|
||||
"\"LaunchType\": \"FARGATE\", \"DeploymentConfiguration\": {\"MaximumPercent\": 150},"));
|
||||
CfnStackWaits.awaitStatus(name, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
Map<String, Object> service = describeService(name).path("services[0]");
|
||||
assertThat(service, not(hasKey("deploymentConfiguration")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_awsvpcServiceWithSubnetListParameterUnderFnIf_usesEverySubnet() {
|
||||
String name = "cfn-stable-list-" + Long.toString(System.nanoTime(), 36);
|
||||
|
||||
+414
-1
@@ -1251,13 +1251,426 @@ class EcsCfnProvisionerTest {
|
||||
verify(ecs, times(2)).updateService(requests.capture(), eq(REGION));
|
||||
UpdateServiceRequest restore = requests.getAllValues().get(1);
|
||||
assertEquals(1, restore.getDesiredCount());
|
||||
assertEquals(Map.of(), restore.getDeploymentConfiguration(), "a deployment configuration the update added is removed");
|
||||
assertNull(restore.getDeploymentConfiguration(), "the restore request leaves the deployment configuration to the sibling");
|
||||
// A deployment configuration the update added is removed: the sibling puts back the prior value, here none.
|
||||
verify(ecs).replaceServiceDeploymentConfiguration(eq("web"), eq("front"), isNull(), eq(REGION));
|
||||
assertEquals(priorStrategy, restore.getCapacityProviderStrategy());
|
||||
assertEquals(List.of(), restore.getServiceRegistries(), "a registry the update added is deregistered");
|
||||
verify(ecs).awaitServiceStable(restored);
|
||||
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
|
||||
}
|
||||
|
||||
private static final String SERVICE_REGISTRIES = "ServiceRegistries";
|
||||
private static final String CAPACITY_PROVIDER_STRATEGY = "CapacityProviderStrategy";
|
||||
private static final String DEPLOYMENT_CONFIGURATION_PROPERTY = "DeploymentConfiguration";
|
||||
private static final List<String> SETTINGS =
|
||||
List.of(SERVICE_REGISTRIES, CAPACITY_PROVIDER_STRATEGY, DEPLOYMENT_CONFIGURATION_PROPERTY);
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {
|
||||
ProvisionContext base = ctx(priorPhysicalId);
|
||||
return new ProvisionContext(base.engine(), REGION, "000000000000", "my-stack", priorPhysicalId,
|
||||
event -> {}, priorProperties);
|
||||
}
|
||||
|
||||
private ObjectNode serviceProps() {
|
||||
return mapper.createObjectNode().put("Cluster", "web").put("ServiceName", "front")
|
||||
.put("TaskDefinition", TASK_DEF_ARN);
|
||||
}
|
||||
|
||||
/** The service properties plus the named ones of the three settings, with the values of {@link #withServiceSettings}. */
|
||||
private ObjectNode declaring(String... settings) {
|
||||
ObjectNode all = withServiceSettings(serviceProps());
|
||||
List<String> kept = new ArrayList<>(List.of("Cluster", "ServiceName", "TaskDefinition"));
|
||||
kept.addAll(List.of(settings));
|
||||
all.retain(kept);
|
||||
return all;
|
||||
}
|
||||
|
||||
private ObjectNode declaringExcept(String dropped) {
|
||||
return declaring(SETTINGS.stream().filter(name -> !name.equals(dropped)).toArray(String[]::new));
|
||||
}
|
||||
|
||||
private StackResource existingService() {
|
||||
StackResource r = resource("AWS::ECS::Service", "Service");
|
||||
r.getAttributes().put("Name", "front");
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Runs an in-place update of the service from {@code prior} to {@code props} and returns the one UpdateService request sent. */
|
||||
private UpdateServiceRequest updateFrom(ObjectNode prior, ObjectNode props) {
|
||||
when(ecs.updateService(any(UpdateServiceRequest.class), eq(REGION))).thenReturn(service("front"));
|
||||
|
||||
provisioner.provision(existingService(), props, ctx(SERVICE_ARN, prior));
|
||||
|
||||
ArgumentCaptor<UpdateServiceRequest> request = ArgumentCaptor.forClass(UpdateServiceRequest.class);
|
||||
verify(ecs).updateService(request.capture(), eq(REGION));
|
||||
return request.getValue();
|
||||
}
|
||||
|
||||
private void verifyNoDeploymentConfigurationReplacement() {
|
||||
verify(ecs, never()).replaceServiceDeploymentConfiguration(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedServiceRegistriesIsLeftOutOfTheRequestSoTheStoredOnesStay() {
|
||||
UpdateServiceRequest request = updateFrom(declaring(SERVICE_REGISTRIES), serviceProps());
|
||||
|
||||
assertNull(request.getServiceRegistries(), "dropped registries are not deregistered");
|
||||
assertNull(request.getCapacityProviderStrategy());
|
||||
assertNull(request.getDeploymentConfiguration());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedCapacityProviderStrategyIsLeftOutOfTheRequestSoTheStoredOneStays() {
|
||||
UpdateServiceRequest request = updateFrom(declaring(CAPACITY_PROVIDER_STRATEGY), serviceProps());
|
||||
|
||||
assertNull(request.getCapacityProviderStrategy(), "a dropped strategy is not removed");
|
||||
assertNull(request.getServiceRegistries());
|
||||
assertNull(request.getDeploymentConfiguration());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedDeploymentConfigurationIsReplacedWithNull() {
|
||||
updateFrom(declaring(DEPLOYMENT_CONFIGURATION_PROPERTY), serviceProps());
|
||||
|
||||
verify(ecs).replaceServiceDeploymentConfiguration(eq("web"), eq("front"), isNull(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyStrategyInTheTemplateClearsTheStrategyOnUpdate() {
|
||||
ObjectNode props = serviceProps();
|
||||
props.putArray(CAPACITY_PROVIDER_STRATEGY);
|
||||
|
||||
UpdateServiceRequest request = updateFrom(declaring(CAPACITY_PROVIDER_STRATEGY), props);
|
||||
|
||||
assertEquals(List.of(), request.getCapacityProviderStrategy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyStrategyClearsTheStrategyEvenWhenThePriorTemplateDidNotDeclareIt() {
|
||||
ObjectNode props = serviceProps();
|
||||
props.putArray(CAPACITY_PROVIDER_STRATEGY);
|
||||
|
||||
UpdateServiceRequest request = updateFrom(serviceProps(), props);
|
||||
|
||||
assertEquals(List.of(), request.getCapacityProviderStrategy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyServiceRegistriesListInTheTemplateClearsTheRegistries() {
|
||||
ObjectNode props = serviceProps();
|
||||
props.putArray(SERVICE_REGISTRIES);
|
||||
|
||||
UpdateServiceRequest request = updateFrom(declaring(SERVICE_REGISTRIES), props);
|
||||
|
||||
assertEquals(List.of(), request.getServiceRegistries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStrategyAndRegistriesDroppedTogetherBothStay() {
|
||||
UpdateServiceRequest request = updateFrom(declaring(SERVICE_REGISTRIES, CAPACITY_PROVIDER_STRATEGY), serviceProps());
|
||||
|
||||
assertNull(request.getServiceRegistries());
|
||||
assertNull(request.getCapacityProviderStrategy());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyStrategyAndAnEmptyRegistriesListDeclaredTogetherClearBoth() {
|
||||
ObjectNode props = serviceProps();
|
||||
props.putArray(CAPACITY_PROVIDER_STRATEGY);
|
||||
props.putArray(SERVICE_REGISTRIES);
|
||||
|
||||
UpdateServiceRequest request = updateFrom(declaring(SERVICE_REGISTRIES, CAPACITY_PROVIDER_STRATEGY), props);
|
||||
|
||||
assertEquals(List.of(), request.getCapacityProviderStrategy());
|
||||
assertEquals(List.of(), request.getServiceRegistries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyServiceRegistriesListClearsTheRegistriesEvenWhenThePriorTemplateDidNotDeclareThem() {
|
||||
ObjectNode props = serviceProps();
|
||||
props.putArray(SERVICE_REGISTRIES);
|
||||
|
||||
UpdateServiceRequest request = updateFrom(serviceProps(), props);
|
||||
|
||||
assertEquals(List.of(), request.getServiceRegistries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyDeploymentConfigurationObjectIsAppliedAsGiven() {
|
||||
ObjectNode props = serviceProps();
|
||||
props.putObject(DEPLOYMENT_CONFIGURATION_PROPERTY);
|
||||
|
||||
UpdateServiceRequest request = updateFrom(declaring(DEPLOYMENT_CONFIGURATION_PROPERTY), props);
|
||||
|
||||
assertEquals(Map.of(), request.getDeploymentConfiguration());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeploymentConfigurationDeclaredEmptyIsReplacedWithNullWhenItIsDropped() {
|
||||
ObjectNode prior = serviceProps();
|
||||
prior.putObject(DEPLOYMENT_CONFIGURATION_PROPERTY);
|
||||
|
||||
updateFrom(prior, serviceProps());
|
||||
|
||||
verify(ecs).replaceServiceDeploymentConfiguration(eq("web"), eq("front"), isNull(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangedValueOfEachSettingIsAppliedAndNothingIsCleared() {
|
||||
ObjectNode prior = serviceProps();
|
||||
prior.putArray(SERVICE_REGISTRIES).addObject().put("RegistryArn", REGISTRY_ARN + "-old");
|
||||
prior.putObject(DEPLOYMENT_CONFIGURATION_PROPERTY).put("MaximumPercent", "100");
|
||||
prior.putArray(CAPACITY_PROVIDER_STRATEGY).addObject()
|
||||
.put("CapacityProvider", "FARGATE_SPOT").put("Weight", "1");
|
||||
|
||||
UpdateServiceRequest request = updateFrom(prior, declaring(SETTINGS.toArray(String[]::new)));
|
||||
|
||||
assertEquals(REGISTRIES, request.getServiceRegistries());
|
||||
assertEquals(DEPLOYMENT_CONFIGURATION, request.getDeploymentConfiguration());
|
||||
assertEquals(STRATEGY, request.getCapacityProviderStrategy());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {SERVICE_REGISTRIES, CAPACITY_PROVIDER_STRATEGY, DEPLOYMENT_CONFIGURATION_PROPERTY})
|
||||
void droppingOneSettingLeavesTheOtherTwoAsDeclared(String dropped) {
|
||||
UpdateServiceRequest request = updateFrom(declaring(SETTINGS.toArray(String[]::new)), declaringExcept(dropped));
|
||||
|
||||
if (!SERVICE_REGISTRIES.equals(dropped)) {
|
||||
assertEquals(REGISTRIES, request.getServiceRegistries(), "registries stay as declared");
|
||||
}
|
||||
if (!CAPACITY_PROVIDER_STRATEGY.equals(dropped)) {
|
||||
assertEquals(STRATEGY, request.getCapacityProviderStrategy(), "strategy stays as declared");
|
||||
}
|
||||
if (!DEPLOYMENT_CONFIGURATION_PROPERTY.equals(dropped)) {
|
||||
assertEquals(DEPLOYMENT_CONFIGURATION, request.getDeploymentConfiguration(),
|
||||
"deployment configuration stays as declared");
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
} else {
|
||||
verify(ecs).replaceServiceDeploymentConfiguration(eq("web"), eq("front"), isNull(), eq(REGION));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsNoTemplateEverDeclaredAreNotSentByAnUpdate() {
|
||||
UpdateServiceRequest request = updateFrom(serviceProps(), serviceProps());
|
||||
|
||||
assertNull(request.getServiceRegistries(), "registries set outside the stack survive");
|
||||
assertNull(request.getCapacityProviderStrategy(), "strategy set outside the stack survives");
|
||||
assertNull(request.getDeploymentConfiguration(), "deployment configuration set outside the stack survives");
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {SERVICE_REGISTRIES, CAPACITY_PROVIDER_STRATEGY, DEPLOYMENT_CONFIGURATION_PROPERTY})
|
||||
void aSettingTheStackNeverDeclaredSurvivesTheDropOfAnotherOne(String dropped) {
|
||||
UpdateServiceRequest request = updateFrom(declaring(dropped), serviceProps());
|
||||
|
||||
if (!SERVICE_REGISTRIES.equals(dropped)) {
|
||||
assertNull(request.getServiceRegistries(), "registries set outside the stack survive");
|
||||
}
|
||||
if (!CAPACITY_PROVIDER_STRATEGY.equals(dropped)) {
|
||||
assertNull(request.getCapacityProviderStrategy(), "strategy set outside the stack survives");
|
||||
}
|
||||
if (!DEPLOYMENT_CONFIGURATION_PROPERTY.equals(dropped)) {
|
||||
assertNull(request.getDeploymentConfiguration(), "deployment configuration set outside the stack survives");
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedTaskDefinitionAndNetworkConfigurationLeaveTheStoredValues() {
|
||||
ObjectNode prior = serviceProps();
|
||||
prior.putObject("NetworkConfiguration").putObject("AwsvpcConfiguration").putArray("Subnets").add("subnet-1");
|
||||
ObjectNode props = mapper.createObjectNode().put("Cluster", "web").put("ServiceName", "front");
|
||||
|
||||
UpdateServiceRequest request = updateFrom(prior, props);
|
||||
|
||||
assertNull(request.getTaskDefinition());
|
||||
assertNull(request.getNetworkConfiguration());
|
||||
assertNull(request.getServiceRegistries());
|
||||
assertNull(request.getCapacityProviderStrategy());
|
||||
assertNull(request.getDeploymentConfiguration());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateClearsNothingEvenWhenThePriorTemplateDeclaredTheSettings() {
|
||||
when(ecs.createService(any(CreateServiceRequest.class), eq(REGION))).thenReturn(service("front"));
|
||||
|
||||
// A resource the previous template had under another physical id counts as a create here.
|
||||
provisioner.provision(resource("AWS::ECS::Service", "Service"), serviceProps(),
|
||||
ctx(null, declaring(SETTINGS.toArray(String[]::new))));
|
||||
|
||||
ArgumentCaptor<CreateServiceRequest> request = ArgumentCaptor.forClass(CreateServiceRequest.class);
|
||||
verify(ecs).createService(request.capture(), eq(REGION));
|
||||
assertNull(request.getValue().getServiceRegistries());
|
||||
assertNull(request.getValue().getCapacityProviderStrategy());
|
||||
assertNull(request.getValue().getDeploymentConfiguration());
|
||||
verify(ecs, never()).updateService(any(UpdateServiceRequest.class), anyString());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
/** What the three settings held after each write to the service, in order; null where the value is null. */
|
||||
private record SettingHistory(EcsServiceModel service, List<Map<String, Object>> deploymentConfigurations,
|
||||
List<List<CapacityProviderStrategyItem>> strategies,
|
||||
List<List<Map<String, Object>>> registries) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a service that held all three settings from a template declaring them to one declaring
|
||||
* {@code props}, with the update failing to stabilize. The stored service behaves as the real one
|
||||
* does: UpdateService assigns each non-null member, the replace method assigns exactly what it is
|
||||
* given, and both change the very model the prior settings were read from.
|
||||
*/
|
||||
private SettingHistory updateThatDoesNotStabilize(ObjectNode props) {
|
||||
return updateThatDoesNotStabilize(declaring(SETTINGS.toArray(String[]::new)), props, DEPLOYMENT_CONFIGURATION);
|
||||
}
|
||||
|
||||
/** As above, for a stored service holding {@code storedDeploymentConfiguration} (null: none) and a prior template declaring {@code prior}. */
|
||||
private SettingHistory updateThatDoesNotStabilize(ObjectNode prior, ObjectNode props,
|
||||
Map<String, Object> storedDeploymentConfiguration) {
|
||||
EcsServiceModel stored = service("front");
|
||||
stored.setTaskDefinition(TASK_DEF_ARN);
|
||||
stored.setDesiredCount(1);
|
||||
stored.setDeploymentConfiguration(storedDeploymentConfiguration);
|
||||
stored.setCapacityProviderStrategy(STRATEGY);
|
||||
stored.setServiceRegistries(REGISTRIES);
|
||||
SettingHistory history = new SettingHistory(stored, new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
|
||||
when(ecs.serviceByArn(SERVICE_ARN)).thenReturn(stored);
|
||||
EcsServiceModel updated = service("front");
|
||||
EcsServiceModel restored = service("front");
|
||||
when(ecs.updateService(any(UpdateServiceRequest.class), eq(REGION))).thenAnswer(inv -> {
|
||||
UpdateServiceRequest request = inv.getArgument(0);
|
||||
if (request.getDeploymentConfiguration() != null) {
|
||||
stored.setDeploymentConfiguration(request.getDeploymentConfiguration());
|
||||
}
|
||||
if (request.getCapacityProviderStrategy() != null) {
|
||||
stored.setCapacityProviderStrategy(request.getCapacityProviderStrategy());
|
||||
}
|
||||
if (request.getServiceRegistries() != null) {
|
||||
stored.setServiceRegistries(request.getServiceRegistries());
|
||||
}
|
||||
record(history);
|
||||
return Integer.valueOf(3).equals(request.getDesiredCount()) ? updated : restored;
|
||||
});
|
||||
when(ecs.replaceServiceDeploymentConfiguration(any(), any(), any(), any())).thenAnswer(inv -> {
|
||||
stored.setDeploymentConfiguration(inv.getArgument(2));
|
||||
record(history);
|
||||
return stored;
|
||||
});
|
||||
doThrow(new AwsException("NotStabilized", "did not stabilize", 500)).when(ecs).awaitServiceStable(updated);
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(existingService(), props.put("DesiredCount", "3"),
|
||||
ctx(SERVICE_ARN, prior)));
|
||||
return history;
|
||||
}
|
||||
|
||||
private static void record(SettingHistory history) {
|
||||
history.deploymentConfigurations().add(history.service().getDeploymentConfiguration());
|
||||
history.strategies().add(history.service().getCapacityProviderStrategy());
|
||||
history.registries().add(history.service().getServiceRegistries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedDesiredCountSetsTheDesiredCountToOne() {
|
||||
ObjectNode prior = serviceProps().put("DesiredCount", "3");
|
||||
|
||||
UpdateServiceRequest request = updateFrom(prior, serviceProps());
|
||||
|
||||
assertEquals(1, request.getDesiredCount());
|
||||
verifyNoDeploymentConfigurationReplacement();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeploymentConfigurationTheServiceNeverHadIsReadBackAsNoneAfterTheRestore() {
|
||||
ObjectNode prior = serviceProps();
|
||||
prior.putArray(SERVICE_REGISTRIES);
|
||||
ObjectNode props = declaring(DEPLOYMENT_CONFIGURATION_PROPERTY);
|
||||
|
||||
SettingHistory history = updateThatDoesNotStabilize(prior, props, null);
|
||||
|
||||
assertTrue(history.deploymentConfigurations().contains(DEPLOYMENT_CONFIGURATION),
|
||||
"the update applied the declared deployment configuration before the wait");
|
||||
assertNull(history.service().getDeploymentConfiguration(), "the restore leaves none, not an empty map");
|
||||
assertNull(history.deploymentConfigurations().getLast(), "none is the last write to the deployment configuration");
|
||||
assertEquals(STRATEGY, history.service().getCapacityProviderStrategy());
|
||||
assertEquals(REGISTRIES, history.service().getServiceRegistries());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"dropped", "changed"})
|
||||
void anUnknownPriorServiceLeavesTheDeploymentConfigurationAloneOnRestore(String change) {
|
||||
when(ecs.serviceByArn(SERVICE_ARN)).thenReturn(null);
|
||||
EcsServiceModel updated = service("front");
|
||||
EcsServiceModel restored = service("front");
|
||||
List<String> writes = new ArrayList<>();
|
||||
when(ecs.updateService(any(UpdateServiceRequest.class), eq(REGION))).thenAnswer(inv -> {
|
||||
UpdateServiceRequest request = inv.getArgument(0);
|
||||
writes.add("update");
|
||||
return Integer.valueOf(3).equals(request.getDesiredCount()) ? updated : restored;
|
||||
});
|
||||
when(ecs.replaceServiceDeploymentConfiguration(any(), any(), any(), any())).thenAnswer(inv -> {
|
||||
writes.add("replace");
|
||||
return service("front");
|
||||
});
|
||||
doThrow(new AwsException("NotStabilized", "did not stabilize", 500)).when(ecs).awaitServiceStable(updated);
|
||||
ObjectNode prior = declaring(SETTINGS.toArray(String[]::new));
|
||||
ObjectNode props = "dropped".equals(change) ? declaringExcept(DEPLOYMENT_CONFIGURATION_PROPERTY)
|
||||
: declaring(SETTINGS.toArray(String[]::new));
|
||||
if ("changed".equals(change)) {
|
||||
((ObjectNode) prior.get(DEPLOYMENT_CONFIGURATION_PROPERTY)).put("MaximumPercent", "100");
|
||||
}
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(existingService(), props.put("DesiredCount", "3"),
|
||||
ctx(SERVICE_ARN, prior)));
|
||||
|
||||
ArgumentCaptor<UpdateServiceRequest> requests = ArgumentCaptor.forClass(UpdateServiceRequest.class);
|
||||
verify(ecs, times(2)).updateService(requests.capture(), eq(REGION));
|
||||
UpdateServiceRequest restore = requests.getAllValues().get(1);
|
||||
assertNull(restore.getDeploymentConfiguration(), "the restore request carries no deployment configuration");
|
||||
assertNull(restore.getTaskDefinition(), "an unknown prior service is restored by cluster and service only");
|
||||
assertNull(restore.getDesiredCount());
|
||||
int restoreAt = writes.lastIndexOf("update");
|
||||
assertEquals(List.of(), writes.subList(restoreAt + 1, writes.size()),
|
||||
"no deployment configuration is written after the restore request");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedDeploymentConfigurationIsPutBackWhenTheUpdateDoesNotStabilize() {
|
||||
SettingHistory history = updateThatDoesNotStabilize(declaringExcept(DEPLOYMENT_CONFIGURATION_PROPERTY));
|
||||
|
||||
assertTrue(history.deploymentConfigurations().contains(null), "the drop was applied before the wait");
|
||||
assertEquals(DEPLOYMENT_CONFIGURATION, history.service().getDeploymentConfiguration());
|
||||
assertEquals(STRATEGY, history.service().getCapacityProviderStrategy());
|
||||
assertEquals(REGISTRIES, history.service().getServiceRegistries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedCapacityProviderStrategyIsNeverClearedWhenTheUpdateDoesNotStabilize() {
|
||||
SettingHistory history = updateThatDoesNotStabilize(declaringExcept(CAPACITY_PROVIDER_STRATEGY));
|
||||
|
||||
assertFalse(history.strategies().contains(List.of()), "the strategy was never cleared");
|
||||
assertEquals(STRATEGY, history.service().getCapacityProviderStrategy());
|
||||
assertEquals(DEPLOYMENT_CONFIGURATION, history.service().getDeploymentConfiguration());
|
||||
assertEquals(REGISTRIES, history.service().getServiceRegistries());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppedServiceRegistriesAreNeverClearedWhenTheUpdateDoesNotStabilize() {
|
||||
SettingHistory history = updateThatDoesNotStabilize(declaringExcept(SERVICE_REGISTRIES));
|
||||
|
||||
assertFalse(history.registries().contains(List.of()), "the registries were never cleared");
|
||||
assertEquals(REGISTRIES, history.service().getServiceRegistries());
|
||||
assertEquals(DEPLOYMENT_CONFIGURATION, history.service().getDeploymentConfiguration());
|
||||
assertEquals(STRATEGY, history.service().getCapacityProviderStrategy());
|
||||
}
|
||||
|
||||
/**
|
||||
* The three service settings, every scalar the text a {@code String} parameter resolves to,
|
||||
* the booleans in each case CloudFormation's handler accepts.
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package io.floci.aws.services.ecs;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.ecs.container.EcsContainerManager;
|
||||
import io.floci.aws.services.ecs.model.CapacityProviderStrategyItem;
|
||||
import io.floci.aws.services.ecs.model.ContainerDefinition;
|
||||
import io.floci.aws.services.ecs.model.CreateServiceRequest;
|
||||
import io.floci.aws.services.ecs.model.EcsServiceModel;
|
||||
import io.floci.aws.services.ecs.model.UpdateServiceRequest;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@code replaceServiceDeploymentConfiguration} writes the stored deployment configuration exactly
|
||||
* as given, null included, which {@code updateService} cannot do: there a null means unchanged.
|
||||
*/
|
||||
class EcsServiceReplaceDeploymentConfigurationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String CLUSTER = "replace-cluster";
|
||||
private static final String SERVICE = "replace-svc";
|
||||
private static final Map<String, Object> PRIOR = Map.of("maximumPercent", 150, "minimumHealthyPercent", 50);
|
||||
private static final List<CapacityProviderStrategyItem> STRATEGY =
|
||||
List.of(new CapacityProviderStrategyItem("FARGATE", 2, 0));
|
||||
private static final List<Map<String, Object>> REGISTRIES = List.of(Map.of(
|
||||
"registryArn", "arn:aws:servicediscovery:us-east-1:000000000000:service/srv-1"));
|
||||
|
||||
private EcsService ecs;
|
||||
|
||||
@BeforeEach
|
||||
void createServiceWithAllThreeSettings() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().ecs().mock()).thenReturn(true);
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
ecs = new EcsService(new RegionResolver(REGION, "000000000000"), mock(EcsContainerManager.class), config,
|
||||
mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory("000000000000"), null);
|
||||
ecs.initializeStorage();
|
||||
ecs.createCluster(CLUSTER, REGION);
|
||||
ContainerDefinition container = new ContainerDefinition();
|
||||
container.setName("app");
|
||||
container.setImage("app:1");
|
||||
ecs.registerTaskDefinition("replace-fam", List.of(container), null, null, null, null, null, List.of(), REGION);
|
||||
CreateServiceRequest create = new CreateServiceRequest();
|
||||
create.setCluster(CLUSTER);
|
||||
create.setServiceName(SERVICE);
|
||||
create.setTaskDefinition("replace-fam");
|
||||
create.setDeploymentConfiguration(PRIOR);
|
||||
create.setCapacityProviderStrategy(STRATEGY);
|
||||
create.setServiceRegistries(REGISTRIES);
|
||||
ecs.createService(create, REGION);
|
||||
}
|
||||
|
||||
private EcsServiceModel stored() {
|
||||
return ecs.describeServices(CLUSTER, List.of(SERVICE), REGION).getFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGivenMapReplacesTheStoredDeploymentConfigurationExactly() {
|
||||
Map<String, Object> given = Map.of("maximumPercent", 175);
|
||||
|
||||
EcsServiceModel returned = ecs.replaceServiceDeploymentConfiguration(CLUSTER, SERVICE, given, REGION);
|
||||
|
||||
assertEquals(given, returned.getDeploymentConfiguration());
|
||||
assertEquals(given, stored().getDeploymentConfiguration(), "no member of the prior value is merged in");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullClearsTheStoredDeploymentConfiguration() {
|
||||
EcsServiceModel returned = ecs.replaceServiceDeploymentConfiguration(CLUSTER, SERVICE, null, REGION);
|
||||
|
||||
assertNull(returned.getDeploymentConfiguration());
|
||||
assertNull(stored().getDeploymentConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyMapIsStoredAsGiven() {
|
||||
ecs.replaceServiceDeploymentConfiguration(CLUSTER, SERVICE, Map.of(), REGION);
|
||||
|
||||
assertEquals(Map.of(), stored().getDeploymentConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReplacementStartsNoNewDeploymentAndTouchesNoOtherSetting() {
|
||||
String deploymentId = stored().getDeploymentId();
|
||||
|
||||
ecs.replaceServiceDeploymentConfiguration(CLUSTER, SERVICE, null, REGION);
|
||||
|
||||
EcsServiceModel after = stored();
|
||||
assertEquals(deploymentId, after.getDeploymentId());
|
||||
assertEquals(STRATEGY, after.getCapacityProviderStrategy());
|
||||
assertEquals(REGISTRIES, after.getServiceRegistries());
|
||||
assertEquals(1, after.getDesiredCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theClusterMayBeGivenAsAnArn() {
|
||||
String clusterArn = ecs.describeClusters(List.of(CLUSTER), REGION).getFirst().getClusterArn();
|
||||
|
||||
ecs.replaceServiceDeploymentConfiguration(clusterArn, SERVICE, null, REGION);
|
||||
|
||||
assertNull(stored().getDeploymentConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownServiceFailsAsUpdateServiceDoes() {
|
||||
UpdateServiceRequest update = new UpdateServiceRequest();
|
||||
update.setCluster(CLUSTER);
|
||||
update.setService("missing-svc");
|
||||
AwsException expected = assertThrows(AwsException.class, () -> ecs.updateService(update, REGION));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> ecs.replaceServiceDeploymentConfiguration(CLUSTER, "missing-svc", null, REGION));
|
||||
|
||||
assertEquals("ServiceNotFoundException", e.getErrorCode());
|
||||
assertEquals(expected.getErrorCode(), e.getErrorCode());
|
||||
assertEquals(expected.getHttpStatus(), e.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateWithoutADeploymentConfigurationKeepsTheStoredOne() {
|
||||
UpdateServiceRequest update = new UpdateServiceRequest();
|
||||
update.setCluster(CLUSTER);
|
||||
update.setService(SERVICE);
|
||||
update.setDesiredCount(2);
|
||||
|
||||
ecs.updateService(update, REGION);
|
||||
|
||||
assertEquals(PRIOR, stored().getDeploymentConfiguration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClearedDeploymentConfigurationStaysClearedAfterAnUnrelatedUpdate() {
|
||||
ecs.replaceServiceDeploymentConfiguration(CLUSTER, SERVICE, null, REGION);
|
||||
UpdateServiceRequest update = new UpdateServiceRequest();
|
||||
update.setCluster(CLUSTER);
|
||||
update.setService(SERVICE);
|
||||
update.setDesiredCount(2);
|
||||
|
||||
ecs.updateService(update, REGION);
|
||||
|
||||
assertNull(stored().getDeploymentConfiguration());
|
||||
}
|
||||
}
|
||||
@@ -102,3 +102,13 @@ AWS::EC2::Subnet CidrBlock create-only a drop never matches the stored block, so
|
||||
AWS::EC2::Subnet MapPublicIpOnLaunch default:false
|
||||
AWS::EC2::Subnet Tags clear
|
||||
AWS::EC2::Subnet VpcId create-only a drop is refused
|
||||
AWS::ECS::Service CapacityProviderStrategy keep:AWS documents a removed strategy as no update; a declared empty list clears it
|
||||
AWS::ECS::Service Cluster create-only
|
||||
AWS::ECS::Service DeploymentConfiguration clear it is stored as none, so it reads back as never set; a declared {} is stored as given
|
||||
AWS::ECS::Service DesiredCount default:1
|
||||
AWS::ECS::Service LaunchType keep:the provisioner leaves it out of the update, so the stored value stays
|
||||
AWS::ECS::Service LoadBalancers keep:the provisioner leaves it out of the update, so the stored value stays
|
||||
AWS::ECS::Service NetworkConfiguration keep:the update leaves a missing network configuration unchanged
|
||||
AWS::ECS::Service ServiceName keep:the prior name is reused
|
||||
AWS::ECS::Service ServiceRegistries keep:AWS removes registries only through a declared empty list
|
||||
AWS::ECS::Service TaskDefinition keep:required for the ECS controller
|
||||
|
Reference in new issue
Block a user