Debian Codegraph @

sftp_test.go

raw
1 package desync
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "net/url"
8 "os"
9 "runtime"
10 "testing"
11 "time"
12
13 "github.com/pkg/sftp"
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
16 )
17
18 // stdioServerConn adapts the process's stdin/stdout to the ReadWriteCloser
19 // the sftp server operates on.
20 type stdioServerConn struct {
21 io.Reader
22 io.WriteCloser
23 }
24
25 // TestMain doubles as the fake ssh command for the SFTP store tests. The
26 // store shells out to ssh for the sftp subsystem, so tests point
27 // CASYNC_SSH_PATH at the test binary itself and set an environment variable
28 // that makes it serve the SFTP protocol on stdin/stdout instead of running
29 // the tests.
30 func TestMain(m *testing.M) {
31 if os.Getenv("DESYNC_SFTP_TEST_SERVER") == "1" {
32 server, err := sftp.NewServer(stdioServerConn{os.Stdin, os.Stdout})
33 if err != nil {
34 fmt.Fprintln(os.Stderr, err)
35 os.Exit(1)
36 }
37 if err := server.Serve(); err != nil && err != io.EOF {
38 fmt.Fprintln(os.Stderr, err)
39 os.Exit(1)
40 }
41 os.Exit(0)
42 }
43 os.Exit(m.Run())
44 }
45
46 func TestSFTPStorePruneSingleConnection(t *testing.T) {
47 if runtime.GOOS == "windows" {
48 t.Skip("the test sftp server serves the local filesystem, which the store cannot address on windows")
49 }
50 t.Setenv("CASYNC_SSH_PATH", os.Args[0])
51 t.Setenv("DESYNC_SFTP_TEST_SERVER", "1")
52
53 u, err := url.Parse("sftp://localhost" + t.TempDir())
54 require.NoError(t, err)
55
56 s, err := NewSFTPStore(u, StoreOptions{N: 1})
57 require.NoError(t, err)
58 defer s.Close()
59
60 keep := NewChunk([]byte("chunk to keep"))
61 prune := NewChunk([]byte("chunk to prune"))
62 keepID := keep.ID()
63 pruneID := prune.ID()
64 require.NoError(t, s.StoreChunk(keep))
65 require.NoError(t, s.StoreChunk(prune))
66
67 // Prune with a pool of just one connection. This deadlocked when the
68 // removal of a chunk waited for a second connection while the prune
69 // held the only one.
70 done := make(chan error)
71 go func() {
72 done <- s.Prune(context.Background(), map[ChunkID]struct{}{keepID: {}})
73 }()
74 select {
75 case err := <-done:
76 require.NoError(t, err)
77 case <-time.After(time.Minute):
78 t.Fatal("prune deadlocked with a single connection")
79 }
80
81 hasKeep, err := s.HasChunk(keepID)
82 require.NoError(t, err)
83 assert.True(t, hasKeep, "chunk in the keep list was removed")
84 hasPrune, err := s.HasChunk(pruneID)
85 require.NoError(t, err)
86 assert.False(t, hasPrune, "unreferenced chunk was not removed")
87 }