621 lines
19 KiB
Go
621 lines
19 KiB
Go
package transfer
|
||
|
||
// Stage 3.7: the key transfer scenarios over SFTP on the in-process stand
|
||
// (internal/testutil/sshtest). The stand serves the real file system, so
|
||
// remote paths are local temp paths and results are checked with os.*.
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"errors"
|
||
"net"
|
||
"os"
|
||
"path/filepath"
|
||
"strconv"
|
||
"strings"
|
||
"sync"
|
||
"sync/atomic"
|
||
"testing"
|
||
"time"
|
||
|
||
"golang.org/x/crypto/ssh/knownhosts"
|
||
|
||
"vcom/internal/ssh/conn"
|
||
"vcom/internal/testutil/sshtest"
|
||
"vcom/internal/vfs"
|
||
"vcom/internal/vfs/sftpfs"
|
||
)
|
||
|
||
// rstand is a server, its keys in an isolated known_hosts and a pool with
|
||
// fast keepalive (a frozen link is Lost within ~0.4 s).
|
||
type rstand struct {
|
||
t *testing.T
|
||
srv *sshtest.Server
|
||
pool *conn.Pool
|
||
kh string
|
||
}
|
||
|
||
func newRStand(t *testing.T) *rstand {
|
||
t.Helper()
|
||
return newRStandWith(t, conn.PoolOptions{
|
||
KeepaliveInterval: 100 * time.Millisecond,
|
||
KeepaliveTimeout: 100 * time.Millisecond,
|
||
KeepaliveMaxMiss: 2,
|
||
ReconnectBackoff: []time.Duration{50 * time.Millisecond, 100 * time.Millisecond},
|
||
})
|
||
}
|
||
|
||
// newRStandWith uses o (keepalive, backoff); zero values are the pool
|
||
// defaults (15 s keepalive).
|
||
func newRStandWith(t *testing.T, o conn.PoolOptions) *rstand {
|
||
t.Helper()
|
||
home := sshtest.IsolatedHome(t)
|
||
s := &rstand{t: t, srv: sshtest.Start(t, sshtest.Options{}), kh: filepath.Join(home, ".ssh", "known_hosts")}
|
||
s.trust(s.srv.Addr)
|
||
o.DialOptions = conn.DialOptions{Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh}}
|
||
s.pool = conn.NewPool(o)
|
||
t.Cleanup(func() { s.pool.Close() })
|
||
return s
|
||
}
|
||
|
||
func (s *rstand) trust(addr string) {
|
||
s.t.Helper()
|
||
f, err := os.OpenFile(s.kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||
if err != nil {
|
||
s.t.Fatal(err)
|
||
}
|
||
defer f.Close()
|
||
for _, k := range s.srv.HostKeys {
|
||
if _, err := f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(addr)}, k.PublicKey()) + "\n"); err != nil {
|
||
s.t.Fatal(err)
|
||
}
|
||
}
|
||
}
|
||
|
||
func (s *rstand) proxy() *sshtest.Proxy {
|
||
px := sshtest.NewProxy(s.t, s.srv.Addr)
|
||
s.trust(px.Addr)
|
||
return px
|
||
}
|
||
|
||
// fs connects as user ("" = "u") to addr ("" = the server itself).
|
||
func (s *rstand) fs(addr, user string) *sftpfs.FS {
|
||
s.t.Helper()
|
||
if addr == "" {
|
||
addr = s.srv.Addr
|
||
}
|
||
if user == "" {
|
||
user = "u"
|
||
}
|
||
host, port, _ := net.SplitHostPort(addr)
|
||
p, _ := strconv.Atoi(port)
|
||
l, err := s.pool.Acquire(context.Background(), conn.Endpoint{
|
||
Alias: "alias-" + port, User: user, Host: host, Port: p, Password: s.srv.Password,
|
||
})
|
||
if err != nil {
|
||
s.t.Fatalf("acquire: %v", err)
|
||
}
|
||
f := sftpfs.New(l)
|
||
s.t.Cleanup(f.Release)
|
||
return f
|
||
}
|
||
|
||
func prepare(t *testing.T, r Request) *Plan {
|
||
t.Helper()
|
||
plan, err := Prepare(bg, r, nil)
|
||
if err != nil {
|
||
t.Fatalf("Prepare: %v", err)
|
||
}
|
||
return plan
|
||
}
|
||
|
||
// partFiles lists .vcom-part-* / .vcom-old-* names directly in dir.
|
||
func partFiles(t *testing.T, dir string) []string {
|
||
t.Helper()
|
||
ents, err := os.ReadDir(dir)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
var out []string
|
||
for _, e := range ents {
|
||
if n := e.Name(); len(n) > len(partPrefix) && (n[:len(partPrefix)] == partPrefix || n[:len(oldPrefix)] == oldPrefix) {
|
||
out = append(out, n)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
// Ported from the testbed (B8), N-P0-4: the connection is cut in the middle
|
||
// of overwriting a remote file. The old file must survive, and nothing
|
||
// partial may sit under its name.
|
||
func TestOverwriteThenDrop(t *testing.T) {
|
||
s := newRStand(t)
|
||
px := s.proxy()
|
||
remote := s.fs(px.Addr, "")
|
||
dir := t.TempDir()
|
||
dst := filepath.Join(dir, "important.db")
|
||
old := sshtest.WriteRandom(t, dst, 2<<20, 0o644)
|
||
srcDir := t.TempDir()
|
||
sshtest.WriteRandom(t, filepath.Join(srcDir, "important.db"), 8<<20, 0o644)
|
||
|
||
plan := prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite))
|
||
px.CutAfter(1 << 20)
|
||
rep := Execute(bg, plan, Hooks{})
|
||
if rep.Failed != 1 || rep.Done != 0 {
|
||
t.Fatalf("report = %+v", rep)
|
||
}
|
||
if !errors.Is(rep.Errors[0].Err, vfs.ErrConnLost) {
|
||
t.Errorf("item error = %v, want ErrConnLost", rep.Errors[0].Err)
|
||
}
|
||
now, err := os.ReadFile(dst)
|
||
if err != nil || !bytes.Equal(now, old) {
|
||
t.Fatalf("old destination damaged: %d bytes, err %v", len(now), err)
|
||
}
|
||
// The temp file cannot be removed over a dead connection; the next plan
|
||
// for this directory must report it.
|
||
parts := partFiles(t, dir)
|
||
if len(parts) != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], parts[0]) {
|
||
t.Fatalf("temp after the cut: %v; the report must name it: %v", parts, rep.Warnings)
|
||
}
|
||
if err := s.pool.Reconnect(bg, remote.Conn().Key()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
plan = prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite))
|
||
for _, p := range parts {
|
||
found := false
|
||
for _, w := range plan.Warnings {
|
||
found = found || strings.Contains(w, p)
|
||
}
|
||
if !found {
|
||
t.Errorf("leftover %s not reported by Prepare: %v", p, plan.Warnings)
|
||
}
|
||
}
|
||
rep = Execute(bg, plan, Hooks{})
|
||
if rep.Done != 1 {
|
||
t.Fatalf("copy after reconnect: %+v", rep)
|
||
}
|
||
if now, _ := os.ReadFile(dst); len(now) != 8<<20 {
|
||
t.Errorf("after retry: %d bytes", len(now))
|
||
}
|
||
}
|
||
|
||
// The same cut, but the caller answers the error with reconnect + Retry
|
||
// inside one Execute: the temp of the failed attempt is removed on the new
|
||
// connection, nothing is left behind.
|
||
func TestOverwriteThenDropRetryLeavesNoTemp(t *testing.T) {
|
||
s := newRStand(t)
|
||
px := s.proxy()
|
||
remote := s.fs(px.Addr, "")
|
||
dir := t.TempDir()
|
||
dst := filepath.Join(dir, "important.db")
|
||
sshtest.WriteRandom(t, dst, 2<<20, 0o644)
|
||
srcDir := t.TempDir()
|
||
want := sshtest.WriteRandom(t, filepath.Join(srcDir, "important.db"), 8<<20, 0o644)
|
||
|
||
plan := prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite))
|
||
px.CutAfter(1 << 20)
|
||
retries := 0
|
||
rep := Execute(bg, plan, Hooks{OnError: func(ctx context.Context, e ItemError) (ErrorAction, error) {
|
||
if !errors.Is(e.Err, vfs.ErrConnLost) || retries > 0 {
|
||
return ErrorStop, nil
|
||
}
|
||
retries++
|
||
if err := s.pool.Reconnect(ctx, remote.Conn().Key()); err != nil {
|
||
return ErrorStop, err
|
||
}
|
||
return ErrorRetry, nil
|
||
}})
|
||
if rep.Done != 1 || rep.Failed != 0 || retries != 1 {
|
||
t.Fatalf("report = %+v, retries %d", rep, retries)
|
||
}
|
||
if now, _ := os.ReadFile(dst); !bytes.Equal(now, want) {
|
||
t.Fatalf("target after retry: %d bytes", len(now))
|
||
}
|
||
if parts := partFiles(t, dir); len(parts) != 0 {
|
||
t.Fatalf("temp files left after a successful retry: %v", parts)
|
||
}
|
||
if len(rep.Warnings) != 0 {
|
||
t.Fatalf("warnings %v", rep.Warnings)
|
||
}
|
||
}
|
||
|
||
// Ported from TestSameFileViaAliasTruncates (B4), N-P0-5: the same file
|
||
// through two aliases of one server was truncated to zero.
|
||
func TestSameFileViaAliasRejected(t *testing.T) {
|
||
s := newRStand(t)
|
||
a := s.fs("", "")
|
||
b := s.fs(s.proxy().Addr, "")
|
||
if a.Conn() == b.Conn() {
|
||
t.Fatal("test needs two connections")
|
||
}
|
||
dir := t.TempDir()
|
||
f := filepath.Join(dir, "data.bin")
|
||
data := sshtest.WriteRandom(t, f, 1<<20, 0o644)
|
||
|
||
_, err := Prepare(bg, req(Copy, a, []string{f}, b, dir, overwrite), nil)
|
||
if !errors.Is(err, ErrSameFile) {
|
||
t.Fatalf("Prepare = %v, want ErrSameFile", err)
|
||
}
|
||
|
||
// Even if the check is bypassed, the write goes to a temp file and the
|
||
// rename replaces the file only with complete content.
|
||
other := t.TempDir()
|
||
plan := prepare(t, req(Copy, a, []string{f}, b, other, overwrite))
|
||
plan.Req.ToDir = dir
|
||
fi, err := b.Lstat(bg, f)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
plan.Items[0].Existing = &fi
|
||
rep := Execute(bg, plan, Hooks{})
|
||
if rep.Done != 1 {
|
||
t.Fatalf("report = %+v", rep)
|
||
}
|
||
if now, _ := os.ReadFile(f); !bytes.Equal(now, data) {
|
||
t.Fatalf("file damaged: %d bytes", len(now))
|
||
}
|
||
noLeftovers(t, dir)
|
||
}
|
||
|
||
func brokenLinkTree(t *testing.T, root string) {
|
||
t.Helper()
|
||
sshtest.WriteRandom(t, filepath.Join(root, "a.txt"), 10, 0o644)
|
||
sshtest.WriteRandom(t, filepath.Join(root, "z_after.txt"), 10, 0o644)
|
||
if err := os.Symlink("/nonexistent/zzz", filepath.Join(root, "broken")); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := os.Symlink(".", filepath.Join(root, "loopdir")); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
}
|
||
|
||
func checkBrokenLinkCopy(t *testing.T, rep Report, dst string) {
|
||
t.Helper()
|
||
if rep.Failed != 0 || rep.Err != nil || rep.Done != 4 {
|
||
t.Fatalf("report = %+v", rep)
|
||
}
|
||
for _, n := range []string{"a.txt", "z_after.txt"} {
|
||
if _, err := os.Stat(filepath.Join(dst, n)); err != nil {
|
||
t.Errorf("%s missing: %v", n, err)
|
||
}
|
||
}
|
||
for n, want := range map[string]string{"broken": "/nonexistent/zzz", "loopdir": "."} {
|
||
if got, err := os.Readlink(filepath.Join(dst, n)); err != nil || got != want {
|
||
t.Errorf("%s -> %q (%v), want link to %q", n, got, err, want)
|
||
}
|
||
}
|
||
noLeftovers(t, dst)
|
||
}
|
||
|
||
// Ported (B2), N-P1-8: a broken symlink aborted a directory upload.
|
||
func TestUploadDirWithBrokenSymlink(t *testing.T) {
|
||
s := newRStand(t)
|
||
remote := s.fs("", "")
|
||
src := filepath.Join(t.TempDir(), "src")
|
||
brokenLinkTree(t, src)
|
||
dst := t.TempDir()
|
||
rep := Execute(bg, prepare(t, req(Copy, local, []string{src}, remote, dst)), Hooks{})
|
||
checkBrokenLinkCopy(t, rep, filepath.Join(dst, "src"))
|
||
}
|
||
|
||
func TestDownloadDirWithBrokenSymlink(t *testing.T) {
|
||
s := newRStand(t)
|
||
remote := s.fs("", "")
|
||
src := filepath.Join(t.TempDir(), "src")
|
||
brokenLinkTree(t, src)
|
||
dst := t.TempDir()
|
||
rep := Execute(bg, prepare(t, req(Copy, remote, []string{src}, local, dst)), Hooks{})
|
||
checkBrokenLinkCopy(t, rep, filepath.Join(dst, "src"))
|
||
}
|
||
|
||
// Ported from TestPermsMtimeLost (B3), N-P1-9.
|
||
func TestRemotePermsMtimePreserved(t *testing.T) {
|
||
s := newRStand(t)
|
||
remote := s.fs("", "")
|
||
dir := t.TempDir()
|
||
src := filepath.Join(dir, "run.sh")
|
||
sshtest.WriteRandom(t, src, 100, 0o755)
|
||
mt := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
|
||
if err := os.Chtimes(src, mt, mt); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
up, down := t.TempDir(), t.TempDir()
|
||
if rep := Execute(bg, prepare(t, req(Copy, local, []string{src}, remote, up)), Hooks{}); rep.Done != 1 {
|
||
t.Fatalf("upload: %+v", rep)
|
||
}
|
||
if rep := Execute(bg, prepare(t, req(Copy, remote, []string{src}, local, down)), Hooks{}); rep.Done != 1 {
|
||
t.Fatalf("download: %+v", rep)
|
||
}
|
||
for _, p := range []string{filepath.Join(up, "run.sh"), filepath.Join(down, "run.sh")} {
|
||
st, err := os.Stat(p)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if st.Mode().Perm() != 0o755 || !st.ModTime().Equal(mt) {
|
||
t.Errorf("%s: mode %v mtime %v", p, st.Mode().Perm(), st.ModTime())
|
||
}
|
||
}
|
||
}
|
||
|
||
// N-P1-10 / N-P2-3: two users on one host are different connections; a
|
||
// remote→remote copy between them merges into an existing directory (no
|
||
// dst/proj/proj) and a move is copy+delete, not a server-side rename.
|
||
func TestRemoteToRemoteDifferentUsersNotSameConn(t *testing.T) {
|
||
s := newRStand(t)
|
||
alice := s.fs("", "alice")
|
||
bob := s.fs("", "bob")
|
||
if alice.Conn() == bob.Conn() {
|
||
t.Fatal("different users share a connection")
|
||
}
|
||
base := t.TempDir()
|
||
src := filepath.Join(base, "src", "proj")
|
||
sshtest.WriteRandom(t, filepath.Join(src, "new.txt"), 100, 0o644)
|
||
sshtest.WriteRandom(t, filepath.Join(src, "sub", "deep.txt"), 100, 0o644)
|
||
dst := filepath.Join(base, "dst")
|
||
sshtest.WriteRandom(t, filepath.Join(dst, "proj", "keep.txt"), 10, 0o644)
|
||
|
||
plan := prepare(t, req(Copy, alice, []string{src}, bob, dst))
|
||
if plan.SameConn {
|
||
t.Error("plan.SameConn for different users")
|
||
}
|
||
rep := Execute(bg, plan, Hooks{})
|
||
if rep.Failed != 0 || rep.Done != 2 {
|
||
t.Fatalf("report = %+v", rep)
|
||
}
|
||
for _, p := range []string{"proj/new.txt", "proj/sub/deep.txt", "proj/keep.txt"} {
|
||
if _, err := os.Stat(filepath.Join(dst, p)); err != nil {
|
||
t.Errorf("%s: %v", p, err)
|
||
}
|
||
}
|
||
if _, err := os.Stat(filepath.Join(dst, "proj", "proj")); err == nil {
|
||
t.Error("copy nested proj/proj")
|
||
}
|
||
|
||
mv := filepath.Join(base, "dst2")
|
||
if err := os.Mkdir(mv, 0o755); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
rep = Execute(bg, prepare(t, req(Move, alice, []string{src}, bob, mv)), Hooks{})
|
||
if rep.Failed != 0 || rep.Done != 2 {
|
||
t.Fatalf("move report = %+v", rep)
|
||
}
|
||
if _, err := os.Lstat(src); !os.IsNotExist(err) {
|
||
t.Errorf("move left the source: %v", err)
|
||
}
|
||
if _, err := os.Stat(filepath.Join(mv, "proj", "sub", "deep.txt")); err != nil {
|
||
t.Errorf("moved content missing: %v", err)
|
||
}
|
||
}
|
||
|
||
// N-P1-2: a cut connection surfaces as ErrConnLost; the caller reconnects
|
||
// and retries, and the copy completes.
|
||
func TestConnLostAsksRetry(t *testing.T) {
|
||
s := newRStand(t)
|
||
px := s.proxy()
|
||
remote := s.fs(px.Addr, "")
|
||
srcDir := t.TempDir()
|
||
data := sshtest.WriteRandom(t, filepath.Join(srcDir, "big.bin"), 4<<20, 0o644)
|
||
dst := t.TempDir()
|
||
plan := prepare(t, req(Copy, local, join(srcDir, "big.bin"), remote, dst))
|
||
px.CutAfter(512 << 10)
|
||
var asked atomic.Int32
|
||
rep := Execute(bg, plan, Hooks{OnError: func(ctx context.Context, e ItemError) (ErrorAction, error) {
|
||
asked.Add(1)
|
||
if !errors.Is(e.Err, vfs.ErrConnLost) {
|
||
t.Errorf("OnError got %v, want ErrConnLost", e.Err)
|
||
return ErrorStop, nil
|
||
}
|
||
if err := s.pool.Reconnect(ctx, remote.Conn().Key()); err != nil {
|
||
t.Errorf("reconnect: %v", err)
|
||
return ErrorStop, nil
|
||
}
|
||
return ErrorRetry, nil
|
||
}})
|
||
if rep.Done != 1 || rep.Failed != 0 || asked.Load() != 1 {
|
||
t.Fatalf("report = %+v, asked %d", rep, asked.Load())
|
||
}
|
||
if got, _ := os.ReadFile(filepath.Join(dst, "big.bin")); !bytes.Equal(got, data) {
|
||
t.Fatal("content mismatch after retry")
|
||
}
|
||
if remote.Conn().Gen() != 2 {
|
||
t.Errorf("gen = %d", remote.Conn().Gen())
|
||
}
|
||
}
|
||
|
||
// Cancelling in the middle of an upload over a live link returns promptly,
|
||
// keeps the old target and removes the temp file (N-P1-7).
|
||
func TestRemoteCancelMidFile(t *testing.T) {
|
||
s := newRStand(t)
|
||
px := s.proxy()
|
||
px.SetDelay(5 * time.Millisecond)
|
||
remote := s.fs(px.Addr, "")
|
||
dir := t.TempDir()
|
||
old := sshtest.WriteRandom(t, filepath.Join(dir, "f.bin"), 1<<20, 0o644)
|
||
srcDir := t.TempDir()
|
||
sshtest.WriteRandom(t, filepath.Join(srcDir, "f.bin"), 32<<20, 0o644)
|
||
plan := prepare(t, req(Copy, local, join(srcDir, "f.bin"), remote, dir, overwrite))
|
||
ctx, cancel := context.WithCancel(bg)
|
||
defer cancel()
|
||
var once sync.Once
|
||
var cancelled time.Time
|
||
rep := Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
|
||
if p.CurrentDone > 2<<20 {
|
||
once.Do(func() { cancelled = time.Now(); cancel() })
|
||
}
|
||
}})
|
||
if cancelled.IsZero() {
|
||
t.Fatal("never cancelled")
|
||
}
|
||
if el := time.Since(cancelled); el > time.Second {
|
||
t.Errorf("Execute returned %v after cancel", el)
|
||
}
|
||
if !rep.Cancelled || rep.Done != 0 {
|
||
t.Errorf("report = %+v", rep)
|
||
}
|
||
if now, _ := os.ReadFile(filepath.Join(dir, "f.bin")); !bytes.Equal(now, old) {
|
||
t.Fatal("old target damaged")
|
||
}
|
||
noLeftovers(t, dir)
|
||
}
|
||
|
||
// A link that freezes in the middle of a file (Wi-Fi gone): cancelling
|
||
// returns once the pool notices the dead link (fast keepalive here), with
|
||
// the old target intact.
|
||
func TestRemoteFreezeMidFileThenCancel(t *testing.T) {
|
||
s := newRStand(t)
|
||
px := s.proxy()
|
||
remote := s.fs(px.Addr, "")
|
||
dir := t.TempDir()
|
||
old := sshtest.WriteRandom(t, filepath.Join(dir, "f.bin"), 1<<20, 0o644)
|
||
srcDir := t.TempDir()
|
||
sshtest.WriteRandom(t, filepath.Join(srcDir, "f.bin"), 16<<20, 0o644)
|
||
plan := prepare(t, req(Copy, local, join(srcDir, "f.bin"), remote, dir, overwrite))
|
||
ctx, cancel := context.WithCancel(bg)
|
||
defer cancel()
|
||
var once sync.Once
|
||
var cancelled time.Time
|
||
var mu sync.Mutex
|
||
done := make(chan Report, 1)
|
||
go func() {
|
||
done <- Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
|
||
if p.CurrentDone > 1<<20 {
|
||
once.Do(func() {
|
||
px.Freeze(true)
|
||
time.AfterFunc(50*time.Millisecond, func() {
|
||
mu.Lock()
|
||
cancelled = time.Now()
|
||
mu.Unlock()
|
||
cancel()
|
||
})
|
||
})
|
||
}
|
||
}})
|
||
}()
|
||
var rep Report
|
||
select {
|
||
case rep = <-done:
|
||
case <-time.After(5 * time.Second):
|
||
t.Fatal("Execute hung on a frozen link after cancel")
|
||
}
|
||
px.Freeze(false)
|
||
mu.Lock()
|
||
el := time.Since(cancelled)
|
||
mu.Unlock()
|
||
t.Logf("returned %v after cancel", el)
|
||
if el > 2*time.Second {
|
||
t.Errorf("returned %v after cancel", el)
|
||
}
|
||
if rep.Done != 0 || !(rep.Cancelled || rep.Failed == 1) {
|
||
t.Errorf("report = %+v", rep)
|
||
}
|
||
if now, _ := os.ReadFile(filepath.Join(dir, "f.bin")); !bytes.Equal(now, old) {
|
||
t.Fatal("old target damaged")
|
||
}
|
||
}
|
||
|
||
// freezeCancel runs plan, freezes px once the current file passed 1 MiB and
|
||
// cancels 50 ms later; it returns the report and the time from cancel to
|
||
// return.
|
||
func freezeCancel(t *testing.T, px *sshtest.Proxy, plan *Plan) (Report, time.Duration) {
|
||
t.Helper()
|
||
ctx, cancel := context.WithCancel(bg)
|
||
defer cancel()
|
||
var once sync.Once
|
||
var mu sync.Mutex
|
||
var cancelled time.Time
|
||
done := make(chan Report, 1)
|
||
go func() {
|
||
done <- Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
|
||
if p.CurrentDone > 1<<20 {
|
||
once.Do(func() {
|
||
px.Freeze(true)
|
||
time.AfterFunc(50*time.Millisecond, func() {
|
||
mu.Lock()
|
||
cancelled = time.Now()
|
||
mu.Unlock()
|
||
cancel()
|
||
})
|
||
})
|
||
}
|
||
}})
|
||
}()
|
||
var rep Report
|
||
select {
|
||
case rep = <-done:
|
||
case <-time.After(20 * time.Second):
|
||
t.Fatal("Execute hung after cancel on a frozen link")
|
||
}
|
||
mu.Lock()
|
||
defer mu.Unlock()
|
||
if cancelled.IsZero() {
|
||
t.Fatal("never cancelled")
|
||
}
|
||
return rep, time.Since(cancelled)
|
||
}
|
||
|
||
// With the DEFAULT keepalive (15 s × 2 + 10 s) a cancel on a link frozen in
|
||
// the middle of a file must return within 3 s: the sftpfs cancel watchdog
|
||
// probes the link and tears it down. Upload and download.
|
||
func TestRemoteFreezeCancelDefaultKeepalive(t *testing.T) {
|
||
for _, dir := range []string{"upload", "download"} {
|
||
t.Run(dir, func(t *testing.T) {
|
||
s := newRStandWith(t, conn.PoolOptions{})
|
||
px := s.proxy()
|
||
remote := s.fs(px.Addr, "")
|
||
src, dst := t.TempDir(), t.TempDir()
|
||
sshtest.WriteRandom(t, filepath.Join(src, "f.bin"), 32<<20, 0o644)
|
||
old := sshtest.WriteRandom(t, filepath.Join(dst, "f.bin"), 1<<20, 0o644)
|
||
from, to := vfs.FS(local), vfs.FS(remote)
|
||
if dir == "download" {
|
||
from, to = remote, local
|
||
}
|
||
px.SetDelay(2 * time.Millisecond) // keep the copy in flight long enough to freeze it
|
||
plan := prepare(t, req(Copy, from, join(src, "f.bin"), to, dst, overwrite))
|
||
rep, el := freezeCancel(t, px, plan)
|
||
px.Freeze(false)
|
||
t.Logf("%s: returned %v after cancel, report %+v", dir, el, rep)
|
||
if el > 3*time.Second {
|
||
t.Errorf("returned %v after cancel, want <= 3s", el)
|
||
}
|
||
if rep.Done != 0 {
|
||
t.Errorf("report = %+v", rep)
|
||
}
|
||
if now, _ := os.ReadFile(filepath.Join(dst, "f.bin")); !bytes.Equal(now, old) {
|
||
t.Fatal("old target damaged")
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// A slow but live link is not torn down by a cancel: the probe answers.
|
||
func TestRemoteSlowLinkCancelKeepsConn(t *testing.T) {
|
||
s := newRStandWith(t, conn.PoolOptions{})
|
||
px := s.proxy()
|
||
remote := s.fs(px.Addr, "")
|
||
src, dst := t.TempDir(), t.TempDir()
|
||
sshtest.WriteRandom(t, filepath.Join(src, "f.bin"), 8<<20, 0o644)
|
||
px.SetDelay(150 * time.Millisecond) // RTT ≈ 300 ms
|
||
plan := prepare(t, req(Copy, local, join(src, "f.bin"), remote, dst))
|
||
ctx, cancel := context.WithCancel(bg)
|
||
defer cancel()
|
||
var once sync.Once
|
||
rep := Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
|
||
if p.CurrentDone > 1<<20 {
|
||
once.Do(cancel)
|
||
}
|
||
}})
|
||
if !rep.Cancelled {
|
||
t.Errorf("report = %+v", rep)
|
||
}
|
||
time.Sleep(cancelWatchdogSettle)
|
||
if st := remote.Conn().State(); st != conn.Ready {
|
||
t.Fatalf("slow but live link torn down by cancel: state %v (%v)", st, remote.Conn().Err())
|
||
}
|
||
if _, err := remote.Stat(bg, dst); err != nil {
|
||
t.Fatalf("conn unusable after cancel: %v", err)
|
||
}
|
||
noLeftovers(t, dst)
|
||
}
|
||
|
||
// cancelWatchdogSettle covers sftpfs' cancel grace + probe timeout.
|
||
const cancelWatchdogSettle = 3 * time.Second
|