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"
23 "github.com/stretchr/testify/assert"
24 "github.com/stretchr/testify/require"
27 type testClientTransferParams struct {
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
39 LeecherStartsWithoutMetadata bool
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)
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) {
53 prevGOMAXPROCS := runtime.GOMAXPROCS(ps.GOMAXPROCS)
54 newGOMAXPROCS := prevGOMAXPROCS
55 if ps.GOMAXPROCS > 0 {
56 newGOMAXPROCS = ps.GOMAXPROCS
59 quicktest.Check(t, runtime.GOMAXPROCS(prevGOMAXPROCS), quicktest.ContentEquals, newGOMAXPROCS)
62 greetingTempDir, mi := testutil.GreetingTestTorrent()
63 defer os.RemoveAll(greetingTempDir)
64 // Create seeder and a Torrent.
65 cfg := torrent.TestingConfig(t)
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
72 // cfg.ListenAddr = "localhost:4000"
73 if ps.SeederStorage != nil {
74 storage := ps.SeederStorage(greetingTempDir)
76 cfg.DefaultStorage = storage
78 cfg.DataDir = greetingTempDir
80 if ps.ConfigureSeeder.Config != nil {
81 ps.ConfigureSeeder.Config(cfg)
83 seeder, err := torrent.NewClient(cfg)
84 require.NoError(t, err)
85 if ps.ConfigureSeeder.Client != nil {
86 ps.ConfigureSeeder.Client(seeder)
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()
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
105 storage := ps.LeecherStorage(leecherDataDir)
106 defer storage.Close()
107 cfg.DefaultStorage = storage
109 if ps.LeecherDownloadRateLimiter != nil {
110 cfg.DownloadRateLimiter = ps.LeecherDownloadRateLimiter
113 if ps.ConfigureLeecher.Config != nil {
114 ps.ConfigureLeecher.Config(cfg)
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)
122 defer testutil.ExportStatusWriter(leecher, "l", t)()
123 leecherTorrent, new, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
124 ret = torrent.TorrentSpecFromMetaInfo(mi)
126 if ps.LeecherStartsWithoutMetadata {
131 require.NoError(t, err)
134 //// This was used when observing coalescing of piece state changes.
135 //logPieceStateChanges(leecherTorrent)
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)
145 if ps.LeecherStartsWithoutMetadata {
146 <-leecherTorrent.GotInfo()
148 r := leecherTorrent.NewReader()
150 go leecherTorrent.SetInfoBytes(mi.InfoBytes)
155 r.SetReadahead(ps.Readahead)
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)
164 assert.NotEmpty(t, leecherPeerConns)
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() {
175 t.Errorf("didn't find seeder amongst leecher peer conns")
178 seederStats := seederTorrent.Stats()
179 assert.True(t, 13 <= seederStats.BytesWrittenData.Int64())
180 assert.True(t, 8 <= seederStats.ChunksWritten.Int64())
182 leecherStats := leecherTorrent.Stats()
183 assert.True(t, 13 <= leecherStats.BytesReadData.Int64())
184 assert.True(t, 8 <= leecherStats.ChunksRead.Int64())
186 // Try reading through again for the cases where the torrent data size
187 // exceeds the size of the cache.
188 assertReadAllGreeting(t, r)
191 type fileCacheClientStorageFactoryParams struct {
194 Wrapper func(*filecache.Cache) storage.ClientImplCloser
197 func newFileCacheClientStorageFactory(ps fileCacheClientStorageFactoryParams) storageFactory {
198 return func(dataDir string) storage.ClientImplCloser {
199 fc, err := filecache.NewCache(dataDir)
204 fc.SetCapacity(ps.Capacity)
206 return ps.Wrapper(fc)
210 type storageFactory func(string) storage.ClientImplCloser
212 func TestClientTransferDefault(t *testing.T) {
213 testClientTransfer(t, testClientTransferParams{
214 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
215 Wrapper: fileCachePieceResourceStorage,
220 func TestClientTransferDefaultNoMetadata(t *testing.T) {
221 testClientTransfer(t, testClientTransferParams{
222 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
223 Wrapper: fileCachePieceResourceStorage,
225 LeecherStartsWithoutMetadata: true,
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),
237 require.True(t, time.Since(started) > time.Second)
240 func TestClientTransferRateLimitedDownload(t *testing.T) {
241 testClientTransfer(t, testClientTransferParams{
242 LeecherDownloadRateLimiter: rate.NewLimiter(512, 512),
246 func fileCachePieceResourceStorage(fc *filecache.Cache) storage.ClientImplCloser {
251 storage.NewResourcePieces(fc.AsResourceProvider()),
252 ioutil.NopCloser(nil),
256 func testClientTransferSmallCache(t *testing.T, setReadahead bool, readahead int64) {
257 testClientTransfer(t, testClientTransferParams{
258 LeecherStorage: newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
260 // Going below the piece length means it can't complete a piece so
261 // that it can be hashed.
263 Wrapper: fileCachePieceResourceStorage,
265 SetReadahead: setReadahead,
266 // Can't readahead too far or the cache will thrash and drop data we
268 Readahead: readahead,
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
281 func TestClientTransferSmallCachePieceSizedReadahead(t *testing.T) {
282 testClientTransferSmallCache(t, true, 5)
285 func TestClientTransferSmallCacheLargeReadahead(t *testing.T) {
286 testClientTransferSmallCache(t, true, 15)
289 func TestClientTransferSmallCacheDefaultReadahead(t *testing.T) {
290 testClientTransferSmallCache(t, false, -1)
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)
305 type leecherStorageTestCase struct {
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"),
326 func TestClientTransferVarious(t *testing.T) {
328 for _, ls := range []leecherStorageTestCase{
329 {"Filecache", newFileCacheClientStorageFactory(fileCacheClientStorageFactoryParams{
330 Wrapper: fileCachePieceResourceStorage,
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{
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, 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{
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)