From 928fc14987a0e07ef3e5ca1fe2fc494fc8dc38e0 Mon Sep 17 00:00:00 2001 From: Sudhanshu Bawane Date: Thu, 1 Feb 2024 10:00:23 +0530 Subject: [PATCH] final Signed-off-by: Sudhanshu Bawane --- asset/boltdb_manager.go | 10 ++++++++++ asset/expander.go | 12 ++++++++++++ asset/expander_test.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/asset/boltdb_manager.go b/asset/boltdb_manager.go index eb9e008db6..a0b9bd850b 100644 --- a/asset/boltdb_manager.go +++ b/asset/boltdb_manager.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "github.com/spf13/viper" "os" "path/filepath" @@ -23,6 +24,7 @@ const ( // ExpandDuration is the name of the prometheus summary vec used to track // average latencies of asset expansion. ExpandDuration = "sensu_go_asset_expand_duration" + FlagCacheDir = "cache-dir" ) var ( @@ -241,6 +243,14 @@ func (b *boltDBAssetManager) expandWithDuration(tmpFile *os.File, asset *corev2. })) defer timer.ObserveDuration() + assetSHA := asset.Sha512 + CacheDir := viper.GetString(FlagCacheDir) + fullPath := filepath.Join(CacheDir, assetSHA) + + if err := CleanUp(fullPath); err != nil { //fix for git issue 5009 + logger.Printf("error cleaning up the SHA dir: %s", err) + } + assetPath = filepath.Join(b.localStorage, asset.Sha512) return assetPath, b.expander.Expand(tmpFile, assetPath) } diff --git a/asset/expander.go b/asset/expander.go index d13df1b1cd..79a1384838 100644 --- a/asset/expander.go +++ b/asset/expander.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io" + "os" archiver "github.com/mholt/archiver/v3" @@ -90,3 +91,14 @@ func sniffType(f io.ReadSeeker) (filetype_types.Type, error) { return ft, nil } + +// Sudhanshu - CleanUp the SHA for the git issue 5009 fix. Making sure that in case of DOS when asset.db gets deleted it gets cleanUp so that asset can be re-downloded + +func CleanUp(fullPath string) error { + errorSHA := os.RemoveAll(fullPath) + if errorSHA != nil { + return errorSHA + } + return nil + +} diff --git a/asset/expander_test.go b/asset/expander_test.go index 6d028bdf90..44236c6b5e 100644 --- a/asset/expander_test.go +++ b/asset/expander_test.go @@ -113,3 +113,33 @@ func TestExpandInvalidArchive(t *testing.T) { t.Fail() } } + +// ---Test to check CleanUp +func TestCleanUp(t *testing.T) { + t.Parallel() + + // Create a temporary directory for testing + tmpDir := t.TempDir() + + // Define the SHA and file name + SHAName := "shaAsset.tar" + SHAFilePath := filepath.Join(tmpDir, SHAName) + + // Create a dummy file inside the temporary directory + SHAFile, err := os.Create(SHAFilePath) + if err != nil { + t.Fatalf("Failed to create dummy file: %v", err) + } + SHAFile.Close() + + // Call CleanUp with the SHA of the dummy file and the temporary directory + err = CleanUp(SHAFilePath) + if err != nil { + t.Errorf("CleanUp returned an error: %v", err) + } + + _, err = os.Stat(SHAFilePath) + if !os.IsNotExist(err) { + t.Errorf("CleanUp did not remove the dummy file as expected") + } +}