pidfile.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 // import "github.com/docker/docker/pkg/pidfile"
  5. import (
  6. "bytes"
  7. "fmt"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "github.com/docker/docker/pkg/process"
  12. "github.com/docker/docker/pkg/system"
  13. )
  14. func checkPIDFileAlreadyExists(path string) error {
  15. pidByte, err := os.ReadFile(path)
  16. if err != nil {
  17. if os.IsNotExist(err) {
  18. return nil
  19. }
  20. return err
  21. }
  22. pid, err := strconv.Atoi(string(bytes.TrimSpace(pidByte)))
  23. if err == nil && process.Alive(pid) {
  24. return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
  25. }
  26. return nil
  27. }
  28. // Write writes a "PID file" at the specified path. It returns an error if the
  29. // file exists and contains a valid PID of a running process, or when failing
  30. // to write the file.
  31. func Write(path string, pid int) error {
  32. if pid < 1 {
  33. // We might be running as PID 1 when running docker-in-docker,
  34. // but 0 or negative PIDs are not acceptable.
  35. return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid)
  36. }
  37. if err := checkPIDFileAlreadyExists(path); err != nil {
  38. return err
  39. }
  40. if err := system.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  41. return err
  42. }
  43. return os.WriteFile(path, []byte(strconv.Itoa(pid)), 0o644)
  44. }