github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/pkg/pidfile/pidfile.go (about)

     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  
     6  import (
     7  	"fmt"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"strconv"
    12  	"strings"
    13  
    14  	"github.com/docker/docker/pkg/system"
    15  )
    16  
    17  // PIDFile is a file used to store the process ID of a running process.
    18  type PIDFile struct {
    19  	path string
    20  }
    21  
    22  func checkPIDFileAlreadyExists(path string) error {
    23  	if pidByte, err := ioutil.ReadFile(path); err == nil {
    24  		pidString := strings.TrimSpace(string(pidByte))
    25  		if pid, err := strconv.Atoi(pidString); err == nil {
    26  			if processExists(pid) {
    27  				return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
    28  			}
    29  		}
    30  	}
    31  	return nil
    32  }
    33  
    34  // New creates a PIDfile using the specified path.
    35  func New(path string) (*PIDFile, error) {
    36  	if err := checkPIDFileAlreadyExists(path); err != nil {
    37  		return nil, err
    38  	}
    39  	// Note MkdirAll returns nil if a directory already exists
    40  	if err := system.MkdirAll(filepath.Dir(path), os.FileMode(0755), ""); err != nil {
    41  		return nil, err
    42  	}
    43  	if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	return &PIDFile{path: path}, nil
    48  }
    49  
    50  // Remove removes the PIDFile.
    51  func (file PIDFile) Remove() error {
    52  	return os.Remove(file.path)
    53  }