diff --git a/pkg/cmd/exec/exec.go b/pkg/cmd/exec/exec.go index 1482556d..d8a88bdb 100644 --- a/pkg/cmd/exec/exec.go +++ b/pkg/cmd/exec/exec.go @@ -2,6 +2,7 @@ package exec import ( "bufio" + "errors" "fmt" "os" "os/exec" @@ -186,13 +187,22 @@ func runExecCommand(t *terminal.Terminal, sstore ExecStore, workspaceNameOrID st // SSH multiplexing (ControlMaster) in the config means subsequent // calls reuse an existing connection and are near-instant. // Use a 5-second connect timeout so we fail fast if the instance is down. - err := runSSHWithTimeout(sshName, command, 5) + err := runExecSSH(sshName, command, 5) if err == nil { // Success — fire analytics in background and return go trackExecAnalytics(sstore, workspaceNameOrID) return nil } + // The first attempt already is the execution. A non-zero remote status, or + // an SSH session that died after the command may have started, must not be + // run again: the instance can still be RUNNING with the original process + // (or its output) in place. Only a failure from before the session exists + // may fall through to the refresh-and-retry path below. + if !sshFailureAllowsReplay(err) { + return breverrors.WrapAndTrace(err) + } + // SSH failed — now check what's going on with the instance fmt.Fprintf(os.Stderr, "Connection failed, checking instance status...\n") @@ -228,7 +238,7 @@ func runExecCommand(t *terminal.Terminal, sstore ExecStore, workspaceNameOrID st // instance and what to check. return err //nolint:wrapcheck // do not present stack trace for this error } - err = runSSH(sshName, command) + err = runExecSSH(sshName, command, 10) if err != nil { return breverrors.WrapAndTrace(err) } @@ -256,27 +266,144 @@ func trackExecAnalytics(sstore ExecStore, workspaceNameOrID string) { _ = analytics.TrackEvent(data) } +// runExecSSH is the SSH invocation used by brev exec. Tests replace it. +var runExecSSH = runSSHWithTimeout + +// sshAttemptError is a failed SSH invocation of the remote command. +// exitCode 255 is ssh's own failure; any other code is the remote command's. +// diag is ssh's private log (ssh -E), not the remote command's stderr. +type sshAttemptError struct { + err error + exitCode int + diag string +} + +func (e *sshAttemptError) Error() string { + if e == nil || e.err == nil { + return "ssh failed" + } + return e.err.Error() +} + +func (e *sshAttemptError) Unwrap() error { return e.err } + +func newSSHAttemptError(err error, diag string) error { + code := -1 + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + code = exitErr.ExitCode() + } + return &sshAttemptError{err: err, exitCode: code, diag: diag} +} + +// sshFailureAllowsReplay reports whether the remote command is known not to +// have started, so the caller may wait for SSH and run it once. A non-zero +// remote status, a session that dropped, or an unrecognized ssh failure is +// not replayed: the command may already be running. +func sshFailureAllowsReplay(err error) bool { + var attempt *sshAttemptError + if !errors.As(err, &attempt) { + return false + } + // OpenSSH uses 255 for its own failures and passes every other status + // through from the remote command. + if attempt.exitCode != 255 { + return false + } + return sshDiagIsPreSession(attempt.diag) +} + +// sshDiagIsPreSession reports whether ssh failed before a session existed. +// Only the last non-empty line of the -E log counts, plus the OpenSSH +// banner-exchange pair below. An earlier "ssh: connect to host" line is +// normal when another address then opens a session that later drops, and +// that command must not be run again. +// The line has to start with an OpenSSH pre-session prefix. A bare errno +// string is not enough: "Read from remote host X: Connection timed out" is +// written after the session is up. The strerror after the prefix is not +// matched, so a translated message still counts. +// +// A banner failure is two lines. kex_exchange_identification logs the +// close, then sshpkt_fatal appends "Connection closed by +// port " or "Connection reset by port " and exits. +// That second line is also printed once a session exists, so it is +// pre-session only when the previous non-empty line is the kex line. +func sshDiagIsPreSession(diag string) bool { + lines := nonEmptyDiagLines(diag) + if len(lines) == 0 { + return false + } + last := lines[len(lines)-1] + prefixes := []string{ + "ssh: connect to host ", + "ssh: Could not resolve hostname", + "kex_exchange_identification:", + } + for _, prefix := range prefixes { + if strings.HasPrefix(last, prefix) { + return true + } + } + if len(lines) < 2 || !strings.HasPrefix(lines[len(lines)-2], "kex_exchange_identification:") { + return false + } + return strings.HasPrefix(last, "Connection closed by ") || + strings.HasPrefix(last, "Connection reset by ") +} + +func nonEmptyDiagLines(diag string) []string { + lines := make([]string, 0) + for _, raw := range strings.Split(diag, "\n") { + if trimmed := strings.TrimSpace(raw); trimmed != "" { + lines = append(lines, trimmed) + } + } + return lines +} + +func shellSingleQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + func runSSHWithTimeout(sshAlias string, command string, connectTimeoutSecs int) error { // Non-interactive: run command and pipe stdout/stderr // Escape the command for passing to SSH escapedCmd := strings.ReplaceAll(command, "'", "'\\''") // -T disables pseudo-terminal allocation (no "Pseudo-terminal will not be allocated" warning) // Only start ssh-agent if one isn't already running (avoids orphaned agent processes) + // -E keeps ssh's own errors out of the remote command's stderr so a dropped + // session is not mistaken for "never connected". agentCmd := `if [ -z "$SSH_AUTH_SOCK" ]; then eval $(ssh-agent -s) > /dev/null; fi` - cmd := fmt.Sprintf("%s && ssh -T -o ConnectTimeout=%d -o LogLevel=ERROR %s '%s'", agentCmd, connectTimeoutSecs, sshAlias, escapedCmd) + diagFile, diagErr := os.CreateTemp("", "brev-exec-ssh-") + if diagErr != nil { + return breverrors.WrapAndTrace(diagErr) + } + diagPath := diagFile.Name() + _ = diagFile.Close() + defer os.Remove(diagPath) + + cmd := fmt.Sprintf("%s && ssh -T -E %s -o ConnectTimeout=%d -o LogLevel=ERROR %s '%s'", + agentCmd, shellSingleQuote(diagPath), connectTimeoutSecs, sshAlias, escapedCmd) - sshCmd := exec.Command("bash", "-c", cmd) //nolint:gosec //cmd is user input + sshCmd := exec.Command("bash", "-c", cmd) //nolint:gosec // cmd is user input sshCmd.Stderr = os.Stderr sshCmd.Stdout = os.Stdout // Don't attach stdin - exec is non-interactive err := sshCmd.Run() + diagBytes, readErr := os.ReadFile(diagPath) + diag := "" + if readErr == nil { + diag = string(diagBytes) + } if err != nil { - return breverrors.WrapAndTrace(err) + if diag != "" { + _, _ = os.Stderr.WriteString(diag) + if !strings.HasSuffix(diag, "\n") { + _, _ = fmt.Fprintln(os.Stderr) + } + } + return newSSHAttemptError(err, diag) } return nil } - -func runSSH(sshAlias string, command string) error { - return runSSHWithTimeout(sshAlias, command, 10) -} diff --git a/pkg/cmd/exec/exec_test.go b/pkg/cmd/exec/exec_test.go new file mode 100644 index 00000000..49f8f007 --- /dev/null +++ b/pkg/cmd/exec/exec_test.go @@ -0,0 +1,288 @@ +package exec + +import ( + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSSHFailureAllowsReplayOnlyBeforeSession(t *testing.T) { + t.Parallel() + cases := []struct { + name string + err error + want bool + }{ + {name: "remote exit", err: &sshAttemptError{exitCode: 1}, want: false}, + {name: "remote exit 127", err: &sshAttemptError{exitCode: 127}, want: false}, + {name: "exit 255 with empty diagnostic", err: &sshAttemptError{exitCode: 255}, want: false}, + { + name: "session dropped", + err: &sshAttemptError{exitCode: 255, diag: "client_loop: send disconnect: Broken pipe\n"}, + want: false, + }, + { + name: "connection closed after the session", + err: &sshAttemptError{exitCode: 255, diag: "Connection closed by 10.0.0.8 port 22"}, + want: false, + }, + { + name: "connection reset after the session", + err: &sshAttemptError{exitCode: 255, diag: "Connection reset by peer"}, + want: false, + }, + { + name: "read timeout after the session", + err: &sshAttemptError{exitCode: 255, diag: "Read from remote host brev: Connection timed out\n"}, + want: false, + }, + { + name: "earlier refusal then a dropped session", + err: &sshAttemptError{ + exitCode: 255, + diag: "ssh: connect to host 10.0.0.1 port 22: Connection refused\nclient_loop: send disconnect: Broken pipe\n", + }, + want: false, + }, + { + name: "every address failed before a session", + err: &sshAttemptError{ + exitCode: 255, + diag: "ssh: connect to host 10.0.0.1 port 22: Connection refused\nssh: connect to host 10.0.0.2 port 22: Connection timed out\n", + }, + want: true, + }, + { + name: "connection refused", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Connection refused"}, + want: true, + }, + { + name: "localized connect failure", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Verbindung abgelehnt"}, + want: true, + }, + { + name: "connect timeout", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Connection timed out"}, + want: true, + }, + { + name: "macos connect timeout", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Operation timed out"}, + want: true, + }, + { + name: "unresolved alias", + err: &sshAttemptError{exitCode: 255, diag: "ssh: Could not resolve hostname gpu: Name or service not known"}, + want: true, + }, + { + name: "handshake closed before the banner", + err: &sshAttemptError{ + exitCode: 255, + diag: "kex_exchange_identification: Connection closed by remote host\n\nConnection closed by UNKNOWN port 65535\n", + }, + want: true, + }, + { + name: "handshake reset before the banner", + err: &sshAttemptError{ + exitCode: 255, + diag: "kex_exchange_identification: read: Connection reset by peer\nConnection reset by UNKNOWN port 65535\n", + }, + want: true, + }, + { + name: "kex line is not the one before the close", + err: &sshAttemptError{ + exitCode: 255, + diag: "kex_exchange_identification: Connection closed by remote host\nclient_loop: send disconnect: Broken pipe\nConnection closed by 10.0.0.8 port 22\n", + }, + want: false, + }, + {name: "untyped error", err: fmt.Errorf("ssh: exit status 1"), want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + if got := sshFailureAllowsReplay(tc.err); got != tc.want { + t.Fatalf("sshFailureAllowsReplay() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestExecDoesNotReplayRemoteExit(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 1"), + exitCode: 1, + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("remote exit was treated as a dead connection:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the remote failure to be returned") + } +} + +func TestExecDoesNotReplaySessionDrop(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "client_loop: send disconnect: Broken pipe\n", + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("dropped session was replayed via SSH recovery:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the ssh failure to be returned") + } +} + +func TestExecDoesNotReplayReadTimeoutAfterSession(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "Read from remote host brev: Connection timed out\n", + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("read timeout after the session was replayed via SSH recovery:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the ssh failure to be returned") + } +} + +func TestExecDoesNotReplayAfterEarlierConnectRefusal(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "ssh: connect to host 10.0.0.1 port 22: Connection refused\nclient_loop: send disconnect: Broken pipe\n", + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("session drop after an earlier refusal was replayed:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the ssh failure to be returned") + } +} + +func TestExecStillRecoversWhenSSHNeverConnected(t *testing.T) { + _, output, _, _ := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "ssh: connect to host gpu port 22: Connection refused\n", + }) + if !strings.Contains(output, "Connection failed, checking instance status...") { + t.Fatalf("a refused connection should still enter recovery, output:\n%s", output) + } +} + +func TestRunSSHWithTimeoutKeepsPreSessionDiagnostic(t *testing.T) { + sshPath := writeFakeSSH(t, `#!/bin/sh +prev= +for a in "$@"; do + if [ "$prev" = "-E" ]; then + printf '%s\n' 'ssh: connect to host inst port 22: Connection refused' > "$a" + exit 255 + fi + prev=$a +done +printf '%s\n' 'fake ssh: missing -E' >&2 +exit 255 +`) + t.Setenv("SSH_AUTH_SOCK", "/tmp/brev-exec-test-sock") + t.Setenv("PATH", filepath.Dir(sshPath)+string(os.PathListSeparator)+os.Getenv("PATH")) + + err := runSSHWithTimeout("inst", "true", 1) + if !sshFailureAllowsReplay(err) { + t.Fatalf("connection refused was not classified as pre-session: %v", err) + } +} + +func TestRunSSHWithTimeoutDoesNotReplayRemoteStatus(t *testing.T) { + sshPath := writeFakeSSH(t, `#!/bin/sh +prev= +for a in "$@"; do + if [ "$prev" = "-E" ]; then + : > "$a" + exit 1 + fi + prev=$a +done +exit 1 +`) + t.Setenv("SSH_AUTH_SOCK", "/tmp/brev-exec-test-sock") + t.Setenv("PATH", filepath.Dir(sshPath)+string(os.PathListSeparator)+os.Getenv("PATH")) + + err := runSSHWithTimeout("inst", "mhcflurry eval", 1) + if sshFailureAllowsReplay(err) { + t.Fatalf("remote exit 1 was classified as replayable: %v", err) + } + var attempt *sshAttemptError + if !errorsAsAttempt(err, &attempt) || attempt.exitCode != 1 { + t.Fatalf("exit code = %v, err = %v", attempt, err) + } +} + +func execWithSSHResult(t *testing.T, sshErr error) (calls int, output string, ret error, panicked any) { + t.Helper() + orig := runExecSSH + t.Cleanup(func() { runExecSSH = orig }) + runExecSSH = func(alias, command string, connectTimeoutSecs int) error { + calls++ + return sshErr + } + + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + oldStderr := os.Stderr + os.Stderr = writer + defer func() { os.Stderr = oldStderr }() + + func() { + defer func() { panicked = recover() }() + ret = runExecCommand(nil, nil, "gpu-01", false, "mhcflurry eval") + }() + _ = writer.Close() + buf, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + return calls, string(buf), ret, panicked +} + +func writeFakeSSH(t *testing.T, script string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "ssh") + if err := os.WriteFile(path, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + return path +} + +func errorsAsAttempt(err error, target **sshAttemptError) bool { + if attempt, ok := err.(*sshAttemptError); ok { + *target = attempt + return true + } + return false +}