diff --git a/cmd/root.go b/cmd/root.go index 2142442..4e827d5 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "os/signal" + "sync/atomic" "syscall" "github.com/devsy-org/devsy/pkg/log" @@ -42,12 +43,23 @@ func Execute() { rootCmd := BuildRoot() // execute command - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + ctx, received, stop := notifyContext(context.Background()) err := rootCmd.ExecuteContext(ctx) stop() if err == nil { return } + // Devsy ends the tunnel by signalling this process once the remote work + // is done. Cleanup has already run, so report the signal as an expected + // end instead of a fatal error. + if sig := received(); sig != nil && errors.Is(err, context.Canceled) { + log.Debugf("stopped by %s", sig) + exitBySignal(sig) + } + exitWithError(err) +} + +func exitWithError(err error) { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { log.Fatal(err) } @@ -63,6 +75,30 @@ func Execute() { log.Fatal(err) } +// notifyContext is signal.NotifyContext that also reports which signal fired. +func notifyContext(parent context.Context) (context.Context, func() os.Signal, func()) { + ctx, cancel := context.WithCancel(parent) + signals := make(chan os.Signal, 1) + signal.Notify(signals, os.Interrupt, syscall.SIGTERM) + var first atomic.Value + go func() { + select { + case sig := <-signals: + first.Store(sig) + cancel() + case <-ctx.Done(): + } + }() + received := func() os.Signal { + sig, _ := first.Load().(os.Signal) + return sig + } + return ctx, received, func() { + signal.Stop(signals) + cancel() + } +} + // BuildRoot creates the SSH provider command tree. func BuildRoot() *cobra.Command { rootCmd := NewRootCmd() diff --git a/cmd/root_unix_test.go b/cmd/root_unix_test.go index 1fc436c..0a6ccba 100644 --- a/cmd/root_unix_test.go +++ b/cmd/root_unix_test.go @@ -10,6 +10,7 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "strings" "syscall" "testing" @@ -52,27 +53,36 @@ func executeTestProcess(t *testing.T, script string) *exec.Cmd { return exec.CommandContext(ctx, executable, "-test.run=^TestExecuteProcess$") } -func TestExecuteCancellation(t *testing.T) { - cmd := executeTestProcess(t, "printf 'ready\\n'\nexec sleep 30\n") - var stderr bytes.Buffer - cmd.Stderr = &stderr - stdout, err := cmd.StdoutPipe() - if err != nil { - t.Fatal(err) - } - if err = cmd.Start(); err != nil { - t.Fatal(err) - } - ready, err := bufio.NewReader(stdout).ReadString('\n') - if err != nil || ready != "ready\n" { - t.Fatalf("SSH child did not start: %q, %v", ready, err) - } - if err = cmd.Process.Signal(syscall.SIGTERM); err != nil { - t.Fatal(err) - } - assertProcessExit(t, cmd.Wait(), 1) - if !strings.Contains(stderr.String(), "context canceled") { - t.Fatalf("missing cancellation diagnostic: %q", stderr.String()) +func TestExecuteSignalEndsQuietlyAfterCleanup(t *testing.T) { + for _, sig := range []syscall.Signal{syscall.SIGTERM, syscall.SIGINT} { + t.Run(sig.String(), func(t *testing.T) { + pidFile := filepath.Join(t.TempDir(), "ssh.pid") + cmd := executeTestProcess( + t, + "printf '%s' \"$$\" > '"+pidFile+"'\nprintf 'ready\\n'\nexec sleep 30\n", + ) + var stderr bytes.Buffer + cmd.Stderr = &stderr + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err = cmd.Start(); err != nil { + t.Fatal(err) + } + ready, err := bufio.NewReader(stdout).ReadString('\n') + if err != nil || ready != "ready\n" { + t.Fatalf("SSH child did not start: %q, %v", ready, err) + } + if err = cmd.Process.Signal(sig); err != nil { + t.Fatal(err) + } + assertProcessSignaled(t, cmd.Wait(), sig) + if stderr.Len() != 0 { + t.Fatalf("expected shutdown logged below error level, got %q", stderr.String()) + } + assertChildGone(t, pidFile) + }) } } @@ -93,3 +103,31 @@ func assertProcessExit(t *testing.T, err error, code int) { t.Fatalf("expected exit %d, got %v", code, err) } } + +func assertProcessSignaled(t *testing.T, err error, want syscall.Signal) { + t.Helper() + var exit *exec.ExitError + if !errors.As(err, &exit) { + t.Fatalf("expected signal death, got %v", err) + } + status, ok := exit.Sys().(syscall.WaitStatus) + if !ok || !status.Signaled() || status.Signal() != want { + t.Fatalf("expected death by %s, got %v", want, err) + } +} + +func assertChildGone(t *testing.T, pidFile string) { + t.Helper() + // #nosec G304 -- Path is a fixture file inside the test's temp directory. + raw, err := os.ReadFile(pidFile) + if err != nil { + t.Fatal(err) + } + pid, err := strconv.Atoi(strings.TrimSpace(string(raw))) + if err != nil { + t.Fatal(err) + } + if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) { + t.Fatalf("SSH child %d survived shutdown: %v", pid, err) + } +} diff --git a/cmd/shutdown_unix.go b/cmd/shutdown_unix.go new file mode 100644 index 0000000..767d425 --- /dev/null +++ b/cmd/shutdown_unix.go @@ -0,0 +1,24 @@ +//go:build !windows + +package cmd + +import ( + "os" + "os/signal" + "syscall" + "time" +) + +// exitBySignal ends the process the way an uncaught signal would, so the +// caller sees a signal death instead of a failure exit code. +func exitBySignal(sig os.Signal) { + if s, ok := sig.(syscall.Signal); ok { + signal.Reset(sig) + _ = syscall.Kill(os.Getpid(), s) + // The signal is delivered asynchronously; the fallback keeps the + // shell convention if it is somehow blocked. + time.Sleep(time.Second) + os.Exit(128 + int(s)) + } + os.Exit(1) +} diff --git a/cmd/shutdown_windows.go b/cmd/shutdown_windows.go new file mode 100644 index 0000000..5d41661 --- /dev/null +++ b/cmd/shutdown_windows.go @@ -0,0 +1,10 @@ +//go:build windows + +package cmd + +import "os" + +// exitBySignal exits with a failure code: Windows cannot re-raise a signal. +func exitBySignal(_ os.Signal) { + os.Exit(1) +}