gitforge/modules/process/manager_unix.go
Mathieu Fenniak 958cface13 fix: terminate git (& other) subcommands gracefully on context timeout/cancellation (#13263)
By default, when you create an `exec.CommandContext` in Go, when the context is cancelled or timed out, Go will SIGKILL the subprocess which does not allow the subprocess to perform any cleanup work.  As some git operations in Forgejo will be linked to the current HTTP context, and the current HTTP context will be closed when the HTTP client disconnects, this can theoretically cause SIGKILLs when locks are being held.

This PR contains two fixes:
- Change the behaviour of all subprocesses that Forgejo creates to use a graceful termination, SIGTERM'ing the process, and then SIGKILL'ing it after a timeout.
- Fixes a bug where previously all subprocesses are setup in a process group (by 1d04e8641d), but they were never *killed* in a process group, preventing child processes from receiving these termination signals.  Both SIGTERM and SIGKILL are sent to the process group.

Introduces new configuration setting which controls subcommand graceful timeouts.  If a subprocess does not shutdown from SIGTERM within `[server].SUBPROCESS_TERMINATE_GRACE` (default 5 seconds), then an error will be logged, and the process will be SIGKILL'd.  The error is:
```
2026/07/01 08:31:20 modules/log/init.go:38:func2() [E] Subprocess pid=3790963 (/nix/store/c0277k5giric1mn9dklllavbzvxl6hzb-git-2.53.0/bin/git blame --porcelain 8ee7e7c32b -- options/locale/locale_en-US.ini) failed to terminate from SIGTERM after grace period 0s, and was sent SIGKILL. The subprocess termination may leave incomplete state on the server, such as lock files. `[server].SUBPROCESS_TERMINATE_GRACE` can be changed to give subprocesses more time to cleanly exit.
```

(This was produced on a live server by setting SUBPROCESS_TERMINATE_GRACE to zero seconds, loading a page that does a `git blame`, and hitting escape in the browser quickly.)

### Tests for Go changes

- I added test coverage for Go changes...
  - [x] in their respective `*_test.go` for unit tests.
  - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I ran...
  - [x] `make pr-go` before pushing

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
    - Will create a documentation PR with new config settings.
- [ ] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [x] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
- [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/13263
Reviewed-by: Andreas Ahlenstorf <aahlenst@noreply.codeberg.org>
2026-07-01 20:26:02 +02:00

118 lines
4.7 KiB
Go

// Copyright 2026 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: GPLv3-or-later
package process
import (
"os"
"os/exec"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// A command run through [SetupCancellableCommand] will be sent SIGKILL after this grace period if the processes do not
// terminate after SIGTERM is sent to them.
var TerminateGraceTimeout = 5 * time.Second
// This closure is invoked in the event that SIGKILL is sent after a grace period has expired. Intended for logging the
// situation, which cannot be performed inside the process module as it would cause a cyclical dependency on Forgejo's
// log module.
var NotifyTerminateGraceExhausted func(cmd *exec.Cmd)
// Identify errors that can occur in kill or wait that indicate the kill was actually successful as the process doesn't
// exist anymore.
func killErrorSafeToIgnore(err error) bool {
errno, isErrno := err.(syscall.Errno)
if isErrno {
switch errno {
case syscall.ESRCH, // No such process
syscall.ECHILD: // No child processes
return true
}
}
syscallErr, isSyscallErr := err.(*os.SyscallError) // errno may be wrapped in SyscallError
if isSyscallErr && killErrorSafeToIgnore(syscallErr.Err) {
return true
}
return false
}
// Configures an [exec.Cmd] so that its Cancel function will gracefully shutdown the process and all subprocesses by
// sending them SIGTERM. If they do not shutdown from the SIGTERM in the [TerminateGraceTimeout] grace period, they
// will be SIGKILL'd instead. Note that `SysProcAttr` and `Cancel` on the provided command are overwritten, and the
// command's `WaitDelay` will no longer have an impact.
func SetupCancellableCommand(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
// When running SubProcessA -> SubProcessB and SubProcessA gets killed by context timeout, use setpgid to make
// sure the sub processes can be reaped instead of leaving defunct(zombie) processes.
Setpgid: true,
}
// Override the default behaviour, which would have been to SIGKILL the process and wouldn't allow subprocesses the
// ability to gracefully shutdown. This could have lead to git subprocesses leaving lock files not cleaned up.
cmd.Cancel = func() error {
// We're going to TERM/KILL this process, but we cannot wait() on the PID within Cancel -- exactly one goroutine
// may wait() the child process, and if we do it in here we'll cause random errors in the other goroutine. A
// PID FD is used to be able to get woken when the process dies, instead.
//
// It would be nice to use SysProcAttr to get the pidfd automatically, which would remove this syscall and
// there'd be no chance of an error here. But we wouldn't be able to close that FD if the process wasn't
// cancelled since SetupCancellableCommand doesn't interact with commands that don't cancel.
pidfd, err := unix.PidfdOpen(cmd.Process.Pid, 0)
if killErrorSafeToIgnore(err) {
return nil
} else if err != nil {
return err
}
defer unix.Close(pidfd)
// When cmd is being killed (typically by Go when CommandContext's ctx is cancelled), send SIGTERM rather than
// the default of SIGKILL. Send it to the entire process group by sending to the negative PID.
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
if killErrorSafeToIgnore(err) {
return nil
} else if err != nil {
return err
}
// Begin waiting for the process to finish by polling the pidfd. This is a bit ugly to have to implement here,
// but as noted earlier we can't just `cmd.Process.Wait()` because another goroutine will be doing that
// concurrently. We need to repeatedly call Poll() until it indicates that the pidfd is readable, recalculating
// remaining time in the grace period -- the repeated calls are needed because EINTR can interrupt the poll
// briefly.
pfds := []unix.PollFd{{Fd: int32(pidfd), Events: unix.POLLIN}}
deadline := time.Now().Add(TerminateGraceTimeout)
for {
timeout := int(time.Until(deadline).Milliseconds())
if timeout < 0 {
// Grace period expired
break
}
n, err := unix.Poll(pfds, timeout)
if err == unix.EINTR {
continue // interrupted by a signal; recompute remaining time and retry
}
if err != nil {
return err
}
if n > 0 {
// pidfd is readable, indicating that the process is terminated. We don't bother actually reading the
// exit code from the fd -- the other goroutine that is Wait()'ing will do that.
return nil
}
}
// After sending SIGTERM, we hit the terminate grace timeout and the subprocess is still running. Send SIGKILL
// to the process group as a fallback.
if NotifyTerminateGraceExhausted != nil {
NotifyTerminateGraceExhausted(cmd)
}
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if killErrorSafeToIgnore(err) {
return nil
}
return err
}
}