-
Notifications
You must be signed in to change notification settings - Fork 193
fix(process): bound context command cleanup #987
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PierrunoYT
wants to merge
19
commits into
Twigpine:main
Choose a base branch
from
PierrunoYT:fix/issue-966-process-tree-timeouts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
4dc570c
fix(process): bound context command cleanup
PierrunoYT 8621fdb
fix(process): retain command tree cancellation identity
ampagent f743018
fix(process): bind Windows jobs before execution
ampagent 44aff3d
fix(execution): preserve successful Windows descendants
PierrunoYT e9af688
fix(execution): fall back when tree containment fails
PierrunoYT 91c5895
fix(execution): require Windows job containment
ampagent 803e076
fix(execution): retain process tree lifecycle ownership
PierrunoYT aac2bd9
fix(process): bound context command cleanup
PierrunoYT 54b457f
fix(process): retain command tree cancellation identity
ampagent 8e69a0b
fix(process): bind Windows jobs before execution
ampagent 20b24c1
fix(execution): preserve successful Windows descendants
PierrunoYT c6e35f0
fix(execution): fall back when tree containment fails
PierrunoYT 56a3503
fix(execution): require Windows job containment
ampagent 53b3ead
fix(execution): retain process tree lifecycle ownership
PierrunoYT d6e8f02
fix(execution): bound configured hook process lifecycles
ampagent 109c345
Merge existing PR ancestry after refreshing upstream base
ampagent 6285a65
Merge upstream main into fix/issue-966-process-tree-timeouts
ampagent aa20bc1
test(plugins): allow race runtime exit delay in origin fixture
ampagent 173ddc3
fix(process): preserve benchmark output drain failures
PierrunoYT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| package execution | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "os/exec" | ||
| "reflect" | ||
| "sync" | ||
| ) | ||
|
|
||
| // RunCommand runs a context-bound command in a retained process tree and | ||
| // prevents inherited output handles from blocking Wait indefinitely. | ||
| func RunCommand(ctx context.Context, command *exec.Cmd) (err error) { | ||
| if command == nil { | ||
| return errors.New("execution: nil command") | ||
| } | ||
| if ctx == nil { | ||
| ctx = context.Background() | ||
| } | ||
| if err := ctx.Err(); err != nil { | ||
| return err | ||
| } | ||
| drains := observeOutputDrains(command) | ||
| tree, err := prepareCommandTree(command) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer func() { err = errors.Join(err, tree.close()) }() | ||
|
|
||
| command.WaitDelay = processWaitDelay | ||
| // Adapters may return exec.Command, which rejects a non-nil Cancel. | ||
| // The watcher below also owns cancellation for commands without that hook. | ||
| if command.Cancel != nil { | ||
| command.Cancel = tree.cancel | ||
| } | ||
| if err := command.Start(); err != nil { | ||
| _ = tree.attach(nil) | ||
| return err | ||
| } | ||
| if err := tree.attach(command.Process); err != nil { | ||
| killErr := command.Process.Kill() | ||
| waitErr := command.Wait() | ||
| return errors.Join(fmt.Errorf("execution: attach process tree: %w", err), killErr, waitErr) | ||
| } | ||
| waitComplete := make(chan struct{}) | ||
| type cancellation struct { | ||
| err error | ||
| canceled bool | ||
| } | ||
| cancelResult := make(chan cancellation, 1) | ||
| go func() { | ||
| select { | ||
| case <-ctx.Done(): | ||
| cancelResult <- cancellation{err: tree.cancel(), canceled: true} | ||
| case <-waitComplete: | ||
| cancelResult <- cancellation{} | ||
| } | ||
| }() | ||
| waitErr := command.Wait() | ||
| close(waitComplete) | ||
| canceled := <-cancelResult | ||
| if canceled.canceled { | ||
| return errors.Join(waitErr, ctx.Err(), canceled.err) | ||
| } | ||
| if waitErr != nil && drains.err() != nil { | ||
| // Cmd.Wait intentionally prefers an ExitError over a copying error. When | ||
| // WaitDelay forcibly closes an inherited output pipe after a nonzero root | ||
| // exit, retain that cleanup failure so result consumers cannot reconcile it | ||
| // as an ordinary command exit. | ||
| return errors.Join(waitErr, exec.ErrWaitDelay, tree.cancel()) | ||
| } | ||
| if waitErr != nil { | ||
| return errors.Join(waitErr, tree.cancel()) | ||
| } | ||
| return waitErr | ||
| } | ||
|
|
||
| type outputDrains struct { | ||
| stdout *drainObserver | ||
| stderr *drainObserver | ||
| } | ||
|
|
||
| func observeOutputDrains(command *exec.Cmd) outputDrains { | ||
| drains := outputDrains{} | ||
| sharedOutput := sameWriter(command.Stderr, command.Stdout) | ||
| if !isFile(command.Stdout) && command.Stdout != nil { | ||
| drains.stdout = &drainObserver{writer: command.Stdout} | ||
| command.Stdout = drains.stdout | ||
| } | ||
| if sharedOutput && drains.stdout != nil { | ||
| command.Stderr = drains.stdout | ||
| drains.stderr = drains.stdout | ||
| } else if !isFile(command.Stderr) && command.Stderr != nil { | ||
| drains.stderr = &drainObserver{writer: command.Stderr} | ||
| command.Stderr = drains.stderr | ||
| } | ||
| return drains | ||
| } | ||
|
|
||
| func (drains outputDrains) err() error { | ||
| if drains.stdout != nil && drains.stdout.err() != nil { | ||
| return drains.stdout.err() | ||
| } | ||
| if drains.stderr != nil { | ||
| return drains.stderr.err() | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func isFile(writer io.Writer) bool { | ||
| _, ok := writer.(*os.File) | ||
| return ok | ||
| } | ||
|
|
||
| func sameWriter(left io.Writer, right io.Writer) bool { | ||
| if left == nil || right == nil { | ||
| return false | ||
| } | ||
| leftType := reflect.TypeOf(left) | ||
| return leftType == reflect.TypeOf(right) && leftType.Comparable() && left == right | ||
| } | ||
|
|
||
| // drainObserver records an error from os/exec's output-copying goroutine. | ||
| // Cmd.Wait drops that error when process exit itself fails. | ||
| type drainObserver struct { | ||
| writer io.Writer | ||
| mu sync.Mutex | ||
| copyErr error | ||
| } | ||
|
|
||
| func (observer *drainObserver) Write(data []byte) (int, error) { | ||
| return observer.writer.Write(data) | ||
| } | ||
|
|
||
| func (observer *drainObserver) ReadFrom(reader io.Reader) (int64, error) { | ||
| written, err := io.Copy(observer.writer, reader) | ||
| if err != nil { | ||
| observer.mu.Lock() | ||
| observer.copyErr = err | ||
| observer.mu.Unlock() | ||
| } | ||
| return written, err | ||
| } | ||
|
|
||
| func (observer *drainObserver) err() error { | ||
| observer.mu.Lock() | ||
| defer observer.mu.Unlock() | ||
| return observer.copyErr | ||
| } | ||
100 changes: 100 additions & 0 deletions
100
internal/execution/command_context_process_unix_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| //go:build !windows | ||
|
|
||
| package execution | ||
|
|
||
| import ( | ||
| "errors" | ||
| "os" | ||
| "strconv" | ||
| "strings" | ||
| "syscall" | ||
| "testing" | ||
| "time" | ||
| ) | ||
|
|
||
| type helperProcessOwner struct { | ||
| pidFile string | ||
| stopFile string | ||
| pid int | ||
| exited bool | ||
| } | ||
|
|
||
| func ownHelperProcess(t *testing.T, pidFile, stopFile string) *helperProcessOwner { | ||
| t.Helper() | ||
| owner := &helperProcessOwner{pidFile: pidFile, stopFile: stopFile} | ||
| t.Cleanup(func() { owner.cleanup(t) }) | ||
| return owner | ||
| } | ||
|
|
||
| func (owner *helperProcessOwner) waitReady(t *testing.T, timeout time.Duration) int { | ||
| t.Helper() | ||
| deadline := time.Now().Add(timeout) | ||
| for { | ||
| data, err := os.ReadFile(owner.pidFile) | ||
| if err == nil { | ||
| pid, parseErr := strconv.Atoi(strings.TrimSpace(string(data))) | ||
| if parseErr == nil && pid > 0 { | ||
| owner.pid = pid | ||
| return pid | ||
| } | ||
| } | ||
| if time.Now().After(deadline) { | ||
| t.Fatalf("helper did not hand off a valid PID within %s", timeout) | ||
| } | ||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
| } | ||
|
|
||
| func (owner *helperProcessOwner) cleanup(t *testing.T) { | ||
| t.Helper() | ||
| if err := os.WriteFile(owner.stopFile, nil, 0o600); err != nil { | ||
| t.Errorf("request helper process stop: %v", err) | ||
| } | ||
| if owner.exited { | ||
| return | ||
| } | ||
| if owner.pid == 0 { | ||
| data, err := os.ReadFile(owner.pidFile) | ||
| if err == nil { | ||
| owner.pid, _ = strconv.Atoi(strings.TrimSpace(string(data))) | ||
| } | ||
| } | ||
| if owner.pid <= 0 { | ||
| return | ||
| } | ||
| deadline := time.Now().Add(2 * time.Second) | ||
| for time.Now().Before(deadline) { | ||
| err := syscall.Kill(owner.pid, syscall.Signal(0)) | ||
| if errors.Is(err, syscall.ESRCH) { | ||
| owner.pid = 0 | ||
| owner.exited = true | ||
| return | ||
| } | ||
| if err != nil { | ||
| t.Errorf("check helper process %d after cleanup: %v", owner.pid, err) | ||
| return | ||
| } | ||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
| t.Errorf("helper process %d survived cleanup", owner.pid) | ||
| } | ||
|
|
||
| func (owner *helperProcessOwner) awaitExit(t *testing.T) { | ||
| t.Helper() | ||
| deadline := time.Now().Add(2 * time.Second) | ||
| for { | ||
| err := syscall.Kill(owner.pid, syscall.Signal(0)) | ||
| if errors.Is(err, syscall.ESRCH) { | ||
| owner.pid = 0 | ||
| owner.exited = true | ||
| return | ||
| } | ||
| if err != nil { | ||
| t.Fatalf("check helper process %d: %v", owner.pid, err) | ||
| } | ||
| if time.Now().After(deadline) { | ||
| t.Fatalf("helper process %d is still running after command cancellation", owner.pid) | ||
| } | ||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.