From 8b0e9f3f09982f12ee35d327bc63eca9d47d10d1 Mon Sep 17 00:00:00 2001 From: jwcesign Date: Tue, 20 Sep 2022 15:24:07 +0800 Subject: [PATCH] Fix bugs about karmada-data dir lost Signed-off-by: jwcesign --- pkg/karmadactl/cmdinit/kubernetes/deploy.go | 13 ++++-- .../cmdinit/kubernetes/deploy_test.go | 41 +++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 pkg/karmadactl/cmdinit/kubernetes/deploy_test.go diff --git a/pkg/karmadactl/cmdinit/kubernetes/deploy.go b/pkg/karmadactl/cmdinit/kubernetes/deploy.go index 913efe256033..7bcec23c0736 100644 --- a/pkg/karmadactl/cmdinit/kubernetes/deploy.go +++ b/pkg/karmadactl/cmdinit/kubernetes/deploy.go @@ -170,12 +170,19 @@ func (i *CommandInitOption) Complete() error { } } - // Determine whether KarmadaDataPath exists, if so, delete it - if utils.IsExist(i.KarmadaDataPath) { - if err := os.RemoveAll(i.KarmadaDataPath); err != nil { + return initializeDirectory(i.KarmadaDataPath) +} + +// initializeDirectory initializes a directory and makes sure it's empty. +func initializeDirectory(path string) error { + if utils.IsExist(path) { + if err := os.RemoveAll(path); err != nil { return err } } + if err := os.MkdirAll(path, os.FileMode(0755)); err != nil { + return fmt.Errorf("failed to create directory: %s, error: %v", path, err) + } return nil } diff --git a/pkg/karmadactl/cmdinit/kubernetes/deploy_test.go b/pkg/karmadactl/cmdinit/kubernetes/deploy_test.go new file mode 100644 index 000000000000..ea4477f8a55a --- /dev/null +++ b/pkg/karmadactl/cmdinit/kubernetes/deploy_test.go @@ -0,0 +1,41 @@ +package kubernetes + +import ( + "os" + "testing" +) + +func Test_initializeDirectory(t *testing.T) { + tests := []struct { + name string + createPathInAdvance bool + wantErr bool + }{ + { + name: "Test when there is no dir exists", + createPathInAdvance: false, + wantErr: false, + }, + { + name: "Test when there is dir exists", + createPathInAdvance: true, + wantErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.createPathInAdvance { + if err := os.MkdirAll("tmp", os.FileMode(0755)); err != nil { + t.Errorf("create test directory failed in advance:%v", err) + } + } + if err := initializeDirectory("tmp"); (err != nil) != tt.wantErr { + t.Errorf("initializeDirectory() error = %v, wantErr %v", err, tt.wantErr) + } + if err := os.RemoveAll("tmp"); err != nil { + t.Errorf("clean up test directory failed after ut case:%s, %v", tt.name, err) + } + }) + } +}