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 type leecherStorageTestCase struct {
297 func TestClientTransferVarious(t *testing.T) {
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
306 cl, err := sqliteStorage.NewDirectStorage(opts)
313 t.Run(fmt.Sprintf("LeecherStorage=%s", ls.name), func(t *testing.T) {
315 for _, ss := range []struct {
319 {"File", storage.NewFile},
320 {"Mmap", storage.NewMMap},
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,
329 LeecherStorage: ls.f,
330 GOMAXPROCS: ls.gomaxprocs,
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{
337 Responsive: responsive,
339 Readahead: readahead,
340 LeecherStorage: ls.f,
341 GOMAXPROCS: ls.gomaxprocs,
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)
359 cfg := torrent.TestingConfig(t)
361 cfg.DataDir = greetingTempDir
362 seeder, err := torrent.NewClient(cfg)
363 require.NoError(t, err)
365 defer testutil.ExportStatusWriter(seeder, "s", t)()
366 seederTorrent, ok, err := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi))
367 require.NoError(t, err)
369 seederTorrent.VerifyData()
371 cfg = torrent.TestingConfig(t)
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)()
381 cfg = torrent.TestingConfig(t)
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)
395 require.NoError(t, err)
397 llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) {
398 ret = torrent.TorrentSpecFromMetaInfo(mi)
402 require.NoError(t, err)
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
413 quicktest.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), quicktest.IsNil)
415 done := make(chan struct{})
417 go leecherGreeting.AddClientPeer(seeder)
418 go leecherGreeting.AddClientPeer(leecherLeecher)
422 leecherGreeting.DownloadAll()
428 type ConfigureClient struct {
429 Config func(*torrent.ClientConfig)
430 Client func(*torrent.Client)