feat(rds): DescribeDBLogFiles and DownloadDBLogFilePortion (#5741)

* feat(rds): DescribeDBLogFiles and DownloadDBLogFilePortion

Both answered UnsupportedOperation, so an instance's log could only be
read with docker logs, outside the AWS API.

An instance's log is now read from its database container and cut into
files the way RDS names them: hourly error/postgresql.log.* files for
PostgreSQL, error/mysql-error.log for MySQL and MariaDB, and log/ERROR
for SQL Server. DescribeDBLogFiles filters and pages them, and
DownloadDBLogFilePortion follows the API reference's marker rules with
a 1 MB block cap. Control characters XML cannot carry come back as
U+FFFD. In mock RDS mode an instance has no log files.

Closes #5733

* fix(rds): bound and validate log file reads

A log read now takes the most recent 100,000 lines instead of the whole
history, fails when Docker does not finish in time instead of returning
part of the log, and, when Docker no longer knows the container, finds
or starts the backend once before answering DBInstanceNotReady rather
than an empty log. A single line over 1 MB is cut at 1 MB like the rest
of the block. Negative FileSize, FileLastWritten and Marker values are
InvalidParameterValue; the shared offset paging refuses a negative
marker instead of starting over.

* fix(rds): close the Docker log stream when a log read times out

A timed-out read now closes its callback before failing, so the stream
stops and nothing writes into the buffer after the read gives up; the
buffer is also written and read under one lock.

* refactor(rds): keep portion's Javadoc on portion

truncateUtf8 had landed between portion's comment and portion itself. It now follows portion.

* test(rds): read log files on the first call, and import class names

CreateDBInstance returns once the database accepts connections, so the startup log is already in the container's output. The Docker and SDK log tests now assert on the first DescribeDBLogFiles and DownloadDBLogFilePortion call instead of polling. The timeout test and RdsLogFilesTest import the classes they had written out in full.
This commit is contained in:
David authored and GitHub committed 2026-10-16 07:16:10 -04:00
1 parent 0264c1b960
commit 4353e4232b
13 files changed
+820 -2

No files matched your search

@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.rds;
import com.github.dockerjava.api.DockerClient;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* A real PostgreSQL instance's log, read through {@code DescribeDBLogFiles} and
* {@code DownloadDBLogFilePortion}: the container's startup line lands in an hourly
* {@code error/postgresql.log.*} file. Skipped without Docker.
*/
@QuarkusTest
@Tag("docker")
class RdsLogFilesDockerIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261015/us-east-1/rds/aws4_request, "
+ "SignedHeaders=content-type;host, Signature=test";
@Inject
DockerClient dockerClient;
@BeforeEach
void checkDocker() {
try {
dockerClient.pingCmd().exec();
} catch (Exception e) {
assumeTrue(false, "Docker is not available: " + e.getMessage());
}
}
private static RequestSpecification query(String action) {
return given().header("Authorization", AUTH)
.contentType(URLENC)
.formParam("Action", action)
.formParam("Version", "2014-10-31");
}
@Test
void aPostgresInstancesLogIsListedAndDownloaded() {
String id = "log-files-pg-" + Long.toString(System.nanoTime(), 36);
try {
query("CreateDBInstance")
.formParam("DBInstanceIdentifier", id)
.formParam("Engine", "postgres")
.formParam("DBInstanceClass", "db.t3.micro")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "password123")
.formParam("AllocatedStorage", "20")
.when().post("/").then().statusCode(200);
// CreateDBInstance returns once the database accepts connections, so its startup log is
// already in the container's output: the first call must see it.
List<String> names = query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", id)
.when().post("/").then().statusCode(200).extract().xmlPath()
.getList("**.findAll { it.name() == 'LogFileName' }", String.class);
assertFalse(names.isEmpty(), "the instance should have a log file");
assertTrue(names.stream().allMatch(n -> n.matches("error/postgresql\\.log\\.\\d{4}-\\d{2}-\\d{2}-\\d{2}")),
names.toString());
StringBuilder all = new StringBuilder();
for (String name : names) {
all.append(query("DownloadDBLogFilePortion").formParam("DBInstanceIdentifier", id)
.formParam("LogFileName", name).formParam("Marker", "0")
.when().post("/").then().statusCode(200).extract().xmlPath()
.getString("DownloadDBLogFilePortionResponse.DownloadDBLogFilePortionResult.LogFileData"));
}
String data = all.toString();
assertTrue(data.contains("ready to accept connections"), data);
} finally {
query("DeleteDBInstance").formParam("DBInstanceIdentifier", id).formParam("SkipFinalSnapshot", "true")
.when().post("/");
}
}
}
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.services.rds;
import io.github.hectorvent.floci.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* {@code DescribeDBLogFiles} and {@code DownloadDBLogFilePortion} over the Query protocol in mock
* RDS mode, where an instance has no container and so no log files, and the errors the API
* reference lists. {@code RdsLogFilesDockerIntegrationTest} reads a real container's log.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class RdsLogFilesIntegrationTest {
private static final String INSTANCE = "log-files-db";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261015/us-east-1/rds/aws4_request, "
+ "SignedHeaders=content-type;host, Signature=test";
private static RequestSpecification query(String action) {
return given().header("Authorization", AUTH)
.contentType(URLENC)
.formParam("Action", action)
.formParam("Version", "2014-10-31");
}
@Test
@Order(1)
void anInstanceWithoutAContainerHasNoLogFiles() {
query("CreateDBInstance")
.formParam("DBInstanceIdentifier", INSTANCE)
.formParam("Engine", "postgres")
.formParam("DBInstanceClass", "db.t3.micro")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "password123")
.formParam("AllocatedStorage", "20")
.when().post("/").then().statusCode(200);
query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", INSTANCE)
.when().post("/").then().statusCode(200)
.body(containsString("<DescribeDBLogFilesResult><DescribeDBLogFiles></DescribeDBLogFiles>"));
query("DownloadDBLogFilePortion").formParam("DBInstanceIdentifier", INSTANCE)
.formParam("LogFileName", "error/postgresql.log.2026-10-15-10")
.when().post("/").then().statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("DBLogFileNotFoundFault"));
}
@Test
@Order(2)
void theApiReferencesErrors() {
query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", "no-such-db")
.when().post("/").then().statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("DBInstanceNotFound"));
query("DescribeDBLogFiles")
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MissingParameter"));
query("DownloadDBLogFilePortion").formParam("DBInstanceIdentifier", INSTANCE)
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MissingParameter"));
query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", INSTANCE).formParam("MaxRecords", "5")
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));
query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", INSTANCE).formParam("FileSize", "big")
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));
for (String[] bad : new String[][] {{"FileSize", "-1"}, {"FileLastWritten", "-1"}, {"Marker", "-1"}}) {
query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", INSTANCE).formParam(bad[0], bad[1])
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));
}
query("StopDBInstance").formParam("DBInstanceIdentifier", INSTANCE)
.when().post("/").then().statusCode(200);
query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", INSTANCE)
.when().post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("DBInstanceNotReady"));
query("StartDBInstance").formParam("DBInstanceIdentifier", INSTANCE)
.when().post("/").then().statusCode(200);
}
}
@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.services.rds;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RdsLogFilesTest {
private static List<String> docker(String... lines) {
return List.of(lines);
}
@Test
void postgresRotatesHourlyAndMysqlKeepsOneErrorLog() {
List<RdsLogFiles.LogLine> lines = RdsLogFiles.parseDockerLines(docker(
"2026-10-15T09:59:59.000000001Z LOG: database system is ready",
"2026-10-15T10:00:00.5Z LOG: checkpoint starting",
"2026-10-15T10:30:00Z ERROR: relation \"t\" does not exist"));
List<RdsLogFiles.LogFile> postgres = RdsLogFiles.files("postgres", lines);
assertEquals(List.of("error/postgresql.log.2026-10-15-09", "error/postgresql.log.2026-10-15-10"),
postgres.stream().map(RdsLogFiles.LogFile::name).toList());
RdsLogFiles.LogFile tenOClock = postgres.get(1);
assertEquals(Instant.parse("2026-10-15T10:30:00Z"), tenOClock.lastWritten());
assertEquals(List.of("LOG: checkpoint starting", "ERROR: relation \"t\" does not exist"), tenOClock.lines());
assertEquals("LOG: checkpoint starting\n".length() + "ERROR: relation \"t\" does not exist\n".length(),
tenOClock.size());
assertEquals(List.of("error/mysql-error.log"),
RdsLogFiles.files("mariadb", lines).stream().map(RdsLogFiles.LogFile::name).toList());
assertEquals(List.of("log/ERROR"),
RdsLogFiles.files("sqlserver-se", lines).stream().map(RdsLogFiles.LogFile::name).toList());
assertEquals(2, RdsLogFiles.files("aurora-postgresql", lines).size());
}
@Test
void aLineWithoutATimestampTakesThePreviousOnesTimeAndControlCharactersAreReplaced() {
List<RdsLogFiles.LogLine> lines = RdsLogFiles.parseDockerLines(docker(
"2026-10-15T10:00:00Z first",
"continued\u001b[0m\ttab"));
assertEquals(Instant.parse("2026-10-15T10:00:00Z"), lines.get(1).time());
assertEquals("continued�[0m\ttab", lines.get(1).text());
}
@Test
void describeFiltersByNameTimeAndSize() {
List<RdsLogFiles.LogFile> files = RdsLogFiles.files("postgres", RdsLogFiles.parseDockerLines(docker(
"2026-10-15T09:00:00Z a",
"2026-10-15T10:00:00Z bbbbbbbbbb")));
assertEquals(1, RdsLogFiles.matching(files, "-09", null, null).size());
long tenOClock = Instant.parse("2026-10-15T10:00:00Z").toEpochMilli();
assertEquals("error/postgresql.log.2026-10-15-10",
RdsLogFiles.matching(files, null, tenOClock, null).get(0).name());
// Larger than the size given: "a\n" is 2 bytes, "bbbbbbbbbb\n" 11.
assertEquals(1, RdsLogFiles.matching(files, null, null, 2L).size());
assertEquals(2, RdsLogFiles.matching(files, "", null, null).size());
}
private static RdsLogFiles.LogFile fileOf(int lines) {
List<String> texts = new ArrayList<>();
for (int i = 0; i < lines; i++) {
texts.add("line " + i);
}
return new RdsLogFiles.LogFile("error/mysql-error.log", Instant.EPOCH, 0, texts);
}
@Test
void downloadFollowsTheApiReferencesMarkerRules() {
RdsLogFiles.LogFile file = fileOf(5);
// No marker: the most recent lines.
RdsLogFiles.Portion tail = RdsLogFiles.portion(file, null, 2);
assertEquals("line 3\nline 4\n", tail.data());
assertFalse(tail.additionalDataPending());
assertEquals("5", tail.marker());
// Marker "0": from the start, in blocks, until nothing is pending.
RdsLogFiles.Portion first = RdsLogFiles.portion(file, "0", 2);
assertEquals("line 0\nline 1\n", first.data());
assertTrue(first.additionalDataPending());
RdsLogFiles.Portion second = RdsLogFiles.portion(file, first.marker(), 2);
assertEquals("line 2\nline 3\n", second.data());
RdsLogFiles.Portion last = RdsLogFiles.portion(file, second.marker(), 2);
assertEquals("line 4\n", last.data());
assertFalse(last.additionalDataPending());
// Neither: the whole file (up to 10000 lines).
assertEquals(5, RdsLogFiles.portion(file, null, null).data().split("\n").length);
// A marker past the end is an empty block.
assertEquals("", RdsLogFiles.portion(file, "99", 2).data());
assertThrows(AwsException.class, () -> RdsLogFiles.portion(file, "next", 2));
assertThrows(AwsException.class, () -> RdsLogFiles.portion(file, "-1", 2));
assertThrows(AwsException.class, () -> RdsLogFiles.portion(file, "0", 0));
}
@Test
void aBlockStopsAtOneMegabyteAndAtTenThousandLines() {
List<String> big = new ArrayList<>();
String kb = "x".repeat(1023);
for (int i = 0; i < 2000; i++) {
big.add(kb);
}
RdsLogFiles.LogFile file = new RdsLogFiles.LogFile("log/ERROR", Instant.EPOCH, 0, big);
RdsLogFiles.Portion portion = RdsLogFiles.portion(file, "0", 5000);
assertEquals(1024, portion.data().split("\n").length);
assertTrue(portion.additionalDataPending());
assertEquals("1024", portion.marker());
assertEquals("10000", RdsLogFiles.portion(fileOf(12_000), "0", 50_000).marker());
}
@Test
void aSingleLineOverOneMegabyteIsCutAtOneMegabyte() {
String huge = "\u00e9".repeat(RdsLogFiles.MAX_BYTES);
RdsLogFiles.LogFile file = new RdsLogFiles.LogFile("log/ERROR", Instant.EPOCH, 0, List.of(huge, "next"));
RdsLogFiles.Portion portion = RdsLogFiles.portion(file, "0", 10);
int bytes = portion.data().getBytes(StandardCharsets.UTF_8).length;
assertTrue(bytes <= RdsLogFiles.MAX_BYTES, Integer.toString(bytes));
assertTrue(portion.data().endsWith("\u00e9\n"), "cut between characters");
assertEquals("1", portion.marker());
assertTrue(portion.additionalDataPending());
assertEquals("next\n", RdsLogFiles.portion(file, portion.marker(), 10).data());
}
}
@@ -510,6 +510,37 @@ class RdsServiceTest {
}
}
@Test
void logFilesRecoverAMissingContainerOnceThenReportTheInstanceNotReady() {
when(rdsConfig.mock()).thenReturn(true);
rdsService.createDbInstance("logs-db", "postgres", "16.3", "admin", "password", "appdb",
"db.t3.micro", 20, false, null, null, null, null, false, false, null,
Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults());
when(rdsConfig.mock()).thenReturn(false);
RdsService service = spy(rdsService);
DbInstance recovered = new DbInstance();
recovered.setContainerId("fresh-container");
doReturn(recovered).when(service).ensureInstanceBackend(eq("logs-db"), any());
// No container id on file: the backend is found once and its log read.
when(containerManager.readLog("fresh-container"))
.thenReturn(List.of("2026-10-15T10:00:00Z LOG: database system is ready to accept connections"));
assertEquals(List.of("error/postgresql.log.2026-10-15-10"),
service.describeDbLogFiles(null, "logs-db", null, null, null, null, null).files().stream()
.map(RdsLogFiles.LogFile::name).toList());
// Docker does not know the recovered container either: the instance is not ready.
when(containerManager.readLog("fresh-container")).thenReturn(null);
AwsException notReady = assertThrows(AwsException.class,
() -> service.describeDbLogFiles(null, "logs-db", null, null, null, null, null));
assertEquals("DBInstanceNotReady", notReady.getErrorCode());
// A read that times out is a failure, not a short log.
when(containerManager.readLog("fresh-container")).thenThrow(new IllegalStateException("Timed out"));
assertEquals("InternalFailure", assertThrows(AwsException.class,
() -> service.describeDbLogFiles(null, "logs-db", null, null, null, null, null)).getErrorCode());
}
@Test
void replacedClusterCannotReceiveAnOldMemberPublicationAndRetryReusesThePort() throws Exception {
when(rdsConfig.mock()).thenReturn(false);
@@ -1,10 +1,14 @@
package io.github.hectorvent.floci.services.rds.container;
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.LogContainerCmd;
import com.github.dockerjava.api.command.PauseContainerCmd;
import com.github.dockerjava.api.command.UnpauseContainerCmd;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
@@ -24,9 +28,12 @@ import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import java.io.Closeable;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@@ -240,6 +247,40 @@ class RdsContainerManagerTest {
verify(lifecycleManager, never()).getDockerClient();
}
@Test
void aLogReadThatTimesOutFailsAndClosesTheStream() throws Exception {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
LogContainerCmd logCmd = mock(LogContainerCmd.class);
when(dockerClient.logContainerCmd("slow")).thenReturn(logCmd);
when(logCmd.withStdOut(true)).thenReturn(logCmd);
when(logCmd.withStdErr(true)).thenReturn(logCmd);
when(logCmd.withTimestamps(true)).thenReturn(logCmd);
when(logCmd.withTail(RdsContainerManager.MAX_LOG_LINES)).thenReturn(logCmd);
Closeable stream = mock(Closeable.class);
// Docker starts the stream and sends one frame, then never completes.
when(logCmd.exec(any())).thenAnswer(invocation -> {
ResultCallback.Adapter<Frame> callback = invocation.getArgument(0);
callback.onStart(stream);
callback.onNext(new Frame(StreamType.STDOUT,
"2026-10-15T10:00:00Z partial\n".getBytes(StandardCharsets.UTF_8)));
return callback;
});
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)),
lifecycleManager, mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
IllegalStateException timedOut = assertThrows(IllegalStateException.class,
() -> manager.readLog("slow", Duration.ofMillis(50)));
assertTrue(timedOut.getMessage().contains("Timed out"), timedOut.getMessage());
verify(stream).close();
}
@Test
void mysqlNonRootMasterStartInstallsGrantInitScriptBeforeStart() throws Exception {
EmulatorConfig config = config(tempDir.resolve("host-root"));