Truncate container log files to remove logging delay on restarted container (#26)

When a container that was writing stdout/stderr to its dedicated
container log file was stopped and started, there was a ~20 second - 1
minute delay from when the init process was restarted and when the
output of the process was written to the log file. This also meant there
was a delay when streaming those logs using `container logs -f`. The
logs from that delay period were lost.

This change forces the container log file to update state after a
container restart which fixes the delays to the container log file. And
the` container logs -f` stream resets its position in the file on a
container restart as well.

---------

Co-authored-by: Arnav Reddy <areddy23@apple.com>
This commit is contained in:
Arnav Reddy
2025-06-06 11:27:34 -07:00
committed by GitHub
co-authored by Arnav Reddy
parent 94e06e28a0
commit cd94337f27
2 changed files with 10 additions and 4 deletions
+8 -3
View File
@@ -117,9 +117,14 @@ extension Application {
fh.readabilityHandler = { handle in
let data = handle.availableData
if data.isEmpty {
fh.readabilityHandler = nil
cont.finish()
return
// Triggers on container restart - can exit here as well
do {
_ = try fh.seekToEnd() // To continue streaming existing truncated log files
} catch {
fh.readabilityHandler = nil
cont.finish()
return
}
}
if let str = String(data: data, encoding: .utf8), !str.isEmpty {
var lines = str.components(separatedBy: .newlines)
@@ -697,7 +697,8 @@ extension ContainerClient.Bundle {
func createLogFile() throws {
// Create the log file we'll write stdio to.
let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY, 0o644)
// O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state
let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)
guard fd > 0 else {
throw POSIXError(.init(rawValue: errno)!)
}