1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00
moby--moby/pkg/pidfile/pidfile.go
Sebastiaan van Stijn 43d6eb7173
pkg/pidfile: remove PIDFile type, rename New() to Write()
This type felt really redundant; `pidfile.New()` takes the path of the file to
create as an argument, so this is already known. The only thing the PIDFile
type provided was a `Remove()` method, which was just calling `os.Remove()` on
the path of the file.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-10-15 16:40:16 +02:00

42 lines
1.1 KiB
Go

// Package pidfile provides structure and helper functions to create and remove
// PID file. A PID file is usually a file used to store the process ID of a
// running process.
package pidfile // import "github.com/docker/docker/pkg/pidfile"
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strconv"
"github.com/docker/docker/pkg/system"
)
func checkPIDFileAlreadyExists(path string) error {
pidByte, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
pid, err := strconv.Atoi(string(bytes.TrimSpace(pidByte)))
if err == nil && processExists(pid) {
return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
}
return nil
}
// Write writes a "PID file" at the specified path. It returns an error if the
// file exists and contains a valid PID of a running process, or when failing
// to write the file.
func Write(path string) error {
if err := checkPIDFileAlreadyExists(path); err != nil {
return err
}
if err := system.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())), 0o644)
}