pidfile.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Package pidfile provides structure and helper functions to create and remove
  2. // PID file. A PID file is usually a file used to store the process ID of a
  3. // running process.
  4. package pidfile
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "github.com/docker/docker/pkg/system"
  13. )
  14. // PIDFile is a file used to store the process ID of a running process.
  15. type PIDFile struct {
  16. path string
  17. }
  18. func checkPIDFileAlreadyExists(path string) error {
  19. if pidByte, err := ioutil.ReadFile(path); err == nil {
  20. pidString := strings.TrimSpace(string(pidByte))
  21. if pid, err := strconv.Atoi(pidString); err == nil {
  22. if processExists(pid) {
  23. return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
  24. }
  25. }
  26. }
  27. return nil
  28. }
  29. // New creates a PIDfile using the specified path.
  30. func New(path string) (*PIDFile, error) {
  31. if err := checkPIDFileAlreadyExists(path); err != nil {
  32. return nil, err
  33. }
  34. // Note MkdirAll returns nil if a directory already exists
  35. if err := system.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
  36. return nil, err
  37. }
  38. if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
  39. return nil, err
  40. }
  41. return &PIDFile{path: path}, nil
  42. }
  43. // Remove removes the PIDFile.
  44. func (file PIDFile) Remove() error {
  45. return os.Remove(file.path)
  46. }