2015-07-25 04:35:07 -04:00
|
|
|
// 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.
|
2015-02-25 13:33:01 -05:00
|
|
|
package pidfile
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2016-10-24 13:21:25 -04:00
|
|
|
"path/filepath"
|
2015-02-25 13:33:01 -05:00
|
|
|
"strconv"
|
2016-01-14 02:43:40 -05:00
|
|
|
"strings"
|
2016-10-24 13:21:25 -04:00
|
|
|
|
|
|
|
"github.com/docker/docker/pkg/system"
|
2015-02-25 13:33:01 -05:00
|
|
|
)
|
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
// PIDFile is a file used to store the process ID of a running process.
|
|
|
|
type PIDFile struct {
|
2015-02-25 13:33:01 -05:00
|
|
|
path string
|
|
|
|
}
|
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
func checkPIDFileAlreadyExists(path string) error {
|
2016-01-14 02:43:40 -05:00
|
|
|
if pidByte, err := ioutil.ReadFile(path); err == nil {
|
|
|
|
pidString := strings.TrimSpace(string(pidByte))
|
|
|
|
if pid, err := strconv.Atoi(pidString); err == nil {
|
2016-04-18 18:09:55 -04:00
|
|
|
if processExists(pid) {
|
2015-02-25 13:33:01 -05:00
|
|
|
return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
// New creates a PIDfile using the specified path.
|
|
|
|
func New(path string) (*PIDFile, error) {
|
|
|
|
if err := checkPIDFileAlreadyExists(path); err != nil {
|
2015-02-25 13:33:01 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
2016-10-24 13:21:25 -04:00
|
|
|
// Note MkdirAll returns nil if a directory already exists
|
|
|
|
if err := system.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-04-27 17:11:29 -04:00
|
|
|
if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-02-25 13:33:01 -05:00
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
return &PIDFile{path: path}, nil
|
2015-02-25 13:33:01 -05:00
|
|
|
}
|
|
|
|
|
2015-07-25 04:35:07 -04:00
|
|
|
// Remove removes the PIDFile.
|
|
|
|
func (file PIDFile) Remove() error {
|
2015-02-25 13:33:01 -05:00
|
|
|
if err := os.Remove(file.path); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|