Skip to content

Commit 13f2c00

Browse files
committed
fix: Improve disconnect logic for ssh-bin
Previously we were only closing stdin, and normally that's enough, but not always: if the connection is gone, but ssh doesn't know about it (e.g. if the OS was suspended for long enough time, and then resumed), then the connection kept hanging. This commit provides custom context for the external ssh command, and cancels it when we need to disconnect.
1 parent 5c6a91d commit 13f2c00

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

core/shell_transport_ssh_bin.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package core
22

33
import (
44
"bufio"
5+
"context"
56
"fmt"
67
"io"
78
"os/exec"
@@ -91,7 +92,8 @@ func (s *ShellTransportSSHBin) doConnect(
9192
}
9293
logger.Infof("Executing external ssh command: %q", sshCmdDebug)
9394

94-
cmd := exec.Command("ssh", sshArgs...)
95+
ctx, cancel := context.WithCancel(context.Background())
96+
cmd := exec.CommandContext(ctx, "ssh", sshArgs...)
9597
stdin, err := cmd.StdinPipe()
9698
if err != nil {
9799
res.Err = errors.Annotatef(err, "getting stdin pipe")
@@ -177,6 +179,8 @@ func (s *ShellTransportSSHBin) doConnect(
177179
stdin: stdin,
178180
stdout: clientStdoutR,
179181
stderr: stderr,
182+
183+
ctxCancel: cancel,
180184
}
181185
return res
182186

@@ -198,6 +202,8 @@ type ShellConnSSHBin struct {
198202
stdin io.WriteCloser
199203
stdout io.Reader
200204
stderr io.Reader
205+
206+
ctxCancel context.CancelFunc
201207
}
202208

203209
func (s *ShellConnSSHBin) Stdin() io.Writer {
@@ -213,5 +219,12 @@ func (s *ShellConnSSHBin) Stderr() io.Reader {
213219
}
214220

215221
func (s *ShellConnSSHBin) Close() {
222+
// Close stdin; normally this is enough for the external process to finish
223+
// gracefully.
216224
s.stdin.Close()
225+
226+
// Cancel context too, so the external process gets killed (closing stdin is
227+
// not always enough; e.g. after the OS gets suspended for long enough time,
228+
// and resumed, the connection keeps hanging without it).
229+
s.ctxCancel()
217230
}

0 commit comments

Comments
 (0)