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