|
| 1 | +//go:build linux |
| 2 | + |
| 3 | +package reaper |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "syscall" |
| 9 | + |
| 10 | + "github.com/hashicorp/go-reap" |
| 11 | + "golang.org/x/xerrors" |
| 12 | +) |
| 13 | + |
| 14 | +// agentEnvMark is a simple environment variable that we use as a marker |
| 15 | +// to indicated that the process is a child as opposed to the reaper. |
| 16 | +// Since we are forkexec'ing we need to be able to differentiate between |
| 17 | +// the two to avoid fork bombing ourselves. |
| 18 | +const agentEnvMark = "CODER_DO_NOT_REAP" |
| 19 | + |
| 20 | +// IsChild returns true if we're the forked process. |
| 21 | +func IsChild() bool { |
| 22 | + return os.Getenv(agentEnvMark) != "" |
| 23 | +} |
| 24 | + |
| 25 | +// IsInitProcess returns true if the current process's PID is 1. |
| 26 | +func IsInitProcess() bool { |
| 27 | + return os.Getpid() == 1 |
| 28 | +} |
| 29 | + |
| 30 | +// ForkReap spawns a goroutine that reaps children. In order to avoid |
| 31 | +// complications with spawning `exec.Commands` in the same process that |
| 32 | +// is reaping, we forkexec a child process. This prevents a race between |
| 33 | +// the reaper and an exec.Command waiting for its process to complete. |
| 34 | +// The provided 'pids' channel may be nil if the caller does not care about the |
| 35 | +// reaped children PIDs. |
| 36 | +func ForkReap(pids reap.PidCh) error { |
| 37 | + // Check if the process is the parent or the child. |
| 38 | + // If it's the child we want to skip attempting to reap. |
| 39 | + if IsChild() { |
| 40 | + return nil |
| 41 | + } |
| 42 | + |
| 43 | + go reap.ReapChildren(pids, nil, nil, nil) |
| 44 | + |
| 45 | + args := os.Args |
| 46 | + // This is simply done to help identify the real agent process |
| 47 | + // when viewing in something like 'ps'. |
| 48 | + args = append(args, "#Agent") |
| 49 | + |
| 50 | + pwd, err := os.Getwd() |
| 51 | + if err != nil { |
| 52 | + return xerrors.Errorf("get wd: %w", err) |
| 53 | + } |
| 54 | + |
| 55 | + pattrs := &syscall.ProcAttr{ |
| 56 | + Dir: pwd, |
| 57 | + // Add our marker for identifying the child process. |
| 58 | + Env: append(os.Environ(), fmt.Sprintf("%s=true", agentEnvMark)), |
| 59 | + Sys: &syscall.SysProcAttr{ |
| 60 | + Setsid: true, |
| 61 | + }, |
| 62 | + Files: []uintptr{ |
| 63 | + uintptr(syscall.Stdin), |
| 64 | + uintptr(syscall.Stdout), |
| 65 | + uintptr(syscall.Stderr), |
| 66 | + }, |
| 67 | + } |
| 68 | + |
| 69 | + //#nosec G204 |
| 70 | + pid, _ := syscall.ForkExec(args[0], args, pattrs) |
| 71 | + |
| 72 | + var wstatus syscall.WaitStatus |
| 73 | + _, err = syscall.Wait4(pid, &wstatus, 0, nil) |
| 74 | + for xerrors.Is(err, syscall.EINTR) { |
| 75 | + _, err = syscall.Wait4(pid, &wstatus, 0, nil) |
| 76 | + } |
| 77 | + |
| 78 | + return nil |
| 79 | +} |
0 commit comments