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