From bbaa508c94ba04a1e1963742fd17aeb8c6b8dfc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szabolcs=20Gelencse=CC=81r?= Date: Tue, 20 Jul 2021 12:02:53 +0200 Subject: [PATCH] client: fix deletion of archive log files --- CHANGELOG.md | 3 +++ command/agent/log_file.go | 3 +++ command/agent/log_file_test.go | 44 ++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9945c15056a..f63272893e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ IMPROVEMENTS: * dispatch jobs: Added optional idempotency token to `WriteOptions` which prevents Nomad from creating new dispatched jobs for retried requests. [[GH-10806](https://github.com/hashicorp/nomad/pull/10806)] +BUG FIXES: +* client: Fixed deletion of archive log files based on `log_rotate_max_files`. [[GH-10913](https://github.com/hashicorp/nomad/issues/10913)] + ## 1.1.2 (June 22, 2021) IMPROVEMENTS: diff --git a/command/agent/log_file.go b/command/agent/log_file.go index bad3c6c179c..1f8c3d49b96 100644 --- a/command/agent/log_file.go +++ b/command/agent/log_file.go @@ -131,6 +131,9 @@ func (l *logFile) Write(b []byte) (int, error) { defer l.acquire.Unlock() //Create a new file if we have no file to write to if l.FileInfo == nil { + if err := l.pruneFiles(); err != nil { + return 0, err + } if err := l.openNew(); err != nil { return 0, err } diff --git a/command/agent/log_file_test.go b/command/agent/log_file_test.go index 12777784d8b..a65ea890752 100644 --- a/command/agent/log_file_test.go +++ b/command/agent/log_file_test.go @@ -144,6 +144,50 @@ func TestLogFile_deleteArchives(t *testing.T) { } } +func TestLogFile_deleteArchivesOnStart(t *testing.T) { + t.Parallel() + require := require.New(t) + + tempDir, err := ioutil.TempDir("", "LogWriterDeleteArchivesOnStartTest") + require.NoError(err) + defer os.Remove(tempDir) + + startNewAgentAndWrite := func(log string) { + filt := LevelFilter() + filt.MinLevel = "INFO" + firstRun := logFile{ + logFilter: filt, + fileName: testFileName, + logPath: tempDir, + MaxBytes: 1024, + duration: 24 * time.Hour, + MaxFiles: 1, + } + firstRun.Write([]byte(log)) + } + + startNewAgentAndWrite("[INFO] Hello World") + startNewAgentAndWrite("[INFO] Second File") + startNewAgentAndWrite("[INFO] Third File") + + want := 2 + tempFiles, _ := ioutil.ReadDir(tempDir) + require.Equal(want, len(tempFiles)) + + for _, tempFile := range tempFiles { + var bytes []byte + var err error + path := filepath.Join(tempDir, tempFile.Name()) + if bytes, err = ioutil.ReadFile(path); err != nil { + t.Errorf(err.Error()) + return + } + contents := string(bytes) + + require.NotEqual("[INFO] Hello World", contents, "oldest log should have been deleted") + } +} + func TestLogFile_deleteArchivesDisabled(t *testing.T) { t.Parallel()