Skip to content
Permalink
Browse files

improve PurgeServices to avoid accidents

  • Loading branch information...
nbari committed Mar 26, 2017
1 parent 8d5eac3 commit 533b9f1dd16f46ea24e9807cd4f34fbdaa9a2a81
Showing with 46 additions and 4 deletions.
  1. +17 −1 ctl.go
  2. +29 −3 ctl_test.go
18 ctl.go
@@ -76,7 +76,23 @@ func (c *Controller) FindServices(dir string) ([]*ServiceStatus, error) {

// PurgeServices remove unused service directory
func (c *Controller) PurgeServices(dir string) error {
return os.RemoveAll(filepath.Dir(dir))
sdir := []string{"lock", "immortal.sock"}
files, err := ioutil.ReadDir(filepath.Dir(dir))
if err != nil {
return err
}
if len(files) == 2 {
for _, f := range files {
if inSlice(sdir, f.Name()) {
continue
}
if f.IsDir() {
return fmt.Errorf("Could not purge dir: %s", dir)
}
}
return os.RemoveAll(filepath.Dir(dir))
}
return fmt.Errorf("Could not purge dir: %s", dir)
}

// Run executes a command and print combinedOutput
@@ -59,19 +59,45 @@ func TestPurgeServices(t *testing.T) {
t.Error(err)
}
defer os.RemoveAll(dir)
err = ctl.PurgeServices(dir)
if err == nil {
t.Error("Expecting an error")
}
tdir := filepath.Join(dir, "test")
os.Mkdir(tdir, 0700)
os.OpenFile(filepath.Join(tdir, "f1"), os.O_RDONLY|os.O_CREATE, 0640)
os.OpenFile(filepath.Join(tdir, "f2"), os.O_RDONLY|os.O_CREATE, 0640)
os.OpenFile(filepath.Join(tdir, "f3"), os.O_RDONLY|os.O_CREATE, 0640)
os.Create(filepath.Join(tdir, "lock"))
os.Create(filepath.Join(tdir, "immortal.sock"))
os.Create(filepath.Join(tdir, "f3"))
files, _ := ioutil.ReadDir(tdir)
expect(t, 3, len(files))
err = ctl.PurgeServices(tdir)
if err == nil {
t.Error("Expecting and error")
}
files, _ = ioutil.ReadDir(tdir)
expect(t, 3, len(files))
err = ctl.PurgeServices(filepath.Join(tdir, "f3"))
if err == nil {
t.Error("Expecting and error")
}
os.Remove(filepath.Join(tdir, "f3"))
err = ctl.PurgeServices(filepath.Join(tdir, "f3"))
if err != nil {
t.Error(err)
}
files, _ = ioutil.ReadDir(tdir)
expect(t, 0, len(files))
tdir = filepath.Join(dir, "test", "root")
os.MkdirAll(tdir, 0700)
os.Create(filepath.Join(dir, "test", "lock"))
err = ctl.PurgeServices(filepath.Join(dir, "test", "immortal.sock"))
if err == nil {
t.Error("Expecting and error")
}
err = ctl.PurgeServices("/dev/null/non-existent")
if err == nil {
t.Error("Expecting and error")
}
}

func TestRun(t *testing.T) {

0 comments on commit 533b9f1

Please sign in to comment.
You can’t perform that action at this time.