-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathreaper.go
254 lines (223 loc) · 6.37 KB
/
reaper.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright (c) 2022 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package reaper
import (
"bytes"
"fmt"
"os"
"os/exec"
"os/signal"
"sync"
"golang.org/x/sys/unix"
"gopkg.in/tomb.v2"
"github.com/canonical/pebble/internals/logger"
)
var (
reaperTomb tomb.Tomb
mutex sync.Mutex
pids = make(map[int]chan int)
started bool
)
// Start starts the child process reaper.
func Start() error {
mutex.Lock()
defer mutex.Unlock()
if started {
return nil // already started
}
isSubreaper, err := setChildSubreaper()
if err != nil {
return fmt.Errorf("cannot set child subreaper: %w", err)
}
if !isSubreaper {
return fmt.Errorf("child subreaping unavailable on this platform")
}
started = true
reaperTomb.Go(reapChildren)
return nil
}
// Stop stops the child process reaper.
func Stop() error {
mutex.Lock()
if !started {
mutex.Unlock()
return nil // already stopped
}
mutex.Unlock()
reaperTomb.Kill(nil)
reaperTomb.Wait()
reaperTomb = tomb.Tomb{}
mutex.Lock()
started = false
mutex.Unlock()
return nil
}
// setChildSubreaper sets the current process as a "child subreaper" so we
// become the parent of dead child processes rather than PID 1. This allows us
// to wait for processes that are started by a Pebble service but then die, to
// "reap" them (see https://unix.stackexchange.com/a/250156/73491).
//
// The function returns true if sub-reaping is available (Linux 3.4+) along
// with an error if it's available but can't be set.
func setChildSubreaper() (bool, error) {
err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)
if err == unix.EINVAL {
return false, nil
}
return true, err
}
// reapChildren "reaps" (waits for) child processes whose parents didn't
// wait() for them. It stops when the reaper tomb is killed.
func reapChildren() error {
logger.Debugf("Reaper started, waiting for SIGCHLD.")
sigChld := make(chan os.Signal, 1)
signal.Notify(sigChld, unix.SIGCHLD)
for {
select {
case <-sigChld:
logger.Debugf("Reaper received SIGCHLD.")
reapOnce()
case <-reaperTomb.Dying():
signal.Reset(unix.SIGCHLD)
logger.Debugf("Reaper stopped.")
return nil
}
}
}
// reapOnce waits for child processes until there are no more to reap.
func reapOnce() {
for {
var status unix.WaitStatus
pid, err := unix.Wait4(-1, &status, unix.WNOHANG, nil)
switch err {
case nil:
if pid <= 0 {
return
}
exitCode := status.ExitStatus()
if status.Signaled() {
exitCode = 128 + int(status.Signal())
}
logger.Debugf("Reaped PID %d which exited with code %d.", pid, exitCode)
// If there's a WaitCommand waiting for this PID, send it the exit code.
mutex.Lock()
ch := pids[pid]
mutex.Unlock()
if ch != nil {
ch <- exitCode
}
case unix.ECHILD:
return
default:
logger.Noticef("Cannot wait for child process: %v", err)
return
}
}
}
// StartCommand starts the command and registers its PID with the reaper.
//
// After the reaper has been started, users of os/exec should call WaitCommand
// and StartCommand rather than cmd.Wait directly, to ensure PIDs are reaped
// correctly.
func StartCommand(cmd *exec.Cmd) error {
// Must lock for the cmd.Start call and the insertion into the PIDs map,
// to avoid the reaper firing before we've registered the PID for a
// process that exits quickly.
mutex.Lock()
defer mutex.Unlock()
if !started {
panic("internal error: reaper must be started")
}
err := cmd.Start()
if err == nil {
if ch, ok := pids[cmd.Process.Pid]; ok {
// Shouldn't happen, but just in case we get the same PID we're
// already waiting on, tell the other waiter to stop waiting.
select {
case ch <- -1:
default:
}
logger.Noticef("internal error: new PID %d observed while still being tracked", cmd.Process.Pid)
}
// Channel is 1-buffered so the send in reapOnce never blocks, if for
// some reason someone forgets to call WaitCommand.
pids[cmd.Process.Pid] = make(chan int, 1)
}
return err
}
// WaitCommand waits for the command (which must have been started with
// StartCommand) to finish and returns its exit code. Unlike cmd.Wait,
// WaitCommand doesn't return an error for nonzero exit codes.
func WaitCommand(cmd *exec.Cmd) (int, error) {
mutex.Lock()
if !started {
mutex.Unlock()
panic("internal error: reaper must be started")
}
ch, ok := pids[cmd.Process.Pid]
if !ok {
// Shouldn't happen, but doesn't hurt to handle it.
mutex.Unlock()
return -1, fmt.Errorf("internal error: PID %d was not started with WaitCommand", cmd.Process.Pid)
}
mutex.Unlock()
// Wait for reaper to reap this PID and send us the exit code.
exitCode := <-ch
// Remove PID from waits map once we've received exit code from reaper.
mutex.Lock()
delete(pids, cmd.Process.Pid)
mutex.Unlock()
// At this point, we expect cmd.Wait to return a syscall error ("wait[id]:
// no child processes"), because the reaper is already waiting for all
// PIDs. This is not pretty, but we need to call cmd.Wait to clean up
// goroutines and file descriptors.
err := cmd.Wait()
switch err := err.(type) {
case nil:
logger.Noticef("Internal error: WaitCommand expected error but got nil (exit code %d)", exitCode)
return exitCode, nil
case *os.SyscallError:
if err.Syscall == "wait" || err.Syscall == "waitid" {
return exitCode, nil
}
return -1, err
default:
return -1, err
}
}
// CommandCombinedOutput is like cmd.CombinedOutput, but for use when the
// reaper is running.
func CommandCombinedOutput(cmd *exec.Cmd) ([]byte, error) {
mutex.Lock()
if !started {
mutex.Unlock()
panic("internal error: reaper must be started")
}
mutex.Unlock()
var b bytes.Buffer
cmd.Stdout = &b
cmd.Stderr = &b
err := StartCommand(cmd)
if err != nil {
return nil, err
}
exitCode, err := WaitCommand(cmd)
if err != nil {
return nil, err
}
if exitCode != 0 {
return nil, fmt.Errorf("exit status %d", exitCode)
}
return b.Bytes(), err
}