]> Sergey Matveev's repositories - btrtrc.git/blob - requesting.go
Use a generic heap implementation for request selection
[btrtrc.git] / requesting.go
1 package torrent
2
3 import (
4         "context"
5         "encoding/gob"
6         "fmt"
7         "reflect"
8         "runtime/pprof"
9         "time"
10         "unsafe"
11
12         "github.com/anacrolix/log"
13         "github.com/anacrolix/multiless"
14         "github.com/lispad/go-generics-tools/binheap"
15
16         request_strategy "github.com/anacrolix/torrent/request-strategy"
17 )
18
19 func (t *Torrent) requestStrategyPieceOrderState(i int) request_strategy.PieceRequestOrderState {
20         return request_strategy.PieceRequestOrderState{
21                 Priority:     t.piece(i).purePriority(),
22                 Partial:      t.piecePartiallyDownloaded(i),
23                 Availability: t.piece(i).availability(),
24         }
25 }
26
27 func init() {
28         gob.Register(peerId{})
29 }
30
31 type peerId struct {
32         *Peer
33         ptr uintptr
34 }
35
36 func (p peerId) Uintptr() uintptr {
37         return p.ptr
38 }
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
49 func (p *peerId) GobDecode(b []byte) error {
50         if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
51                 panic(len(b))
52         }
53         ptr := unsafe.Pointer(&b[0])
54         p.ptr = *(*uintptr)(ptr)
55         log.Printf("%p", ptr)
56         dst := reflect.SliceHeader{
57                 Data: uintptr(unsafe.Pointer(&p.Peer)),
58                 Len:  int(unsafe.Sizeof(p.Peer)),
59                 Cap:  int(unsafe.Sizeof(p.Peer)),
60         }
61         copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
62         return nil
63 }
64
65 type (
66         RequestIndex   = request_strategy.RequestIndex
67         chunkIndexType = request_strategy.ChunkIndex
68 )
69
70 type desiredPeerRequests struct {
71         requestIndexes []RequestIndex
72         peer           *Peer
73 }
74
75 func (p *desiredPeerRequests) Len() int {
76         return len(p.requestIndexes)
77 }
78
79 func (p *desiredPeerRequests) Less(i, j int) bool {
80         return p.lessByValue(p.requestIndexes[i], p.requestIndexes[j])
81 }
82
83 func (p *desiredPeerRequests) lessByValue(leftRequest, rightRequest RequestIndex) bool {
84         t := p.peer.t
85         leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
86         rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
87         ml := multiless.New()
88         // Push requests that can't be served right now to the end. But we don't throw them away unless
89         // there's a better alternative. This is for when we're using the fast extension and get choked
90         // but our requests could still be good when we get unchoked.
91         if p.peer.peerChoking {
92                 ml = ml.Bool(
93                         !p.peer.peerAllowedFast.Contains(leftPieceIndex),
94                         !p.peer.peerAllowedFast.Contains(rightPieceIndex),
95                 )
96         }
97         leftPiece := t.piece(leftPieceIndex)
98         rightPiece := t.piece(rightPieceIndex)
99         // Putting this first means we can steal requests from lesser-performing peers for our first few
100         // new requests.
101         priority := func() piecePriority {
102                 // Technically we would be happy with the cached priority here, except we don't actually
103                 // cache it anymore, and Torrent.piecePriority just does another lookup of *Piece to resolve
104                 // the priority through Piece.purePriority, which is probably slower.
105                 leftPriority := leftPiece.purePriority()
106                 rightPriority := rightPiece.purePriority()
107                 ml = ml.Int(
108                         -int(leftPriority),
109                         -int(rightPriority),
110                 )
111                 if !ml.Ok() {
112                         if leftPriority != rightPriority {
113                                 panic("expected equal")
114                         }
115                 }
116                 return leftPriority
117         }()
118         if ml.Ok() {
119                 return ml.MustLess()
120         }
121         leftPeer := t.pendingRequests[leftRequest]
122         rightPeer := t.pendingRequests[rightRequest]
123         // Prefer chunks already requested from this peer.
124         ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
125         // Prefer unrequested chunks.
126         ml = ml.Bool(rightPeer == nil, leftPeer == nil)
127         if ml.Ok() {
128                 return ml.MustLess()
129         }
130         if leftPeer != nil {
131                 // The right peer should also be set, or we'd have resolved the computation by now.
132                 ml = ml.Uint64(
133                         rightPeer.requestState.Requests.GetCardinality(),
134                         leftPeer.requestState.Requests.GetCardinality(),
135                 )
136                 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
137                 leftLast := t.lastRequested[leftRequest]
138                 rightLast := t.lastRequested[rightRequest]
139                 if leftLast.IsZero() || rightLast.IsZero() {
140                         panic("expected non-zero last requested times")
141                 }
142                 // We want the most-recently requested on the left. Clients like Transmission serve requests
143                 // in received order, so the most recently-requested is the one that has the longest until
144                 // it will be served and therefore is the best candidate to cancel.
145                 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
146         }
147         ml = ml.Int(
148                 leftPiece.relativeAvailability,
149                 rightPiece.relativeAvailability)
150         if priority == PiecePriorityReadahead {
151                 // TODO: For readahead in particular, it would be even better to consider distance from the
152                 // reader position so that reads earlier in a torrent don't starve reads later in the
153                 // torrent. This would probably require reconsideration of how readahead priority works.
154                 ml = ml.Int(leftPieceIndex, rightPieceIndex)
155         } else {
156                 // TODO: To prevent unnecessarily requesting from disparate pieces, and to ensure pieces are
157                 // selected randomly when availability is even, there should be some fixed ordering of
158                 // pieces.
159         }
160         return ml.Less()
161 }
162
163 func (p *desiredPeerRequests) Swap(i, j int) {
164         p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
165 }
166
167 func (p *desiredPeerRequests) Push(x interface{}) {
168         p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
169 }
170
171 func (p *desiredPeerRequests) Pop() interface{} {
172         last := len(p.requestIndexes) - 1
173         x := p.requestIndexes[last]
174         p.requestIndexes = p.requestIndexes[:last]
175         return x
176 }
177
178 type desiredRequestState struct {
179         Requests   desiredPeerRequests
180         Interested bool
181 }
182
183 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
184         if !p.t.haveInfo() {
185                 return
186         }
187         if p.t.closed.IsSet() {
188                 return
189         }
190         input := p.t.getRequestStrategyInput()
191         requestHeap := desiredPeerRequests{
192                 peer: p,
193         }
194         request_strategy.GetRequestablePieces(
195                 input,
196                 p.t.getPieceRequestOrder(),
197                 func(ih InfoHash, pieceIndex int) {
198                         if ih != p.t.infoHash {
199                                 return
200                         }
201                         if !p.peerHasPiece(pieceIndex) {
202                                 return
203                         }
204                         allowedFast := p.peerAllowedFast.Contains(pieceIndex)
205                         p.t.piece(pieceIndex).undirtiedChunksIter.Iter(func(ci request_strategy.ChunkIndex) {
206                                 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
207                                 if !allowedFast {
208                                         // We must signal interest to request this. TODO: We could set interested if the
209                                         // peers pieces (minus the allowed fast set) overlap with our missing pieces if
210                                         // there are any readers, or any pending pieces.
211                                         desired.Interested = true
212                                         // We can make or will allow sustaining a request here if we're not choked, or
213                                         // have made the request previously (presumably while unchoked), and haven't had
214                                         // the peer respond yet (and the request was retained because we are using the
215                                         // fast extension).
216                                         if p.peerChoking && !p.requestState.Requests.Contains(r) {
217                                                 // We can't request this right now.
218                                                 return
219                                         }
220                                 }
221                                 if p.requestState.Cancelled.Contains(r) {
222                                         // Can't re-request while awaiting acknowledgement.
223                                         return
224                                 }
225                                 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
226                         })
227                 },
228         )
229         p.t.assertPendingRequests()
230         desired.Requests = requestHeap
231         return
232 }
233
234 func (p *Peer) maybeUpdateActualRequestState() {
235         if p.closed.IsSet() {
236                 return
237         }
238         if p.needRequestUpdate == "" {
239                 return
240         }
241         if p.needRequestUpdate == peerUpdateRequestsTimerReason {
242                 since := time.Since(p.lastRequestUpdate)
243                 if since < updateRequestsTimerDuration {
244                         panic(since)
245                 }
246         }
247         pprof.Do(
248                 context.Background(),
249                 pprof.Labels("update request", p.needRequestUpdate),
250                 func(_ context.Context) {
251                         next := p.getDesiredRequestState()
252                         p.applyRequestState(next)
253                 },
254         )
255 }
256
257 // Transmit/action the request state to the peer.
258 func (p *Peer) applyRequestState(next desiredRequestState) {
259         current := &p.requestState
260         if !p.setInterested(next.Interested) {
261                 panic("insufficient write buffer")
262         }
263         more := true
264         requestHeap := binheap.FromSlice(next.Requests.requestIndexes, next.Requests.lessByValue)
265         t := p.t
266         originalRequestCount := current.Requests.GetCardinality()
267         // We're either here on a timer, or because we ran out of requests. Both are valid reasons to
268         // alter peakRequests.
269         if originalRequestCount != 0 && p.needRequestUpdate != peerUpdateRequestsTimerReason {
270                 panic(fmt.Sprintf(
271                         "expected zero existing requests (%v) for update reason %q",
272                         originalRequestCount, p.needRequestUpdate))
273         }
274         for requestHeap.Len() != 0 && maxRequests(current.Requests.GetCardinality()+current.Cancelled.GetCardinality()) < p.nominalMaxRequests() {
275                 req := requestHeap.Pop()
276                 existing := t.requestingPeer(req)
277                 if existing != nil && existing != p {
278                         // Don't steal from the poor.
279                         diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
280                         // Steal a request that leaves us with one more request than the existing peer
281                         // connection if the stealer more recently received a chunk.
282                         if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
283                                 continue
284                         }
285                         t.cancelRequest(req)
286                 }
287                 more = p.mustRequest(req)
288                 if !more {
289                         break
290                 }
291         }
292         if !more {
293                 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
294                 // requests into the available write buffer space. We don't want that to happen because it
295                 // makes our peak requests dependent on how much was already in the buffer.
296                 panic(fmt.Sprintf(
297                         "couldn't fill apply entire request state [newRequests=%v]",
298                         current.Requests.GetCardinality()-originalRequestCount))
299         }
300         newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
301         // log.Printf(
302         //      "requests %v->%v (peak %v->%v) reason %q (peer %v)",
303         //      originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
304         p.peakRequests = newPeakRequests
305         p.needRequestUpdate = ""
306         p.lastRequestUpdate = time.Now()
307         p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
308 }
309
310 // This could be set to 10s to match the unchoke/request update interval recommended by some
311 // specifications. I've set it shorter to trigger it more often for testing for now.
312 const updateRequestsTimerDuration = 3 * time.Second