Skip to content

Commit cd94337

Browse files
ArnavReddyArnav Reddy
andauthored
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>
1 parent 94e06e2 commit cd94337

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

Sources/CLI/Container/ContainerLogs.swift

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,14 @@ extension Application {
117117
fh.readabilityHandler = { handle in
118118
let data = handle.availableData
119119
if data.isEmpty {
120-
fh.readabilityHandler = nil
121-
cont.finish()
122-
return
120+
// Triggers on container restart - can exit here as well
121+
do {
122+
_ = try fh.seekToEnd() // To continue streaming existing truncated log files
123+
} catch {
124+
fh.readabilityHandler = nil
125+
cont.finish()
126+
return
127+
}
123128
}
124129
if let str = String(data: data, encoding: .utf8), !str.isEmpty {
125130
var lines = str.components(separatedBy: .newlines)

Sources/Services/ContainerSandboxService/SandboxService.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -697,7 +697,8 @@ extension ContainerClient.Bundle {
697697

698698
func createLogFile() throws {
699699
// Create the log file we'll write stdio to.
700-
let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY, 0o644)
700+
// O_TRUNC resolves a log delay issue on restarted containers by force-updating internal state
701+
let fd = Darwin.open(self.containerLog.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644)
701702
guard fd > 0 else {
702703
throw POSIXError(.init(rawValue: errno)!)
703704
}

0 commit comments

Comments
 (0)