From c0c4f688934fbe403e280faef6b521ccd48ddde8 Mon Sep 17 00:00:00 2001 From: Rick Wieman Date: Wed, 25 Feb 2015 19:33:01 +0100 Subject: [PATCH] Moved pidfile from utils to pkg Fixes #10958 by moving utils.daemon to pkg.pidfile. Test cases were also added. Updated the daemon to use the new pidfile. Signed-off-by: Rick Wieman --- pidfile/pidfile.go | 44 +++++++++++++++++++++++++++++++++++++++++ pidfile/pidfile_test.go | 32 ++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 pidfile/pidfile.go create mode 100644 pidfile/pidfile_test.go diff --git a/pidfile/pidfile.go b/pidfile/pidfile.go new file mode 100644 index 0000000..21a5438 --- /dev/null +++ b/pidfile/pidfile.go @@ -0,0 +1,44 @@ +package pidfile + +import ( + "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" + "strconv" +) + +type PidFile struct { + path string +} + +func checkPidFileAlreadyExists(path string) error { + if pidString, err := ioutil.ReadFile(path); err == nil { + if pid, err := strconv.Atoi(string(pidString)); err == nil { + if _, err := os.Stat(filepath.Join("/proc", string(pid))); err == nil { + return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path) + } + } + } + return nil +} + +func New(path string) (file *PidFile, err error) { + if err := checkPidFileAlreadyExists(path); err != nil { + return nil, err + } + + file = &PidFile{path: path} + err = ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644) + + return file, err +} + +func (file PidFile) Remove() error { + if err := os.Remove(file.path); err != nil { + log.Printf("Error removing %s: %s", file.path, err) + return err + } + return nil +} diff --git a/pidfile/pidfile_test.go b/pidfile/pidfile_test.go new file mode 100644 index 0000000..6ed9cfc --- /dev/null +++ b/pidfile/pidfile_test.go @@ -0,0 +1,32 @@ +package pidfile + +import ( + "io/ioutil" + "os" + "path/filepath" + "testing" +) + +func TestNewAndRemove(t *testing.T) { + dir, err := ioutil.TempDir(os.TempDir(), "test-pidfile") + if err != nil { + t.Fatal("Could not create test directory") + } + + file, err := New(filepath.Join(dir, "testfile")) + if err != nil { + t.Fatal("Could not create test file", err) + } + + if err := file.Remove(); err != nil { + t.Fatal("Could not delete created test file") + } +} + +func TestRemoveInvalidPath(t *testing.T) { + file := PidFile{path: filepath.Join("foo", "bar")} + + if err := file.Remove(); err == nil { + t.Fatal("Non-existing file doesn't give an error on delete") + } +}