...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package pidfile
23
24 import (
25 "fmt"
26 "io/ioutil"
27 "os"
28 "path/filepath"
29 "strconv"
30 "strings"
31 )
32
33
34 type PIDFile struct {
35 path string
36 }
37
38 func processExists(pid int) bool {
39 if _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid))); err == nil {
40 return true
41 }
42 return false
43 }
44
45 func checkPIDFileAlreadyExists(path string) error {
46 if pidByte, err := ioutil.ReadFile(path); err == nil {
47 pidString := strings.TrimSpace(string(pidByte))
48 if pid, err := strconv.Atoi(pidString); err == nil {
49 if processExists(pid) {
50 return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
51 }
52 }
53 }
54 return nil
55 }
56
57
58 func New(path string) (*PIDFile, error) {
59 if err := checkPIDFileAlreadyExists(path); err != nil {
60 return nil, err
61 }
62
63 if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
64 return nil, err
65 }
66 if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
67 return nil, err
68 }
69
70 return &PIDFile{path: path}, nil
71 }
72
73
74 func (file PIDFile) Remove() error {
75 return os.Remove(file.path)
76 }
77