Skip to content
quarry Artifact [f4ba436925]
Login

Artifact [f4ba436925]

Artifact f4ba4369257431e87922539f69736ce7c7f2ca499724f6385f422ef09251c8fd:


//go:build unix

package runner

import (
	"errors"
	"os"
	"os/exec"
	"syscall"
	"time"
)

// endOwn kills every process this user may signal, which for anyone
// but root is this user's own, except the caller (kill(2), pid -1).
// None left is success.
func endOwn() error {
	if err := syscall.Kill(-1, syscall.SIGKILL); err != nil && err != syscall.ESRCH {
		return err
	}
	return nil
}

// become replaces job-env with the command, under a umask that keeps
// what it writes from everyone outside its group.
func become(path string, argv, env []string) error {
	syscall.Umask(0o007)
	return syscall.Exec(path, argv, env)
}

// stopGrace is how long a cancelled step's process group gets between
// SIGTERM and SIGKILL. Short enough that a cancelled job frees its
// runner slot promptly, long enough for a clean signal handler to exit.
const stopGrace = 200 * time.Millisecond

// stopTogether puts a command in a process group of its own and, when
// its context ends, stops the whole group: SIGTERM first so a test or
// helper can clean up, then SIGKILL after stopGrace so nothing that
// ignores TERM — or any grandchild it spawned — outlives the step and
// holds the runner slot open.
func stopTogether(cmd *exec.Cmd) {
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
	cmd.Cancel = func() error {
		if cmd.Process == nil {
			return nil
		}
		pgid := -cmd.Process.Pid
		if err := syscall.Kill(pgid, syscall.SIGTERM); err != nil {
			if errors.Is(err, syscall.ESRCH) {
				return os.ErrProcessDone
			}
			return err
		}
		deadline := time.Now().Add(stopGrace)
		for time.Now().Before(deadline) {
			if err := syscall.Kill(pgid, 0); errors.Is(err, syscall.ESRCH) {
				return nil
			}
			time.Sleep(10 * time.Millisecond)
		}
		if err := syscall.Kill(pgid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
			return err
		}
		return nil
	}
	cmd.WaitDelay = 5 * time.Second
}

// pidAlive reports whether a process with this pid exists.
func pidAlive(pid int) bool {
	err := syscall.Kill(pid, 0)
	return err == nil || err == syscall.EPERM
}