pidfile.go 932 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package pidfile
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. )
  10. type PidFile struct {
  11. path string
  12. }
  13. func checkPidFileAlreadyExists(path string) error {
  14. if pidString, err := ioutil.ReadFile(path); err == nil {
  15. if pid, err := strconv.Atoi(string(pidString)); err == nil {
  16. if _, err := os.Stat(filepath.Join("/proc", string(pid))); err == nil {
  17. return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
  18. }
  19. }
  20. }
  21. return nil
  22. }
  23. func New(path string) (*PidFile, error) {
  24. if err := checkPidFileAlreadyExists(path); err != nil {
  25. return nil, err
  26. }
  27. if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
  28. return nil, err
  29. }
  30. return &PidFile{path: path}, nil
  31. }
  32. func (file PidFile) Remove() error {
  33. if err := os.Remove(file.path); err != nil {
  34. log.Printf("Error removing %s: %s", file.path, err)
  35. return err
  36. }
  37. return nil
  38. }