From e7f3ef81a8c0fe94a1295608ddd4d8e10f96faab Mon Sep 17 00:00:00 2001 From: Adam Saponara Date: Tue, 3 Sep 2019 17:28:23 -0400 Subject: [PATCH] Prevent log purging of symlinks Signed-off-by: Adam Saponara --- go/vt/logutil/logutil_test.go | 15 +++++++++------ go/vt/logutil/purge.go | 8 +++++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/go/vt/logutil/logutil_test.go b/go/vt/logutil/logutil_test.go index 605adad4ffa..4d07abf7ad0 100644 --- a/go/vt/logutil/logutil_test.go +++ b/go/vt/logutil/logutil_test.go @@ -103,9 +103,8 @@ func TestPurgeByMtime(t *testing.T) { t.Fatalf("os.Chtimes: %v", err) } } - now := time.Date(2020, 1, 1, 12, 15, 0, 0, time.UTC) + now := time.Date(2020, 1, 1, 12, 0, 0, 0, time.UTC) filenameMtimeMap := map[string]string{ - "vtadam.localhost.vitess.log.INFO.20200101-120000.00000": "2020-01-01T12:00:00.000Z", "vtadam.localhost.vitess.log.INFO.20200101-113000.00000": "2020-01-01T11:30:00.000Z", "vtadam.localhost.vitess.log.INFO.20200101-100000.00000": "2020-01-01T10:00:00.000Z", "vtadam.localhost.vitess.log.INFO.20200101-090000.00000": "2020-01-01T09:00:00.000Z", @@ -114,7 +113,11 @@ func TestPurgeByMtime(t *testing.T) { for filename, mtimeStr := range filenameMtimeMap { createFileWithMtime(filename, mtimeStr) } - if err := os.Symlink("vtadam.localhost.vitess.log.INFO.20200101-120000.00000", path.Join(logDir, "vtadam.INFO")); err != nil { + + // Create vtadam.INFO symlink to 100000. This is a contrived example in that + // current log (100000) is not the latest log (113000). This will not happen + // IRL but it helps us test edge cases of purging by mtime. + if err := os.Symlink("vtadam.localhost.vitess.log.INFO.20200101-100000.00000", path.Join(logDir, "vtadam.INFO")); err != nil { t.Fatalf("os.Symlink: %v", err) } @@ -126,9 +129,9 @@ func TestPurgeByMtime(t *testing.T) { } if len(left) != 3 { - // 20200101-120000 is current - // 20200101-113000 is within 1 hour - // symlink remains + // 1. 113000 is within 1 hour + // 2. 100000 is current (vtadam.INFO) + // 3. vtadam.INFO symlink remains // rest are removed t.Errorf("wrong number of files remain: want %v, got %v", 3, len(left)) } diff --git a/go/vt/logutil/purge.go b/go/vt/logutil/purge.go index c7825098a11..55701c37db6 100644 --- a/go/vt/logutil/purge.go +++ b/go/vt/logutil/purge.go @@ -70,7 +70,13 @@ func purgeLogsOnce(now time.Time, dir, program string, ctimeDelta time.Duration, return } for _, file := range files { - if current[file] { + statInfo, err := os.Lstat(file) + if err != nil { + // Failed to stat file + continue + } + if current[file] || !statInfo.Mode().IsRegular() { + // Do not purge current file or any non-regular files (symlinks etc) continue } purgeFile := false