pkg, clientv3: etcdctl snaprestore when data-dir empty (#11648)

release-3.5
zhanwang 2020-04-05 05:41:19 +08:00 committed by GitHub
parent dbcf540c88
commit 2092b5b1a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 2 deletions

View File

@ -268,8 +268,8 @@ func (s *v3Manager) Restore(cfg RestoreConfig) error {
if dataDir == "" {
dataDir = cfg.Name + ".etcd"
}
if fileutil.Exist(dataDir) {
return fmt.Errorf("data-dir %q exists", dataDir)
if fileutil.Exist(dataDir) && !fileutil.DirEmpty(dataDir) {
return fmt.Errorf("data-dir %q not empty or could not be read", dataDir)
}
walDir := cfg.OutputWALDir

View File

@ -76,6 +76,12 @@ func Exist(name string) bool {
return err == nil
}
// DirEmpty returns true if a directory empty and can access.
func DirEmpty(name string) bool {
ns, err := ReadDir(name)
return len(ns) == 0 && err == nil
}
// ZeroToEnd zeros a file starting from SEEK_CUR to its SEEK_END. May temporarily
// shorten the length of the file.
func ZeroToEnd(f *os.File) error {

View File

@ -105,6 +105,31 @@ func TestExist(t *testing.T) {
}
}
func TestDirEmpty(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "empty_dir")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
if !DirEmpty(dir) {
t.Fatalf("expected DirEmpty true, got %v", DirEmpty(dir))
}
file, err := ioutil.TempFile(dir, "new_file")
if err != nil {
t.Fatal(err)
}
file.Close()
if DirEmpty(dir) {
t.Fatalf("expected DirEmpty false, got %v", DirEmpty(dir))
}
if DirEmpty(file.Name()) {
t.Fatalf("expected DirEmpty false, got %v", DirEmpty(file.Name()))
}
}
func TestZeroToEnd(t *testing.T) {
f, err := ioutil.TempFile(os.TempDir(), "fileutil")
if err != nil {