mirror of
https://github.com/coder/coder.git
synced 2025-07-13 21:36:50 +00:00
fix: cleanup reaper implementation (#2563)
- Clean up the agent/reaper API to be a more isolated and reusable package.
This commit is contained in:
@ -3,7 +3,6 @@
|
||||
package reaper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
@ -11,17 +10,6 @@ import (
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
// agentEnvMark is a simple environment variable that we use as a marker
|
||||
// to indicated that the process is a child as opposed to the reaper.
|
||||
// Since we are forkexec'ing we need to be able to differentiate between
|
||||
// the two to avoid fork bombing ourselves.
|
||||
const agentEnvMark = "CODER_DO_NOT_REAP"
|
||||
|
||||
// IsChild returns true if we're the forked process.
|
||||
func IsChild() bool {
|
||||
return os.Getenv(agentEnvMark) != ""
|
||||
}
|
||||
|
||||
// IsInitProcess returns true if the current process's PID is 1.
|
||||
func IsInitProcess() bool {
|
||||
return os.Getpid() == 1
|
||||
@ -33,19 +21,16 @@ func IsInitProcess() bool {
|
||||
// the reaper and an exec.Command waiting for its process to complete.
|
||||
// The provided 'pids' channel may be nil if the caller does not care about the
|
||||
// reaped children PIDs.
|
||||
func ForkReap(pids reap.PidCh) error {
|
||||
// Check if the process is the parent or the child.
|
||||
// If it's the child we want to skip attempting to reap.
|
||||
if IsChild() {
|
||||
return nil
|
||||
func ForkReap(opt ...Option) error {
|
||||
opts := &options{
|
||||
ExecArgs: os.Args,
|
||||
}
|
||||
|
||||
go reap.ReapChildren(pids, nil, nil, nil)
|
||||
for _, o := range opt {
|
||||
o(opts)
|
||||
}
|
||||
|
||||
args := os.Args
|
||||
// This is simply done to help identify the real agent process
|
||||
// when viewing in something like 'ps'.
|
||||
args = append(args, "#Agent")
|
||||
go reap.ReapChildren(opts.PIDs, nil, nil, nil)
|
||||
|
||||
pwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
@ -54,8 +39,7 @@ func ForkReap(pids reap.PidCh) error {
|
||||
|
||||
pattrs := &syscall.ProcAttr{
|
||||
Dir: pwd,
|
||||
// Add our marker for identifying the child process.
|
||||
Env: append(os.Environ(), fmt.Sprintf("%s=true", agentEnvMark)),
|
||||
Env: os.Environ(),
|
||||
Sys: &syscall.SysProcAttr{
|
||||
Setsid: true,
|
||||
},
|
||||
@ -67,7 +51,7 @@ func ForkReap(pids reap.PidCh) error {
|
||||
}
|
||||
|
||||
//#nosec G204
|
||||
pid, _ := syscall.ForkExec(args[0], args, pattrs)
|
||||
pid, _ := syscall.ForkExec(opts.ExecArgs[0], opts.ExecArgs, pattrs)
|
||||
|
||||
var wstatus syscall.WaitStatus
|
||||
_, err = syscall.Wait4(pid, &wstatus, 0, nil)
|
||||
|
Reference in New Issue
Block a user