diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingMembershipTagTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingMembershipTagTest.java new file mode 100644 index 0000000000..a505b16325 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingMembershipTagTest.java @@ -0,0 +1,130 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.autoscaling.AutoScalingClient; +import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; +import software.amazon.awssdk.services.autoscaling.model.Instance; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.InstanceType; +import software.amazon.awssdk.services.ec2.model.ResourceType; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * The {@code aws:autoscaling:groupName} tag through a member's lifecycle, as the EC2 Auto Scaling + * user guide's instance tagging lifecycle describes it. + */ +@DisplayName("Auto Scaling membership tag") +class AutoScalingMembershipTagTest { + + private static final String GROUP_NAME_TAG = "aws:autoscaling:groupName"; + + @Test + @DisplayName("aws:autoscaling:groupName is added on launch and attach and removed on detach") + void groupNameTagFollowsLaunchAttachAndDetach() throws InterruptedException { + String name = TestFixtures.uniqueName("membership-tag"); + String other = name + "-other"; + String zone = TestFixtures.availabilityZone(); + try (AutoScalingClient autoScaling = TestFixtures.autoScalingClient(); + Ec2Client ec2 = TestFixtures.ec2Client()) { + ec2.createLaunchTemplate(request -> request.launchTemplateName(name).launchTemplateData(data -> data + .imageId("ami-amazonlinux2023").instanceType(InstanceType.T3_MICRO) + .tagSpecifications(spec -> spec.resourceType(ResourceType.INSTANCE).tags( + tag -> tag.key("Source").value("template"), + tag -> tag.key("Shared").value("template"))))); + String standalone = ec2.runInstances(request -> request.imageId("ami-amazonlinux2023") + .instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1) + .placement(placement -> placement.availabilityZone(zone)) + .tagSpecifications(spec -> spec.resourceType(ResourceType.INSTANCE).tags( + tag -> tag.key("Shared").value("mine"), tag -> tag.key("Owner").value("me")))) + .instances().get(0).instanceId(); + try { + autoScaling.createAutoScalingGroup(request -> request.autoScalingGroupName(name) + .launchTemplate(template -> template.launchTemplateName(name).version("1")) + .minSize(0).maxSize(2).desiredCapacity(1).availabilityZones(zone) + .tags(tag -> tag.key("Shared").value("group").propagateAtLaunch(true), + tag -> tag.key("Private").value("group-only").propagateAtLaunch(false))); + autoScaling.createAutoScalingGroup(request -> request.autoScalingGroupName(other) + .launchTemplate(template -> template.launchTemplateName(name).version("1")) + .minSize(0).maxSize(2).desiredCapacity(0).availabilityZones(zone)); + + AtomicReference launched = new AtomicReference<>(); + TestFixtures.await(() -> { + List members = autoScaling.describeAutoScalingGroups(request -> + request.autoScalingGroupNames(name)).autoScalingGroups().get(0).instances(); + members.stream().findFirst().ifPresent(member -> launched.set(member.instanceId())); + return launched.get() != null; + }, name, "an instance launched by the group", TimeUnit.SECONDS.toNanos(60), 1000); + assertThat(userTags(ec2, launched.get())).containsExactlyInAnyOrderEntriesOf( + Map.of("Source", "template", "Shared", "group")); + assertThat(tags(ec2, launched.get())).containsEntry(GROUP_NAME_TAG, name); + assertThat(instancesTaggedWith(ec2, name)).containsExactly(launched.get()); + + autoScaling.attachInstances(request -> request.autoScalingGroupName(name).instanceIds(standalone)); + assertThat(userTags(ec2, standalone)).containsExactlyInAnyOrderEntriesOf( + Map.of("Owner", "me", "Shared", "group")); + assertThat(tags(ec2, standalone)).containsEntry(GROUP_NAME_TAG, name); + + String alreadyMember = "The Instance: " + standalone + " is already part of AutoScalingGroup:" + name; + for (String group : List.of(name, other)) { + assertThatThrownBy(() -> autoScaling.attachInstances(request -> + request.autoScalingGroupName(group).instanceIds(standalone))) + .isInstanceOfSatisfying(AutoScalingException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(error.awsErrorDetails().errorMessage()).contains(alreadyMember); + }); + } + assertThat(tags(ec2, standalone)).containsEntry(GROUP_NAME_TAG, name); + + autoScaling.detachInstances(request -> request.autoScalingGroupName(name).instanceIds(standalone) + .shouldDecrementDesiredCapacity(true)); + assertThat(tags(ec2, standalone)).doesNotContainKey(GROUP_NAME_TAG); + assertThat(userTags(ec2, standalone)).containsExactlyInAnyOrderEntriesOf( + Map.of("Owner", "me", "Shared", "group")); + assertThat(instancesTaggedWith(ec2, name)).containsExactly(launched.get()); + } finally { + for (String group : List.of(name, other)) { + try { + autoScaling.deleteAutoScalingGroup(request -> request.autoScalingGroupName(group) + .forceDelete(true)); + } catch (AutoScalingException ignored) { + // A group that was never created has nothing to clean up. + } + } + ec2.terminateInstances(request -> request.instanceIds(standalone)); + ec2.deleteLaunchTemplate(request -> request.launchTemplateName(name)); + } + } + } + + private static Map tags(Ec2Client ec2, String instanceId) { + return ec2.describeInstances(request -> request.instanceIds(instanceId)).reservations().get(0) + .instances().get(0).tags().stream() + .collect(Collectors.toMap(tag -> tag.key(), tag -> tag.value())); + } + + /** The instance's tags without the {@code aws:} ones AWS adds on its own, such as launch template ids. */ + private static Map userTags(Ec2Client ec2, String instanceId) { + Map tags = new HashMap<>(tags(ec2, instanceId)); + tags.keySet().removeIf(key -> key.startsWith("aws:")); + return tags; + } + + private static List instancesTaggedWith(Ec2Client ec2, String group) { + return ec2.describeInstances(request -> request.filters(filter -> filter.name("tag:" + GROUP_NAME_TAG) + .values(group))).reservations().stream() + .flatMap(reservation -> reservation.instances().stream()) + .map(instance -> instance.instanceId()) + .toList(); + } +} diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md index 0e67a17912..80d9e3b88f 100644 --- a/docs/services/autoscaling.md +++ b/docs/services/autoscaling.md @@ -72,12 +72,24 @@ EC2 instance can use a default subnet in a different zone. | `SetInstanceHealth` | Updates an instance's health status immediately; accepts but does not enforce the grace-period flag | | `SetInstanceProtection` | Enables or disables scale-in protection for named instances in a group | | `SetDesiredCapacity` | Updates desired count; reconciler handles scale-out / scale-in within 10 s | -| `AttachInstances` | Attaches existing EC2 instances to a group; sets lifecycle state to `InService` | +| `AttachInstances` | Attaches existing EC2 instances to a group; sets lifecycle state to `InService`. Refuses the whole batch with `ValidationError` when an instance already belongs to a group | | `DetachInstances` | Detaches instances from a group; optionally decrements desired capacity | | `TerminateInstanceInAutoScalingGroup` | Terminates a specific instance; optionally decrements desired capacity | | `SuspendProcesses` | Records suspended scaling processes (empty list suspends all); reported back by `DescribeAutoScalingGroups` | | `ResumeProcesses` | Clears suspended processes (empty list resumes all) | +Member instances carry the tags the +[EC2 instance tagging lifecycle](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-tagging.html#tag-lifecycle) +describes. An instance the group launches gets its launch template's instance tags, then the +group's `PropagateAtLaunch` tags, which win a key both set, then `aws:autoscaling:groupName` with +the group's name. `AttachInstances` adds the same group tags and `aws:autoscaling:groupName`, +overwriting existing tags with the same keys. `DetachInstances` removes only +`aws:autoscaling:groupName`, and only while it names the group being detached from. + +`AttachInstances` does not yet refuse what AWS refuses for the instance's state or zone or for +the group's `MaxSize`, and does not grow desired capacity by the number of instances attached. +An ID EC2 has no instance for joins the group without tags. + ### Instance Refresh | Operation | Notes | diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java index 3cfcfac317..aaabf33ca6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java @@ -596,7 +596,7 @@ public class AutoScalingReconciler { return ec2Service.runInstances( asg.getRegion(), launchSource.imageId(), launchSource.instanceType(), 1, 1, launchSource.keyName(), launchSource.securityGroupIds(), placement.subnetId(), clientToken, - propagatedInstanceTags(asg, launchSource), launchSource.userData(), + AutoScalingService.propagatedInstanceTags(asg, launchSource.instanceTags()), launchSource.userData(), launchSource.launchConfigurationName() == null ? launchSource.iamInstanceProfile() : asgService.resolveLaunchConfigurationProfile(launchSource.iamInstanceProfile()), launchSource.associatePublicIpAddress(), null, 0, launchZone, launchSource.metadataOptions(), null, @@ -718,23 +718,6 @@ public class AutoScalingReconciler { private record LaunchPlacement(String subnetId, String availabilityZone, int availableIpAddresses, boolean requiresIpv4Address) {} - private static List propagatedInstanceTags( - AutoScalingGroup asg, - LaunchSource launchSource) { - Map tags = new LinkedHashMap<>(); - for (io.github.hectorvent.floci.services.ec2.model.Tag tag : launchSource.instanceTags()) { - tags.put(tag.getKey(), tag.getValue()); - } - asg.getTags().forEach((key, value) -> { - if (asg.getTagPropagateAtLaunch().getOrDefault(key, false)) { - tags.put(key, value); - } - }); - return tags.entrySet().stream() - .map(entry -> new io.github.hectorvent.floci.services.ec2.model.Tag(entry.getKey(), entry.getValue())) - .toList(); - } - private void scaleIn(AutoScalingGroup asg, int count) { List candidates = asg.getInstances().stream() .filter(i -> "InService".equals(i.getLifecycleState())) diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index 413d2ffbfd..6003e53566 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder; import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; +import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.iam.PassedRoleLookup; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; @@ -35,6 +36,9 @@ import java.util.stream.Collectors; @ApplicationScoped public class AutoScalingService implements PassedRoleLookup { + /** The tag Auto Scaling puts on every instance it launches or attaches, valued with the group's name. */ + static final String GROUP_NAME_TAG = "aws:autoscaling:groupName"; + private static final Logger LOG = Logger.getLogger(AutoScalingService.class); private static final String FULLY_FORMED_LAUNCH_TEMPLATE = "You must use a valid fully-formed launch template. "; static final String MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE = @@ -846,25 +850,77 @@ public class AutoScalingService implements PassedRoleLookup { return instanceId != null && asg.getInstances().stream().anyMatch(i -> instanceId.equals(i.getInstanceId())); } + /** + * The tags an instance carries as a member of {@code asg}: the launch template's instance tags, + * then the group's PropagateAtLaunch tags, which win a key both set, then the group-name tag, + * which names {@code asg} whatever the other two say. + */ + static List propagatedInstanceTags(AutoScalingGroup asg, List templateTags) { + Map tags = new LinkedHashMap<>(); + templateTags.forEach(tag -> tags.put(tag.getKey(), tag.getValue())); + asg.getTags().forEach((key, value) -> { + if (asg.getTagPropagateAtLaunch().getOrDefault(key, false)) { + tags.put(key, value); + } + }); + tags.put(GROUP_NAME_TAG, asg.getAutoScalingGroupName()); + return tags.entrySet().stream().map(entry -> new Tag(entry.getKey(), entry.getValue())).toList(); + } + public void attachInstances(String region, String name, List instanceIds) { - AutoScalingGroup asg = requireGroup(region, name); - for (String id : instanceIds) { - AsgInstance inst = new AsgInstance(); - inst.setInstanceId(id); - inst.setLifecycleState("InService"); - inst.setHealthStatus("Healthy"); - inst.setAvailabilityZone( - asg.getAvailabilityZones().isEmpty() ? region + "a" : asg.getAvailabilityZones().get(0)); - inst.setLaunchConfigurationName(asg.getLaunchConfigurationName()); - inst.setLaunchTemplateId(asg.getLaunchTemplateId()); - inst.setLaunchTemplateName(asg.getLaunchTemplateName()); - inst.setLaunchTemplateVersion(asg.getLaunchTemplateVersion()); - asg.getInstances().add(inst); + // An instance joins once, however often the request names it. + List requested = new ArrayList<>(new LinkedHashSet<>(instanceIds)); + // The region lock keeps two groups from each attaching the same instance at once. + synchronized (lockFor(region)) { + synchronized (lockFor(asgKey(region, name))) { + AutoScalingGroup asg = requireGroup(region, name); + // An instance belongs to one group at a time, so the whole batch fails before any tag changes. + List conflicts = new ArrayList<>(); + for (AutoScalingGroup group : groups.values()) { + if (group == null || !region.equals(group.getRegion())) { + continue; + } + // Under the group's own lock, which guards its member list against the reconciler. + synchronized (lockFor(asgKey(region, group.getAutoScalingGroupName()))) { + for (AsgInstance member : group.getInstances()) { + if (requested.contains(member.getInstanceId())) { + conflicts.add("The Instance: " + member.getInstanceId() + + " is already part of AutoScalingGroup:" + group.getAutoScalingGroupName()); + } + } + } + } + if (!conflicts.isEmpty()) { + throw new AwsException("ValidationError", conflicts.toString(), 400); + } + // Attaching does not yet refuse an ID EC2 has no instance for, as AWS does, so such + // an ID gets no tags: they would outlive it in EC2's DescribeTags. + List existing = requested.stream() + .filter(id -> ec2Service.findInstanceForAccount(regionResolver.getAccountId(), region, id) + .isPresent()) + .toList(); + if (!existing.isEmpty()) { + ec2Service.createSystemTags(region, existing, propagatedInstanceTags(asg, List.of())); + } + for (String id : requested) { + AsgInstance inst = new AsgInstance(); + inst.setInstanceId(id); + inst.setLifecycleState("InService"); + inst.setHealthStatus("Healthy"); + inst.setAvailabilityZone( + asg.getAvailabilityZones().isEmpty() ? region + "a" : asg.getAvailabilityZones().get(0)); + inst.setLaunchConfigurationName(asg.getLaunchConfigurationName()); + inst.setLaunchTemplateId(asg.getLaunchTemplateId()); + inst.setLaunchTemplateName(asg.getLaunchTemplateName()); + inst.setLaunchTemplateVersion(asg.getLaunchTemplateVersion()); + asg.getInstances().add(inst); + } + if (asg.getInstances().size() > asg.getDesiredCapacity()) { + asg.setDesiredCapacity(asg.getInstances().size()); + } + groups.put(asgKey(region, name), asg); + } } - if (asg.getInstances().size() > asg.getDesiredCapacity()) { - asg.setDesiredCapacity(asg.getInstances().size()); - } - groups.put(asgKey(region, name), asg); } public void detachInstances(String region, String name, List instanceIds, @@ -874,6 +930,10 @@ public class AutoScalingService implements PassedRoleLookup { AutoScalingGroup asg = requireGroup(region, name); List detached = asg.getInstances().stream().map(AsgInstance::getInstanceId) .filter(instanceIds::contains).toList(); + if (!detached.isEmpty()) { + // Detaching removes only the group-name tag, and only where it still names this group. + ec2Service.deleteSystemTag(region, detached, GROUP_NAME_TAG, name); + } releaseRefreshOwnership(asg, detached); asg.getInstances().removeIf(i -> instanceIds.contains(i.getInstanceId())); if (decrementDesiredCapacity) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index ba19309488..72fcaae145 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -9984,6 +9984,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab public void deleteTags(String region, List resourceIds, List tagList) { validateTagTargets(region, resourceIds); validateUserTagKeys(tagList); + deleteResourceTags(region, resourceIds, tagList); + } + + /** Service-owned tag cleanup, separate from the public EC2 DeleteTags operation. */ + public void deleteSystemTag(String region, List resourceIds, String tagKey, String tagValue) { + deleteResourceTags(region, resourceIds, List.of(new Tag(tagKey, tagValue))); + } + + private void deleteResourceTags(String region, List resourceIds, List tagList) { ensureDefaultResources(region); for (String resourceId : resourceIds) { withTopologyLockIfNeeded(region, resourceId, () -> { diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingInstanceMembershipTagIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingInstanceMembershipTagIntegrationTest.java new file mode 100644 index 0000000000..d5b05d87ed --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingInstanceMembershipTagIntegrationTest.java @@ -0,0 +1,158 @@ +package io.github.hectorvent.floci.services.autoscaling; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The {@code aws:autoscaling:groupName} tag over a member's lifecycle, as the EC2 Auto Scaling user + * guide describes it: the group adds it to the instances it launches and attaches, attaching also + * applies the group's PropagateAtLaunch tags, and detaching removes only that one tag. + */ +@QuarkusTest +class AutoScalingInstanceMembershipTagIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=414141414141/20261022/us-east-1/autoscaling/aws4_request"; + private static final String EC2_AUTH = AUTH.replace("/autoscaling/", "/ec2/"); + private static final String GROUP_NAME_TAG = "aws:autoscaling:groupName"; + + @Inject + AutoScalingReconciler reconciler; + + @Test + void groupNameTagFollowsLaunchAttachAndDetach() { + String name = "membership-" + UUID.randomUUID(); + String other = name + "-other"; + given().header("Authorization", EC2_AUTH).formParam("Action", "CreateLaunchTemplate") + .formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", "ami-12345678") + .formParam("LaunchTemplateData.InstanceType", "t3.micro") + .formParam("LaunchTemplateData.TagSpecification.1.ResourceType", "instance") + .formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Key", "Source") + .formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Value", "template") + .post("/").then().statusCode(200); + given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", name) + .formParam("LaunchTemplate.LaunchTemplateName", name).formParam("LaunchTemplate.Version", "1") + .formParam("MinSize", "0").formParam("MaxSize", "3").formParam("DesiredCapacity", "1") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .formParam("Tags.member.1.Key", "Team").formParam("Tags.member.1.Value", "blue") + .formParam("Tags.member.1.PropagateAtLaunch", "true") + .formParam("Tags.member.2.Key", "Private").formParam("Tags.member.2.Value", "group-only") + .formParam("Tags.member.2.PropagateAtLaunch", "false") + .post("/").then().statusCode(200); + given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup") + .formParam("AutoScalingGroupName", other) + .formParam("LaunchTemplate.LaunchTemplateName", name).formParam("LaunchTemplate.Version", "1") + .formParam("MinSize", "0").formParam("MaxSize", "3").formParam("DesiredCapacity", "0") + .formParam("AvailabilityZones.member.1", "us-east-1a") + .post("/").then().statusCode(200); + String standalone = null; + try { + reconciler.reconcileAll(); + String launched = given().header("Authorization", AUTH) + .formParam("Action", "DescribeAutoScalingGroups").formParam("AutoScalingGroupNames.member.1", name) + .post("/").then().statusCode(200) + .body("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult" + + ".AutoScalingGroups.member.Instances.member.size()", equalTo(1)) + .extract().path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult" + + ".AutoScalingGroups.member.Instances.member.InstanceId"); + assertEquals(Map.of("Source", "template", "Team", "blue"), userTags(launched)); + assertEquals(name, instanceTags(launched).get(GROUP_NAME_TAG)); + assertEquals(List.of(launched), instancesTaggedWith(name)); + + standalone = given().header("Authorization", EC2_AUTH).formParam("Action", "RunInstances") + .formParam("ImageId", "ami-12345678").formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1").formParam("MaxCount", "1") + .formParam("TagSpecification.1.ResourceType", "instance") + .formParam("TagSpecification.1.Tag.1.Key", "Team") + .formParam("TagSpecification.1.Tag.1.Value", "red") + .formParam("TagSpecification.1.Tag.2.Key", "Owner") + .formParam("TagSpecification.1.Tag.2.Value", "me") + .post("/").then().statusCode(200) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + attach(name, standalone).statusCode(200); + assertEquals(Map.of("Owner", "me", "Team", "blue"), userTags(standalone)); + assertEquals(name, instanceTags(standalone).get(GROUP_NAME_TAG)); + + // An ID EC2 has no instance for gets no tags, which would otherwise outlive it in DescribeTags. + String unknown = "i-0abcdef1234567890"; + attach(other, unknown); + given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeTags") + .formParam("Filter.1.Name", "resource-id").formParam("Filter.1.Value.1", unknown) + .post("/").then().statusCode(200) + .body("DescribeTagsResponse.tagSet.item.size()", equalTo(0)); + + String alreadyMember = "[The Instance: " + standalone + " is already part of AutoScalingGroup:" + name + "]"; + for (String group : List.of(name, other)) { + attach(group, standalone).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo(alreadyMember)); + } + assertEquals(name, instanceTags(standalone).get(GROUP_NAME_TAG)); + + given().header("Authorization", AUTH).formParam("Action", "DetachInstances") + .formParam("AutoScalingGroupName", name).formParam("InstanceIds.member.1", standalone) + .formParam("ShouldDecrementDesiredCapacity", "true") + .post("/").then().statusCode(200); + assertEquals(Map.of("Owner", "me", "Team", "blue"), instanceTags(standalone)); + assertEquals(List.of(launched), instancesTaggedWith(name)); + } finally { + for (String group : List.of(name, other)) { + given().header("Authorization", AUTH).formParam("Action", "DeleteAutoScalingGroup") + .formParam("AutoScalingGroupName", group).formParam("ForceDelete", "true").post("/"); + } + if (standalone != null) { + given().header("Authorization", EC2_AUTH).formParam("Action", "TerminateInstances") + .formParam("InstanceId.1", standalone).post("/"); + } + given().header("Authorization", EC2_AUTH).formParam("Action", "DeleteLaunchTemplate") + .formParam("LaunchTemplateName", name).post("/"); + } + } + + private static ValidatableResponse attach(String group, String instanceId) { + return given().header("Authorization", AUTH).formParam("Action", "AttachInstances") + .formParam("AutoScalingGroupName", group).formParam("InstanceIds.member.1", instanceId) + .post("/").then(); + } + + private static Map instanceTags(String instanceId) { + XmlPath xml = given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeInstances") + .formParam("InstanceId.1", instanceId).post("/").then().statusCode(200).extract().xmlPath(); + String item = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.tagSet.item"; + List keys = xml.getList(item + ".key"); + List values = xml.getList(item + ".value"); + Map tags = new HashMap<>(); + for (int i = 0; i < keys.size(); i++) { + tags.put(keys.get(i), values.get(i)); + } + return tags; + } + + /** The instance's tags without the {@code aws:} ones AWS adds on its own, such as launch template ids. */ + private static Map userTags(String instanceId) { + Map tags = instanceTags(instanceId); + tags.keySet().removeIf(key -> key.startsWith("aws:")); + return tags; + } + + private static List instancesTaggedWith(String group) { + return given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeInstances") + .formParam("Filter.1.Name", "tag:" + GROUP_NAME_TAG).formParam("Filter.1.Value.1", group) + .post("/").then().statusCode(200).extract().xmlPath() + .getList("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java index 15a719cc8f..42aded3cc0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.autoscaling; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance; import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup; +import io.github.hectorvent.floci.services.autoscaling.model.CapacityReservationSpecification; import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration; import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy; import io.github.hectorvent.floci.services.autoscaling.model.ScalingActivity; @@ -28,6 +29,7 @@ import org.mockito.ArgumentCaptor; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -39,6 +41,7 @@ import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.isNull; @@ -183,7 +186,8 @@ class AutoScalingReconcilerTest { when(ec2Service.iamInstanceProfileArn(version.getData())) .thenReturn("arn:aws:iam::000000000000:instance-profile/app-profile"); List instanceTags = List.of(new Tag("app.ClusterId", "development")); - List propagatedTags = List.of(new Tag("app.ClusterId", "development"), new Tag("job-id", "2001")); + List propagatedTags = List.of(new Tag("app.ClusterId", "development"), new Tag("job-id", "2001"), + new Tag("aws:autoscaling:groupName", "app-asg")); version.getData().setTagSpecifications(List.of( new LaunchTemplateData.TagSpecification("instance", instanceTags))); when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of())) @@ -221,6 +225,74 @@ class AutoScalingReconcilerTest { assertEquals("development", tags.getValue().get(0).getValue()); assertEquals("job-id", tags.getValue().get(1).getKey()); assertEquals("2001", tags.getValue().get(1).getValue()); + assertEquals("aws:autoscaling:groupName", tags.getValue().get(2).getKey()); + assertEquals("app-asg", tags.getValue().get(2).getValue()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void scaleOutTagsTheActualGroupNameOverConflictingTemplateAndGroupTags(boolean propagateGroupNameTag) { + AutoScalingService asgService = scalingService(); + Ec2Service ec2Service = mock(Ec2Service.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class)); + AutoScalingGroup asg = launchTemplateAsg(); + asg.getTags().put("aws:autoscaling:groupName", "spoofed-group"); + asg.getTagPropagateAtLaunch().put("aws:autoscaling:groupName", propagateGroupNameTag); + asg.getTags().put("shared", "group-value"); + asg.getTagPropagateAtLaunch().put("shared", true); + asg.getTags().put("control-plane-only", "private"); + asg.getTagPropagateAtLaunch().put("control-plane-only", false); + stubLaunchTemplate(ec2Service, "ami-version-1", "t3.micro"); + LaunchTemplate version = ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("1")) + .getFirst(); + version.getData().setTagSpecifications(List.of(new LaunchTemplateData.TagSpecification("instance", List.of( + new Tag("aws:autoscaling:groupName", "spoofed-template"), new Tag("shared", "template-value"), + new Tag("template-only", "kept"))))); + when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true); + when(ec2Service.runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(), + any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(), + anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull())) + .thenReturn(reservation(ec2Instance("i-tagged", InstanceState.pending()))); + + reconciler.reconcile(asg); + + ArgumentCaptor> tags = ArgumentCaptor.captor(); + verify(ec2Service).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(), + any(), any(), any(), tags.capture(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), + any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()); + assertEquals(Map.of("aws:autoscaling:groupName", "app-asg", "shared", "group-value", "template-only", "kept"), + tags.getValue().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue))); + assertEquals("spoofed-group", asg.getTags().get("aws:autoscaling:groupName")); + } + + @Test + void capacityFallbackRetryStillTagsTheGroupName() { + AutoScalingService asgService = scalingService(); + Ec2Service ec2Service = mock(Ec2Service.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class)); + AutoScalingGroup asg = launchTemplateAsg(); + CapacityReservationSpecification capacity = new CapacityReservationSpecification(); + capacity.setCapacityReservationPreference("capacity-reservations-first"); + asg.setCapacityReservationSpecification(capacity); + stubLaunchTemplate(ec2Service, "ami-version-1", "t3.micro"); + when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true); + when(ec2Service.runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(), + any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(), + anyBoolean(), any(), any(), any(), eq(false), isNull(), any())) + .thenThrow(new AwsException("InsufficientInstanceCapacity", "no reserved capacity", 400)) + .thenReturn(reservation(ec2Instance("i-fallback", InstanceState.pending()))); + + reconciler.reconcile(asg); + + ArgumentCaptor> tags = ArgumentCaptor.captor(); + verify(ec2Service, times(2)).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(), + any(), any(), any(), tags.capture(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), + any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), any()); + for (List launchTags : tags.getAllValues()) { + assertEquals(Map.of("aws:autoscaling:groupName", "app-asg"), + launchTags.stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue))); + } + assertEquals("i-fallback", asg.getInstances().getFirst().getInstanceId()); } @Test @@ -238,7 +310,7 @@ class AutoScalingReconcilerTest { Reservation reservation = new Reservation(); reservation.setInstances(List.of(ec2Instance)); when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"), - eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), eq(List.of()), + eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(null), isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation); @@ -333,7 +405,7 @@ class AutoScalingReconcilerTest { Reservation reservation = new Reservation(); reservation.setInstances(List.of(ec2Instance)); when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"), - eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), eq(List.of()), + eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(null), isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation); @@ -380,7 +452,7 @@ class AutoScalingReconcilerTest { reservation.setInstances(List.of(ec2Instance)); when(ec2Service.runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"), eq(1), eq(1), eq(null), anyList(), eq(null), eq(null), - anyList(), eq(null), eq(null), eq(associatePublicIp), + onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(associatePublicIp), isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation); @@ -388,7 +460,7 @@ class AutoScalingReconcilerTest { verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"), eq(1), eq(1), eq(null), anyList(), eq(null), eq(null), - anyList(), eq(null), eq(null), eq(associatePublicIp), + onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(associatePublicIp), isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull()); } @@ -422,7 +494,7 @@ class AutoScalingReconcilerTest { reservation.setInstances(List.of(ec2Instance)); when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-7"), eq("t3.micro"), eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), - eq(List.of()), eq(null), eq(null), eq(null), + onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(null), isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation); @@ -480,7 +552,7 @@ class AutoScalingReconcilerTest { reservation.setInstances(List.of(ec2Instance)); when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"), eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), - eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null), + onlyGroupNameTag("app-asg"), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null), isNull(), eq(0), isNull(), eq(metadata), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation); @@ -493,7 +565,7 @@ class AutoScalingReconcilerTest { assertEquals("t3.small", asg.getInstances().getFirst().getInstanceType()); verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"), eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), - eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null), + onlyGroupNameTag("app-asg"), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null), isNull(), eq(0), isNull(), eq(metadata), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull()); assertNull(version.getData().getUserData()); } @@ -1100,6 +1172,13 @@ class AutoScalingReconcilerTest { return asg; } + /** Matches the tags of a launch whose template and group add none of their own. */ + private static List onlyGroupNameTag(String groupName) { + return argThat(tags -> tags != null && tags.size() == 1 + && "aws:autoscaling:groupName".equals(tags.getFirst().getKey()) + && groupName.equals(tags.getFirst().getValue())); + } + private static void stubLaunchTemplate(Ec2Service ec2Service, String imageId, String instanceType) { LaunchTemplate launchTemplate = new LaunchTemplate(); launchTemplate.setLaunchTemplateId("lt-123"); diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java index 8b636eb90a..828c323c80 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java @@ -22,11 +22,13 @@ import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; import io.github.hectorvent.floci.services.ec2.model.Reservation; +import io.github.hectorvent.floci.services.ec2.model.Tag; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -36,12 +38,19 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPOutputStream; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -136,6 +145,110 @@ class AutoScalingServiceTest { assertNull(group.getLaunchConfigurationName()); } + @Test + void attachedInstancesReceiveThePropagatingTagsAndTheirGroupName() { + service.ec2Service = mock(Ec2Service.class); + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst(); + group.getTags().put("env", "group"); + group.getTags().put("hidden", "group"); + group.getTags().put("aws:autoscaling:groupName", "spoofed"); + group.getTagPropagateAtLaunch().putAll(Map.of("env", true, "hidden", false, + "aws:autoscaling:groupName", true)); + ec2HoldsInstances("i-attached"); + + service.attachInstances(REGION, "test-asg", List.of("i-attached")); + + ArgumentCaptor> appliedTags = ArgumentCaptor.captor(); + verify(service.ec2Service).createSystemTags(eq(REGION), eq(List.of("i-attached")), appliedTags.capture()); + assertEquals(Map.of("env", "group", "aws:autoscaling:groupName", "test-asg"), + appliedTags.getValue().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue))); + assertEquals(List.of("i-attached"), group.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + } + + @Test + void attachTagsOnlyTheInstancesEc2Holds() { + service.ec2Service = mock(Ec2Service.class); + ec2HoldsInstances("i-held"); + + service.attachInstances(REGION, "test-asg", List.of("i-held", "i-unknown")); + + verify(service.ec2Service).createSystemTags(eq(REGION), eq(List.of("i-held")), anyList()); + verify(service.ec2Service, times(1)).createSystemTags(anyString(), anyList(), anyList()); + } + + @Test + void attachCountsARepeatedInstanceOnce() { + service.ec2Service = mock(Ec2Service.class); + ec2HoldsInstances("i-repeated"); + + service.attachInstances(REGION, "test-asg", List.of("i-repeated", "i-repeated")); + + verify(service.ec2Service).createSystemTags(eq(REGION), eq(List.of("i-repeated")), anyList()); + assertEquals(List.of("i-repeated"), service.describeAutoScalingGroups(REGION, List.of("test-asg")) + .getFirst().getInstances().stream().map(AsgInstance::getInstanceId).toList()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void attachRejectsAnInstanceThatAlreadyBelongsToAGroupBeforeTaggingAnyOfTheBatch(boolean sameGroup) { + service.createAutoScalingGroup(REGION, "other-asg", null, "lt-original", null, "1", null, + 0, 3, 0, 300, List.of(REGION + "a"), List.of(), List.of(), List.of(), + "EC2", 0, List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none()); + service.ec2Service = mock(Ec2Service.class); + service.attachInstances(REGION, "test-asg", List.of("i-owned")); + clearInvocations(service.ec2Service); + String target = sameGroup ? "test-asg" : "other-asg"; + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of(target)).getFirst(); + int desired = group.getDesiredCapacity(); + List members = group.getInstances().stream().map(AsgInstance::getInstanceId).toList(); + + AwsException failure = assertThrows(AwsException.class, + () -> service.attachInstances(REGION, target, List.of("i-free", "i-owned"))); + + assertEquals("ValidationError", failure.getErrorCode()); + assertEquals(400, failure.getHttpStatus()); + assertEquals("[The Instance: i-owned is already part of AutoScalingGroup:test-asg]", failure.getMessage()); + assertEquals(members, group.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + assertEquals(desired, group.getDesiredCapacity()); + verifyNoInteractions(service.ec2Service); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void detachRemovesOnlyTheDetachedInstancesGroupNameTag(boolean decrementDesiredCapacity) { + service.ec2Service = mock(Ec2Service.class); + service.attachInstances(REGION, "test-asg", List.of("i-detached", "i-retained")); + + service.detachInstances(REGION, "test-asg", List.of("i-detached"), decrementDesiredCapacity); + + verify(service.ec2Service).deleteSystemTag( + REGION, List.of("i-detached"), "aws:autoscaling:groupName", "test-asg"); + AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst(); + assertEquals(List.of("i-retained"), group.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + assertEquals(decrementDesiredCapacity ? 1 : 2, group.getDesiredCapacity()); + } + + @Test + void detachingAnInstanceTheGroupDoesNotHoldChangesNoTags() { + service.ec2Service = mock(Ec2Service.class); + service.attachInstances(REGION, "test-asg", List.of("i-member")); + clearInvocations(service.ec2Service); + + service.detachInstances(REGION, "test-asg", List.of("i-stranger"), false); + + verify(service.ec2Service, never()).deleteSystemTag(anyString(), anyList(), anyString(), anyString()); + assertEquals(List.of("i-member"), service.describeAutoScalingGroups(REGION, List.of("test-asg")) + .getFirst().getInstances().stream().map(AsgInstance::getInstanceId).toList()); + } + + private void ec2HoldsInstances(String... instanceIds) { + for (String id : instanceIds) { + Instance instance = new Instance(); + instance.setInstanceId(id); + when(service.ec2Service.findInstanceForAccount("000000000000", REGION, id)).thenReturn(Optional.of(instance)); + } + } + @Test void anInstanceRefreshResolvesTheProfileOfTheTemplateItsGroupLaunchesFromOnceItApplies() { Ec2Service ec2Service = mock(Ec2Service.class); @@ -971,6 +1084,7 @@ class AutoScalingServiceTest { StorageBackedMap groups = new StorageBackedMap<>(storage); groups.putAll(service.groups); service.groups = groups; + service.ec2Service = mock(Ec2Service.class); service.attachInstances(REGION, "test-asg", List.of("i-live")); service.createOrUpdateTags(REGION, "test-asg", "auto-scaling-group", Map.of("k", "v"), Map.of()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 95bf1712ea..6d03a8567d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -202,6 +202,27 @@ class Ec2ServiceTest { assertEquals(List.of(membership), instance.getTags()); } + @Test + void deleteSystemTagRemovesTheTagOnlyWhenItsValueMatches() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + Tag membership = new Tag("aws:autoscaling:groupName", "group-a"); + Tag userTag = new Tag("env", "test"); + List ids = List.of(service.runInstances("us-east-1", "ami-test", "t3.micro", + 1, 1, null, List.of(), null, null, List.of(membership, userTag), null, null) + .getInstances().getFirst().getInstanceId()); + + service.deleteSystemTag("us-east-1", ids, membership.getKey(), "group-b"); + assertEquals(List.of(membership, userTag), service.describeInstances("us-east-1", ids, Map.of()) + .getFirst().getInstances().getFirst().getTags()); + + service.deleteSystemTag("us-east-1", ids, membership.getKey(), "group-a"); + assertEquals(List.of(userTag), service.describeInstances("us-east-1", ids, Map.of()) + .getFirst().getInstances().getFirst().getTags()); + assertEquals(List.of(userTag), service.resourceTags("us-east-1", ids.getFirst())); + } + @Test void subnetAvailableAddressesTrackAllocationsAndRelease() {