-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtsr_posix.go
190 lines (169 loc) · 4.92 KB
/
tsr_posix.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//go:build linux || darwin || freebsd || openbsd || netbsd || dragonfly || solaris || aix
package gotsr
import (
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"syscall"
"time"
)
var (
errInvalidStage = errors.New("invalid stage")
errTimeout = errors.New("stage 1 process timeout")
)
// tsr is the main function that starts the program in the detached mode.
func tsr(pidFile string, timeout time.Duration, atExit ...func()) (bool, error) {
stg, err := summon(pidFile, timeout, atExit...)
return stg == sRunning, err
}
// summon is the posix-specific function that starts the program in the
// detached mode.
//
// It does it in three stages:
// 1. Initialisation: starts a new process with the same arguments and
// environment, but with STDIN, STDOUT and STDERR disconnected, and SetSid
// set to true to create a new session (thanks to this advice:
// https://stackoverflow.com/a/46799048/1169992)
// 2. Detach: restarts the process further detached from the terminal.
// 3. Running: the program is running in the background.
//
// It identifies the current stage by reading the STAGE environment variable.
func summon(pidFile string, timeout time.Duration, atExit ...func()) (stage, error) {
image, err := os.Executable()
if err != nil {
return sUnknown, err
}
vars := newEnvVar(pidFile) // initialise environment variable base name from pidFile.
stage := os.Getenv(vars.stage())
switch stage {
default:
return sUnknown, errInvalidStage
case "": // initial setup and preparing for detachment
return sInitialise, stageInit(pidFile, vars, image, timeout)
case sDetach.String(): // releasing handles, clean start
return sDetach, stageDetach(vars, image)
case sRunning.String(): // running TSR program
return sRunning, stageRun(pidFile, vars, atExit)
}
// unreachable
}
// stageInit is the first stage that starts a new detached instance of the
// program in a new session.
func stageInit(pidFile string, vars envVar, image string, timeout time.Duration) error {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGUSR1)
os.Setenv(vars.stage(), sDetach.String())
os.Setenv(vars.pid(), strconv.Itoa(os.Getpid()))
cmd := exec.Command(image, os.Args[1:]...)
cmd.Env = os.Environ()
cmd.Stderr = nil
cmd.Stdout = nil
cmd.Stdin = nil
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
err := cmd.Start()
if err != nil {
return fmt.Errorf("failed to initialise the process: %s", err)
}
timer := time.After(timeout)
select {
case <-sig:
pid, err := readPID(pidFile)
if err != nil {
lg.Printf("process started, but PID file is missing: %s", err)
} else if pid == 0 {
lg.Println("warning: process started, but PID is 0")
} else {
lg.Printf("process started with PID: %d", pid)
}
case <-timer:
return errTimeout
}
return nil
}
// stageDetach starts a new process with the same arguments and environment.
func stageDetach(vars envVar, image string) error {
os.Setenv(vars.stage(), sRunning.String())
cmd := exec.Command(image, os.Args[1:]...)
cmd.Env = os.Environ()
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
return cmd.Start()
}
// stageRun runs the main program.
func stageRun(pidFile string, vars envVar, atExit []func()) error {
pid := os.Getpid()
if err := writePID(pidFile, pid); err != nil {
return err
}
_ = notifySuccess(vars)
// unset the environment variables once the program is running.
for _, envVar := range []string{vars.stage(), vars.pid()} {
os.Unsetenv(envVar)
}
quit := make(chan os.Signal, 1)
go func() {
<-quit
for _, fn := range atExit {
fn()
}
os.Remove(pidFile)
os.Exit(0)
}()
signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
return nil
}
// notifySuccess notifies the parent process that the program has started.
func notifySuccess(vars envVar) error {
sPID := os.Getenv(vars.pid())
if pid, err := strconv.Atoi(sPID); err != nil {
return fmt.Errorf("invalid pid value: %q, error: %w", sPID, err)
} else {
p, err := os.FindProcess(pid)
if err != nil {
return fmt.Errorf("parent process not found: %d: %w", p, err)
}
if err := p.Signal(syscall.SIGUSR1); err != nil {
return fmt.Errorf("failed to notify parent with PID=%d: %w", pid, err)
}
}
return nil
}
// isRunning checks if the process with the given PID is running.
func isRunning(pidFile string) (bool, error) {
pid, err := readPID(pidFile)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
p, err := os.FindProcess(pid)
if err != nil {
return false, nil
}
if err := p.Signal(syscall.SIGUSR2); err != nil {
return false, nil
}
return true, nil
}
// terminate sends a SIGTERM signal to the process with the given PID.
func terminate(pidFile string) error {
pid, err := readPID(pidFile)
if err != nil {
if os.IsNotExist(err) {
return ErrNotRunning
}
return err
} else if pid == 0 {
return ErrNoPID
}
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGTERM)
}