|
| 1 | +// Copyright 2026 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +//go:build unix |
| 5 | + |
| 6 | +package process |
| 7 | + |
| 8 | +import ( |
| 9 | + "bufio" |
| 10 | + "context" |
| 11 | + "os" |
| 12 | + "strconv" |
| 13 | + "strings" |
| 14 | + "syscall" |
| 15 | + "testing" |
| 16 | + "time" |
| 17 | + |
| 18 | + "github.com/stretchr/testify/assert" |
| 19 | + "github.com/stretchr/testify/require" |
| 20 | +) |
| 21 | + |
| 22 | +func TestCommandContextCancelKillProcessGroup(t *testing.T) { |
| 23 | + ctx, cancel := context.WithCancel(t.Context()) |
| 24 | + defer cancel() |
| 25 | + |
| 26 | + // When executing external commands, there can be multiple subprocesses involved. |
| 27 | + // e.g.: Gitea -> "git upload-pack" -> "git pack-objects". |
| 28 | + // If the context is canceled (HTTP client disconnects), all subprocesses must terminate. |
| 29 | + |
| 30 | + // Spawn a shell that itself spawns a long-lived background process and |
| 31 | + // prints its PID — mimicking git upload-pack spawning git pack-objects. |
| 32 | + |
| 33 | + r, w, err := os.Pipe() |
| 34 | + require.NoError(t, err) |
| 35 | + |
| 36 | + cmd := CommandContext(ctx, "sh", "-c", "sleep 600 & echo $!; wait") |
| 37 | + cmd.Stdout = w |
| 38 | + require.NoError(t, cmd.Start()) |
| 39 | + _ = w.Close() // parent keeps only the read end |
| 40 | + |
| 41 | + t.Cleanup(func() { |
| 42 | + // make sure our test doesn't leave a zombie process even if test fails |
| 43 | + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) |
| 44 | + _ = cmd.Wait() |
| 45 | + }) |
| 46 | + |
| 47 | + // Block until the shell prints the grandchild PID. |
| 48 | + scanner := bufio.NewScanner(r) |
| 49 | + require.True(t, scanner.Scan(), "expected grandchild PID on stdout") |
| 50 | + grandchildPID, err := strconv.Atoi(strings.TrimSpace(scanner.Text())) |
| 51 | + require.NoError(t, err) |
| 52 | + _ = r.Close() |
| 53 | + |
| 54 | + // Sanity: grandchild must be alive before we cancel. |
| 55 | + grandchild, err := os.FindProcess(grandchildPID) |
| 56 | + require.NoError(t, err) |
| 57 | + require.NoError(t, grandchild.Signal(syscall.Signal(0)), "grandchild should be alive before cancel") |
| 58 | + |
| 59 | + // Cancel the context |
| 60 | + cancel() |
| 61 | + _ = cmd.Wait() |
| 62 | + |
| 63 | + // Subprocess should not exist after context cancel (killed by process group) |
| 64 | + assert.Eventually(t, func() bool { |
| 65 | + return grandchild.Signal(syscall.Signal(0)) != nil |
| 66 | + }, 5*time.Second, 10*time.Millisecond) |
| 67 | +} |
0 commit comments