Skip to content

Commit b1abaa2

Browse files
andrewkrohmergify[bot]
authored andcommitted
fix(diagnostics): handle log rotation races (#8215)
Handle a race condition that can occur in Agent diagnostics if log rotation happens while logs are being zipped. There is a time window between when `filepath.WalkDir` reads the directory contents and when log files are opened for reading. During this time window, log rotation can happen, resulting in files that no longer exist and cannot be added to the diagnostic archive. To handle this, `fs.ErrNotExist` errors are ignored when attempting to add log files. Also, address and unrelated linter warning by using fmt.Fprintf. (cherry picked from commit 751acc1)
1 parent 87d037c commit b1abaa2

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
kind: bug-fix
2+
summary: Address a race condition that can occur in Agent diagnostics if log rotation runs while logs are being zipped.
3+
component: elastic-agent
4+
pull_request: https://github.com/elastic/elastic-agent/pull/8215

internal/pkg/diagnostics/diagnostics.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ func writeErrorResult(zw *zip.Writer, path string, errBody string) error {
314314
if err != nil {
315315
return fmt.Errorf("error writing header for error.txt file for component: %w", err)
316316
}
317-
_, err = w.Write([]byte(fmt.Sprintf("%s\n", errBody)))
317+
_, err = fmt.Fprintf(w, "%s\n", errBody)
318318
if err != nil {
319319
return fmt.Errorf("error writing error.txt file for component: %w", err)
320320
}
@@ -507,7 +507,12 @@ func zipLogsWithPath(pathsHome, commitName string, collectServices, excludeEvent
507507
return nil
508508
}
509509

510-
return saveLogs(name, path, zw)
510+
// Add the file to the zip.
511+
// Ignore files that don't exist to account for races with log rotation.
512+
if err := saveLogs(name, path, zw); err != nil && !errors.Is(err, fs.ErrNotExist) {
513+
return err
514+
}
515+
return nil
511516
})
512517
}
513518

0 commit comments

Comments
 (0)