From 2b1d3d27e46a5a53af07a89c4f8aa65b84edd104 Mon Sep 17 00:00:00 2001 From: gotjosh Date: Tue, 14 Sep 2021 14:40:59 +0100 Subject: [PATCH] Alerting: Fix bug not creating filepath for silences/nflog if it does not exist (#39174) We created this filepath just as we're about persist the templates - with the latest change, we now need to create it sooner. --- pkg/services/ngalert/notifier/file_store.go | 6 ++++++ .../ngalert/notifier/file_store_test.go | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/pkg/services/ngalert/notifier/file_store.go b/pkg/services/ngalert/notifier/file_store.go index 0e9ef84648c..98c3759f260 100644 --- a/pkg/services/ngalert/notifier/file_store.go +++ b/pkg/services/ngalert/notifier/file_store.go @@ -93,6 +93,12 @@ func (fs *FileStore) IsExists(fn string) bool { // WriteFileToDisk writes a file with the provided name and contents to the Alertmanager working directory with the default grafana permission. func (fs *FileStore) WriteFileToDisk(fn string, content []byte) error { + // Ensure the working directory is created + err := os.MkdirAll(fs.workingDirPath, 0750) + if err != nil { + return fmt.Errorf("unable to create the working directory %q: %s", fs.workingDirPath, err) + } + return os.WriteFile(fs.pathFor(fn), content, 0644) } diff --git a/pkg/services/ngalert/notifier/file_store_test.go b/pkg/services/ngalert/notifier/file_store_test.go index 6c47868c097..be97e4509dd 100644 --- a/pkg/services/ngalert/notifier/file_store_test.go +++ b/pkg/services/ngalert/notifier/file_store_test.go @@ -10,6 +10,27 @@ import ( "github.com/stretchr/testify/require" ) +func TestFileStore_FilepathFor_DirectoryNotExist(t *testing.T) { + store := newFakeKVStore(t) + workingDir := filepath.Join(t.TempDir(), "notexistdir") + fs := NewFileStore(1, store, workingDir) + filekey := "silences" + filePath := filepath.Join(workingDir, filekey) + + // With a file already on the database and the path does not exist yet, it creates the path, + // writes the file to disk, then returns the filepath. + { + require.NoError(t, store.Set(context.Background(), 1, KVNamespace, filekey, encode([]byte("silence1,silence3")))) + r, err := fs.FilepathFor(context.Background(), filekey) + require.NoError(t, err) + require.Equal(t, filePath, r) + f, err := ioutil.ReadFile(filepath.Clean(filePath)) + require.NoError(t, err) + require.Equal(t, "silence1,silence3", string(f)) + require.NoError(t, os.Remove(filePath)) + require.NoError(t, store.Del(context.Background(), 1, KVNamespace, filekey)) + } +} func TestFileStore_FilepathFor(t *testing.T) { store := newFakeKVStore(t) workingDir := t.TempDir()