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