]> Sergey Matveev's repositories - btrtrc.git/blob - test/transfer_test.go
Replace internal/tmproot with Testing.TB.TempDir
[btrtrc.git] / test / transfer_test.go
1 package test
2
3 import (
4         "fmt"
5         "io"
6         "io/ioutil"
7         "os"
8         "path/filepath"
9         "runtime"
10         "sync"
11         "testing"
12         "testing/iotest"
13         "time"
14
15         "github.com/anacrolix/missinggo/v2/filecache"
16         "github.com/anacrolix/torrent"
17         "github.com/anacrolix/torrent/internal/testutil"
18         "github.com/anacrolix/torrent/storage"
19         sqliteStorage "github.com/anacrolix/torrent/storage/sqlite"
20         "github.com/frankban/quicktest"
21         "golang.org/x/time/rate"
22
23         "github.com/stretchr/testify/assert"
24         "github.com/stretchr/testify/require"
25 )
26
27 type testClientTransferParams struct {
28         Responsive                 bool
29         Readahead                  int64
30         SetReadahead               bool
31         LeecherStorage             func(string) storage.ClientImplCloser
32         SeederStorage              func(string) storage.ClientImplCloser
33         SeederUploadRateLimiter    *rate.Limiter
34         LeecherDownloadRateLimiter *rate.Limiter
35         ConfigureSeeder            ConfigureClient
36         ConfigureLeecher           ConfigureClient
37         GOMAXPROCS                 int
38
39         LeecherStartsWithoutMetadata bool
40 }
41
42 func assertReadAllGreeting(t *testing.T, r io.ReadSeeker) {
43         pos, err := r.Seek(0, io.SeekStart)
44         assert.NoError(t, err)
45         assert.EqualValues(t, 0, pos)
46         quicktest.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), quicktest.IsNil)
47 }
48
49 // Creates a seeder and a leecher, and ensures the data transfers when a read
50 // is attempted on the leecher.
51 func testClientTransfer(t *testing.T, ps testClientTransferParams) {
52
53         prevGOMAXPROCS := runtime.GOMAXPROCS(ps.GOMAXPROCS)
54         newGOMAXPROCS := prevGOMAXPROCS
55         if ps.GOMAXPROCS > 0 {
56                 newGOMAXPROCS = ps.GOMAXPROCS
57         }
58         defer func() {
59                 quicktest.Check(t, runtime.GOMAXPROCS(prevGOMAXPROCS), quicktest.ContentEquals, newGOMAXPROCS)
60         }()
61
62         greetingTempDir, mi := testutil.GreetingTestTorrent()
63         defer os.RemoveAll(greetingTempDir)
64         // Create seeder and a Torrent.
65         cfg := torrent.TestingConfig(t)
66         cfg.Seed = true
67         // Some test instances don't like this being on, even when there's no cache involved.
68         cfg.DropMutuallyCompletePeers = false
69         if ps.SeederUploadRateLimiter != nil {
70                 cfg.UploadRateLimiter = ps.SeederUploadRateLimiter
71         }
72         // cfg.ListenAddr = "localhost:4000"
73         if ps.SeederStorage != nil {
74                 storage := ps.SeederStorage(greetingTempDir)
75                 defer storage.Close()
76                 cfg.DefaultStorage = storage
77         } else {
78                 cfg.DataDir = greetingTempDir
79         }
80         if ps.ConfigureSeeder.Config != nil {
81                 ps.ConfigureSeeder.Config(cfg)
82         }
83         seeder, err := torrent.NewClient(cfg)
84         require.NoError(t, err)
85         if ps.ConfigureSeeder.Client != nil {
86                 ps.ConfigureSeeder.Client(seeder)
87         }
88         defer testutil.ExportStatusWriter(seeder, "s", t)()
89         seederTorrent, _, _ := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi))
90         // Run a Stats right after Closing the Client. This will trigger the Stats
91         // panic in #214 caused by RemoteAddr on Closed uTP sockets.
92         defer seederTorrent.Stats()
93         defer seeder.Close()
94         seederTorrent.VerifyData()
95         // Create leecher and a Torrent.
96         leecherDataDir, err := ioutil.TempDir("", "")
97         require.NoError(t, err)
98         defer os.RemoveAll(leecherDataDir)
99         cfg = torrent.TestingConfig(t)
100         // See the seeder client config comment.
101         cfg.DropMutuallyCompletePeers = false
102         if ps.LeecherStorage == nil {
103                 cfg.DataDir = leecherDataDir
104         } else {
105                 storage := ps.LeecherStorage(leecherDataDir)
106                 defer storage.Close()
107                 cfg.DefaultStorage = storage
108         }
109         if ps.LeecherDownloadRateLimiter != nil {
110                 cfg.DownloadRateLimiter = ps.LeecherDownloadRateLimiter
111         }
112         cfg.Seed = false
113         if ps.ConfigureLeecher.Config != nil {
114                 ps.ConfigureLeecher.Config(cfg)
115         }
116         leecher, err := torrent.NewClient(cfg)
117         require.NoError(t, err)
118         defer leecher.Close()
119         if ps.ConfigureLeecher.Client != nil {
120                 ps.ConfigureLeecher.Client(leecher)
121         }
122         defer testutil.ExportStatusWriter(leecher, "l", t)()
123         leecherTorrent, new, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
124                 ret = torrent.TorrentSpecFromMetaInfo(mi)
125                 ret.ChunkSize = 2
126                 if ps.LeecherStartsWithoutMetadata {
127                         ret.InfoBytes = nil
128                 }
129                 return
130         }())
131         require.NoError(t, err)
132         assert.True(t, new)
133
134         //// This was used when observing coalescing of piece state changes.
135         //logPieceStateChanges(leecherTorrent)
136
137         // Now do some things with leecher and seeder.
138         added := leecherTorrent.AddClientPeer(seeder)
139         assert.False(t, leecherTorrent.Seeding())
140         // The leecher will use peers immediately if it doesn't have the metadata. Otherwise, they
141         // should be sitting idle until we demand data.
142         if !ps.LeecherStartsWithoutMetadata {
143                 assert.EqualValues(t, added, leecherTorrent.Stats().PendingPeers)
144         }
145         if ps.LeecherStartsWithoutMetadata {
146                 <-leecherTorrent.GotInfo()
147         }
148         r := leecherTorrent.NewReader()
149         defer r.Close()
150         go leecherTorrent.SetInfoBytes(mi.InfoBytes)
151         if ps.Responsive {
152                 r.SetResponsive()
153         }
154         if ps.SetReadahead {
155                 r.SetReadahead(ps.Readahead)
156         }
157         assertReadAllGreeting(t, r)
158         assert.NotEmpty(t, seederTorrent.PeerConns())
159         leecherPeerConns := leecherTorrent.PeerConns()
160         if cfg.DropMutuallyCompletePeers {
161                 // I don't think we can assume it will be empty already, due to timing.
162                 //assert.Empty(t, leecherPeerConns)
163         } else {
164                 assert.NotEmpty(t, leecherPeerConns)
165         }
166         foundSeeder := false
167         for _, pc := range leecherPeerConns {
168                 completed := pc.PeerPieces().Len()
169                 t.Logf("peer conn %v has %v completed pieces", pc, completed)
170                 if completed == leecherTorrent.Info().NumPieces() {
171                         foundSeeder = true
172                 }
173         }
174         if !foundSeeder {
175                 t.Errorf("didn't find seeder amongst leecher peer conns")
176         }
177
178         seederStats := seederTorrent.Stats()
179         assert.True(t, 13 <= seederStats.BytesWrittenData.Int64())
180         assert.True(t, 8 <= seederStats.ChunksWritten.Int64())
181
182         leecherStats := leecherTorrent.Stats()
183         assert.True(t, 13 <= leecherStats.BytesReadData.Int64())
184         assert.True(t, 8 <= leecherStats.ChunksRead.Int64())
185
186         // Try reading through again for the cases where the torrent data size
187         // exceeds the size of the cache.
188         assertReadAllGreeting(t, r)
189 }
190
191 type fileCacheClientStorageFactoryParams struct {
192         Capacity    int64
193         SetCapacity bool
194         Wrapper     func(*filecache.Cache) storage.ClientImplCloser
195 }
196
197 func newFileCacheClientStorageFactory(ps fileCacheClientStorageFactoryParams) storageFactory {
198         return func(dataDir string) storage.ClientImplCloser {
199                 fc, err := filecache.NewCache(dataDir)
200                 if err != nil {
201                         panic(err)
202                 }
203                 if ps.SetCapacity {
204                         fc.SetCapacity(ps.Capacity)
205                 }
206                 return ps.Wrapper(fc)
207         }
208 }
209
210 type storageFactory func(string) storage.ClientImplCloser
211
212 func TestClientTransferDefault(t *testing.T) {
213         testClientTransfer(t, testClientTransferParams{
214                 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
215                         Wrapper: fileCachePieceResourceStorage,
216                 }),
217         })
218 }
219
220 func TestClientTransferDefaultNoMetadata(t *testing.T) {
221         testClientTransfer(t, testClientTransferParams{
222                 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
223                         Wrapper: fileCachePieceResourceStorage,
224                 }),
225                 LeecherStartsWithoutMetadata: true,
226         })
227 }
228
229 func TestClientTransferRateLimitedUpload(t *testing.T) {
230         started := time.Now()
231         testClientTransfer(t, testClientTransferParams{
232                 // We are uploading 13 bytes (the length of the greeting torrent). The
233                 // chunks are 2 bytes in length. Then the smallest burst we can run
234                 // with is 2. Time taken is (13-burst)/rate.
235                 SeederUploadRateLimiter: rate.NewLimiter(11, 2),
236         })
237         require.True(t, time.Since(started) > time.Second)
238 }
239
240 func TestClientTransferRateLimitedDownload(t *testing.T) {
241         testClientTransfer(t, testClientTransferParams{
242                 LeecherDownloadRateLimiter: rate.NewLimiter(512, 512),
243         })
244 }
245
246 func fileCachePieceResourceStorage(fc *filecache.Cache) storage.ClientImplCloser {
247         return struct {
248                 storage.ClientImpl
249                 io.Closer
250         }{
251                 storage.NewResourcePieces(fc.AsResourceProvider()),
252                 ioutil.NopCloser(nil),
253         }
254 }
255
256 func testClientTransferSmallCache(t *testing.T, setReadahead bool, readahead int64) {
257         testClientTransfer(t, testClientTransferParams{
258                 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
259                         SetCapacity: true,
260                         // Going below the piece length means it can't complete a piece so
261                         // that it can be hashed.
262                         Capacity: 5,
263                         Wrapper:  fileCachePieceResourceStorage,
264                 }),
265                 SetReadahead: setReadahead,
266                 // Can't readahead too far or the cache will thrash and drop data we
267                 // thought we had.
268                 Readahead: readahead,
269
270                 // These tests don't work well with more than 1 connection to the seeder.
271                 ConfigureLeecher: ConfigureClient{
272                         Config: func(cfg *torrent.ClientConfig) {
273                                 cfg.DropDuplicatePeerIds = true
274                                 //cfg.DisableIPv6 = true
275                                 //cfg.DisableUTP = true
276                         },
277                 },
278         })
279 }
280
281 func TestClientTransferSmallCachePieceSizedReadahead(t *testing.T) {
282         testClientTransferSmallCache(t, true, 5)
283 }
284
285 func TestClientTransferSmallCacheLargeReadahead(t *testing.T) {
286         testClientTransferSmallCache(t, true, 15)
287 }
288
289 func TestClientTransferSmallCacheDefaultReadahead(t *testing.T) {
290         testClientTransferSmallCache(t, false, -1)
291 }
292
293 func sqliteClientStorageFactory(optsMaker func(dataDir string) sqliteStorage.NewPiecesStorageOpts) storageFactory {
294         return func(dataDir string) storage.ClientImplCloser {
295                 opts := optsMaker(dataDir)
296                 //log.Printf("opening sqlite db: %#v", opts)
297                 ret, err := sqliteStorage.NewPiecesStorage(opts)
298                 if err != nil {
299                         panic(err)
300                 }
301                 return ret
302         }
303 }
304
305 type leecherStorageTestCase struct {
306         name       string
307         f          storageFactory
308         gomaxprocs int
309 }
310
311 func sqliteLeecherStorageTestCase(numConns int) leecherStorageTestCase {
312         return leecherStorageTestCase{
313                 fmt.Sprintf("SqliteFile,NumConns=%v", numConns),
314                 sqliteClientStorageFactory(func(dataDir string) sqliteStorage.NewPiecesStorageOpts {
315                         return sqliteStorage.NewPiecesStorageOpts{
316                                 NewPoolOpts: sqliteStorage.NewPoolOpts{
317                                         Path:     filepath.Join(dataDir, "sqlite.db"),
318                                         NumConns: numConns,
319                                 },
320                         }
321                 }),
322                 numConns,
323         }
324 }
325
326 func TestClientTransferVarious(t *testing.T) {
327         // Leecher storage
328         for _, ls := range []leecherStorageTestCase{
329                 {"Filecache", newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
330                         Wrapper: fileCachePieceResourceStorage,
331                 }), 0},
332                 {"Boltdb", storage.NewBoltDB, 0},
333                 sqliteLeecherStorageTestCase(1),
334                 sqliteLeecherStorageTestCase(2),
335                 // This should use a number of connections equal to the number of CPUs
336                 sqliteLeecherStorageTestCase(0),
337                 {"SqliteMemory", sqliteClientStorageFactory(func(dataDir string) sqliteStorage.NewPiecesStorageOpts {
338                         return sqliteStorage.NewPiecesStorageOpts{
339                                 NewPoolOpts: sqliteStorage.NewPoolOpts{
340                                         Memory: true,
341                                 },
342                         }
343                 }), 0},
344         } {
345                 t.Run(fmt.Sprintf("LeecherStorage=%s", ls.name), func(t *testing.T) {
346                         // Seeder storage
347                         for _, ss := range []struct {
348                                 name string
349                                 f    storageFactory
350                         }{
351                                 {"File", storage.NewFile},
352                                 {"Mmap", storage.NewMMap},
353                         } {
354                                 t.Run(fmt.Sprintf("%sSeederStorage", ss.name), func(t *testing.T) {
355                                         for _, responsive := range []bool{false, true} {
356                                                 t.Run(fmt.Sprintf("Responsive=%v", responsive), func(t *testing.T) {
357                                                         t.Run("NoReadahead", func(t *testing.T) {
358                                                                 testClientTransfer(t, testClientTransferParams{
359                                                                         Responsive:     responsive,
360                                                                         SeederStorage:  ss.f,
361                                                                         LeecherStorage: ls.f,
362                                                                         GOMAXPROCS:     ls.gomaxprocs,
363                                                                 })
364                                                         })
365                                                         for _, readahead := range []int64{-1, 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 20} {
366                                                                 t.Run(fmt.Sprintf("readahead=%v", readahead), func(t *testing.T) {
367                                                                         testClientTransfer(t, testClientTransferParams{
368                                                                                 SeederStorage:  ss.f,
369                                                                                 Responsive:     responsive,
370                                                                                 SetReadahead:   true,
371                                                                                 Readahead:      readahead,
372                                                                                 LeecherStorage: ls.f,
373                                                                                 GOMAXPROCS:     ls.gomaxprocs,
374                                                                         })
375                                                                 })
376                                                         }
377                                                 })
378                                         }
379                                 })
380                         }
381                 })
382         }
383 }
384
385 // Check that after completing leeching, a leecher transitions to a seeding
386 // correctly. Connected in a chain like so: Seeder <-> Leecher <-> LeecherLeecher.
387 func TestSeedAfterDownloading(t *testing.T) {
388         greetingTempDir, mi := testutil.GreetingTestTorrent()
389         defer os.RemoveAll(greetingTempDir)
390
391         cfg := torrent.TestingConfig(t)
392         cfg.Seed = true
393         cfg.DataDir = greetingTempDir
394         seeder, err := torrent.NewClient(cfg)
395         require.NoError(t, err)
396         defer seeder.Close()
397         defer testutil.ExportStatusWriter(seeder, "s", t)()
398         seederTorrent, ok, err := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi))
399         require.NoError(t, err)
400         assert.True(t, ok)
401         seederTorrent.VerifyData()
402
403         cfg = torrent.TestingConfig(t)
404         cfg.Seed = true
405         cfg.DataDir, err = ioutil.TempDir("", "")
406         require.NoError(t, err)
407         defer os.RemoveAll(cfg.DataDir)
408         leecher, err := torrent.NewClient(cfg)
409         require.NoError(t, err)
410         defer leecher.Close()
411         defer testutil.ExportStatusWriter(leecher, "l", t)()
412
413         cfg = torrent.TestingConfig(t)
414         cfg.Seed = false
415         cfg.DataDir, err = ioutil.TempDir("", "")
416         require.NoError(t, err)
417         defer os.RemoveAll(cfg.DataDir)
418         leecherLeecher, _ := torrent.NewClient(cfg)
419         require.NoError(t, err)
420         defer leecherLeecher.Close()
421         defer testutil.ExportStatusWriter(leecherLeecher, "ll", t)()
422         leecherGreeting, ok, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
423                 ret = torrent.TorrentSpecFromMetaInfo(mi)
424                 ret.ChunkSize = 2
425                 return
426         }())
427         require.NoError(t, err)
428         assert.True(t, ok)
429         llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
430                 ret = torrent.TorrentSpecFromMetaInfo(mi)
431                 ret.ChunkSize = 3
432                 return
433         }())
434         require.NoError(t, err)
435         assert.True(t, ok)
436         // Simultaneously DownloadAll in Leecher, and read the contents
437         // consecutively in LeecherLeecher. This non-deterministically triggered a
438         // case where the leecher wouldn't unchoke the LeecherLeecher.
439         var wg sync.WaitGroup
440         wg.Add(1)
441         go func() {
442                 defer wg.Done()
443                 r := llg.NewReader()
444                 defer r.Close()
445                 quicktest.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), quicktest.IsNil)
446         }()
447         done := make(chan struct{})
448         defer close(done)
449         go leecherGreeting.AddClientPeer(seeder)
450         go leecherGreeting.AddClientPeer(leecherLeecher)
451         wg.Add(1)
452         go func() {
453                 defer wg.Done()
454                 leecherGreeting.DownloadAll()
455                 leecher.WaitAll()
456         }()
457         wg.Wait()
458 }
459
460 type ConfigureClient struct {
461         Config func(*torrent.ClientConfig)
462         Client func(*torrent.Client)
463 }