mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(ecs): publish Container Insights task counts (#6054)
* feat(ecs): publish Container Insights task counts A service on a cluster whose containerInsights setting is enabled or enhanced publishes RunningTaskCount, PendingTaskCount and DesiredTaskCount to ECS/ContainerInsights once a minute, with ClusterName and ServiceName dimensions, while it has a running task. The AWS::ECS::Cluster provisioner applies ClusterSettings and restores the prior settings when a stack update rolls back. * fix(ecs): resolve ClusterSettings as a whole before reading it A ClusterSettings list wrapped in Fn::If was iterated unresolved and stored a setting with no name or value. Resolve the property node first, as the provisioner does for its other list properties. * fix(ecs): resolve ClusterSettings before creating the cluster A ClusterSettings value that failed to resolve left a cluster the stack did not track. Resolve first, and skip an entry that resolved to AWS::NoValue. * fix(ecs): date Container Insights counts by the minute they were observed * fix(ecs): count Container Insights tasks when they are published The task counts came from the service's cached runningCount, which the reconcile sets before it scales the service in or out, and from a pendingCount nothing ever sets. They are now counted from the service's own tasks after the tick has started and stopped them, so a scale-in is reported in the tick that stops the task and a PENDING task is counted. A committed in-place cluster update now drops its settings snapshot in completeUpdate: the engine only calls clearUpdate after a replacement, so the snapshot outlived the update it belonged to. * docs(ecs): note that removing ClusterSettings keeps the cluster's settings * test(ecs): cover restoring null cluster settings and read the latest metric bucket A stack update that adds ClusterSettings to a cluster created without any rolls back to null settings, through the JSON null in the snapshot; the rollback test now covers that case alongside a prior disabled setting. The scale-in test reads the latest one-minute bucket, so a minute rollover between its two reconciles no longer splits the samples into two buckets and fails the test. * fix(ecs): log a failed Container Insights write as a warning The publish ran inside the reconcile's catch, which logs only the message at debug level, so a failed metric write left the minute's sample missing without a trace. It now has its own try and logs the exception at warn. * perf(ecs): write a Container Insights sample only when a count changes The reconciler ticks every five seconds and wrote all three counts each time, and a persistent metric store rewrites its file on every put. The last sample written per account and service is kept, and the minute's sample is written again only when a count changes. A reset clears it, since it wipes the samples too. * fix(cloudformation): restore ECS cluster settings when their own update fails A failed provision puts back the resource the stack held before the attempt, which never carried the settings snapshot, so the rollback walker skipped it and the new settings stayed. The provisioner now restores the snapshot itself, as the other in-place provisioners do, and records a restore that fails as a rollback failure. The physical id is set before the settings call, so the restore and a create rollback both find the cluster. * fix(ecs): repeat a Container Insights write that failed partway The last sample written was kept until the next one replaced it, so when one count landed and the next write failed, and the counts then went back to the ones last written, the next tick skipped the minute and left the partial value in place. The record is now dropped before writing and set again only once all three counts are written. * fix(cloudformation): keep an ECS settings snapshot whose restore failed When a cluster's settings update and its own restore both failed, the snapshot stayed on the attempted resource, and the engine put back the prior resource without it. The first rollback reported the failure, and ContinueUpdateRollback then found no snapshot and reported the rollback complete with the new settings still live. The snapshot is now carried onto the restored resource, so the continuation retries the restore. * fix(cloudformation): create an ECS cluster with its settings A new cluster was created and then given its ClusterSettings in a second call. When that call failed, on a stack create or a rename, nothing tracked the cluster: the create rollback skips a CREATE_FAILED resource it does not own, and a rename never reached the replacement record. The settings now go into CreateCluster itself, so a new cluster is never left without them. A cluster the idempotent create returned, which the stack did not create, still has them applied separately and is not deleted when that fails. * fix(cloudformation): set an ECS cluster's id only once its settings apply The physical id was set before the settings call. When an update added a cluster under the name of one created outside the stack, the idempotent create returned that cluster, and if its settings then failed, the update rollback deleted the added resource and with it a cluster the stack never created. The id is set after the settings again; an update of the resource's own cluster already carries its prior id for the restore. * fix(cloudformation): restore the settings of an ECS cluster the stack found Only a resource's own cluster had its prior settings put back when the settings call failed. A cluster the idempotent create returned for a resource the stack creates or adds kept whatever a failed call left on it, while the rollback, which drops the resource, reported a clean finish. A cluster whose settings still differ after CreateCluster existed before, so its prior settings are now captured and restored either way; the snapshot attribute for the rollback walker stays on the resource's own cluster only. * test(ecs): date Container Insights samples by a clock the test pins publishContainerInsights read the minute from the wall clock, so the test of an unchanged sample skipped itself when the minute rolled over between its ticks. The minute now comes from a Clock given to a package-private constructor, which the injected one calls with Clock.systemUTC(); the test pins it and asserts the sample is dated by it. * test(ecs): drive the reconciler instead of waiting on its ticks The CloudFormation integration test waited up to 30 seconds for the background reconciler to launch the task and publish its count. It now calls reconcileServices twice, as the other ECS integration tests do.
This commit is contained in:
1 parent
538a81d871
commit
1b15299228
7 files changed
+872
-12
No files matched your search
+250
-4
@@ -8,6 +8,7 @@ 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 io.github.hectorvent.floci.services.ecs.EcsService;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
|
||||
@@ -17,8 +18,12 @@ import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
@@ -30,6 +35,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.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -116,7 +122,7 @@ class EcsCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void clusterUsesTheDeclaredNameAndExposesArn() {
|
||||
when(ecs.createCluster("web", REGION)).thenReturn(cluster("web"));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(cluster("web"));
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("ClusterName", "web"), ctx());
|
||||
@@ -128,7 +134,7 @@ class EcsCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void anUnnamedClusterGeneratesANameOnCreateAndKeepsItOnUpdate() {
|
||||
when(ecs.createCluster(anyString(), eq(REGION))).thenAnswer(inv -> cluster(inv.getArgument(0)));
|
||||
when(ecs.createCluster(anyString(), isNull(), anyList(), eq(REGION))).thenAnswer(inv -> cluster(inv.getArgument(0)));
|
||||
StackResource created = resource("AWS::ECS::Cluster", "Cluster");
|
||||
provisioner.provision(created, mapper.createObjectNode(), ctx());
|
||||
String generated = created.getPhysicalId();
|
||||
@@ -140,7 +146,7 @@ class EcsCfnProvisionerTest {
|
||||
// createCluster is idempotent, so the update re-issues it under the same name instead of
|
||||
// minting a second cluster.
|
||||
assertEquals(generated, updated.getPhysicalId());
|
||||
verify(ecs, times(2)).createCluster(generated, REGION);
|
||||
verify(ecs, times(2)).createCluster(eq(generated), isNull(), anyList(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -696,7 +702,7 @@ class EcsCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void anUnchangedClusterHasNothingToRollBack() {
|
||||
when(ecs.createCluster("web", REGION)).thenReturn(cluster("web"));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(cluster("web"));
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
provisioner.provision(r, mapper.createObjectNode().put("ClusterName", "web"), ctx("web"));
|
||||
|
||||
@@ -706,6 +712,246 @@ class EcsCfnProvisionerTest {
|
||||
verify(ecs, never()).deleteCluster(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterSettingsAreAppliedOnCreate() {
|
||||
List<ClusterSetting> enabled = List.of(new ClusterSetting("containerInsights", "enabled"));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenAnswer(inv -> created(inv));
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, clusterWithInsights("enabled"), ctx());
|
||||
|
||||
// In the create itself, so no later call can fail and leave a cluster the rollback misses.
|
||||
verify(ecs).createCluster("web", null, enabled, REGION);
|
||||
verify(ecs, never()).updateClusterSettings(anyString(), any(), anyString());
|
||||
assertEquals(Set.of("Arn"), r.getAttributes().keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenamedClusterTakesItsSettingsAtCreation() {
|
||||
List<ClusterSetting> enabled = List.of(new ClusterSetting("containerInsights", "enabled"));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenAnswer(inv -> created(inv));
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, clusterWithInsights("enabled"), ctx("old"));
|
||||
|
||||
verify(ecs).createCluster("web", null, enabled, REGION);
|
||||
verify(ecs, never()).updateClusterSettings(anyString(), any(), anyString());
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterThatAlreadyExistedGetsItsSettingsBackAndIsNotDeleted() {
|
||||
// The idempotent create hands back a cluster the stack did not create, without the settings.
|
||||
List<ClusterSetting> priorSettings = List.of(new ClusterSetting("containerInsights", "disabled"));
|
||||
EcsCluster existing = cluster("web");
|
||||
existing.setSettings(priorSettings);
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(existing);
|
||||
AwsException failure = new AwsException("ServerException", "write failed", 500);
|
||||
when(ecs.updateClusterSettings("web", List.of(new ClusterSetting("containerInsights", "enabled")), REGION))
|
||||
.thenThrow(failure);
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, clusterWithInsights("enabled"), ctx()));
|
||||
|
||||
assertSame(failure, thrown);
|
||||
// The failed call may have changed them, and nothing else puts back a cluster the stack found.
|
||||
verify(ecs).updateClusterSettings("web", priorSettings, REGION);
|
||||
// Without an id, neither a create rollback nor an update that added this resource deletes it.
|
||||
assertNull(r.getPhysicalId());
|
||||
verify(ecs, never()).deleteCluster(anyString(), anyString());
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
private EcsCluster created(InvocationOnMock inv) {
|
||||
EcsCluster c = cluster(inv.getArgument(0));
|
||||
List<ClusterSetting> settings = inv.getArgument(2);
|
||||
c.setSettings(settings.isEmpty() ? null : settings);
|
||||
return c;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
@ValueSource(strings = "disabled")
|
||||
void aFailedStackUpdateRestoresThePriorClusterSettings(String priorValue) {
|
||||
List<ClusterSetting> priorSettings = priorValue == null ? null : List.of(new ClusterSetting("containerInsights", priorValue));
|
||||
EcsCluster prior = cluster("web");
|
||||
prior.setSettings(priorSettings);
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(prior);
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, clusterWithInsights("enhanced"), ctx("web"));
|
||||
verify(ecs).updateClusterSettings("web", List.of(new ClusterSetting("containerInsights", "enhanced")), REGION);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
verify(ecs).updateClusterSettings("web", priorSettings, REGION);
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSettingsUpdateThatFailsPutsThePriorSettingsBackItself() {
|
||||
List<ClusterSetting> priorSettings = List.of(new ClusterSetting("containerInsights", "disabled"));
|
||||
EcsCluster prior = cluster("web");
|
||||
prior.setSettings(priorSettings);
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(prior);
|
||||
AwsException failure = new AwsException("ServerException", "write failed", 500);
|
||||
when(ecs.updateClusterSettings("web", List.of(new ClusterSetting("containerInsights", "enhanced")), REGION))
|
||||
.thenThrow(failure);
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
// An update hands the provisioner the resource with its prior physical id.
|
||||
r.setPhysicalId("web");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, clusterWithInsights("enhanced"), ctx("web")));
|
||||
|
||||
// The engine restores the resource it held before this attempt, which never carried the
|
||||
// snapshot, so the rollback walker would not put these settings back.
|
||||
assertSame(failure, thrown);
|
||||
verify(ecs).updateClusterSettings("web", priorSettings, REGION);
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSettingsRestoreThatAlsoFailsIsRecordedAsARollbackFailure() {
|
||||
EcsCluster prior = cluster("web");
|
||||
prior.setSettings(List.of(new ClusterSetting("containerInsights", "disabled")));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(prior);
|
||||
AwsException failure = new AwsException("ServerException", "write failed", 500);
|
||||
AwsException restoreFailure = new AwsException("ServerException", "still failing", 500);
|
||||
when(ecs.updateClusterSettings(eq("web"), any(), eq(REGION))).thenThrow(failure, restoreFailure);
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
// An update hands the provisioner the resource with its prior physical id.
|
||||
r.setPhysicalId("web");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, clusterWithInsights("enhanced"), ctx("web")));
|
||||
|
||||
assertSame(failure, thrown);
|
||||
assertEquals(List.of(restoreFailure), List.of(thrown.getSuppressed()));
|
||||
assertEquals("Could not restore the settings of ECS cluster web: still failing",
|
||||
r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatFailedIsRetriedWhenTheRollbackIsContinued() {
|
||||
List<ClusterSetting> priorSettings = List.of(new ClusterSetting("containerInsights", "disabled"));
|
||||
EcsCluster prior = cluster("web");
|
||||
prior.setSettings(priorSettings);
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(prior);
|
||||
when(ecs.updateClusterSettings(eq("web"), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ServerException", "write failed", 500))
|
||||
.thenThrow(new AwsException("ServerException", "still failing", 500))
|
||||
.thenReturn(prior);
|
||||
StackResource previous = resource("AWS::ECS::Cluster", "Cluster");
|
||||
previous.setPhysicalId("web");
|
||||
StackResource attempted = resource("AWS::ECS::Cluster", "Cluster");
|
||||
attempted.setPhysicalId("web");
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(attempted, clusterWithInsights("enhanced"), ctx("web")));
|
||||
|
||||
// The engine puts the previous resource back after the failed provision, and the first
|
||||
// rollback walk reports the recorded failure without calling rollbackUpdate.
|
||||
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
|
||||
// ContinueUpdateRollback then asks for the restore again.
|
||||
assertTrue(provisioner.rollbackUpdate(previous));
|
||||
|
||||
verify(ecs, times(2)).updateClusterSettings("web", priorSettings, REGION);
|
||||
assertFalse(previous.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatSucceededLeavesNothingToCarryOver() {
|
||||
EcsCluster prior = cluster("web");
|
||||
prior.setSettings(List.of(new ClusterSetting("containerInsights", "disabled")));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(prior);
|
||||
when(ecs.updateClusterSettings("web", List.of(new ClusterSetting("containerInsights", "enhanced")), REGION))
|
||||
.thenThrow(new AwsException("ServerException", "write failed", 500));
|
||||
StackResource previous = resource("AWS::ECS::Cluster", "Cluster");
|
||||
StackResource attempted = resource("AWS::ECS::Cluster", "Cluster");
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(attempted, clusterWithInsights("enhanced"), ctx("web")));
|
||||
|
||||
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
|
||||
|
||||
assertFalse(previous.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommittedSettingsUpdateDropsItsSnapshot() {
|
||||
EcsCluster prior = cluster("web");
|
||||
prior.setSettings(List.of(new ClusterSetting("containerInsights", "disabled")));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(prior);
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
provisioner.provision(r, clusterWithInsights("enabled"), ctx("web"));
|
||||
|
||||
assertEquals(UpdateCleanupResult.notApplicable(), provisioner.completeUpdate(r));
|
||||
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnchangedSettingIsNotReappliedAndDropsAnEarlierSnapshot() {
|
||||
EcsCluster current = cluster("web");
|
||||
current.setSettings(List.of(new ClusterSetting("containerInsights", "enabled")));
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(current);
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
r.getAttributes().put(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR,
|
||||
"{\"region\":\"us-east-1\",\"settings\":null}");
|
||||
|
||||
provisioner.provision(r, clusterWithInsights("enabled"), ctx("web"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
verify(ecs, never()).updateClusterSettings(anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalClusterSettingsAreResolvedBeforeTheyAreRead() {
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(cluster("web"));
|
||||
StackResource r = resource("AWS::ECS::Cluster", "Cluster");
|
||||
ObjectNode props = clusterWithInsights("enabled");
|
||||
JsonNode resolved = props.get("ClusterSettings");
|
||||
ObjectNode conditional = mapper.createObjectNode();
|
||||
conditional.putArray("Fn::If").add("Insights").add(resolved).addObject().put("Ref", "AWS::NoValue");
|
||||
props.set("ClusterSettings", conditional);
|
||||
ProvisionContext ctx = ctx();
|
||||
when(ctx.engine().resolveNode(conditional)).thenReturn(resolved);
|
||||
|
||||
provisioner.provision(r, props, ctx);
|
||||
|
||||
verify(ecs).updateClusterSettings("web", List.of(new ClusterSetting("containerInsights", "enabled")), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterSettingsThatFailToResolveCreateNoCluster() {
|
||||
ObjectNode props = clusterWithInsights("enabled");
|
||||
ProvisionContext ctx = ctx();
|
||||
when(ctx.engine().resolveNode(props.get("ClusterSettings"))).thenThrow(new IllegalStateException("unresolvable"));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> provisioner.provision(resource("AWS::ECS::Cluster", "Cluster"), props, ctx));
|
||||
|
||||
verify(ecs, never()).createCluster(anyString(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterSettingResolvedToNoValueIsDropped() {
|
||||
when(ecs.createCluster(eq("web"), isNull(), anyList(), eq(REGION))).thenReturn(cluster("web"));
|
||||
ObjectNode props = clusterWithInsights("enabled");
|
||||
((ArrayNode) props.get("ClusterSettings")).add("");
|
||||
|
||||
provisioner.provision(resource("AWS::ECS::Cluster", "Cluster"), props, ctx());
|
||||
|
||||
verify(ecs).updateClusterSettings("web", List.of(new ClusterSetting("containerInsights", "enabled")), REGION);
|
||||
}
|
||||
|
||||
private ObjectNode clusterWithInsights(String value) {
|
||||
ObjectNode props = mapper.createObjectNode().put("ClusterName", "web");
|
||||
props.putArray("ClusterSettings").addObject().put("Name", "containerInsights").put("Value", value);
|
||||
return props;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInPlaceUpdateIsNotRolledBackHere() {
|
||||
when(ecs.updateService(eq("web"), eq("front"), eq(TASK_DEF_ARN), eq(3), isNull(), eq(REGION)))
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package io.github.hectorvent.floci.services.ecs;
|
||||
|
||||
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
|
||||
/**
|
||||
* A cluster whose CloudFormation {@code ClusterSettings} enable Container Insights publishes its
|
||||
* services' task counts to {@code ECS/ContainerInsights}, which is what an alarm on a stopped
|
||||
* service watches. The test drives the reconciler itself, as the other ECS integration tests do,
|
||||
* rather than waiting on its five-second ticks: one pass launches the task, the next counts it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EcsContainerInsightsIntegrationTest {
|
||||
|
||||
@InjectSpy
|
||||
EcsService ecsService;
|
||||
|
||||
private static final String CLOUDWATCH_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260908/us-east-1/monitoring/aws4_request";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithInsightsFromCloudFormationPublishesItsRunningTaskCount() {
|
||||
String cluster = "insights-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{"Resources": {
|
||||
"Cluster": {"Type": "AWS::ECS::Cluster", "Properties": {"ClusterName": "%1$s",
|
||||
"ClusterSettings": [{"Name": "containerInsights", "Value": "enabled"}]}},
|
||||
"TaskDef": {"Type": "AWS::ECS::TaskDefinition", "Properties": {"Family": "%1$s",
|
||||
"NetworkMode": "awsvpc", "RequiresCompatibilities": ["FARGATE"], "Cpu": "256", "Memory": "512",
|
||||
"ContainerDefinitions": [{"Name": "app", "Image": "nginx:alpine", "Essential": true}]}},
|
||||
"Service": {"Type": "AWS::ECS::Service", "Properties": {"ServiceName": "web",
|
||||
"Cluster": {"Ref": "Cluster"}, "TaskDefinition": {"Ref": "TaskDef"},
|
||||
"DesiredCount": 1, "LaunchType": "FARGATE", "NetworkConfiguration": {"AwsvpcConfiguration":
|
||||
{"Subnets": ["subnet-default-us-east-1-a"]}}}}}}
|
||||
""".formatted(cluster);
|
||||
|
||||
given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", cluster)
|
||||
.formParam("TemplateBody", template)
|
||||
.post("/").then().statusCode(200);
|
||||
given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", cluster)
|
||||
.post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
|
||||
given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DescribeClusters")
|
||||
.body("{\"clusters\": [\"" + cluster + "\"], \"include\": [\"SETTINGS\"]}")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("clusters[0].settings[0].value", equalTo("enabled"));
|
||||
|
||||
ecsService.reconcileServices();
|
||||
ecsService.reconcileServices();
|
||||
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.header("Authorization", CLOUDWATCH_AUTH)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics")
|
||||
.body("""
|
||||
{"Namespace": "ECS/ContainerInsights", "MetricName": "RunningTaskCount",
|
||||
"Dimensions": [{"Name": "ClusterName", "Value": "%s"}, {"Name": "ServiceName", "Value": "web"}],
|
||||
"StartTime": %d, "EndTime": %d, "Period": 60, "Statistics": ["Maximum"]}
|
||||
""".formatted(cluster, Instant.now().minusSeconds(300).getEpochSecond(),
|
||||
Instant.now().plusSeconds(60).getEpochSecond()))
|
||||
.post("/").then().statusCode(200)
|
||||
.body("Datapoints.Maximum", hasItem(1.0f));
|
||||
}
|
||||
|
||||
/**
|
||||
* The update's settings land and the call still fails, and the provisioner's own restore fails
|
||||
* too, so the stack ends in UPDATE_ROLLBACK_FAILED with the new setting live. The snapshot
|
||||
* survives on the resource the stack keeps, so ContinueUpdateRollback puts the prior setting
|
||||
* back rather than reporting a rollback with nothing left to do.
|
||||
*/
|
||||
@Test
|
||||
void continueUpdateRollbackRetriesASettingsRestoreThatFailed() {
|
||||
String cluster = "insights-rb-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{"Resources": {"Cluster": {"Type": "AWS::ECS::Cluster", "Properties": {"ClusterName": "%s",
|
||||
"ClusterSettings": [{"Name": "containerInsights", "Value": "%s"}]}}}}
|
||||
""";
|
||||
cloudFormation("CreateStack", cluster, template.formatted(cluster, "disabled"));
|
||||
awaitStackStatus(cluster, "CREATE_COMPLETE");
|
||||
|
||||
List<ClusterSetting> enabled = List.of(new ClusterSetting("containerInsights", "enabled"));
|
||||
doAnswer(invocation -> {
|
||||
if (enabled.equals(invocation.getArgument(1))) {
|
||||
invocation.callRealMethod();
|
||||
}
|
||||
throw new IllegalStateException("simulated settings write failure");
|
||||
}).when(ecsService).updateClusterSettings(anyString(), anyList(), anyString());
|
||||
try {
|
||||
cloudFormation("UpdateStack", cluster, template.formatted(cluster, "enabled"));
|
||||
awaitStackStatus(cluster, "UPDATE_ROLLBACK_FAILED");
|
||||
} finally {
|
||||
doCallRealMethod().when(ecsService).updateClusterSettings(anyString(), anyList(), anyString());
|
||||
}
|
||||
assertInsightsSetting(cluster, "enabled");
|
||||
|
||||
cloudFormation("ContinueUpdateRollback", cluster, null);
|
||||
awaitStackStatus(cluster, "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertInsightsSetting(cluster, "disabled");
|
||||
}
|
||||
|
||||
/**
|
||||
* An update that adds a cluster under the name of one created outside the stack gets that
|
||||
* cluster back from the idempotent create. When its settings then land and the call still
|
||||
* fails, the cluster gets its own settings back, and the update rollback, which deletes what
|
||||
* the update added, leaves the cluster in place because the resource never claimed it.
|
||||
*/
|
||||
@Test
|
||||
void aFailedUpdateLeavesAClusterItFoundAsItWas() {
|
||||
String name = "insights-pre-" + Long.toString(System.nanoTime(), 36);
|
||||
given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.CreateCluster")
|
||||
.body("{\"clusterName\": \"" + name + "\", "
|
||||
+ "\"settings\": [{\"name\": \"containerInsights\", \"value\": \"disabled\"}]}")
|
||||
.post("/").then().statusCode(200);
|
||||
String parameter = """
|
||||
"Param": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": "v"}}""";
|
||||
cloudFormation("CreateStack", name, "{\"Resources\": {" + parameter + "}}");
|
||||
awaitStackStatus(name, "CREATE_COMPLETE");
|
||||
|
||||
List<ClusterSetting> enabled = List.of(new ClusterSetting("containerInsights", "enabled"));
|
||||
doAnswer(invocation -> {
|
||||
Object result = invocation.callRealMethod();
|
||||
if (enabled.equals(invocation.getArgument(1))) {
|
||||
throw new IllegalStateException("simulated settings write failure");
|
||||
}
|
||||
return result;
|
||||
}).when(ecsService).updateClusterSettings(anyString(), anyList(), anyString());
|
||||
try {
|
||||
cloudFormation("UpdateStack", name, """
|
||||
{"Resources": {%s, "Cluster": {"Type": "AWS::ECS::Cluster", "Properties": {"ClusterName": "%s",
|
||||
"ClusterSettings": [{"Name": "containerInsights", "Value": "enabled"}]}}}}
|
||||
""".formatted(parameter, name));
|
||||
awaitStackStatus(name, "UPDATE_ROLLBACK_COMPLETE");
|
||||
} finally {
|
||||
doCallRealMethod().when(ecsService).updateClusterSettings(anyString(), anyList(), anyString());
|
||||
}
|
||||
|
||||
given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DescribeClusters")
|
||||
.body("{\"clusters\": [\"" + name + "\"], \"include\": [\"SETTINGS\"]}")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("clusters[0].status", equalTo("ACTIVE"))
|
||||
.body("clusters[0].settings[0].value", equalTo("disabled"));
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String stack, String template) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stack);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template);
|
||||
}
|
||||
request.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void awaitStackStatus(String stack, String status) {
|
||||
await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + status + "</StackStatus>")));
|
||||
}
|
||||
|
||||
private static void assertInsightsSetting(String cluster, String value) {
|
||||
given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DescribeClusters")
|
||||
.body("{\"clusters\": [\"" + cluster + "\"], \"include\": [\"SETTINGS\"]}")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("clusters[0].settings[0].value", equalTo(value));
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService.Datapoint;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
|
||||
import io.github.hectorvent.floci.services.ecs.exec.EcsExecSessionRegistry;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
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.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Container Insights task counts, published by the service reconciler into a real CloudWatch
|
||||
* metric store: {@code ECS/ContainerInsights} on {@code ClusterName} and {@code ServiceName}, once
|
||||
* per minute, only for a cluster whose containerInsights setting turns it on and only while the
|
||||
* service has a RUNNING task.
|
||||
*/
|
||||
class EcsServiceContainerInsightsTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String NAMESPACE = "ECS/ContainerInsights";
|
||||
private static final Instant MINUTE = Instant.parse("2026-10-20T12:00:00Z");
|
||||
|
||||
private CloudWatchMetricsService metrics;
|
||||
private EcsService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
InMemoryStorageFactory storage = new InMemoryStorageFactory();
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
metrics = spy(new CloudWatchMetricsService(storage, regionResolver));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().ecs().mock()).thenReturn(true);
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
service = new EcsService(regionResolver, mock(EcsContainerManager.class), config,
|
||||
mock(EcsLoadBalancerRegistrar.class), storage, null, new EcsExecSessionRegistry(), null, metrics,
|
||||
Clock.fixed(MINUTE.plusSeconds(42), ZoneOffset.UTC));
|
||||
service.initializeStorage();
|
||||
ContainerDefinition cd = new ContainerDefinition();
|
||||
cd.setName("app");
|
||||
cd.setImage("nginx:alpine");
|
||||
service.registerTaskDefinition("ci-fam", List.of(cd), null, null, null, null, null, List.of(), REGION);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"enabled", "enhanced"})
|
||||
void anInsightsClusterPublishesItsServiceTaskCounts(String mode) {
|
||||
startService(List.of(new ClusterSetting("containerInsights", mode)), 1);
|
||||
|
||||
service.reconcile();
|
||||
|
||||
Datapoint running = only("RunningTaskCount");
|
||||
assertEquals(MINUTE, running.timestamp());
|
||||
assertEquals(1.0, running.maximum());
|
||||
assertEquals("Count", running.unit());
|
||||
assertEquals(0.0, only("PendingTaskCount").maximum());
|
||||
assertEquals(1.0, only("DesiredTaskCount").maximum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedTicksKeepOneSamplePerMinute() {
|
||||
startService(List.of(new ClusterSetting("containerInsights", "enabled")), 1);
|
||||
|
||||
service.reconcile();
|
||||
service.reconcile();
|
||||
|
||||
List<Datapoint> points = statistics("RunningTaskCount");
|
||||
assertFalse(points.isEmpty());
|
||||
assertTrue(points.stream().allMatch(p -> p.sampleCount() == 1.0), points.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnchangedSampleIsNotWrittenAgainWithinTheMinute() {
|
||||
startService(List.of(new ClusterSetting("containerInsights", "enabled")), 1);
|
||||
|
||||
service.reconcile();
|
||||
service.reconcile();
|
||||
|
||||
verify(metrics, times(3)).publishMetricForAccount(anyString(), eq(NAMESPACE), any(), eq(REGION), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteThatFailsPartwayIsRepeatedEvenWhenTheCountsReturn() {
|
||||
startService(List.of(new ClusterSetting("containerInsights", "enabled")), 1);
|
||||
service.reconcile();
|
||||
service.updateService("insights", "web", null, 2, null, REGION);
|
||||
// One of the three counts lands, the next write fails.
|
||||
doCallRealMethod().doThrow(new IllegalStateException("disk full")).doCallRealMethod().when(metrics)
|
||||
.publishMetricForAccount(anyString(), eq(NAMESPACE), any(), eq(REGION), anyString());
|
||||
service.reconcile();
|
||||
|
||||
service.updateService("insights", "web", null, 1, null, REGION);
|
||||
clearInvocations(metrics);
|
||||
service.reconcile();
|
||||
|
||||
verify(metrics, times(3)).publishMetricForAccount(anyString(), eq(NAMESPACE), any(), eq(REGION), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScaleInIsCountedInTheTickThatStopsTheTask() {
|
||||
startService(List.of(new ClusterSetting("containerInsights", "enabled")), 2);
|
||||
service.reconcile();
|
||||
|
||||
service.updateService("insights", "web", null, 1, null, REGION);
|
||||
service.reconcile();
|
||||
|
||||
assertEquals(1.0, statistics("RunningTaskCount").getLast().maximum());
|
||||
assertEquals(1.0, statistics("DesiredTaskCount").getLast().maximum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithoutInsightsPublishesNothing() {
|
||||
startService(List.of(new ClusterSetting("containerInsights", "disabled")), 1);
|
||||
service.createCluster("plain", REGION);
|
||||
service.createService("plain", "web", "ci-fam", 1, LaunchType.FARGATE, List.of(), null, REGION);
|
||||
|
||||
service.reconcile();
|
||||
|
||||
assertTrue(metrics.listMetrics(NAMESPACE, null, null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceWithoutARunningTaskPublishesNothing() {
|
||||
startService(List.of(new ClusterSetting("containerInsights", "enabled")), 0);
|
||||
|
||||
service.reconcile();
|
||||
|
||||
assertTrue(metrics.listMetrics(NAMESPACE, null, null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
private void startService(List<ClusterSetting> settings, int desiredCount) {
|
||||
service.createCluster("insights", null, settings, REGION);
|
||||
service.createService("insights", "web", "ci-fam", desiredCount, LaunchType.FARGATE, List.of(), null, REGION);
|
||||
}
|
||||
|
||||
private Datapoint only(String metricName) {
|
||||
List<Datapoint> points = statistics(metricName);
|
||||
assertEquals(1, points.size(), metricName + ": " + points);
|
||||
return points.get(0);
|
||||
}
|
||||
|
||||
private List<Datapoint> statistics(String metricName) {
|
||||
return metrics.getMetricStatistics(NAMESPACE, metricName,
|
||||
List.of(new Dimension("ServiceName", "web"), new Dimension("ClusterName", "insights")),
|
||||
MINUTE.minusSeconds(600), MINUTE.plusSeconds(600), 60, List.of("Maximum"), null, REGION);
|
||||
}
|
||||
|
||||
private static final class InMemoryStorageFactory extends StorageFactory {
|
||||
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
|
||||
|
||||
private InMemoryStorageFactory() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName,
|
||||
String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
|
||||
ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user