feat(timestream-influxdb): add Timestream for InfluxDB backed by InfluxDB 2.x containers (#3683)

* feat(timestream-influxdb): add Timestream for InfluxDB backed by InfluxDB 2.x containers

Implements all 24 AmazonTimestreamInfluxDB operations; DB instances and
read replica clusters run real influxdb:2.7 containers.

* Fix #2566

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(timestream-influxdb): reject unsupported RestoreFromDbBackup parameters

Point-in-time restore needs a continuous backup, and REPLACE_EXISTING
accepts no configuration overrides, so both are rejected instead of
silently restoring on-demand data or dropping the overrides.

* Fix #2566

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* style(timestream-influxdb): import the classes used instead of naming them inline

Replaces the inline fully-qualified LinkedHashMap, Comparator, Predicate
and TimestreamInfluxDbService references with imports.

* Fix #2566

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-18 09:09:51 -04:00
1 parent 918a09f54a
commit eb787672b8
27 files changed
+4202 -4

No files matched your search

@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.pipes.PipesService;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.timestreaminfluxdb.TimestreamInfluxDbService;
import io.quarkus.runtime.ShutdownDelayInitiatedEvent;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
@@ -79,6 +80,8 @@ class EmulatorLifecycleTest {
@Mock private io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager rabbitMqManager;
@Mock private io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager flinkContainerManager;
@Mock private RdsService rdsService;
@Mock private TimestreamInfluxDbService timestreamInfluxDbService;
@Mock private EmulatorConfig.TimestreamInfluxDbServiceConfig timestreamInfluxDbServiceConfig;
@Mock private io.github.hectorvent.floci.services.elbv2.ElbV2Service elbV2Service;
@Mock private io.github.hectorvent.floci.services.elb.ElbClassicService elbClassicService;
@Mock private InitializationHooksRunner initializationHooksRunner;
@@ -111,6 +114,8 @@ class EmulatorLifecycleTest {
Mockito.lenient().when(elbServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.eks()).thenReturn(eksServiceConfig);
Mockito.lenient().when(eksServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.timestreamInfluxdb()).thenReturn(timestreamInfluxDbServiceConfig);
Mockito.lenient().when(timestreamInfluxDbServiceConfig.enabled()).thenReturn(true);
Mockito.lenient().when(config.tls()).thenReturn(tlsConfig);
Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false);
Mockito.lenient().when(config.port()).thenReturn(4566);
@@ -122,7 +127,8 @@ class EmulatorLifecycleTest {
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
memoryDbContainerManager, memoryDbProxyManager,
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
rabbitMqManager, flinkContainerManager, rdsService, elbV2Service, elbClassicService,
rabbitMqManager, flinkContainerManager, rdsService, timestreamInfluxDbService,
elbV2Service, elbClassicService,
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState,
schemaCreationWorker, stepFunctionsService, containerTeardowns, persistentPathValidator);
@@ -0,0 +1,155 @@
package io.github.hectorvent.floci.services.timestreaminfluxdb;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@Tag("docker")
@QuarkusTest
@TestProfile(TimestreamInfluxDbDockerIntegrationTest.RealContainerProfile.class)
class TimestreamInfluxDbDockerIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TARGET = "AmazonTimestreamInfluxDB.";
private static final String USERNAME = "operator";
private static final String PASSWORD = "password123";
public static class RealContainerProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.timestream-influxdb.mock", "false",
"floci.services.timestream-influxdb.host-port-base", "18186",
"floci.services.timestream-influxdb.host-port-max", "18285");
}
}
@Inject
DockerClient dockerClient;
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
@BeforeEach
void requireDocker() {
RestAssuredJsonUtils.configureAwsContentTypes();
boolean available;
try {
dockerClient.pingCmd().exec();
available = true;
} catch (RuntimeException e) {
available = false;
}
Assumptions.assumeTrue(available, "Docker daemon must be available for InfluxDB container tests");
}
@Test
void instanceEndpointServesInfluxDbAndBackupsRestoreItsData() throws Exception {
String sourceId = call("CreateDbInstance", """
{"name":"docker-source","username":"%s","password":"%s","organization":"acme","bucket":"metrics",
"dbInstanceType":"db.influx.medium","allocatedStorage":20,
"vpcSubnetIds":["subnet-abc123"],"vpcSecurityGroupIds":["sg-abc123"]}
""".formatted(USERNAME, PASSWORD)).statusCode(200).extract().path("id");
String restoredId = null;
try {
Map<String, Object> source = awaitInstance(sourceId, "AVAILABLE");
String sourceUrl = "http://" + source.get("endpoint") + ":" + source.get("port");
String session = signIn(sourceUrl);
HttpResponse<String> write = http.send(HttpRequest.newBuilder(
URI.create(sourceUrl + "/api/v2/write?org=acme&bucket=metrics&precision=s"))
.header("Cookie", session)
.POST(HttpRequest.BodyPublishers.ofString("cpu,host=a value=42 1700000000"))
.build(), HttpResponse.BodyHandlers.ofString());
assertEquals(204, write.statusCode(), write.body());
assertTrue(query(sourceUrl, session).contains(",42,value,cpu,a"));
String backupId = call("CreateDbBackup", "{\"name\":\"docker-snap\",\"dbResourceId\":\"" + sourceId + "\"}")
.statusCode(200).extract().path("id");
awaitStatus("GetDbBackup", backupId, "COMPLETED");
restoredId = call("RestoreFromDbBackup", "{\"name\":\"docker-restored\",\"dbBackupId\":\"" + backupId + "\"}")
.statusCode(200).extract().path("restoredDbResourceId");
Map<String, Object> restored = awaitInstance(restoredId, "AVAILABLE");
String restoredUrl = "http://" + restored.get("endpoint") + ":" + restored.get("port");
assertTrue(query(restoredUrl, signIn(restoredUrl)).contains(",42,value,cpu,a"));
} finally {
call("DeleteDbInstance", "{\"identifier\":\"" + sourceId + "\"}");
if (restoredId != null) {
call("DeleteDbInstance", "{\"identifier\":\"" + restoredId + "\"}");
}
}
}
private String signIn(String baseUrl) throws Exception {
String basic = Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.UTF_8));
HttpResponse<String> response = http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/api/v2/signin"))
.header("Authorization", "Basic " + basic)
.POST(HttpRequest.BodyPublishers.noBody())
.build(), HttpResponse.BodyHandlers.ofString());
assertEquals(204, response.statusCode(), response.body());
return response.headers().firstValue("Set-Cookie").orElseThrow().split(";")[0];
}
private String query(String baseUrl, String session) throws Exception {
HttpResponse<String> response = http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/api/v2/query?org=acme"))
.header("Cookie", session)
.header("Content-Type", "application/vnd.flux")
.POST(HttpRequest.BodyPublishers.ofString(
"from(bucket:\"metrics\") |> range(start: 0) |> filter(fn: (r) => r._measurement == \"cpu\")"))
.build(), HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode(), response.body());
return response.body();
}
private Map<String, Object> awaitInstance(String id, String expectedStatus) throws InterruptedException {
awaitStatus("GetDbInstance", id, expectedStatus);
return call("GetDbInstance", "{\"identifier\":\"" + id + "\"}").extract().jsonPath().getMap("$");
}
private void awaitStatus(String action, String id, String expectedStatus) throws InterruptedException {
long deadline = System.currentTimeMillis() + 180_000;
String status = null;
while (System.currentTimeMillis() < deadline) {
status = call(action, "{\"identifier\":\"" + id + "\"}").statusCode(200).extract().path("status");
if (expectedStatus.equals(status)) {
return;
}
if (status.endsWith("FAILED")) {
break;
}
Thread.sleep(1000);
}
fail(action + " " + id + " ended in status " + status + " instead of " + expectedStatus);
}
private static ValidatableResponse call(String action, String body) {
return given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then();
}
}
@@ -0,0 +1,496 @@
package io.github.hectorvent.floci.services.timestreaminfluxdb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@QuarkusTest
class TimestreamInfluxDbIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TARGET = "AmazonTimestreamInfluxDB.";
private static final String ACCOUNT = "000000000000";
private static final String ID_PATTERN = "[a-z0-9]{10}";
@BeforeAll
static void setup() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void instanceLifecycleReportsTransitionalStatusesAndSimulatedEndpoint() {
String id = createInstance("lifecycle-db", "")
.statusCode(200)
.body("id", matchesPattern(ID_PATTERN))
.body("name", equalTo("lifecycle-db"))
.body("status", equalTo("CREATING"))
.body("port", equalTo(8086))
.body("deploymentType", equalTo("SINGLE_AZ"))
.body("networkType", equalTo("IPV4"))
.body("dbStorageType", equalTo("InfluxIOIncludedT1"))
.body("publiclyAccessible", equalTo(false))
.body("availabilityZone", equalTo("us-east-1a"))
.body("vpcSubnetIds", contains("subnet-abc123"))
.body("vpcSecurityGroupIds", contains("sg-abc123"))
.body("influxAuthParametersSecretArn", nullValue())
.extract().path("id");
call("GetDbInstance", "{\"identifier\":\"" + id + "\"}")
.statusCode(200)
.body("status", equalTo("AVAILABLE"))
.body("arn", equalTo("arn:aws:timestream-influxdb:us-east-1:" + ACCOUNT + ":db-instance/" + id))
.body("endpoint", equalTo("localhost"))
.body("influxAuthParametersSecretArn", startsWith("arn:aws:secretsmanager:us-east-1:" + ACCOUNT + ":secret:"));
call("ListDbInstances", "{}")
.statusCode(200)
.body("items.id", hasItem(id));
call("UpdateDbInstance", """
{"identifier":"%s","dbInstanceType":"db.influx.xlarge","port":9000}
""".formatted(id))
.statusCode(200)
.body("status", equalTo("UPDATING_INSTANCE_TYPE"))
.body("dbInstanceType", equalTo("db.influx.xlarge"))
.body("port", equalTo(9000));
call("RebootDbInstance", "{\"identifier\":\"" + id + "\"}")
.statusCode(200)
.body("status", equalTo("REBOOTING"));
call("GetDbInstance", "{\"identifier\":\"" + id + "\"}")
.statusCode(200)
.body("status", equalTo("AVAILABLE"))
.body("port", equalTo(9000));
call("DeleteDbInstance", "{\"identifier\":\"" + id + "\"}")
.statusCode(200)
.body("status", equalTo("DELETING"));
call("GetDbInstance", "{\"identifier\":\"" + id + "\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("resourceId", equalTo(id))
.body("resourceType", equalTo("DB_INSTANCE"));
}
@Test
void createInstanceStoresInitialAuthParametersInSecretsManager() {
String id = createInstance("secret-db", ",\"username\":\"operator\",\"organization\":\"acme\",\"bucket\":\"metrics\"")
.statusCode(200)
.extract().path("id");
String secretArn = call("GetDbInstance", "{\"identifier\":\"" + id + "\"}")
.statusCode(200)
.extract().path("influxAuthParametersSecretArn");
String secret = given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "secretsmanager.GetSecretValue")
.body("{\"SecretId\":\"" + secretArn + "\"}")
.when().post("/")
.then().statusCode(200)
.extract().path("SecretString");
assertEquals("{\"organization\":\"acme\",\"bucket\":\"metrics\",\"username\":\"operator\",\"password\":\"password123\"}",
secret);
}
@Test
void createInstanceRejectsInputOutsideTheModelConstraints() {
call("CreateDbInstance", """
{"name":"no-password","dbInstanceType":"db.influx.medium","allocatedStorage":20,
"vpcSubnetIds":["subnet-abc123"],"vpcSecurityGroupIds":["sg-abc123"]}
""")
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("reason", equalTo("FIELD_VALIDATION_FAILED"));
assertValidation(instanceBody("1bad", "db.influx.medium", 20, "8086"));
assertValidation(instanceBody("bad-storage", "db.influx.medium", 19, "8086"));
assertValidation(instanceBody("bad-type", "db.influx.tiny", 20, "8086"));
assertValidation(instanceBody("reserved-port", "db.influx.medium", 20, "8090"));
assertValidation("""
{"name":"no-subnets","password":"password123","dbInstanceType":"db.influx.medium","allocatedStorage":20,
"vpcSubnetIds":[],"vpcSecurityGroupIds":["sg-abc123"]}
""");
}
@Test
void instanceNamesAreUniquePerAccountAndRegion() {
String id = createInstance("dup-db", "").statusCode(200).extract().path("id");
createInstance("dup-db", "")
.statusCode(400)
.body("__type", equalTo("ConflictException"))
.body("resourceId", equalTo(id))
.body("resourceType", equalTo("DB_INSTANCE"));
}
@Test
void listDbParameterGroupsPaginatesWithMaxResultsAndNextToken() {
for (int i = 0; i < 3; i++) {
call("CreateDbParameterGroup", "{\"name\":\"page-group-" + i + "\"}").statusCode(200);
}
int total = call("ListDbParameterGroups", "{}").statusCode(200).extract().path("items.size()");
String token = call("ListDbParameterGroups", "{\"maxResults\":2}")
.statusCode(200)
.body("items", hasSize(2))
.body("nextToken", notNullValue())
.extract().path("nextToken");
call("ListDbParameterGroups", "{\"maxResults\":100,\"nextToken\":\"" + token + "\"}")
.statusCode(200)
.body("items", hasSize(total - 2))
.body("nextToken", nullValue());
assertValidationFor("ListDbParameterGroups", "{\"maxResults\":0}");
assertValidationFor("ListDbParameterGroups", "{\"maxResults\":101}");
}
@Test
void parameterGroupsAreRetrievableAndReferencedByInstances() {
String groupId = call("CreateDbParameterGroup", """
{"name":"tuned-v2","description":"tuned","parameters":{"InfluxDBv2":{"logLevel":"debug","queryConcurrency":10}},
"tags":{"team":"metrics"}}
""")
.statusCode(200)
.body("id", matchesPattern(ID_PATTERN))
.body("arn", endsWithResource("db-parameter-group"))
.body("parameters.InfluxDBv2.logLevel", equalTo("debug"))
.extract().path("id");
call("GetDbParameterGroup", "{\"identifier\":\"" + groupId + "\"}")
.statusCode(200)
.body("name", equalTo("tuned-v2"))
.body("description", equalTo("tuned"))
.body("parameters.InfluxDBv2.queryConcurrency", equalTo(10));
call("CreateDbParameterGroup", "{\"name\":\"tuned-v2\"}")
.statusCode(400)
.body("__type", equalTo("ConflictException"))
.body("resourceType", equalTo("DB_PARAMETER_GROUP"));
assertValidationFor("CreateDbParameterGroup",
"{\"name\":\"bad-level\",\"parameters\":{\"InfluxDBv2\":{\"logLevel\":\"verbose\"}}}");
createInstance("grouped-db", ",\"dbParameterGroupIdentifier\":\"" + groupId + "\"")
.statusCode(200)
.body("dbParameterGroupIdentifier", equalTo(groupId));
createInstance("missing-group-db", ",\"dbParameterGroupIdentifier\":\"nosuchgroup\"")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("resourceType", equalTo("DB_PARAMETER_GROUP"));
}
@Test
void clusterLifecycleManagesItsMemberInstances() {
String clusterId = call("CreateDbCluster", """
{"name":"lifecycle-cluster","password":"password123","dbInstanceType":"db.influx.large",
"allocatedStorage":40,"vpcSubnetIds":["subnet-abc123","subnet-def456"],"vpcSecurityGroupIds":["sg-abc123"]}
""")
.statusCode(200)
.body("dbClusterId", matchesPattern(ID_PATTERN))
.body("dbClusterStatus", equalTo("CREATING"))
.extract().path("dbClusterId");
call("GetDbCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(200)
.body("status", equalTo("AVAILABLE"))
.body("arn", equalTo("arn:aws:timestream-influxdb:us-east-1:" + ACCOUNT + ":db-cluster/" + clusterId))
.body("endpoint", equalTo("localhost"))
.body("readerEndpoint", equalTo("localhost"))
.body("engineType", equalTo("INFLUXDB_V2"))
.body("deploymentType", equalTo("MULTI_NODE_READ_REPLICAS"))
.body("failoverMode", equalTo("AUTOMATIC"))
.body("port", equalTo(8086));
call("ListDbClusters", "{}")
.statusCode(200)
.body("items.id", hasItem(clusterId));
ValidatableResponse members = call("ListDbInstancesForCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(200)
.body("items", hasSize(2))
.body("items.instanceMode", containsInAnyOrder("PRIMARY", "REPLICA"))
.body("items.dbInstanceType", contains("db.influx.large", "db.influx.large"));
List<String> memberIds = members.extract().path("items.id");
call("GetDbInstance", "{\"identifier\":\"" + memberIds.get(0) + "\"}")
.statusCode(200)
.body("dbClusterId", equalTo(clusterId));
call("DeleteDbInstance", "{\"identifier\":\"" + memberIds.get(0) + "\"}")
.statusCode(400)
.body("__type", equalTo("ConflictException"));
call("UpdateDbCluster", "{\"dbClusterId\":\"" + clusterId + "\",\"dbInstanceType\":\"db.influx.2xlarge\"}")
.statusCode(200)
.body("dbClusterStatus", equalTo("UPDATING_INSTANCE_TYPE"));
call("ListDbInstancesForCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(200)
.body("items.dbInstanceType", contains("db.influx.2xlarge", "db.influx.2xlarge"));
call("RebootDbCluster", "{\"dbClusterId\":\"" + clusterId + "\",\"instanceIds\":[\"" + memberIds.get(1) + "\"]}")
.statusCode(200)
.body("dbClusterStatus", equalTo("REBOOTING"));
call("RebootDbCluster", "{\"dbClusterId\":\"" + clusterId + "\",\"instanceIds\":[\"notamember\"]}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("resourceType", equalTo("DB_INSTANCE"));
call("DeleteDbCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(200)
.body("dbClusterStatus", equalTo("DELETING"));
call("ListDbInstancesForCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("resourceType", equalTo("DB_CLUSTER"));
call("ListDbInstances", "{}")
.statusCode(200)
.body("items.id", not(hasItem(memberIds.get(0))));
}
@Test
void enterpriseClusterIsSizedFromItsParameterGroup() {
String groupId = call("CreateDbParameterGroup", """
{"name":"enterprise-group","parameters":{"InfluxDBv3Enterprise":
{"ingestQueryInstances":2,"queryOnlyInstances":1,"dedicatedCompactor":true}}}
""")
.statusCode(200)
.extract().path("id");
String clusterId = call("CreateDbCluster", """
{"name":"enterprise-cluster","dbInstanceType":"db.influx.large","dbParameterGroupIdentifier":"%s",
"vpcSubnetIds":["subnet-abc123"],"vpcSecurityGroupIds":["sg-abc123"]}
""".formatted(groupId))
.statusCode(200)
.extract().path("dbClusterId");
call("GetDbCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(200)
.body("engineType", equalTo("INFLUXDB_V3_ENTERPRISE"))
.body("port", equalTo(8181))
.body("dbParameterGroupIdentifier", equalTo(groupId))
.body("clusterConfiguration.ingestQueryInstances", equalTo(2))
.body("clusterConfiguration.queryOnlyInstances", equalTo(1))
.body("clusterConfiguration.dedicatedCompactor", equalTo(true));
call("ListDbInstancesForCluster", "{\"dbClusterId\":\"" + clusterId + "\"}")
.statusCode(200)
.body("items", hasSize(4));
assertValidationFor("CreateDbParameterGroup",
"{\"name\":\"enterprise-missing\",\"parameters\":{\"InfluxDBv3Enterprise\":{\"queryOnlyInstances\":1}}}");
createInstance("v3-standalone", ",\"dbParameterGroupIdentifier\":\"" + groupId + "\"")
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void tagsCanBeAddedListedAndRemovedByArn() {
String arn = createInstance("tagged-db", ",\"tags\":{\"env\":\"dev\"}")
.statusCode(200)
.extract().path("arn");
call("TagResource", "{\"resourceArn\":\"" + arn + "\",\"tags\":{\"team\":\"metrics\"}}")
.statusCode(200);
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
.statusCode(200)
.body("tags.env", equalTo("dev"))
.body("tags.team", equalTo("metrics"));
call("UntagResource", "{\"resourceArn\":\"" + arn + "\",\"tagKeys\":[\"env\"]}")
.statusCode(200);
call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
.statusCode(200)
.body("tags.env", nullValue())
.body("tags.team", equalTo("metrics"));
call("ListTagsForResource",
"{\"resourceArn\":\"arn:aws:timestream-influxdb:us-east-1:" + ACCOUNT + ":db-instance/missing123\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
assertValidationFor("ListTagsForResource", "{\"resourceArn\":\"arn:aws:s3:::bucket\"}");
}
@Test
void backupsCanBeTakenRestoredAndDeleted() {
String instanceId = createInstance("backup-source", "").statusCode(200).extract().path("id");
String backupId = call("CreateDbBackup", """
{"name":"nightly","dbResourceId":"%s","retentionDays":7}
""".formatted(instanceId))
.statusCode(200)
.body("id", matchesPattern(ID_PATTERN))
.body("arn", endsWithResource("db-backup"))
.body("status", equalTo("IN_PROGRESS"))
.body("type", equalTo("ON_DEMAND"))
.body("dbResourceId", equalTo(instanceId))
.body("engineType", equalTo("INFLUXDB_V2"))
.body("createdAt", instanceOf(Number.class))
.body("expiresAfter", matchesPattern("\\d{4}-\\d{2}-\\d{2}"))
.extract().path("id");
call("GetDbBackup", "{\"identifier\":\"" + backupId + "\"}")
.statusCode(200)
.body("status", equalTo("COMPLETED"))
.body("dbInstanceType", equalTo("db.influx.medium"))
.body("allocatedStorage", equalTo(20));
call("ListDbBackups", "{\"dbResourceId\":\"" + instanceId + "\"}")
.statusCode(200)
.body("items.id", contains(backupId));
call("CreateDbBackup", "{\"name\":\"nightly\",\"dbResourceId\":\"" + instanceId + "\"}")
.statusCode(400)
.body("__type", equalTo("ConflictException"));
call("CreateDbBackup", "{\"name\":\"orphan\",\"dbResourceId\":\"missing123\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
String restoredId = call("RestoreFromDbBackup", "{\"name\":\"restored-db\",\"dbBackupId\":\"" + backupId + "\"}")
.statusCode(200)
.body("restoreStatus", equalTo("RESTORING"))
.body("resourceType", equalTo("DB_INSTANCE"))
.body("engineType", equalTo("INFLUXDB_V2"))
.body("deploymentType", equalTo("SINGLE_AZ"))
.extract().path("restoredDbResourceId");
assertNotEquals(instanceId, restoredId);
call("GetDbInstance", "{\"identifier\":\"" + restoredId + "\"}")
.statusCode(200)
.body("name", equalTo("restored-db"))
.body("status", equalTo("AVAILABLE"))
.body("dbInstanceType", equalTo("db.influx.medium"));
call("RestoreFromDbBackup", "{\"name\":\"backup-source\",\"dbBackupId\":\"" + backupId + "\"}")
.statusCode(400)
.body("__type", equalTo("ConflictException"));
assertValidationFor("RestoreFromDbBackup",
"{\"name\":\"other-name\",\"dbBackupId\":\"" + backupId + "\",\"restoreMode\":\"REPLACE_EXISTING\"}");
call("RestoreFromDbBackup",
"{\"name\":\"backup-source\",\"dbBackupId\":\"" + backupId + "\",\"restoreMode\":\"REPLACE_EXISTING\"}")
.statusCode(200)
.body("restoredDbResourceId", equalTo(instanceId));
call("DeleteDbBackup", "{\"identifier\":\"" + backupId + "\"}")
.statusCode(200)
.body("status", equalTo("DELETING"));
call("GetDbBackup", "{\"identifier\":\"" + backupId + "\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("resourceType", equalTo("DB_BACKUP"));
}
@Test
void pointInTimeRestoreIsRejectedAndLeavesNothingBehind() {
String instanceId = createInstance("pitr-source", "").statusCode(200).extract().path("id");
String backupId = call("CreateDbBackup", "{\"name\":\"pitr-snap\",\"dbResourceId\":\"" + instanceId + "\"}")
.statusCode(200).extract().path("id");
assertValidationFor("RestoreFromDbBackup",
"{\"name\":\"pitr-restored\",\"dbBackupId\":\"" + backupId + "\",\"restoreToTime\":1700000000}");
call("ListDbInstances", "{\"maxResults\":100}")
.statusCode(200)
.body("items.name", not(hasItem("pitr-restored")));
}
@Test
void replaceExistingRejectsConfigurationOverrides() {
String instanceId = createInstance("replace-source", "").statusCode(200).extract().path("id");
String backupId = call("CreateDbBackup", "{\"name\":\"replace-snap\",\"dbResourceId\":\"" + instanceId + "\"}")
.statusCode(200).extract().path("id");
String replaceBase = "{\"name\":\"replace-source\",\"dbBackupId\":\"" + backupId
+ "\",\"restoreMode\":\"REPLACE_EXISTING\"";
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"port\":9100}");
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"tags\":{\"env\":\"dev\"}}");
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"networkType\":\"DUAL\"}");
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"vpcSubnetIds\":[\"subnet-zzz999\"]}");
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"publiclyAccessible\":true}");
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"deploymentType\":\"WITH_MULTIAZ_STANDBY\"}");
assertValidationFor("RestoreFromDbBackup", replaceBase + ",\"kmsKeyId\":\"alias/floci\"}");
call("GetDbInstance", "{\"identifier\":\"" + instanceId + "\"}")
.statusCode(200)
.body("port", equalTo(8086))
.body("networkType", equalTo("IPV4"))
.body("deploymentType", equalTo("SINGLE_AZ"))
.body("publiclyAccessible", equalTo(false))
.body("vpcSubnetIds", contains("subnet-abc123"));
call("RestoreFromDbBackup", replaceBase + "}")
.statusCode(200)
.body("restoredDbResourceId", equalTo(instanceId));
}
private static org.hamcrest.Matcher<String> endsWithResource(String resourceType) {
return matchesPattern("arn:aws:timestream-influxdb:us-east-1:" + ACCOUNT + ":" + resourceType + "/" + ID_PATTERN);
}
private static ValidatableResponse createInstance(String name, String extraFields) {
return call("CreateDbInstance", """
{"name":"%s","password":"password123","dbInstanceType":"db.influx.medium","allocatedStorage":20,
"vpcSubnetIds":["subnet-abc123"],"vpcSecurityGroupIds":["sg-abc123"]%s}
""".formatted(name, extraFields));
}
private static String instanceBody(String name, String instanceType, int storage, String port) {
return """
{"name":"%s","password":"password123","dbInstanceType":"%s","allocatedStorage":%d,"port":%s,
"vpcSubnetIds":["subnet-abc123"],"vpcSecurityGroupIds":["sg-abc123"]}
""".formatted(name, instanceType, storage, port);
}
private static void assertValidation(String body) {
assertValidationFor("CreateDbInstance", body);
}
private static void assertValidationFor(String action, String body) {
call(action, body)
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("reason", equalTo("FIELD_VALIDATION_FAILED"));
}
private static ValidatableResponse call(String action, String body) {
return given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then();
}
}
@@ -0,0 +1,308 @@
package io.github.hectorvent.floci.services.timestreaminfluxdb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.services.timestreaminfluxdb.TimestreamInfluxDbService.RestoreResult;
import io.github.hectorvent.floci.services.timestreaminfluxdb.container.TimestreamInfluxDbContainerManager;
import io.github.hectorvent.floci.services.timestreaminfluxdb.container.TimestreamInfluxDbContainerManager.InfluxDbEndpoint;
import io.github.hectorvent.floci.services.timestreaminfluxdb.container.TimestreamInfluxDbContainerManager.InfluxDbSetup;
import io.github.hectorvent.floci.services.timestreaminfluxdb.model.DbBackup;
import io.github.hectorvent.floci.services.timestreaminfluxdb.model.DbCluster;
import io.github.hectorvent.floci.services.timestreaminfluxdb.model.DbInstance;
import io.github.hectorvent.floci.services.timestreaminfluxdb.model.DbParameterGroup;
import org.junit.jupiter.api.BeforeEach;
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.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TimestreamInfluxDbServiceTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private final ObjectMapper objectMapper = new ObjectMapper();
private TimestreamInfluxDbContainerManager containerManager;
private TimestreamInfluxDbService service;
@BeforeEach
void setUp() {
containerManager = mock(TimestreamInfluxDbContainerManager.class);
when(containerManager.isDockerReachable()).thenReturn(true);
when(containerManager.start(anyString(), anyString(), anyString(), any(), anyMap()))
.thenReturn(new InfluxDbEndpoint("container-1", "localhost", 18086));
SecretsManagerService secrets = mock(SecretsManagerService.class);
Secret secret = mock(Secret.class);
when(secret.getArn()).thenReturn("arn:aws:secretsmanager:us-east-1:000000000000:secret:influx");
when(secrets.createSecret(anyString(), anyString(), isNull(), anyString(), isNull(), isNull(), eq(REGION)))
.thenReturn(secret);
service = new TimestreamInfluxDbService(
AccountAwareStorageBackend.<DbInstance>inMemory(ACCOUNT),
AccountAwareStorageBackend.<DbCluster>inMemory(ACCOUNT),
AccountAwareStorageBackend.<DbParameterGroup>inMemory(ACCOUNT),
AccountAwareStorageBackend.<DbBackup>inMemory(ACCOUNT),
new RegionResolver(REGION, ACCOUNT), secrets, objectMapper, containerManager, false, Runnable::run);
}
@Test
void createInstanceStartsAContainerWithTheInitialAuthParametersAndBecomesAvailable() throws Exception {
DbInstance created = service.createDbInstance(json("""
{"name":"real-db","username":"operator","password":"password123","organization":"acme",
"bucket":"metrics","dbInstanceType":"db.influx.medium","allocatedStorage":20,
"vpcSubnetIds":["subnet-abc"],"vpcSecurityGroupIds":["sg-abc"]}
"""), REGION).resource();
ArgumentCaptor<InfluxDbSetup> setup = ArgumentCaptor.forClass(InfluxDbSetup.class);
verify(containerManager).start(eq(created.getId()), eq(ACCOUNT), eq(REGION), setup.capture(), eq(Map.of()));
assertEquals(new InfluxDbSetup("operator", "password123", "acme", "metrics"), setup.getValue());
DbInstance stored = service.getDbInstance(json("{\"identifier\":\"" + created.getId() + "\"}"), REGION);
assertEquals("AVAILABLE", stored.getStatus());
assertEquals("localhost", stored.getEndpoint());
assertEquals(18086, stored.getPort());
assertEquals("container-1", stored.getContainerId());
}
@Test
void instanceIsFailedWhenTheContainerDoesNotBecomeHealthy() throws Exception {
doThrow(new IllegalStateException("not healthy")).when(containerManager).waitUntilReady(any());
String id = createInstance("unhealthy-db", null).getId();
assertEquals("FAILED", service.getDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION).getStatus());
}
@Test
void instanceIsAvailableWithoutAContainerWhenNoDockerDaemonIsReachable() throws Exception {
when(containerManager.isDockerReachable()).thenReturn(false);
String id = createInstance("no-docker-db", null).getId();
DbInstance stored = service.getDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION);
assertEquals("AVAILABLE", stored.getStatus());
assertNull(stored.getContainerId());
verify(containerManager, never()).start(anyString(), anyString(), anyString(), any(), anyMap());
}
@Test
void parameterGroupValuesReachTheContainerAsInfluxdEnvironment() throws Exception {
String groupId = service.createDbParameterGroup(json("""
{"name":"tuned","parameters":{"InfluxDBv2":{"logLevel":"debug",
"httpIdleTimeout":{"durationType":"minutes","value":5}}}}
"""), REGION).getId();
createInstance("tuned-db", groupId);
verify(containerManager).start(anyString(), eq(ACCOUNT), eq(REGION), any(),
eq(Map.of("INFLUXD_LOG_LEVEL", "debug", "INFLUXD_HTTP_IDLE_TIMEOUT", "5m")));
}
@Test
void switchingParameterGroupRecreatesTheContainerWithoutSetup() throws Exception {
String id = createInstance("switch-db", null).getId();
String groupId = service.createDbParameterGroup(json("""
{"name":"no-ui","parameters":{"InfluxDBv2":{"uiDisabled":true}}}
"""), REGION).getId();
service.updateDbInstance(json("{\"identifier\":\"" + id + "\",\"dbParameterGroupIdentifier\":\"" + groupId + "\"}"),
REGION);
verify(containerManager).start(eq(id), eq(ACCOUNT), eq(REGION), isNull(), eq(Map.of("INFLUXD_UI_DISABLED", "true")));
assertEquals("AVAILABLE", service.getDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION).getStatus());
}
@Test
void rebootRestartsTheContainerAndDeleteRemovesContainerAndVolumes() throws Exception {
String id = createInstance("reboot-db", null).getId();
service.rebootDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION);
verify(containerManager).restart("container-1");
assertEquals("AVAILABLE", service.getDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION).getStatus());
service.deleteDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION);
verify(containerManager).stop(id, "container-1");
verify(containerManager).removeStorage(id);
}
@Test
void rebootFailureIsReportedAsRebootFailed() throws Exception {
String id = createInstance("reboot-fail-db", null).getId();
doThrow(new IllegalStateException("restart failed")).when(containerManager).restart("container-1");
service.rebootDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION);
assertEquals("REBOOT_FAILED", service.getDbInstance(json("{\"identifier\":\"" + id + "\"}"), REGION).getStatus());
}
@Test
void backupCapturesContainerDataAndRestoreLoadsItIntoANewContainer() throws Exception {
String sourceId = createInstance("backup-db", null).getId();
DbBackup backup = service.createDbBackup(json("{\"name\":\"snap\",\"dbResourceId\":\"" + sourceId + "\"}"), REGION)
.resource();
verify(containerManager).backup("container-1", backup.getId());
DbBackup stored = service.getDbBackup(json("{\"identifier\":\"" + backup.getId() + "\"}"), REGION);
assertEquals("COMPLETED", stored.getStatus());
assertTrue(stored.isDataCaptured());
when(containerManager.start(anyString(), anyString(), anyString(), any(), anyMap()))
.thenReturn(new InfluxDbEndpoint("container-2", "localhost", 18087));
RestoreResult result = service.restoreFromDbBackup(
json("{\"name\":\"restored\",\"dbBackupId\":\"" + backup.getId() + "\"}"), REGION);
verify(containerManager).restore("container-2", backup.getId());
DbInstance restored = service.getDbInstance(json("{\"identifier\":\"" + result.restoredDbResourceId() + "\"}"),
REGION);
assertEquals("AVAILABLE", restored.getStatus());
assertEquals(18087, restored.getPort());
service.deleteDbBackup(json("{\"identifier\":\"" + backup.getId() + "\"}"), REGION);
verify(containerManager).deleteBackupArtifacts(backup.getId());
}
@Test
void failedCaptureMarksTheBackupFailedAndBlocksRestore() throws Exception {
String sourceId = createInstance("failed-backup-db", null).getId();
doThrow(new IllegalStateException("influx backup failed")).when(containerManager).backup(anyString(), anyString());
String backupId = service.createDbBackup(json("{\"name\":\"broken\",\"dbResourceId\":\"" + sourceId + "\"}"),
REGION).resource().getId();
assertEquals("FAILED", service.getDbBackup(json("{\"identifier\":\"" + backupId + "\"}"), REGION).getStatus());
AwsException error = assertThrows(AwsException.class, () -> service.restoreFromDbBackup(
json("{\"name\":\"never\",\"dbBackupId\":\"" + backupId + "\"}"), REGION));
assertEquals("ConflictException", error.getErrorCode());
}
@Test
void readReplicaClusterSharesOneContainerAcrossItsNodes() throws Exception {
String clusterId = service.createDbCluster(json("""
{"name":"replicas","password":"password123","dbInstanceType":"db.influx.large",
"vpcSubnetIds":["subnet-abc"],"vpcSecurityGroupIds":["sg-abc"]}
"""), REGION).resource().getId();
verify(containerManager).start(eq(clusterId), eq(ACCOUNT), eq(REGION), any(), anyMap());
DbCluster cluster = service.getDbCluster(json("{\"dbClusterId\":\"" + clusterId + "\"}"), REGION);
assertEquals("AVAILABLE", cluster.getStatus());
List<DbInstance> members = service.listDbInstancesForCluster(
json("{\"dbClusterId\":\"" + clusterId + "\"}"), REGION).items();
assertEquals(2, members.size());
for (DbInstance member : members) {
assertEquals("AVAILABLE", member.getStatus());
assertEquals(18086, member.getPort());
}
}
@Test
void influxDb3ClustersHaveNoInfluxDb2Container() throws Exception {
String groupId = service.createDbParameterGroup(json("{\"name\":\"core\",\"parameters\":{\"InfluxDBv3Core\":{}}}"),
REGION).getId();
String clusterId = service.createDbCluster(json("""
{"name":"core-cluster","dbInstanceType":"db.influx.large","dbParameterGroupIdentifier":"%s",
"vpcSubnetIds":["subnet-abc"],"vpcSecurityGroupIds":["sg-abc"]}
""".formatted(groupId)), REGION).resource().getId();
verify(containerManager, never()).start(anyString(), anyString(), anyString(), any(), anyMap());
DbCluster cluster = service.getDbCluster(json("{\"dbClusterId\":\"" + clusterId + "\"}"), REGION);
assertEquals("AVAILABLE", cluster.getStatus());
assertEquals(8181, cluster.getPort());
List<DbInstance> members = service.listDbInstancesForCluster(
json("{\"dbClusterId\":\"" + clusterId + "\"}"), REGION).items();
assertEquals(1, members.size());
assertEquals(List.of("INGEST", "QUERY", "COMPACT", "PROCESS"), members.get(0).getInstanceModes());
}
@Test
void restoreToTimeIsRejectedBecausePointInTimeRestoreNeedsContinuousBackups() throws Exception {
String sourceId = createInstance("pitr-db", null).getId();
String backupId = service.createDbBackup(json("{\"name\":\"pitr\",\"dbResourceId\":\"" + sourceId + "\"}"),
REGION).resource().getId();
AwsException error = assertThrows(AwsException.class, () -> service.restoreFromDbBackup(json(
"{\"name\":\"pitr-copy\",\"dbBackupId\":\"" + backupId + "\",\"restoreToTime\":1700000000}"), REGION));
assertEquals("ValidationException", error.getErrorCode());
assertTrue(error.getMessage().contains("continuous"), error.getMessage());
verify(containerManager, never()).restore(anyString(), anyString());
}
@Test
void replaceExistingRejectsOverridesAndRestoresDataWithoutThem() throws Exception {
String sourceId = createInstance("replace-db", null).getId();
String backupId = service.createDbBackup(json("{\"name\":\"replace\",\"dbResourceId\":\"" + sourceId + "\"}"),
REGION).resource().getId();
String replaceBase = "{\"name\":\"replace-db\",\"dbBackupId\":\"" + backupId
+ "\",\"restoreMode\":\"REPLACE_EXISTING\"";
AwsException error = assertThrows(AwsException.class, () -> service.restoreFromDbBackup(
json(replaceBase + ",\"port\":9100}"), REGION));
assertEquals("ValidationException", error.getErrorCode());
assertTrue(error.getMessage().contains("port"), error.getMessage());
verify(containerManager, never()).restore(anyString(), anyString());
assertEquals(18086, service.getDbInstance(json("{\"identifier\":\"" + sourceId + "\"}"), REGION).getPort());
service.restoreFromDbBackup(json(replaceBase + "}"), REGION);
verify(containerManager).restore("container-1", backupId);
}
@Test
void tagsBeyondTheQuotaAreRejected() throws Exception {
String arn = createInstance("quota-db", null).getArn();
StringBuilder tags = new StringBuilder();
for (int i = 0; i < 200; i++) {
tags.append(i == 0 ? "" : ",").append("\"k").append(i).append("\":\"v\"");
}
service.tagResource(json("{\"resourceArn\":\"" + arn + "\",\"tags\":{" + tags + "}}"));
AwsException error = assertThrows(AwsException.class,
() -> service.tagResource(json("{\"resourceArn\":\"" + arn + "\",\"tags\":{\"extra\":\"v\"}}")));
assertEquals("ServiceQuotaExceededException", error.getErrorCode());
}
@Test
void higherStorageTiersRequireAtLeast400GiB() {
AwsException error = assertThrows(AwsException.class, () -> service.createDbInstance(json("""
{"name":"t2-db","password":"password123","dbInstanceType":"db.influx.medium","allocatedStorage":100,
"dbStorageType":"InfluxIOIncludedT2","vpcSubnetIds":["subnet-abc"],"vpcSecurityGroupIds":["sg-abc"]}
"""), REGION));
assertEquals("ValidationException", error.getErrorCode());
}
private DbInstance createInstance(String name, String parameterGroupId) throws Exception {
String groupField = parameterGroupId == null ? "" : ",\"dbParameterGroupIdentifier\":\"" + parameterGroupId + "\"";
return service.createDbInstance(json("""
{"name":"%s","password":"password123","dbInstanceType":"db.influx.medium","allocatedStorage":20,
"vpcSubnetIds":["subnet-abc"],"vpcSecurityGroupIds":["sg-abc"]%s}
""".formatted(name, groupField)), REGION).resource();
}
private JsonNode json(String value) {
try {
return objectMapper.readTree(value);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
@@ -0,0 +1,137 @@
package io.github.hectorvent.floci.services.timestreaminfluxdb.container;
import com.fasterxml.jackson.databind.ObjectMapper;
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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.services.timestreaminfluxdb.container.TimestreamInfluxDbContainerManager.InfluxDbEndpoint;
import io.github.hectorvent.floci.services.timestreaminfluxdb.container.TimestreamInfluxDbContainerManager.InfluxDbSetup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TimestreamInfluxDbContainerManagerTest {
private ContainerLifecycleManager lifecycleManager;
private ContainerBuilder.Builder builder;
private PortAllocator portAllocator;
private TimestreamInfluxDbContainerManager manager;
@BeforeEach
void setUp() {
lifecycleManager = mock(ContainerLifecycleManager.class);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
portAllocator = mock(PortAllocator.class);
when(portAllocator.allocate(8086, 8185)).thenReturn(8090);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.TimestreamInfluxDbServiceConfig influx = mock(EmulatorConfig.TimestreamInfluxDbServiceConfig.class);
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
when(config.services()).thenReturn(services);
when(config.storage()).thenReturn(storage);
when(services.timestreamInfluxdb()).thenReturn(influx);
when(influx.defaultImage()).thenReturn("influxdb:2.7");
when(influx.hostPortBase()).thenReturn(8086);
when(influx.hostPortMax()).thenReturn(8185);
when(influx.dockerNetwork()).thenReturn(Optional.empty());
manager = new TimestreamInfluxDbContainerManager(containerBuilder, lifecycleManager,
mock(ContainerDetector.class), portAllocator, config);
}
@Test
void startRunsImageSetupPublishesTheHttpPortAndLabelsTheContainer() {
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("container-id",
Map.of(8086, new EndpointInfo("localhost", 8090))));
InfluxDbEndpoint endpoint = manager.start("abc1234567", "000000000000", "us-east-1",
new InfluxDbSetup("admin", "password123", "acme", "metrics"), Map.of("INFLUXD_LOG_LEVEL", "debug"));
assertEquals(new InfluxDbEndpoint("container-id", "localhost", 8090), endpoint);
verify(builder).withEnv("DOCKER_INFLUXDB_INIT_MODE", "setup");
verify(builder).withEnv("DOCKER_INFLUXDB_INIT_USERNAME", "admin");
verify(builder).withEnv("DOCKER_INFLUXDB_INIT_PASSWORD", "password123");
verify(builder).withEnv("DOCKER_INFLUXDB_INIT_ORG", "acme");
verify(builder).withEnv("DOCKER_INFLUXDB_INIT_BUCKET", "metrics");
verify(builder).withEnv("INFLUXD_LOG_LEVEL", "debug");
verify(builder).withPortBinding(8086, 8090);
verify(builder).withNamedVolume("floci-timestream-influxdb-abc1234567", "/var/lib/influxdb2");
verify(builder).withNamedVolume("floci-timestream-influxdb-abc1234567-config", "/etc/influxdb2");
verify(builder).withLabels(Map.of(
"io.floci", "aws",
"io.floci.service", "timestream-influxdb",
"io.floci.resource-id", "abc1234567",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
}
@Test
void restartingOnExistingVolumesSkipsSetup() {
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("container-id",
Map.of(8086, new EndpointInfo("localhost", 8090))));
manager.start("abc1234567", "000000000000", "us-east-1", null, Map.of());
verify(builder, never()).withEnv("DOCKER_INFLUXDB_INIT_MODE", "setup");
}
@Test
void failedStartRemovesTheContainerAndReleasesThePort() {
when(lifecycleManager.createAndStart(any())).thenThrow(new RuntimeException("port already allocated"));
assertThrows(RuntimeException.class, () -> manager.start("abc1234567", "000000000000", "us-east-1",
new InfluxDbSetup("admin", "password123", "acme", "metrics"), Map.of()));
verify(portAllocator).release(8090);
verify(lifecycleManager, Mockito.times(2)).removeIfExists("floci-timestream-influxdb-abc1234567");
}
@Test
void stopReleasesThePublishedPort() {
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("container-id",
Map.of(8086, new EndpointInfo("localhost", 8090))));
manager.start("abc1234567", "000000000000", "us-east-1", null, Map.of());
manager.stop("abc1234567", "container-id");
verify(lifecycleManager).stopAndRemove("container-id", null);
verify(portAllocator).release(8090);
}
@Test
void parameterGroupMembersMapToInfluxdEnvironmentVariables() throws Exception {
Map<String, String> environment = TimestreamInfluxDbContainerManager.engineEnvironment(new ObjectMapper().readTree("""
{"fluxLogEnabled":true,"queryConcurrency":10,"influxqlMaxSelectBuckets":5,
"storageCacheSnapshotWriteColdDuration":{"durationType":"days","value":2},
"httpWriteTimeout":{"durationType":"milliseconds","value":250}}
"""));
assertEquals(Map.of(
"INFLUXD_FLUX_LOG_ENABLED", "true",
"INFLUXD_QUERY_CONCURRENCY", "10",
"INFLUXD_INFLUXQL_MAX_SELECT_BUCKETS", "5",
"INFLUXD_STORAGE_CACHE_SNAPSHOT_WRITE_COLD_DURATION", "48h",
"INFLUXD_HTTP_WRITE_TIMEOUT", "250ms"), environment);
}
}