feat(autoscaling): support group reconciliation and refresh (#1393)

* feat(autoscaling): support group reconciliation and refresh

* fix(ec2): align instance runtime parity

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Jason van ZylandHector Ventura authored and GitHub committed 2026-06-18 18:14:19 -05:00
1 parent 31991ac5c3
commit 56706217d3
24 files changed
+3067 -132

No files matched your search

@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@@ -17,6 +18,8 @@ class AutoScalingIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260501/us-east-1/autoscaling/aws4_request";
private static String policyArn;
private static String instanceRefreshId;
private static String pagedInstanceRefreshId;
// ── Launch Configurations ─────────────────────────────────────────────────
@@ -386,10 +389,216 @@ class AutoScalingIntegrationTest {
.body(containsString("DescribeScalingActivitiesResponse"));
}
@Test
@Order(21)
void createAutoScalingGroupWithLaunchTemplateId() {
given()
.formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("LaunchTemplate.LaunchTemplateId", "lt-0123456789abcdef0")
.formParam("LaunchTemplate.Version", "$Latest")
.formParam("MinSize", "0")
.formParam("MaxSize", "1")
.formParam("DesiredCapacity", "0")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.formParam("VPCZoneIdentifier", "subnet-12345678,subnet-87654321")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("CreateAutoScalingGroupResponse"));
given()
.formParam("Action", "CreateOrUpdateTags")
.formParam("Tags.member.1.ResourceId", "my-lt-asg")
.formParam("Tags.member.1.ResourceType", "auto-scaling-group")
.formParam("Tags.member.1.Key", "owner")
.formParam("Tags.member.1.Value", "sample-app")
.formParam("Tags.member.1.PropagateAtLaunch", "true")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("CreateOrUpdateTagsResponse"));
}
@Test
@Order(22)
void describeAutoScalingGroupWithLaunchTemplateId() {
given()
.formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", "my-lt-asg")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("my-lt-asg"))
.body(containsString("<LaunchTemplateId>lt-0123456789abcdef0</LaunchTemplateId>"))
.body(containsString("<Version>$Latest</Version>"))
.body(containsString("<VPCZoneIdentifier>subnet-12345678,subnet-87654321</VPCZoneIdentifier>"))
.body(containsString("owner"))
.body(containsString("sample-app"));
given()
.formParam("Action", "DeleteTags")
.formParam("Tags.member.1.ResourceId", "my-lt-asg")
.formParam("Tags.member.1.ResourceType", "auto-scaling-group")
.formParam("Tags.member.1.Key", "owner")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("DeleteTagsResponse"));
given()
.formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", "my-lt-asg")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("sample-app")));
}
@Test
@Order(23)
void startInstanceRefresh() {
instanceRefreshId = given()
.formParam("Action", "StartInstanceRefresh")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("Strategy", "Rolling")
.formParam("DesiredConfiguration.LaunchTemplate.LaunchTemplateId", "lt-0fedcba9876543210")
.formParam("DesiredConfiguration.LaunchTemplate.Version", "2")
.formParam("Preferences.MinHealthyPercentage", "90")
.formParam("Preferences.MaxHealthyPercentage", "120")
.formParam("Preferences.InstanceWarmup", "200")
.formParam("Preferences.SkipMatching", "true")
.formParam("Preferences.AutoRollback", "true")
.formParam("Preferences.CheckpointPercentages.member.1", "50")
.formParam("Preferences.CheckpointPercentages.member.2", "100")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("StartInstanceRefreshResponse"))
.body(containsString("InstanceRefreshId"))
.extract().xmlPath()
.getString("StartInstanceRefreshResponse.StartInstanceRefreshResult.InstanceRefreshId");
assertThat(instanceRefreshId, not(emptyOrNullString()));
}
@Test
@Order(24)
void describeInstanceRefreshes() {
String body = given()
.formParam("Action", "DescribeInstanceRefreshes")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("InstanceRefreshIds.member.1", instanceRefreshId)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("DescribeInstanceRefreshesResponse"))
.extract().body().asString();
assertThat(body, containsString(instanceRefreshId));
assertThat(body, containsString("<AutoScalingGroupName>my-lt-asg</AutoScalingGroupName>"));
assertThat(body, containsString("<Status>Successful</Status>"));
assertThat(body, containsString("<PercentageComplete>100</PercentageComplete>"));
assertThat(body, containsString("<InstancesToUpdate>0</InstancesToUpdate>"));
assertThat(body, containsString("<Strategy>Rolling</Strategy>"));
assertThat(body, containsString("<LaunchTemplateId>lt-0fedcba9876543210</LaunchTemplateId>"));
assertThat(body, containsString("<Version>2</Version>"));
assertThat(body, containsString("<MinHealthyPercentage>90</MinHealthyPercentage>"));
assertThat(body, containsString("<MaxHealthyPercentage>120</MaxHealthyPercentage>"));
assertThat(body, containsString("<InstanceWarmup>200</InstanceWarmup>"));
assertThat(body, containsString("<SkipMatching>true</SkipMatching>"));
assertThat(body, containsString("<AutoRollback>true</AutoRollback>"));
assertThat(body, containsString("<CheckpointPercentages>"));
given()
.formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", "my-lt-asg")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<LaunchTemplateId>lt-0fedcba9876543210</LaunchTemplateId>"))
.body(containsString("<Version>2</Version>"));
}
@Test
@Order(25)
void describeInstanceRefreshesPaginatesNewestFirst() {
pagedInstanceRefreshId = given()
.formParam("Action", "StartInstanceRefresh")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("Preferences.SkipMatching", "true")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath()
.getString("StartInstanceRefreshResponse.StartInstanceRefreshResult.InstanceRefreshId");
String firstPage = given()
.formParam("Action", "DescribeInstanceRefreshes")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("MaxRecords", "1")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<NextToken>1</NextToken>"))
.extract().body().asString();
assertThat(firstPage, containsString(pagedInstanceRefreshId));
assertThat(firstPage, not(containsString(instanceRefreshId)));
given()
.formParam("Action", "DescribeInstanceRefreshes")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("MaxRecords", "1")
.formParam("NextToken", "1")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(instanceRefreshId))
.body(not(containsString("<NextToken>")));
}
@Test
@Order(26)
void deleteLaunchTemplateAutoScalingGroup() {
given()
.formParam("Action", "DeleteAutoScalingGroup")
.formParam("AutoScalingGroupName", "my-lt-asg")
.formParam("ForceDelete", "true")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("DeleteAutoScalingGroupResponse"));
}
// ── Cleanup ───────────────────────────────────────────────────────────────
@Test
@Order(21)
@Order(27)
void deleteAutoScalingGroup() {
given()
.formParam("Action", "DeleteAutoScalingGroup")
@@ -404,7 +613,7 @@ class AutoScalingIntegrationTest {
}
@Test
@Order(22)
@Order(28)
void deleteLaunchConfiguration() {
given()
.formParam("Action", "DeleteLaunchConfiguration")
@@ -418,7 +627,7 @@ class AutoScalingIntegrationTest {
}
@Test
@Order(23)
@Order(29)
void describeAutoScalingGroupsEmpty() {
given()
.formParam("Action", "DescribeAutoScalingGroups")
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AutoScalingQueryHandlerTest {
private static final String REGION = "us-east-1";
@Test
void startAndDescribeInstanceRefreshUseAwsQueryXmlShape() {
AutoScalingService service = new AutoScalingService();
service.regionResolver = new RegionResolver(REGION, "000000000000");
service.createAutoScalingGroup(REGION,
"query-asg",
null,
"lt-original",
null,
"1",
0,
3,
1,
300,
List.of("us-east-1a"),
List.of(),
List.of(),
List.of(),
"EC2",
0,
List.of("Default"),
java.util.Map.of());
AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service);
MultivaluedHashMap<String, String> startParams = new MultivaluedHashMap<>();
startParams.add("AutoScalingGroupName", "query-asg");
startParams.add("DesiredConfiguration.LaunchTemplate.LaunchTemplateId", "lt-updated");
startParams.add("DesiredConfiguration.LaunchTemplate.Version", "2");
startParams.add("Preferences.MinHealthyPercentage", "90");
startParams.add("Preferences.SkipMatching", "true");
Response startResponse = handler.handle("StartInstanceRefresh", startParams, REGION);
assertEquals(200, startResponse.getStatus());
String startXml = (String) startResponse.getEntity();
assertTrue(startXml.contains("<StartInstanceRefreshResponse"));
assertTrue(startXml.contains("<StartInstanceRefreshResult>"));
assertTrue(startXml.contains("<InstanceRefreshId>"));
String refreshId = service.describeInstanceRefreshes(REGION, "query-asg", List.of(), null, null)
.instanceRefreshes().getFirst().getInstanceRefreshId();
MultivaluedHashMap<String, String> describeParams = new MultivaluedHashMap<>();
describeParams.add("AutoScalingGroupName", "query-asg");
describeParams.add("InstanceRefreshIds.member.1", refreshId);
Response describeResponse = handler.handle("DescribeInstanceRefreshes", describeParams, REGION);
assertEquals(200, describeResponse.getStatus());
String describeXml = (String) describeResponse.getEntity();
assertTrue(describeXml.contains("<DescribeInstanceRefreshesResponse"));
assertTrue(describeXml.contains("<InstanceRefreshes>"));
assertTrue(describeXml.contains("<InstanceRefreshId>" + refreshId + "</InstanceRefreshId>"));
assertTrue(describeXml.contains("<AutoScalingGroupName>query-asg</AutoScalingGroupName>"));
assertTrue(describeXml.contains("<Status>Successful</Status>"));
assertTrue(describeXml.contains("<PercentageComplete>100</PercentageComplete>"));
assertTrue(describeXml.contains("<InstancesToUpdate>0</InstancesToUpdate>"));
assertTrue(describeXml.contains("<DesiredConfiguration>"));
assertTrue(describeXml.contains("<LaunchTemplateId>lt-updated</LaunchTemplateId>"));
assertTrue(describeXml.contains("<Version>2</Version>"));
assertTrue(describeXml.contains("<Preferences>"));
assertTrue(describeXml.contains("<MinHealthyPercentage>90</MinHealthyPercentage>"));
assertTrue(describeXml.contains("<SkipMatching>true</SkipMatching>"));
}
@Test
void describeAutoScalingGroupsIncludesInstanceLaunchTemplateMetadata() {
AutoScalingService service = new AutoScalingService();
service.regionResolver = new RegionResolver(REGION, "000000000000");
service.createAutoScalingGroup(REGION,
"query-asg",
null,
"lt-current",
null,
"$Latest",
0,
3,
1,
300,
List.of("us-east-1a"),
List.of(),
List.of(),
List.of(),
"EC2",
0,
List.of("Default"),
java.util.Map.of());
AsgInstance instance = new AsgInstance();
instance.setInstanceId("i-current");
instance.setAvailabilityZone("us-east-1a");
instance.setLifecycleState("InService");
instance.setHealthStatus("Healthy");
instance.setLaunchTemplateId("lt-current");
instance.setLaunchTemplateVersion("7");
service.describeAutoScalingGroups(REGION, List.of("query-asg"))
.getFirst()
.getInstances()
.add(instance);
AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service);
MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
params.add("AutoScalingGroupNames.member.1", "query-asg");
Response response = handler.handle("DescribeAutoScalingGroups", params, REGION);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<InstanceId>i-current</InstanceId>"));
assertTrue(xml.contains("<LaunchTemplate>"));
assertTrue(xml.contains("<LaunchTemplateId>lt-current</LaunchTemplateId>"));
assertTrue(xml.contains("<Version>7</Version>"));
}
}
@@ -0,0 +1,219 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
import io.github.hectorvent.floci.services.elbv2.model.TargetHealth;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.when;
class AutoScalingReconcilerTest {
@Test
void pendingInstancesCountAsActiveCapacity() {
AutoScalingGroup asg = new AutoScalingGroup();
asg.getInstances().add(instance("Pending"));
asg.getInstances().add(instance("InService"));
asg.getInstances().add(instance("Terminating"));
asg.getInstances().add(instance("Terminated"));
asg.getInstances().add(instance("Detached"));
assertEquals(2, AutoScalingReconciler.activeCapacity(asg));
}
@Test
void reconcileCompletesSettledInstanceRefreshes() {
AutoScalingService asgService = mock(AutoScalingService.class);
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
asg.setDesiredCapacity(0);
reconciler.reconcile(asg);
verify(asgService).completeInstanceRefreshIfSettled("us-east-1", "app-asg");
}
@Test
void scaleOutUsesRequestedLaunchTemplateVersionData() {
AutoScalingService asgService = mock(AutoScalingService.class);
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
asg.setDesiredCapacity(1);
asg.setLaunchTemplateId("lt-123");
asg.setLaunchTemplateVersion("1");
LaunchTemplate launchTemplate = new LaunchTemplate();
launchTemplate.setLaunchTemplateId("lt-123");
LaunchTemplate version = new LaunchTemplate();
version.setLatestVersionNumber("1");
version.setImageId("ami-version-1");
version.setInstanceType("t3.micro");
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
.thenReturn(List.of(launchTemplate));
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("1")))
.thenReturn(List.of(version));
Instance ec2Instance = new Instance();
ec2Instance.setInstanceId("i-launched");
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(null), eq(null))).thenReturn(reservation);
reconciler.reconcile(asg);
assertEquals(1, asg.getInstances().size());
assertEquals("i-launched", asg.getInstances().getFirst().getInstanceId());
assertEquals("lt-123", asg.getInstances().getFirst().getLaunchTemplateId());
assertEquals("1", asg.getInstances().getFirst().getLaunchTemplateVersion());
verify(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(null), eq(null));
}
@Test
void scaleOutStoresResolvedLaunchTemplateVersionForAliases() {
AutoScalingService asgService = mock(AutoScalingService.class);
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
asg.setDesiredCapacity(1);
asg.setLaunchTemplateId("lt-123");
asg.setLaunchTemplateVersion("$Latest");
LaunchTemplate launchTemplate = new LaunchTemplate();
launchTemplate.setLaunchTemplateId("lt-123");
LaunchTemplate version = new LaunchTemplate();
version.setLatestVersionNumber("7");
version.setImageId("ami-version-7");
version.setInstanceType("t3.micro");
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
.thenReturn(List.of(launchTemplate));
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("$Latest")))
.thenReturn(List.of(version));
Instance ec2Instance = new Instance();
ec2Instance.setInstanceId("i-launched");
Reservation reservation = new Reservation();
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))).thenReturn(reservation);
reconciler.reconcile(asg);
assertEquals("$Latest", asg.getLaunchTemplateVersion());
assertEquals("7", asg.getInstances().getFirst().getLaunchTemplateVersion());
}
@Test
void reconcileDeregistersTargetsThatAreNotActiveAsgInstances() {
AutoScalingService asgService = mock(AutoScalingService.class);
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
asg.setDesiredCapacity(1);
asg.setTargetGroupARNs(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/app/123"));
asg.getInstances().add(instance("i-active", "InService"));
when(ec2Service.isInstanceContainerRunning("i-active")).thenReturn(true);
when(elbV2Service.describeTargetHealth(asg.getRegion(), asg.getTargetGroupARNs().getFirst(), List.of()))
.thenReturn(List.of(targetHealth("i-active"), targetHealth("i-stale")));
reconciler.reconcile(asg);
ArgumentCaptor<List<TargetDescription>> targets = ArgumentCaptor.captor();
verify(elbV2Service).deregisterTargets(
eq(asg.getRegion()),
eq(asg.getTargetGroupARNs().getFirst()),
targets.capture());
assertEquals(1, targets.getValue().size());
assertEquals("i-stale", targets.getValue().getFirst().getId());
verify(asgService).saveAutoScalingGroup(asg);
verify(ec2Service, never()).terminateInstances(asg.getRegion(), List.of("i-active"));
}
@Test
void reconcilePromotesPendingAsgInstanceWhenEc2InstanceIsRunning() {
AutoScalingService asgService = mock(AutoScalingService.class);
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
asg.setDesiredCapacity(1);
asg.getInstances().add(instance("i-pending", "Pending"));
Instance ec2Instance = new Instance();
ec2Instance.setInstanceId("i-pending");
ec2Instance.setState(InstanceState.running());
Reservation reservation = new Reservation();
reservation.setInstances(List.of(ec2Instance));
when(ec2Service.describeInstances(asg.getRegion(), List.of("i-pending"), null))
.thenReturn(List.of(reservation));
when(ec2Service.isInstanceContainerRunning("i-pending")).thenReturn(true);
reconciler.reconcile(asg);
assertEquals("InService", asg.getInstances().getFirst().getLifecycleState());
assertEquals("Healthy", asg.getInstances().getFirst().getHealthStatus());
verify(asgService).recordActivity(
eq(asg.getRegion()),
eq(asg.getAutoScalingGroupName()),
eq("Launching a new EC2 instance: i-pending"),
eq("An instance was started in response to a desired capacity change."),
eq("Successful"));
verify(asgService, times(2)).saveAutoScalingGroup(asg);
}
private static AsgInstance instance(String lifecycleState) {
AsgInstance instance = new AsgInstance();
instance.setLifecycleState(lifecycleState);
return instance;
}
private static AsgInstance instance(String instanceId, String lifecycleState) {
AsgInstance instance = instance(lifecycleState);
instance.setInstanceId(instanceId);
instance.setHealthStatus("Healthy");
return instance;
}
private static TargetHealth targetHealth(String instanceId) {
TargetDescription target = new TargetDescription();
target.setId(instanceId);
TargetHealth health = new TargetHealth();
health.setTarget(target);
return health;
}
}
@@ -0,0 +1,334 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class AutoScalingServiceTest {
private static final String REGION = "us-east-1";
private AutoScalingService service;
@BeforeEach
void setUp() {
service = new AutoScalingService();
service.regionResolver = new RegionResolver(REGION, "000000000000");
service.createAutoScalingGroup(REGION,
"test-asg",
null,
"lt-original",
null,
"1",
0,
3,
1,
300,
List.of("us-east-1a"),
List.of("subnet-12345678"),
List.of(),
List.of(),
"EC2",
0,
List.of("Default"),
java.util.Map.of());
}
@Test
void startInstanceRefreshStoresCompletedRefreshAndAppliesDesiredLaunchTemplate() {
InstanceRefresh request = new InstanceRefresh();
request.setStrategy("Rolling");
request.setDesiredLaunchTemplateId("lt-updated");
request.setDesiredLaunchTemplateVersion("2");
request.setMinHealthyPercentage(90);
request.setMaxHealthyPercentage(120);
request.setInstanceWarmup(200);
request.setSkipMatching(true);
request.setAutoRollback(true);
request.setCheckpointPercentages(List.of(50, 100));
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
assertNotNull(refresh.getInstanceRefreshId());
assertEquals("test-asg", refresh.getAutoScalingGroupName());
assertEquals("Rolling", refresh.getStrategy());
assertEquals("Successful", refresh.getStatus());
assertEquals(100, refresh.getPercentageComplete());
assertEquals(0, refresh.getInstancesToUpdate());
assertEquals("lt-updated", refresh.getDesiredLaunchTemplateId());
assertEquals("2", refresh.getDesiredLaunchTemplateVersion());
assertEquals(90, refresh.getMinHealthyPercentage());
assertEquals(120, refresh.getMaxHealthyPercentage());
assertEquals(200, refresh.getInstanceWarmup());
assertEquals(Boolean.TRUE, refresh.getSkipMatching());
assertEquals(Boolean.TRUE, refresh.getAutoRollback());
assertEquals(List.of(50, 100), refresh.getCheckpointPercentages());
AutoScalingService.InstanceRefreshPage page =
service.describeInstanceRefreshes(REGION, "test-asg", List.of(refresh.getInstanceRefreshId()), null, null);
assertEquals(1, page.instanceRefreshes().size());
assertEquals(refresh.getInstanceRefreshId(), page.instanceRefreshes().getFirst().getInstanceRefreshId());
assertNull(page.nextToken());
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
assertEquals("lt-updated", group.getLaunchTemplateId());
assertEquals("2", group.getLaunchTemplateVersion());
assertNull(group.getLaunchConfigurationName());
}
@Test
void describeInstanceRefreshesPaginatesNewestFirst() {
InstanceRefresh first = service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh());
InstanceRefresh second = service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh());
AutoScalingService.InstanceRefreshPage firstPage =
service.describeInstanceRefreshes(REGION, "test-asg", List.of(), 1, null);
assertEquals(1, firstPage.instanceRefreshes().size());
assertEquals(second.getInstanceRefreshId(), firstPage.instanceRefreshes().getFirst().getInstanceRefreshId());
assertEquals("1", firstPage.nextToken());
AutoScalingService.InstanceRefreshPage secondPage =
service.describeInstanceRefreshes(REGION, "test-asg", List.of(), 1, firstPage.nextToken());
assertEquals(1, secondPage.instanceRefreshes().size());
assertEquals(first.getInstanceRefreshId(), secondPage.instanceRefreshes().getFirst().getInstanceRefreshId());
assertNull(secondPage.nextToken());
}
@Test
void startInstanceRefreshMarksActiveInstancesForReplacement() {
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh());
assertEquals("InProgress", refresh.getStatus());
assertEquals("Instance refresh in progress.", refresh.getStatusReason());
assertEquals(0, refresh.getPercentageComplete());
assertEquals(1, refresh.getInstancesToUpdate());
assertNull(refresh.getEndTime());
AsgInstance instance = service.describeAutoScalingGroups(REGION, List.of("test-asg"))
.getFirst()
.getInstances()
.getFirst();
assertEquals("Terminating", instance.getLifecycleState());
}
@Test
void startInstanceRefreshRejectsSecondRefreshWhileFirstIsActive() {
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh());
AwsException error = assertThrows(AwsException.class,
() -> service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh()));
assertEquals("InstanceRefreshInProgress", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void startInstanceRefreshSkipMatchingLeavesMatchingInstancesInService() {
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-matching", "InService", "lt-original", "1");
InstanceRefresh request = new InstanceRefresh();
request.setSkipMatching(true);
service.startInstanceRefresh(REGION, "test-asg", request);
AsgInstance instance = service.describeAutoScalingGroups(REGION, List.of("test-asg"))
.getFirst()
.getInstances()
.getFirst();
assertEquals("InService", instance.getLifecycleState());
}
@Test
void startInstanceRefreshWithLaunchTemplateAliasDoesNotSkipExistingInstances() {
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.setLaunchTemplateVersion("$Latest");
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh request = new InstanceRefresh();
request.setSkipMatching(true);
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
assertEquals("InProgress", refresh.getStatus());
assertEquals(1, refresh.getInstancesToUpdate());
AsgInstance original = group.getInstances().getFirst();
assertEquals("Terminating", original.getLifecycleState());
group.getInstances().clear();
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-replacement", "InService", "lt-original", "2");
service.completeInstanceRefreshIfSettled(REGION, "test-asg");
InstanceRefresh completed = service.describeInstanceRefreshes(
REGION, "test-asg", List.of(refresh.getInstanceRefreshId()), null, null)
.instanceRefreshes()
.getFirst();
assertEquals("Successful", completed.getStatus());
assertEquals(0, completed.getInstancesToUpdate());
}
@Test
void startInstanceRefreshWithDefaultLaunchTemplateAliasDoesNotSkipExistingInstances() {
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.setLaunchTemplateVersion("$Default");
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh request = new InstanceRefresh();
request.setSkipMatching(true);
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
assertEquals("InProgress", refresh.getStatus());
assertEquals(1, refresh.getInstancesToUpdate());
AsgInstance original = group.getInstances().getFirst();
assertEquals("Terminating", original.getLifecycleState());
group.getInstances().clear();
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-replacement", "InService", "lt-original", "2");
service.completeInstanceRefreshIfSettled(REGION, "test-asg");
InstanceRefresh completed = service.describeInstanceRefreshes(
REGION, "test-asg", List.of(refresh.getInstanceRefreshId()), null, null)
.instanceRefreshes()
.getFirst();
assertEquals("Successful", completed.getStatus());
assertEquals(0, completed.getInstancesToUpdate());
}
@Test
void startInstanceRefreshWithDefaultLaunchTemplateVersionDoesNotSkipExistingInstances() {
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.setLaunchTemplateVersion(null);
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh request = new InstanceRefresh();
request.setSkipMatching(true);
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
assertEquals("InProgress", refresh.getStatus());
assertEquals(1, refresh.getInstancesToUpdate());
AsgInstance original = group.getInstances().getFirst();
assertEquals("Terminating", original.getLifecycleState());
}
@Test
void startInstanceRefreshWithBlankLaunchTemplateVersionDoesNotSkipExistingInstances() {
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.setLaunchTemplateVersion("");
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh request = new InstanceRefresh();
request.setSkipMatching(true);
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
assertEquals("InProgress", refresh.getStatus());
assertEquals(1, refresh.getInstancesToUpdate());
AsgInstance original = group.getInstances().getFirst();
assertEquals("Terminating", original.getLifecycleState());
}
@Test
void completeInstanceRefreshMarksSettledReplacementSuccessful() {
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh request = new InstanceRefresh();
request.setDesiredLaunchTemplateId("lt-updated");
request.setDesiredLaunchTemplateVersion("2");
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.getInstances().clear();
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-replacement", "InService", "lt-updated", "2");
service.completeInstanceRefreshIfSettled(REGION, "test-asg");
InstanceRefresh completed = service.describeInstanceRefreshes(
REGION, "test-asg", List.of(refresh.getInstanceRefreshId()), null, null)
.instanceRefreshes()
.getFirst();
assertEquals("Successful", completed.getStatus());
assertEquals(100, completed.getPercentageComplete());
assertEquals(0, completed.getInstancesToUpdate());
assertNotNull(completed.getEndTime());
}
@Test
void completeInstanceRefreshWaitsForReplacementCapacity() {
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh());
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.getInstances().clear();
service.completeInstanceRefreshIfSettled(REGION, "test-asg");
InstanceRefresh inProgress = service.describeInstanceRefreshes(
REGION, "test-asg", List.of(refresh.getInstanceRefreshId()), null, null)
.instanceRefreshes()
.getFirst();
assertEquals("InProgress", inProgress.getStatus());
assertEquals(0, inProgress.getPercentageComplete());
assertEquals(1, inProgress.getInstancesToUpdate());
assertNull(inProgress.getEndTime());
}
@Test
void deleteAutoScalingGroupWithoutForceRejectsActiveInstances() {
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-active", "InService", "lt-original", "1");
AwsException error = assertThrows(AwsException.class,
() -> service.deleteAutoScalingGroup(REGION, "test-asg", false));
assertEquals("ResourceInUse", error.getErrorCode());
}
@Test
void forceDeleteAutoScalingGroupTerminatesActiveEc2Instances() {
Ec2Service ec2Service = mock(Ec2Service.class);
service.ec2Service = ec2Service;
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-active", "InService", "lt-original", "1");
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-terminated", "Terminated", "lt-original", "1");
service.deleteAutoScalingGroup(REGION, "test-asg", true);
verify(ec2Service).terminateInstances(REGION, List.of("i-active"));
assertTrue(service.describeAutoScalingGroups(REGION, List.of("test-asg")).isEmpty());
}
@Test
void forceDeleteAutoScalingGroupIgnoresStaleEc2Membership() {
Ec2Service ec2Service = mock(Ec2Service.class);
service.ec2Service = ec2Service;
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-stale", "InService", "lt-original", "1");
doThrow(new AwsException("InvalidInstanceID.NotFound", "Instance i-stale was not found.", 400))
.when(ec2Service)
.terminateInstances(REGION, List.of("i-stale"));
service.deleteAutoScalingGroup(REGION, "test-asg", true);
verify(ec2Service).terminateInstances(REGION, List.of("i-stale"));
assertTrue(service.describeAutoScalingGroups(REGION, List.of("test-asg")).isEmpty());
}
private static final class AutoScalingGroupFixture {
private static void addInstance(AutoScalingService service, String region, String name, String instanceId,
String lifecycleState, String launchTemplateId, String launchTemplateVersion) {
AsgInstance instance = new AsgInstance();
instance.setInstanceId(instanceId);
instance.setLifecycleState(lifecycleState);
instance.setHealthStatus("Healthy");
instance.setLaunchTemplateId(launchTemplateId);
instance.setLaunchTemplateVersion(launchTemplateVersion);
service.describeAutoScalingGroups(region, List.of(name))
.getFirst()
.getInstances()
.add(instance);
}
}
}
@@ -0,0 +1,436 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectExecCmd;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.NetworkSettings;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Answers.RETURNS_SELF;
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.when;
import static org.mockito.Mockito.withSettings;
class Ec2ContainerManagerTest {
@org.junit.jupiter.api.AfterEach
void resetBridgeIpPolling() {
Ec2ContainerManager.containerBridgeIpAttempts = 30;
Ec2ContainerManager.containerBridgeIpPollMillis = 500;
}
@Test
void exposeReachablePrivateAddressUpdatesInstanceAndAttachedNetworkInterfaces() {
Instance instance = new Instance();
instance.setPrivateIpAddress("10.82.32.10");
instance.setPrivateDnsName("ip-10-82-32-10.ec2.internal");
InstanceNetworkInterface networkInterface = new InstanceNetworkInterface();
networkInterface.setPrivateIpAddress("10.82.32.10");
networkInterface.setPrivateDnsName("ip-10-82-32-10.ec2.internal");
instance.setNetworkInterfaces(List.of(networkInterface));
Ec2ContainerManager.exposeReachablePrivateAddress(instance, "192.168.215.21");
assertEquals("192.168.215.21", instance.getPrivateIpAddress());
assertEquals("ip-192-168-215-21.ec2.internal", instance.getPrivateDnsName());
assertEquals("192.168.215.21", networkInterface.getPrivateIpAddress());
assertEquals("ip-192-168-215-21.ec2.internal", networkInterface.getPrivateDnsName());
}
@Test
void restoreMetadataRegistrationRegistersRunningPersistedContainer() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning("container-1")).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse response = inspectResponse("192.168.215.42");
when(dockerClient.inspectContainerCmd("container-1")).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = new Ec2ContainerManager(
mock(ContainerBuilder.class),
lifecycleManager,
mock(ContainerLogStreamer.class),
mock(ContainerDetector.class),
mock(DockerHostResolver.class),
dockerClient,
mock(PortAllocator.class),
mock(EmulatorConfig.class),
metadataServer);
Instance instance = new Instance();
instance.setInstanceId("i-restored");
instance.setDockerContainerId("container-1");
instance.setContainerBridgeIp("192.168.215.7");
assertTrue(manager.restoreMetadataRegistration(instance));
assertEquals("192.168.215.42", instance.getContainerBridgeIp());
assertEquals("192.168.215.42", instance.getPrivateIpAddress());
verify(metadataServer).unregisterContainer("192.168.215.7", instance);
verify(metadataServer).registerContainer("192.168.215.42", "i-restored", instance);
}
@Test
void userDataExecutionCommandRunsScriptDirectlySoShebangIsHonored() {
assertArrayEquals(new String[]{"/tmp/user-data.sh"}, Ec2ContainerManager.userDataExecutionCommand());
}
@Test
void userDataShellScriptsPreservesRawShellScript() {
String script = "#!/bin/bash\nset -euo pipefail\necho ready\n";
assertEquals(List.of(script), Ec2ContainerManager.userDataShellScripts(script));
}
@Test
void userDataShellScriptsExtractsMimeShellscriptPartsInOrder() {
String userData = """
Content-Type: multipart/mixed; boundary="==SAMPLE-CLOUD-INIT=="
MIME-Version: 1.0
--==SAMPLE-CLOUD-INIT==
Content-Type: text/cloud-config; charset="us-ascii"
#cloud-config
--==SAMPLE-CLOUD-INIT==
Content-Type: text/x-shellscript; charset="us-ascii"
#!/bin/bash
echo first
--==SAMPLE-CLOUD-INIT==
Content-Type: text/x-shellscript
#!/bin/sh
echo second
--==SAMPLE-CLOUD-INIT==--
""";
assertEquals(
List.of(
"#!/bin/bash\necho first\n",
"#!/bin/sh\necho second\n"),
Ec2ContainerManager.userDataShellScripts(userData));
}
@Test
void userDataShellScriptsIgnoresCloudConfigWithoutShellscript() {
String userData = """
Content-Type: multipart/mixed; boundary=cloudinit
MIME-Version: 1.0
--cloudinit
Content-Type: text/cloud-config
#cloud-config
--cloudinit--
""";
assertTrue(Ec2ContainerManager.userDataShellScripts(userData).isEmpty());
}
@Test
void metadataProxyInstallCommandInstallsLinkLocalProxyDependencies() {
String[] command = Ec2ContainerManager.metadataProxyInstallCommand();
assertEquals("sh", command[0]);
assertTrue(command[2].contains("iproute2"));
assertTrue(command[2].contains("socat"));
assertTrue(command[2].contains("curl"));
}
@Test
void metadataProxyStartCommandBindsAwsLinkLocalMetadataAddress() {
String[] command = Ec2ContainerManager.metadataProxyStartCommand("floci", 9169);
assertEquals("sh", command[0]);
assertTrue(command[2].contains("169.254.169.254/32"));
assertTrue(command[2].contains("TCP-LISTEN:80,bind=169.254.169.254"));
assertTrue(command[2].contains("TCP:floci:9169"));
assertTrue(command[2].contains("http://169.254.169.254/latest/meta-data/instance-id"));
}
@Test
void localAwsEnvironmentProvidesCliCredentialsAndFlociEndpoint() {
assertEquals(
java.util.List.of(
"AWS_EC2_METADATA_SERVICE_ENDPOINT=http://floci:9169",
"AWS_ENDPOINT_URL=http://floci:4566",
"AWS_DEFAULT_REGION=us-west-2",
"AWS_REGION=us-west-2",
"AWS_ACCESS_KEY_ID=test",
"AWS_SECRET_ACCESS_KEY=test",
"AWS_SESSION_TOKEN=test-session-token"),
Ec2ContainerManager.localAwsEnvironment(
"us-west-2",
"http://floci:4566",
"http://floci:9169"));
}
@Test
void preferredMetadataSourceIpUsesConfiguredNetworkBeforeBridge() {
ContainerNetwork bridge = new ContainerNetwork();
bridge.withIpv4Address("172.17.0.8");
ContainerNetwork floci = new ContainerNetwork();
floci.withIpv4Address("192.168.215.10");
assertEquals(
"192.168.215.10",
Ec2ContainerManager.preferredMetadataSourceIp(Map.of(
"bridge", bridge,
"custom-floci-network", floci)).orElseThrow());
}
@Test
void preferredMetadataSourceIpFallsBackToBridge() {
ContainerNetwork bridge = new ContainerNetwork();
bridge.withIpv4Address("172.17.0.8");
assertEquals(
"172.17.0.8",
Ec2ContainerManager.preferredMetadataSourceIp(Map.of("bridge", bridge)).orElseThrow());
}
@Test
void preferredMetadataSourceIpIsEmptyWithoutUsableAddress() {
ContainerNetwork bridge = new ContainerNetwork();
assertTrue(Ec2ContainerManager.preferredMetadataSourceIp(Map.of("bridge", bridge)).isEmpty());
}
@Test
void launchWaitsForContainerBridgeIpBeforeRegisteringImds() throws Exception {
Ec2ContainerManager.containerBridgeIpAttempts = 3;
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse noIp = inspectResponse(null);
InspectContainerResponse withIp = inspectResponse("172.18.0.9");
when(harness.dockerClient.inspectContainerCmd("container-1")).thenReturn(inspect);
when(inspect.exec()).thenReturn(noIp).thenReturn(withIp);
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
Instance instance = instance("i-waitip");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
assertEquals("container-1", instance.getDockerContainerId());
assertEquals("172.18.0.9", instance.getContainerBridgeIp());
assertEquals("172.18.0.9", instance.getPrivateIpAddress());
verify(inspect, times(2)).exec();
verify(harness.metadataServer).registerContainer("172.18.0.9", "i-waitip", instance);
}
@Test
void launchTerminatesWhenContainerBridgeIpNeverAppears() throws Exception {
Ec2ContainerManager.containerBridgeIpAttempts = 2;
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse noIp = inspectResponse(null);
when(harness.dockerClient.inspectContainerCmd("container-1")).thenReturn(inspect);
when(inspect.exec()).thenReturn(noIp);
Instance instance = instance("i-noip");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
assertEquals("container-1", instance.getDockerContainerId());
verify(harness.metadataServer, never()).registerContainer(anyString(), anyString(), any());
}
@Test
void launchMarksInstanceRunningBeforeUserDataCompletes() throws Exception {
Ec2ContainerManager.containerBridgeIpAttempts = 2;
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse withIp = inspectResponse("172.18.0.10");
when(harness.dockerClient.inspectContainerCmd("container-1")).thenReturn(inspect);
when(inspect.exec()).thenReturn(withIp);
CountDownLatch userDataStarted = new CountDownLatch(1);
CountDownLatch finishUserData = new CountDownLatch(1);
harness.stubSuccessfulExecs(userDataStarted, finishUserData);
Instance instance = instance("i-userdata");
instance.setUserData("#!/bin/sh\necho ready\n");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
assertTrue(userDataStarted.await(2, TimeUnit.SECONDS), "user data should start");
assertEquals("running", instance.getState().getName());
assertFalse(finishUserData.await(10, TimeUnit.MILLISECONDS), "user data should still be blocked");
finishUserData.countDown();
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
}
private static LaunchHarness launchHarness() {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(RETURNS_SELF));
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("ubuntu:24.04"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.create(any(ContainerSpec.class))).thenReturn("container-1");
when(lifecycleManager.isContainerRunning("container-1")).thenReturn(true);
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
when(dockerHostResolver.resolve()).thenReturn("floci");
PortAllocator portAllocator = mock(PortAllocator.class);
when(portAllocator.allocate(anyInt(), anyInt())).thenReturn(2201);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.sshPortRangeStart()).thenReturn(2200);
when(ec2.sshPortRangeEnd()).thenReturn(2299);
when(ec2.imdsPort()).thenReturn(9169);
DockerClient dockerClient = mock(DockerClient.class);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = new Ec2ContainerManager(
containerBuilder,
lifecycleManager,
mock(ContainerLogStreamer.class),
mock(ContainerDetector.class),
dockerHostResolver,
dockerClient,
portAllocator,
config,
metadataServer);
return new LaunchHarness(manager, dockerClient, metadataServer);
}
private static Instance instance(String instanceId) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
return instance;
}
private static InspectContainerResponse inspectResponse(String ipAddress) {
InspectContainerResponse inspect = mock(InspectContainerResponse.class);
NetworkSettings networkSettings = mock(NetworkSettings.class);
when(inspect.getNetworkSettings()).thenReturn(networkSettings);
if (ipAddress != null) {
ContainerNetwork bridge = new ContainerNetwork().withIpv4Address(ipAddress);
when(networkSettings.getNetworks()).thenReturn(Map.of("bridge", bridge));
}
return inspect;
}
private static void awaitUntil(BooleanSupplier condition, Duration timeout) throws InterruptedException {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
if (condition.getAsBoolean()) {
return;
}
Thread.sleep(10);
}
assertTrue(condition.getAsBoolean(), "condition was not met before timeout");
}
private record LaunchHarness(Ec2ContainerManager manager,
DockerClient dockerClient,
Ec2MetadataServer metadataServer) {
void stubSuccessfulExecs(CountDownLatch userDataStarted, CountDownLatch finishUserData) throws Exception {
AtomicReference<String[]> currentCommand = new AtomicReference<>();
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
ExecCreateCmdResponse metadataExec = mock(ExecCreateCmdResponse.class);
ExecCreateCmdResponse userDataExec = mock(ExecCreateCmdResponse.class);
when(metadataExec.getId()).thenReturn("metadata-exec");
when(userDataExec.getId()).thenReturn("userdata-exec");
when(dockerClient.execCreateCmd("container-1")).thenReturn(execCreate);
when(execCreate.withCmd(any(String[].class))).thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
if (args.length == 1 && args[0] instanceof String[] command) {
currentCommand.set(command);
} else {
currentCommand.set(Arrays.copyOf(args, args.length, String[].class));
}
return execCreate;
});
when(execCreate.exec()).thenAnswer(invocation -> {
String[] command = currentCommand.get();
if (command != null && command.length == 1 && "/tmp/user-data.sh".equals(command[0])) {
return userDataExec;
}
return metadataExec;
});
when(dockerClient.execStartCmd(anyString())).thenAnswer(invocation -> {
String execId = invocation.getArgument(0);
ExecStartCmd execStart = mock(ExecStartCmd.class);
when(execStart.exec(any())).thenAnswer(startInvocation -> {
@SuppressWarnings("unchecked")
ResultCallback<Frame> callback = startInvocation.getArgument(0);
if ("userdata-exec".equals(execId)) {
userDataStarted.countDown();
finishUserData.await(2, TimeUnit.SECONDS);
}
callback.onComplete();
return callback;
});
return execStart;
});
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
when(inspectExecResponse.getExitCodeLong()).thenReturn(0L);
when(inspectExec.exec()).thenReturn(inspectExecResponse);
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.copyArchiveToContainerCmd("container-1")).thenReturn(copy);
when(copy.withTarInputStream(any(InputStream.class))).thenReturn(copy);
}
}
}
@@ -646,6 +646,11 @@ class Ec2IntegrationTest {
.formParam("LaunchTemplateData.KeyName", "test-key")
.formParam("LaunchTemplateData.SecurityGroupId.1", securityGroupId)
.formParam("LaunchTemplateData.UserData", gzipBase64("#!/bin/sh\necho launch-template\n"))
.formParam("LaunchTemplateData.TagSpecification.1.ResourceType", "instance")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Key", "example:ClusterId")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Value", "sample-template")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.2.Key", "example:NodeType")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.2.Value", "COORDINATOR")
.formParam("TagSpecification.1.ResourceType", "launch-template")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "sample-template")
@@ -696,7 +701,13 @@ class Ec2IntegrationTest {
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.instanceType",
equalTo("t3.micro"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.userData",
equalTo("#!/bin/sh\necho launch-template\n"));
equalTo("#!/bin/sh\necho launch-template\n"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.resourceType",
equalTo("instance"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:ClusterId' }.value",
equalTo("sample-template"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:NodeType' }.value",
equalTo("COORDINATOR"));
}
@Test
@@ -713,6 +724,9 @@ class Ec2IntegrationTest {
.formParam("LaunchTemplateData.KeyName", "test-key")
.formParam("LaunchTemplateData.SecurityGroupId.1", securityGroupId)
.formParam("LaunchTemplateData.UserData", gzipBase64("#!/bin/sh\necho launch-template-version\n"))
.formParam("LaunchTemplateData.TagSpecification.1.ResourceType", "instance")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Key", "example:NodeType")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Value", "WORKER")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -727,7 +741,9 @@ class Ec2IntegrationTest {
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.instanceType",
equalTo("t3.small"))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.userData",
equalTo("#!/bin/sh\necho launch-template-version\n"));
equalTo("#!/bin/sh\necho launch-template-version\n"))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:NodeType' }.value",
equalTo("WORKER"));
given()
.formParam("Action", "DescribeLaunchTemplateVersions")
@@ -743,7 +759,11 @@ class Ec2IntegrationTest {
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.defaultVersion",
equalTo("true"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.instanceType",
equalTo("t3.micro"));
equalTo("t3.micro"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.userData",
equalTo("#!/bin/sh\necho launch-template\n"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:NodeType' }.value",
equalTo("COORDINATOR"));
}
@Test
@@ -1246,6 +1266,8 @@ class Ec2IntegrationTest {
.formParam("Action", "DescribeInstances")
.formParam("Filter.1.Name", "instance-state-name")
.formParam("Filter.1.Value.1", "running")
.formParam("Filter.2.Name", "instance-id")
.formParam("Filter.2.Value.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -1337,9 +1359,10 @@ class Ec2IntegrationTest {
@Test
@Order(79)
void describeNetworkInterfacesBeforeRun() {
// Before any instances exist, the set should be empty
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "attachment.instance-id")
.formParam("Filter.1.Value.1", "i-00000000000000000")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -1354,13 +1377,15 @@ class Ec2IntegrationTest {
void describeNetworkInterfacesAfterRun() {
networkInterfaceId = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "attachment.instance-id")
.formParam("Filter.1.Value.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", greaterThanOrEqualTo(1))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(1))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].networkInterfaceId",
startsWith("eni-"))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].vpcId", notNullValue())
@@ -1373,7 +1398,7 @@ class Ec2IntegrationTest {
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].attachment.deviceIndex",
equalTo("0"))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].attachment.instanceId",
notNullValue())
equalTo(instanceId))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].groupSet.item.size()",
greaterThanOrEqualTo(1))
.extract().path("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].networkInterfaceId");
@@ -1576,13 +1601,15 @@ class Ec2IntegrationTest {
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "status")
.formParam("Filter.1.Value.1", "in-use")
.formParam("Filter.2.Name", "attachment.instance-id")
.formParam("Filter.2.Value.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()",
greaterThanOrEqualTo(1))
equalTo(1))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item[0].status",
equalTo("in-use"));
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class Ec2MetadataServerTest {
@Test
void instanceMetadataListsTagKeys() {
Instance instance = new Instance();
instance.setTags(List.of(
new Tag("Environment", "dev"),
new Tag("Service", "orders")));
assertEquals("Environment\nService", Ec2MetadataServer.instanceTagKeys(instance));
}
@Test
void instanceMetadataReturnsTagValue() {
Instance instance = new Instance();
instance.setTags(List.of(
new Tag("Environment", "dev"),
new Tag("Service", "orders")));
assertEquals("orders", Ec2MetadataServer.instanceTagValue(instance, "Service").orElseThrow());
}
@Test
void instanceMetadataReturnsEmptyValueForEmptyTag() {
Instance instance = new Instance();
instance.setTags(List.of(new Tag("Owner", null)));
assertTrue(Ec2MetadataServer.instanceTagValue(instance, "Owner").isPresent());
assertEquals("", Ec2MetadataServer.instanceTagValue(instance, "Owner").orElseThrow());
}
@Test
void instanceMetadataReturnsMissingForUnknownTag() {
Instance instance = new Instance();
instance.setTags(List.of(new Tag("Environment", "dev")));
assertTrue(Ec2MetadataServer.instanceTagValue(instance, "Missing").isEmpty());
}
@Test
void staleContainerUnregisterDoesNotRemoveCurrentRegistration() {
Ec2MetadataServer server = new Ec2MetadataServer(null, null);
Instance oldInstance = new Instance();
oldInstance.setInstanceId("i-old");
Instance currentInstance = new Instance();
currentInstance.setInstanceId("i-current");
server.registerContainer("192.168.215.7", oldInstance.getInstanceId(), oldInstance);
server.registerContainer("192.168.215.7", currentInstance.getInstanceId(), currentInstance);
server.unregisterContainer("192.168.215.7", oldInstance);
assertEquals(
currentInstance,
server.registeredContainer("192.168.215.7").orElseThrow());
}
}
@@ -33,6 +33,7 @@ class Ec2Phase2IntegrationTest {
private static String instanceWithUserData;
private static String instanceWithProfile;
private static String instanceWithProfileName;
private static String instanceForTerminate;
private static String importedKeyName = "phase2-imported-key";
@@ -119,6 +120,46 @@ class Ec2Phase2IntegrationTest {
equalTo("running"));
}
@Test
@Order(12)
void runInstancesWithIamInstanceProfileName() {
String profileName = "my-app-profile";
instanceWithProfileName = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-ubuntu2204")
.formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("IamInstanceProfile.Name", profileName)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("RunInstancesResponse.instancesSet.item.instanceId", startsWith("i-"))
.body("RunInstancesResponse.instancesSet.item.iamInstanceProfile.arn",
equalTo("arn:aws:iam::000000000000:instance-profile/" + profileName))
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
}
@Test
@Order(13)
void describeInstanceWithProfileName() {
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceWithProfileName)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId",
equalTo(instanceWithProfileName))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.arn",
equalTo("arn:aws:iam::000000000000:instance-profile/my-app-profile"));
}
// ─── SSH key import ────────────────────────────────────────────────────────
@Test
@@ -0,0 +1,86 @@
package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Tag;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class Ec2ServiceTest {
@Test
void mockModeTreatsExistingNonTerminatedInstanceAsRunningContainer() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
Ec2Service service = new Ec2Service(mockConfig(true), containerManager,
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new InMemoryStorageFactory());
Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null);
String instanceId = reservation.getInstances().getFirst().getInstanceId();
assertTrue(service.isInstanceContainerRunning(instanceId));
service.terminateInstances("us-east-1", List.of(instanceId));
assertFalse(service.isInstanceContainerRunning(instanceId));
verifyNoInteractions(containerManager);
}
@Test
void launchTemplateVersionInheritsOmittedFieldsFromRequestedSourceVersion() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new InMemoryStorageFactory());
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "app-template",
"ami-source", "t3.micro", "app-key", List.of("sg-source"),
"source-user-data", List.of(), List.of(new Tag("Role", "source")));
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null,
"1", null, "t3.small", null, List.of(), null, List.of());
LaunchTemplate version = service.describeLaunchTemplateVersions(
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
assertEquals("ami-source", version.getImageId());
assertEquals("t3.small", version.getInstanceType());
assertEquals("app-key", version.getKeyName());
assertEquals(List.of("sg-source"), version.getSecurityGroupIds());
assertEquals("source-user-data", version.getUserData());
assertEquals("2", version.getLatestVersionNumber());
assertEquals(1, version.getInstanceTags().size());
assertEquals("Role", version.getInstanceTags().getFirst().getKey());
assertEquals("source", version.getInstanceTags().getFirst().getValue());
}
private static EmulatorConfig mockConfig(boolean ec2Mock) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(ec2Mock);
return config;
}
private static final class InMemoryStorageFactory extends StorageFactory {
private InMemoryStorageFactory() {
super(null, null);
}
@Override
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
}
}