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"
24 "github.com/stretchr/testify/assert"
25 "github.com/stretchr/testify/require"
28 type testClientTransferParams struct {
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
40 LeecherStartsWithoutMetadata bool
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)
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) {
54 prevGOMAXPROCS := runtime.GOMAXPROCS(ps.GOMAXPROCS)
55 newGOMAXPROCS := prevGOMAXPROCS
56 if ps.GOMAXPROCS > 0 {
57 newGOMAXPROCS = ps.GOMAXPROCS
60 quicktest.Check(t, runtime.GOMAXPROCS(prevGOMAXPROCS), quicktest.ContentEquals, newGOMAXPROCS)
63 greetingTempDir, mi := testutil.GreetingTestTorrent()
64 defer os.RemoveAll(greetingTempDir)
65 // Create seeder and a Torrent.
66 cfg := torrent.TestingConfig(t)
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
73 // cfg.ListenAddr = "localhost:4000"
74 if ps.SeederStorage != nil {
75 storage := ps.SeederStorage(greetingTempDir)
77 cfg.DefaultStorage = storage
79 cfg.DataDir = greetingTempDir
81 if ps.ConfigureSeeder.Config != nil {
82 ps.ConfigureSeeder.Config(cfg)
84 seeder, err := torrent.NewClient(cfg)
85 require.NoError(t, err)
86 if ps.ConfigureSeeder.Client != nil {
87 ps.ConfigureSeeder.Client(seeder)
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()
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
106 storage := ps.LeecherStorage(leecherDataDir)
107 defer storage.Close()
108 cfg.DefaultStorage = storage
110 if ps.LeecherDownloadRateLimiter != nil {
111 cfg.DownloadRateLimiter = ps.LeecherDownloadRateLimiter
115 if ps.ConfigureLeecher.Config != nil {
116 ps.ConfigureLeecher.Config(cfg)
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)
124 defer testutil.ExportStatusWriter(leecher, "l", t)()
125 leecherTorrent, new, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
126 ret = torrent.TorrentSpecFromMetaInfo(mi)
128 if ps.LeecherStartsWithoutMetadata {
133 require.NoError(t, err)
136 //// This was used when observing coalescing of piece state changes.
137 //logPieceStateChanges(leecherTorrent)
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)
147 if ps.LeecherStartsWithoutMetadata {
148 <-leecherTorrent.GotInfo()
150 r := leecherTorrent.NewReader()
152 go leecherTorrent.SetInfoBytes(mi.InfoBytes)
157 r.SetReadahead(ps.Readahead)
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)
166 assert.NotEmpty(t, leecherPeerConns)
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()) {
177 t.Errorf("didn't find seeder amongst leecher peer conns")
180 seederStats := seederTorrent.Stats()
181 assert.True(t, 13 <= seederStats.BytesWrittenData.Int64())
182 assert.True(t, 8 <= seederStats.ChunksWritten.Int64())
184 leecherStats := leecherTorrent.Stats()
185 assert.True(t, 13 <= leecherStats.BytesReadData.Int64())
186 assert.True(t, 8 <= leecherStats.ChunksRead.Int64())
188 // Try reading through again for the cases where the torrent data size
189 // exceeds the size of the cache.
190 assertReadAllGreeting(t, r)
193 type fileCacheClientStorageFactoryParams struct {
198 func newFileCacheClientStorageFactory(ps fileCacheClientStorageFactoryParams) storageFactory {
199 return func(dataDir string) storage.ClientImplCloser {
200 fc, err := filecache.NewCache(dataDir)
204 var sharedCapacity *int64
206 sharedCapacity = &ps.Capacity
207 fc.SetCapacity(ps.Capacity)
213 storage.NewResourcePiecesOpts(
214 fc.AsResourceProvider(),
215 storage.ResourcePiecesOpts{
216 Capacity: sharedCapacity,
218 ioutil.NopCloser(nil),
223 type storageFactory func(string) storage.ClientImplCloser
225 func TestClientTransferDefault(t *testing.T) {
226 testClientTransfer(t, testClientTransferParams{
227 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{}),
231 func TestClientTransferDefaultNoMetadata(t *testing.T) {
232 testClientTransfer(t, testClientTransferParams{
233 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{}),
234 LeecherStartsWithoutMetadata: true,
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),
246 require.True(t, time.Since(started) > time.Second)
249 func TestClientTransferRateLimitedDownload(t *testing.T) {
250 testClientTransfer(t, testClientTransferParams{
251 LeecherDownloadRateLimiter: rate.NewLimiter(512, 512),
255 func testClientTransferSmallCache(t *testing.T, setReadahead bool, readahead int64) {
256 testClientTransfer(t, testClientTransferParams{
257 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
259 // Going below the piece length means it can't complete a piece so
260 // that it can be hashed.
263 SetReadahead: setReadahead,
264 // Can't readahead too far or the cache will thrash and drop data we
266 Readahead: readahead,
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
279 func TestClientTransferSmallCachePieceSizedReadahead(t *testing.T) {
280 testClientTransferSmallCache(t, true, 5)
283 func TestClientTransferSmallCacheLargeReadahead(t *testing.T) {
284 testClientTransferSmallCache(t, true, 15)
287 func TestClientTransferSmallCacheDefaultReadahead(t *testing.T) {
288 testClientTransferSmallCache(t, false, -1)
291 func sqliteClientStorageFactory(optsMaker func(dataDir string) sqliteStorage.NewPiecesStorageOpts) storageFactory {
292 return func(dataDir string) storage.ClientImplCloser {
293 opts := optsMaker(dataDir)
294 //log.Printf("opening sqlite db: %#v", opts)
295 ret, err := sqliteStorage.NewPiecesStorage(opts)
303 type leecherStorageTestCase struct {
309 func sqliteLeecherStorageTestCase(numConns int) leecherStorageTestCase {
310 return leecherStorageTestCase{
311 fmt.Sprintf("SqliteFile,NumConns=%v", numConns),
312 sqliteClientStorageFactory(func(dataDir string) (opts sqliteStorage.NewPiecesStorageOpts) {
313 opts.Path = filepath.Join(dataDir, "sqlite.db")
314 opts.NumConns = numConns
321 func TestClientTransferVarious(t *testing.T) {
323 for _, ls := range []leecherStorageTestCase{
324 {"Filecache", newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{}), 0},
325 {"Boltdb", storage.NewBoltDB, 0},
326 {"SqliteDirect", func(s string) storage.ClientImplCloser {
327 path := filepath.Join(s, "sqlite3.db")
328 var opts sqliteStorage.NewDirectStorageOpts
330 cl, err := sqliteStorage.NewDirectStorage(opts)
336 sqliteLeecherStorageTestCase(1),
337 sqliteLeecherStorageTestCase(2),
338 // This should use a number of connections equal to the number of CPUs
339 sqliteLeecherStorageTestCase(0),
340 {"SqliteMemory", sqliteClientStorageFactory(func(dataDir string) (opts sqliteStorage.NewPiecesStorageOpts) {
345 t.Run(fmt.Sprintf("LeecherStorage=%s", ls.name), func(t *testing.T) {
347 for _, ss := range []struct {
351 {"File", storage.NewFile},
352 {"Mmap", storage.NewMMap},
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,
361 LeecherStorage: ls.f,
362 GOMAXPROCS: ls.gomaxprocs,
365 for _, readahead := range []int64{-1, 0, 1, 2, 9, 20} {
366 t.Run(fmt.Sprintf("readahead=%v", readahead), func(t *testing.T) {
367 testClientTransfer(t, testClientTransferParams{
369 Responsive: responsive,
371 Readahead: readahead,
372 LeecherStorage: ls.f,
373 GOMAXPROCS: ls.gomaxprocs,
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)
391 cfg := torrent.TestingConfig(t)
393 cfg.DataDir = greetingTempDir
394 seeder, err := torrent.NewClient(cfg)
395 require.NoError(t, err)
397 defer testutil.ExportStatusWriter(seeder, "s", t)()
398 seederTorrent, ok, err := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi))
399 require.NoError(t, err)
401 seederTorrent.VerifyData()
403 cfg = torrent.TestingConfig(t)
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)()
413 cfg = torrent.TestingConfig(t)
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)
427 require.NoError(t, err)
429 llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
430 ret = torrent.TorrentSpecFromMetaInfo(mi)
434 require.NoError(t, err)
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
445 quicktest.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), quicktest.IsNil)
447 done := make(chan struct{})
449 go leecherGreeting.AddClientPeer(seeder)
450 go leecherGreeting.AddClientPeer(leecherLeecher)
454 leecherGreeting.DownloadAll()
460 type ConfigureClient struct {
461 Config func(*torrent.ClientConfig)
462 Client func(*torrent.Client)