2015-02-25 18:33:01 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2015-04-27 21:11:29 +00:00
|
|
|
func New(path string) (*PidFile, error) {
|
2015-02-25 18:33:01 +00:00
|
|
|
if err := checkPidFileAlreadyExists(path); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-04-27 21:11:29 +00:00
|
|
|
if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-02-25 18:33:01 +00:00
|
|
|
|
2015-04-27 21:11:29 +00:00
|
|
|
return &PidFile{path: path}, nil
|
2015-02-25 18:33:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|