requesting.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package torrent
  2. import (
  3. "context"
  4. "encoding/gob"
  5. "fmt"
  6. "reflect"
  7. "runtime/pprof"
  8. "time"
  9. "unsafe"
  10. "github.com/RoaringBitmap/roaring"
  11. g "github.com/anacrolix/generics"
  12. "github.com/anacrolix/generics/heap"
  13. "github.com/anacrolix/log"
  14. "github.com/anacrolix/multiless"
  15. requestStrategy "github.com/anacrolix/torrent/request-strategy"
  16. typedRoaring "github.com/anacrolix/torrent/typed-roaring"
  17. )
  18. type (
  19. // Since we have to store all the requests in memory, we can't reasonably exceed what could be
  20. // indexed with the memory space available.
  21. maxRequests = int
  22. )
  23. func (t *Torrent) requestStrategyPieceOrderState(i int) requestStrategy.PieceRequestOrderState {
  24. return requestStrategy.PieceRequestOrderState{
  25. Priority: t.piece(i).purePriority(),
  26. Partial: t.piecePartiallyDownloaded(i),
  27. Availability: t.piece(i).availability(),
  28. }
  29. }
  30. func init() {
  31. gob.Register(peerId{})
  32. }
  33. type peerId struct {
  34. *Peer
  35. ptr uintptr
  36. }
  37. func (p peerId) Uintptr() uintptr {
  38. return p.ptr
  39. }
  40. func (p peerId) GobEncode() (b []byte, _ error) {
  41. *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
  42. Data: uintptr(unsafe.Pointer(&p.ptr)),
  43. Len: int(unsafe.Sizeof(p.ptr)),
  44. Cap: int(unsafe.Sizeof(p.ptr)),
  45. }
  46. return
  47. }
  48. func (p *peerId) GobDecode(b []byte) error {
  49. if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
  50. panic(len(b))
  51. }
  52. ptr := unsafe.Pointer(&b[0])
  53. p.ptr = *(*uintptr)(ptr)
  54. log.Printf("%p", ptr)
  55. dst := reflect.SliceHeader{
  56. Data: uintptr(unsafe.Pointer(&p.Peer)),
  57. Len: int(unsafe.Sizeof(p.Peer)),
  58. Cap: int(unsafe.Sizeof(p.Peer)),
  59. }
  60. copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
  61. return nil
  62. }
  63. type (
  64. RequestIndex = requestStrategy.RequestIndex
  65. chunkIndexType = requestStrategy.ChunkIndex
  66. )
  67. type desiredPeerRequests struct {
  68. requestIndexes []RequestIndex
  69. peer *Peer
  70. pieceStates []g.Option[requestStrategy.PieceRequestOrderState]
  71. }
  72. func (p *desiredPeerRequests) lessByValue(leftRequest, rightRequest RequestIndex) bool {
  73. t := p.peer.t
  74. leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
  75. rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
  76. ml := multiless.New()
  77. // Push requests that can't be served right now to the end. But we don't throw them away unless
  78. // there's a better alternative. This is for when we're using the fast extension and get choked
  79. // but our requests could still be good when we get unchoked.
  80. if p.peer.peerChoking {
  81. ml = ml.Bool(
  82. !p.peer.peerAllowedFast.Contains(leftPieceIndex),
  83. !p.peer.peerAllowedFast.Contains(rightPieceIndex),
  84. )
  85. }
  86. leftPiece := p.pieceStates[leftPieceIndex].UnwrapPtr()
  87. rightPiece := p.pieceStates[rightPieceIndex].UnwrapPtr()
  88. // Putting this first means we can steal requests from lesser-performing peers for our first few
  89. // new requests.
  90. priority := func() PiecePriority {
  91. // Technically we would be happy with the cached priority here, except we don't actually
  92. // cache it anymore, and Torrent.PiecePriority just does another lookup of *Piece to resolve
  93. // the priority through Piece.purePriority, which is probably slower.
  94. leftPriority := leftPiece.Priority
  95. rightPriority := rightPiece.Priority
  96. ml = ml.Int(
  97. -int(leftPriority),
  98. -int(rightPriority),
  99. )
  100. if !ml.Ok() {
  101. if leftPriority != rightPriority {
  102. panic("expected equal")
  103. }
  104. }
  105. return leftPriority
  106. }()
  107. if ml.Ok() {
  108. return ml.MustLess()
  109. }
  110. leftRequestState := t.requestState[leftRequest]
  111. rightRequestState := t.requestState[rightRequest]
  112. leftPeer := leftRequestState.peer
  113. rightPeer := rightRequestState.peer
  114. // Prefer chunks already requested from this peer.
  115. ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
  116. // Prefer unrequested chunks.
  117. ml = ml.Bool(rightPeer == nil, leftPeer == nil)
  118. if ml.Ok() {
  119. return ml.MustLess()
  120. }
  121. if leftPeer != nil {
  122. // The right peer should also be set, or we'd have resolved the computation by now.
  123. ml = ml.Uint64(
  124. rightPeer.requestState.Requests.GetCardinality(),
  125. leftPeer.requestState.Requests.GetCardinality(),
  126. )
  127. // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
  128. leftLast := leftRequestState.when
  129. rightLast := rightRequestState.when
  130. if leftLast.IsZero() || rightLast.IsZero() {
  131. panic("expected non-zero last requested times")
  132. }
  133. // We want the most-recently requested on the left. Clients like Transmission serve requests
  134. // in received order, so the most recently-requested is the one that has the longest until
  135. // it will be served and therefore is the best candidate to cancel.
  136. ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
  137. }
  138. ml = ml.Int(
  139. leftPiece.Availability,
  140. rightPiece.Availability)
  141. if priority == PiecePriorityReadahead {
  142. // TODO: For readahead in particular, it would be even better to consider distance from the
  143. // reader position so that reads earlier in a torrent don't starve reads later in the
  144. // torrent. This would probably require reconsideration of how readahead priority works.
  145. ml = ml.Int(leftPieceIndex, rightPieceIndex)
  146. } else {
  147. ml = ml.Int(t.pieceRequestOrder[leftPieceIndex], t.pieceRequestOrder[rightPieceIndex])
  148. }
  149. return ml.Less()
  150. }
  151. type desiredRequestState struct {
  152. Requests desiredPeerRequests
  153. Interested bool
  154. }
  155. func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
  156. t := p.t
  157. if !t.haveInfo() {
  158. return
  159. }
  160. if t.closed.IsSet() {
  161. return
  162. }
  163. if t.dataDownloadDisallowed.Bool() {
  164. return
  165. }
  166. input := t.getRequestStrategyInput()
  167. requestHeap := desiredPeerRequests{
  168. peer: p,
  169. pieceStates: t.requestPieceStates,
  170. requestIndexes: t.requestIndexes,
  171. }
  172. clear(requestHeap.pieceStates)
  173. // Caller-provided allocation for roaring bitmap iteration.
  174. var it typedRoaring.Iterator[RequestIndex]
  175. requestStrategy.GetRequestablePieces(
  176. input,
  177. t.getPieceRequestOrder(),
  178. func(ih InfoHash, pieceIndex int, pieceExtra requestStrategy.PieceRequestOrderState) bool {
  179. if ih != *t.canonicalShortInfohash() {
  180. return false
  181. }
  182. if !p.peerHasPiece(pieceIndex) {
  183. return false
  184. }
  185. requestHeap.pieceStates[pieceIndex].Set(pieceExtra)
  186. allowedFast := p.peerAllowedFast.Contains(pieceIndex)
  187. t.iterUndirtiedRequestIndexesInPiece(&it, pieceIndex, func(r requestStrategy.RequestIndex) {
  188. if !allowedFast {
  189. // We must signal interest to request this. TODO: We could set interested if the
  190. // peers pieces (minus the allowed fast set) overlap with our missing pieces if
  191. // there are any readers, or any pending pieces.
  192. desired.Interested = true
  193. // We can make or will allow sustaining a request here if we're not choked, or
  194. // have made the request previously (presumably while unchoked), and haven't had
  195. // the peer respond yet (and the request was retained because we are using the
  196. // fast extension).
  197. if p.peerChoking && !p.requestState.Requests.Contains(r) {
  198. // We can't request this right now.
  199. return
  200. }
  201. }
  202. cancelled := &p.requestState.Cancelled
  203. if !cancelled.IsEmpty() && cancelled.Contains(r) {
  204. // Can't re-request while awaiting acknowledgement.
  205. return
  206. }
  207. requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
  208. })
  209. return true
  210. },
  211. )
  212. t.assertPendingRequests()
  213. desired.Requests = requestHeap
  214. return
  215. }
  216. func (p *Peer) maybeUpdateActualRequestState() {
  217. if p.closed.IsSet() {
  218. return
  219. }
  220. if p.needRequestUpdate == "" {
  221. return
  222. }
  223. if p.needRequestUpdate == peerUpdateRequestsTimerReason {
  224. since := time.Since(p.lastRequestUpdate)
  225. if since < updateRequestsTimerDuration {
  226. panic(since)
  227. }
  228. }
  229. pprof.Do(
  230. context.Background(),
  231. pprof.Labels("update request", string(p.needRequestUpdate)),
  232. func(_ context.Context) {
  233. next := p.getDesiredRequestState()
  234. p.applyRequestState(next)
  235. p.t.cacheNextRequestIndexesForReuse(next.Requests.requestIndexes)
  236. },
  237. )
  238. }
  239. func (t *Torrent) cacheNextRequestIndexesForReuse(slice []RequestIndex) {
  240. // The incoming slice can be smaller when getDesiredRequestState short circuits on some
  241. // conditions.
  242. if cap(slice) > cap(t.requestIndexes) {
  243. t.requestIndexes = slice[:0]
  244. }
  245. }
  246. // Whether we should allow sending not interested ("losing interest") to the peer. I noticed
  247. // qBitTorrent seems to punish us for sending not interested when we're streaming and don't
  248. // currently need anything.
  249. func (p *Peer) allowSendNotInterested() bool {
  250. // Except for caching, we're not likely to lose pieces very soon.
  251. if p.t.haveAllPieces() {
  252. return true
  253. }
  254. all, known := p.peerHasAllPieces()
  255. if all || !known {
  256. return false
  257. }
  258. // Allow losing interest if we have all the pieces the peer has.
  259. return roaring.AndNot(p.peerPieces(), &p.t._completedPieces).IsEmpty()
  260. }
  261. // Transmit/action the request state to the peer.
  262. func (p *Peer) applyRequestState(next desiredRequestState) {
  263. current := &p.requestState
  264. // Make interest sticky
  265. if !next.Interested && p.requestState.Interested {
  266. if !p.allowSendNotInterested() {
  267. next.Interested = true
  268. }
  269. }
  270. if !p.setInterested(next.Interested) {
  271. return
  272. }
  273. more := true
  274. orig := next.Requests.requestIndexes
  275. requestHeap := heap.InterfaceForSlice(
  276. &next.Requests.requestIndexes,
  277. next.Requests.lessByValue,
  278. )
  279. heap.Init(requestHeap)
  280. t := p.t
  281. originalRequestCount := current.Requests.GetCardinality()
  282. for {
  283. if requestHeap.Len() == 0 {
  284. break
  285. }
  286. numPending := maxRequests(current.Requests.GetCardinality() + current.Cancelled.GetCardinality())
  287. if numPending >= p.nominalMaxRequests() {
  288. break
  289. }
  290. req := heap.Pop(requestHeap)
  291. if cap(next.Requests.requestIndexes) != cap(orig) {
  292. panic("changed")
  293. }
  294. // don't add requests on reciept of a reject - because this causes request back
  295. // to potentially permanently unresponive peers - which just adds network noise. If
  296. // the peer can handle more requests it will send an "unchoked" message - which
  297. // will cause it to get added back to the request queue
  298. if p.needRequestUpdate == peerUpdateRequestsRemoteRejectReason {
  299. continue
  300. }
  301. existing := t.requestingPeer(req)
  302. if existing != nil && existing != p {
  303. // don't steal on cancel - because this is triggered by t.cancelRequest below
  304. // which means that the cancelled can immediately try to steal back a request
  305. // it has lost which can lead to circular cancel/add processing
  306. if p.needRequestUpdate == peerUpdateRequestsPeerCancelReason {
  307. continue
  308. }
  309. // Don't steal from the poor.
  310. diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
  311. // Steal a request that leaves us with one more request than the existing peer
  312. // connection if the stealer more recently received a chunk.
  313. if diff > 1 || (diff == 1 && !p.lastUsefulChunkReceived.After(existing.lastUsefulChunkReceived)) {
  314. continue
  315. }
  316. t.cancelRequest(req)
  317. }
  318. more = p.mustRequest(req)
  319. if !more {
  320. break
  321. }
  322. }
  323. if !more {
  324. // This might fail if we incorrectly determine that we can fit up to the maximum allowed
  325. // requests into the available write buffer space. We don't want that to happen because it
  326. // makes our peak requests dependent on how much was already in the buffer.
  327. panic(fmt.Sprintf(
  328. "couldn't fill apply entire request state [newRequests=%v]",
  329. current.Requests.GetCardinality()-originalRequestCount))
  330. }
  331. newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
  332. // log.Printf(
  333. // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
  334. // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
  335. p.peakRequests = newPeakRequests
  336. p.needRequestUpdate = ""
  337. p.lastRequestUpdate = time.Now()
  338. if enableUpdateRequestsTimer {
  339. p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
  340. }
  341. }
  342. // This could be set to 10s to match the unchoke/request update interval recommended by some
  343. // specifications. I've set it shorter to trigger it more often for testing for now.
  344. const (
  345. updateRequestsTimerDuration = 3 * time.Second
  346. enableUpdateRequestsTimer = false
  347. )