]> Sergey Matveev's repositories - btrtrc.git/blob - requesting.go
gofumpt
[btrtrc.git] / requesting.go
1 package torrent
2
3 import (
4         "container/heap"
5         "context"
6         "encoding/gob"
7         "reflect"
8         "runtime/pprof"
9         "time"
10         "unsafe"
11
12         "github.com/anacrolix/log"
13         "github.com/anacrolix/multiless"
14
15         request_strategy "github.com/anacrolix/torrent/request-strategy"
16 )
17
18 func (cl *Client) tickleRequester() {
19         cl.updateRequests.Broadcast()
20 }
21
22 func (cl *Client) getRequestStrategyInput() request_strategy.Input {
23         ts := make([]request_strategy.Torrent, 0, len(cl.torrents))
24         for _, t := range cl.torrents {
25                 if !t.haveInfo() {
26                         // This would be removed if metadata is handled here. We have to guard against not
27                         // knowing the piece size. If we have no info, we have no pieces too, so the end result
28                         // is the same.
29                         continue
30                 }
31                 rst := request_strategy.Torrent{
32                         InfoHash:       t.infoHash,
33                         ChunksPerPiece: t.chunksPerRegularPiece(),
34                 }
35                 if t.storage != nil {
36                         rst.Capacity = t.storage.Capacity
37                 }
38                 rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
39                 for i := range t.pieces {
40                         p := &t.pieces[i]
41                         rst.Pieces = append(rst.Pieces, request_strategy.Piece{
42                                 Request:           !t.ignorePieceForRequests(i),
43                                 Priority:          p.purePriority(),
44                                 Partial:           t.piecePartiallyDownloaded(i),
45                                 Availability:      p.availability,
46                                 Length:            int64(p.length()),
47                                 NumPendingChunks:  int(t.pieceNumPendingChunks(i)),
48                                 IterPendingChunks: &p.undirtiedChunksIter,
49                         })
50                 }
51                 t.iterPeers(func(p *Peer) {
52                         if p.closed.IsSet() {
53                                 return
54                         }
55                         if p.piecesReceivedSinceLastRequestUpdate > p.maxPiecesReceivedBetweenRequestUpdates {
56                                 p.maxPiecesReceivedBetweenRequestUpdates = p.piecesReceivedSinceLastRequestUpdate
57                         }
58                         p.piecesReceivedSinceLastRequestUpdate = 0
59                         rst.Peers = append(rst.Peers, request_strategy.Peer{
60                                 Pieces:           *p.newPeerPieces(),
61                                 MaxRequests:      p.nominalMaxRequests(),
62                                 ExistingRequests: p.actualRequestState.Requests,
63                                 Choking:          p.peerChoking,
64                                 PieceAllowedFast: p.peerAllowedFast,
65                                 DownloadRate:     p.downloadRate(),
66                                 Age:              time.Since(p.completedHandshake),
67                                 Id: peerId{
68                                         Peer: p,
69                                         ptr:  uintptr(unsafe.Pointer(p)),
70                                 },
71                         })
72                 })
73                 ts = append(ts, rst)
74         }
75         return request_strategy.Input{
76                 Torrents:           ts,
77                 MaxUnverifiedBytes: cl.config.MaxUnverifiedBytes,
78         }
79 }
80
81 func init() {
82         gob.Register(peerId{})
83 }
84
85 type peerId struct {
86         *Peer
87         ptr uintptr
88 }
89
90 func (p peerId) Uintptr() uintptr {
91         return p.ptr
92 }
93
94 func (p peerId) GobEncode() (b []byte, _ error) {
95         *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
96                 Data: uintptr(unsafe.Pointer(&p.ptr)),
97                 Len:  int(unsafe.Sizeof(p.ptr)),
98                 Cap:  int(unsafe.Sizeof(p.ptr)),
99         }
100         return
101 }
102
103 func (p *peerId) GobDecode(b []byte) error {
104         if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
105                 panic(len(b))
106         }
107         ptr := unsafe.Pointer(&b[0])
108         p.ptr = *(*uintptr)(ptr)
109         log.Printf("%p", ptr)
110         dst := reflect.SliceHeader{
111                 Data: uintptr(unsafe.Pointer(&p.Peer)),
112                 Len:  int(unsafe.Sizeof(p.Peer)),
113                 Cap:  int(unsafe.Sizeof(p.Peer)),
114         }
115         copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
116         return nil
117 }
118
119 type (
120         RequestIndex   = request_strategy.RequestIndex
121         chunkIndexType = request_strategy.ChunkIndex
122 )
123
124 type peerRequests struct {
125         requestIndexes       []RequestIndex
126         peer                 *Peer
127         torrentStrategyInput request_strategy.Torrent
128 }
129
130 func (p *peerRequests) Len() int {
131         return len(p.requestIndexes)
132 }
133
134 func (p *peerRequests) Less(i, j int) bool {
135         leftRequest := p.requestIndexes[i]
136         rightRequest := p.requestIndexes[j]
137         t := p.peer.t
138         leftPieceIndex := leftRequest / p.torrentStrategyInput.ChunksPerPiece
139         rightPieceIndex := rightRequest / p.torrentStrategyInput.ChunksPerPiece
140         leftCurrent := p.peer.actualRequestState.Requests.Contains(leftRequest)
141         rightCurrent := p.peer.actualRequestState.Requests.Contains(rightRequest)
142         pending := func(index RequestIndex, current bool) int {
143                 ret := t.pendingRequests.Get(index)
144                 if current {
145                         ret--
146                 }
147                 // See https://github.com/anacrolix/torrent/issues/679 for possible issues. This should be
148                 // resolved.
149                 if ret < 0 {
150                         panic(ret)
151                 }
152                 return ret
153         }
154         ml := multiless.New()
155         // Push requests that can't be served right now to the end. But we don't throw them away unless
156         // there's a better alternative. This is for when we're using the fast extension and get choked
157         // but our requests could still be good when we get unchoked.
158         if p.peer.peerChoking {
159                 ml = ml.Bool(
160                         !p.peer.peerAllowedFast.Contains(leftPieceIndex),
161                         !p.peer.peerAllowedFast.Contains(rightPieceIndex),
162                 )
163         }
164         ml = ml.Int(
165                 pending(leftRequest, leftCurrent),
166                 pending(rightRequest, rightCurrent))
167         ml = ml.Bool(!leftCurrent, !rightCurrent)
168         ml = ml.Int(
169                 -int(p.torrentStrategyInput.Pieces[leftPieceIndex].Priority),
170                 -int(p.torrentStrategyInput.Pieces[rightPieceIndex].Priority),
171         )
172         ml = ml.Int(
173                 int(p.torrentStrategyInput.Pieces[leftPieceIndex].Availability),
174                 int(p.torrentStrategyInput.Pieces[rightPieceIndex].Availability))
175         ml = ml.Uint32(leftPieceIndex, rightPieceIndex)
176         ml = ml.Uint32(leftRequest, rightRequest)
177         return ml.MustLess()
178 }
179
180 func (p *peerRequests) Swap(i, j int) {
181         p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
182 }
183
184 func (p *peerRequests) Push(x interface{}) {
185         p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
186 }
187
188 func (p *peerRequests) Pop() interface{} {
189         last := len(p.requestIndexes) - 1
190         x := p.requestIndexes[last]
191         p.requestIndexes = p.requestIndexes[:last]
192         return x
193 }
194
195 type desiredRequestState struct {
196         Requests   []RequestIndex
197         Interested bool
198 }
199
200 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
201         input := p.t.cl.getRequestStrategyInput()
202         requestHeap := peerRequests{
203                 peer: p,
204         }
205         for _, t := range input.Torrents {
206                 if t.InfoHash == p.t.infoHash {
207                         requestHeap.torrentStrategyInput = t
208                         break
209                 }
210         }
211         request_strategy.GetRequestablePieces(
212                 input,
213                 func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
214                         if t.InfoHash != p.t.infoHash {
215                                 return
216                         }
217                         if !p.peerHasPiece(pieceIndex) {
218                                 return
219                         }
220                         allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
221                         rsp.IterPendingChunks.Iter(func(ci request_strategy.ChunkIndex) {
222                                 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
223                                 //if p.t.pendingRequests.Get(r) != 0 && !p.actualRequestState.Requests.Contains(r) {
224                                 //      return
225                                 //}
226                                 if !allowedFast {
227                                         // We must signal interest to request this
228                                         desired.Interested = true
229                                         // We can make or will allow sustaining a request here if we're not choked, or
230                                         // have made the request previously (presumably while unchoked), and haven't had
231                                         // the peer respond yet (and the request was retained because we are using the
232                                         // fast extension).
233                                         if p.peerChoking && !p.actualRequestState.Requests.Contains(r) {
234                                                 // We can't request this right now.
235                                                 return
236                                         }
237                                 }
238                                 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
239                         })
240                 },
241         )
242         p.t.assertPendingRequests()
243         heap.Init(&requestHeap)
244         for requestHeap.Len() != 0 && len(desired.Requests) < p.nominalMaxRequests() {
245                 requestIndex := heap.Pop(&requestHeap).(RequestIndex)
246                 desired.Requests = append(desired.Requests, requestIndex)
247         }
248         return
249 }
250
251 func (p *Peer) maybeUpdateActualRequestState() bool {
252         if p.needRequestUpdate == "" {
253                 return true
254         }
255         var more bool
256         pprof.Do(
257                 context.Background(),
258                 pprof.Labels("update request", p.needRequestUpdate),
259                 func(_ context.Context) {
260                         next := p.getDesiredRequestState()
261                         more = p.applyRequestState(next)
262                 },
263         )
264         return more
265 }
266
267 // Transmit/action the request state to the peer.
268 func (p *Peer) applyRequestState(next desiredRequestState) bool {
269         current := &p.actualRequestState
270         if !p.setInterested(next.Interested) {
271                 return false
272         }
273         more := true
274         cancel := current.Requests.Clone()
275         for _, ri := range next.Requests {
276                 cancel.Remove(ri)
277         }
278         cancel.Iterate(func(req uint32) bool {
279                 more = p.cancel(req)
280                 return more
281         })
282         if !more {
283                 return false
284         }
285         for _, req := range next.Requests {
286                 if p.cancelledRequests.Contains(req) {
287                         // Waiting for a reject or piece message, which will suitably trigger us to update our
288                         // requests, so we can skip this one with no additional consideration.
289                         continue
290                 }
291                 // The cardinality of our desired requests shouldn't exceed the max requests since it's used
292                 // in the calculation of the requests. However, if we cancelled requests and they haven't
293                 // been rejected or serviced yet with the fast extension enabled, we can end up with more
294                 // extra outstanding requests. We could subtract the number of outstanding cancels from the
295                 // next request cardinality, but peers might not like that.
296                 if maxRequests(current.Requests.GetCardinality()) >= p.nominalMaxRequests() {
297                         //log.Printf("not assigning all requests [desired=%v, cancelled=%v, current=%v, max=%v]",
298                         //      next.Requests.GetCardinality(),
299                         //      p.cancelledRequests.GetCardinality(),
300                         //      current.Requests.GetCardinality(),
301                         //      p.nominalMaxRequests(),
302                         //)
303                         break
304                 }
305                 more = p.mustRequest(req)
306                 if !more {
307                         break
308                 }
309         }
310         p.updateRequestsTimer.Stop()
311         if more {
312                 p.needRequestUpdate = ""
313                 if !current.Requests.IsEmpty() {
314                         p.updateRequestsTimer.Reset(3 * time.Second)
315                 }
316         }
317         return more
318 }