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