This repository has been archived by the owner on Nov 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pid.go
74 lines (64 loc) · 1.57 KB
/
pid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
log "github.com/sirupsen/logrus"
)
// writePid writes current process ID into a file
func writePid(file string) error {
if file == "" {
return nil
}
log.Debugf("writing PID to %s", file)
pid := strconv.Itoa(os.Getpid())
f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(pid)
return err
}
// removePid removes file containing the process ID
func removePid(file string) error {
if file == "" {
return nil
}
if _, err := os.Stat(file); err == nil {
log.Debugf("removing PID file %s", file)
return os.Remove(file)
}
return nil
}
// waitPid check if another instance is running and eventually wait for it to terminate (with a timeout)
func waitPid(pidFile string, waitTimeout int) error {
if pidFile == "" {
return nil
}
waitTime := 100 * time.Millisecond // initial backoff time for waiting
maxBackoffTime := 1000 // maximum time in millisecond to add between each waiting runs
timeout := false
maxTime := time.Now().Add(time.Second * time.Duration(waitTimeout))
for {
if _, err := os.Stat(pidFile); err == nil {
// PID file exists
log.Debugf("waiting %s before checking PID again", waitTime)
time.Sleep(waitTime)
waitTime = waitTime + time.Duration(rand.Intn(maxBackoffTime))*time.Millisecond
} else {
// file does not exist
break
}
if time.Now().After(maxTime) {
timeout = true
break
}
}
if timeout {
return fmt.Errorf("timeout waiting for PID file")
}
return nil
}