]> Sergey Matveev's repositories - btrtrc.git/blob - requesting.go
Don't put requests we can't make into the request heap
[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/RoaringBitmap/roaring"
13         "github.com/anacrolix/log"
14         "github.com/anacrolix/missinggo/v2/bitmap"
15         "github.com/anacrolix/multiless"
16
17         request_strategy "github.com/anacrolix/torrent/request-strategy"
18 )
19
20 func (cl *Client) tickleRequester() {
21         cl.updateRequests.Broadcast()
22 }
23
24 func (cl *Client) getRequestStrategyInput() request_strategy.Input {
25         ts := make([]request_strategy.Torrent, 0, len(cl.torrents))
26         for _, t := range cl.torrents {
27                 if !t.haveInfo() {
28                         // This would be removed if metadata is handled here. We have to guard against not
29                         // knowing the piece size. If we have no info, we have no pieces too, so the end result
30                         // is the same.
31                         continue
32                 }
33                 rst := request_strategy.Torrent{
34                         InfoHash:       t.infoHash,
35                         ChunksPerPiece: t.chunksPerRegularPiece(),
36                 }
37                 if t.storage != nil {
38                         rst.Capacity = t.storage.Capacity
39                 }
40                 rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
41                 for i := range t.pieces {
42                         p := &t.pieces[i]
43                         rst.Pieces = append(rst.Pieces, request_strategy.Piece{
44                                 Request:           !t.ignorePieceForRequests(i),
45                                 Priority:          p.purePriority(),
46                                 Partial:           t.piecePartiallyDownloaded(i),
47                                 Availability:      p.availability,
48                                 Length:            int64(p.length()),
49                                 NumPendingChunks:  int(t.pieceNumPendingChunks(i)),
50                                 IterPendingChunks: p.undirtiedChunksIter(),
51                         })
52                 }
53                 t.iterPeers(func(p *Peer) {
54                         if p.closed.IsSet() {
55                                 return
56                         }
57                         if p.piecesReceivedSinceLastRequestUpdate > p.maxPiecesReceivedBetweenRequestUpdates {
58                                 p.maxPiecesReceivedBetweenRequestUpdates = p.piecesReceivedSinceLastRequestUpdate
59                         }
60                         p.piecesReceivedSinceLastRequestUpdate = 0
61                         rst.Peers = append(rst.Peers, request_strategy.Peer{
62                                 Pieces:           *p.newPeerPieces(),
63                                 MaxRequests:      p.nominalMaxRequests(),
64                                 ExistingRequests: p.actualRequestState.Requests,
65                                 Choking:          p.peerChoking,
66                                 PieceAllowedFast: p.peerAllowedFast,
67                                 DownloadRate:     p.downloadRate(),
68                                 Age:              time.Since(p.completedHandshake),
69                                 Id: peerId{
70                                         Peer: p,
71                                         ptr:  uintptr(unsafe.Pointer(p)),
72                                 },
73                         })
74                 })
75                 ts = append(ts, rst)
76         }
77         return request_strategy.Input{
78                 Torrents:           ts,
79                 MaxUnverifiedBytes: cl.config.MaxUnverifiedBytes,
80         }
81 }
82
83 func init() {
84         gob.Register(peerId{})
85 }
86
87 type peerId struct {
88         *Peer
89         ptr uintptr
90 }
91
92 func (p peerId) Uintptr() uintptr {
93         return p.ptr
94 }
95
96 func (p peerId) GobEncode() (b []byte, _ error) {
97         *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
98                 Data: uintptr(unsafe.Pointer(&p.ptr)),
99                 Len:  int(unsafe.Sizeof(p.ptr)),
100                 Cap:  int(unsafe.Sizeof(p.ptr)),
101         }
102         return
103 }
104
105 func (p *peerId) GobDecode(b []byte) error {
106         if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
107                 panic(len(b))
108         }
109         ptr := unsafe.Pointer(&b[0])
110         p.ptr = *(*uintptr)(ptr)
111         log.Printf("%p", ptr)
112         dst := reflect.SliceHeader{
113                 Data: uintptr(unsafe.Pointer(&p.Peer)),
114                 Len:  int(unsafe.Sizeof(p.Peer)),
115                 Cap:  int(unsafe.Sizeof(p.Peer)),
116         }
117         copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
118         return nil
119 }
120
121 type RequestIndex = request_strategy.RequestIndex
122 type chunkIndexType = request_strategy.ChunkIndex
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                 return ret
148         }
149         ml := multiless.New()
150         ml = ml.Int(
151                 pending(leftRequest, leftCurrent),
152                 pending(rightRequest, rightCurrent))
153         ml = ml.Bool(rightCurrent, leftCurrent)
154         ml = ml.Int(
155                 int(p.torrentStrategyInput.Pieces[leftPieceIndex].Priority),
156                 int(p.torrentStrategyInput.Pieces[rightPieceIndex].Priority))
157         ml = ml.Int(
158                 int(p.torrentStrategyInput.Pieces[leftPieceIndex].Availability),
159                 int(p.torrentStrategyInput.Pieces[rightPieceIndex].Availability))
160         ml = ml.Uint32(leftPieceIndex, rightPieceIndex)
161         ml = ml.Uint32(leftRequest, rightRequest)
162         return ml.MustLess()
163 }
164
165 func (p peerRequests) Swap(i, j int) {
166         p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
167 }
168
169 func (p *peerRequests) Push(x interface{}) {
170         p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
171 }
172
173 func (p *peerRequests) Pop() interface{} {
174         last := len(p.requestIndexes) - 1
175         x := p.requestIndexes[last]
176         p.requestIndexes = p.requestIndexes[:last]
177         return x
178 }
179
180 func (p *Peer) getDesiredRequestState() (desired requestState) {
181         input := p.t.cl.getRequestStrategyInput()
182         requestHeap := peerRequests{
183                 peer: p,
184         }
185         for _, t := range input.Torrents {
186                 if t.InfoHash == p.t.infoHash {
187                         requestHeap.torrentStrategyInput = t
188                         break
189                 }
190         }
191         request_strategy.GetRequestablePieces(
192                 input,
193                 func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
194                         if t.InfoHash != p.t.infoHash {
195                                 return
196                         }
197                         if !p.peerHasPiece(pieceIndex) {
198                                 return
199                         }
200                         allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
201                         if !allowedFast {
202                                 // We must signal interest to request this piece.
203                                 desired.Interested = true
204                                 if p.peerChoking {
205                                         // We can't request from this piece right now then.
206                                         return
207                                 }
208                         }
209                         rsp.IterPendingChunks.Iter(func(ci request_strategy.ChunkIndex) {
210                                 requestHeap.requestIndexes = append(
211                                         requestHeap.requestIndexes,
212                                         p.t.pieceRequestIndexOffset(pieceIndex)+ci)
213                         })
214                 },
215         )
216         heap.Init(&requestHeap)
217         for requestHeap.Len() != 0 && desired.Requests.GetCardinality() < uint64(p.nominalMaxRequests()) {
218                 requestIndex := heap.Pop(&requestHeap).(RequestIndex)
219                 desired.Requests.Add(requestIndex)
220         }
221         return
222 }
223
224 func (p *Peer) applyNextRequestState() bool {
225         if p.needRequestUpdate == "" {
226                 return true
227         }
228         var more bool
229         pprof.Do(
230                 context.Background(),
231                 pprof.Labels("update request", p.needRequestUpdate),
232                 func(_ context.Context) {
233                         next := p.getDesiredRequestState()
234                         more = p.applyRequestState(next)
235                 },
236         )
237         return more
238 }
239
240 func (p *Peer) applyRequestState(next requestState) bool {
241         current := p.actualRequestState
242         if !p.setInterested(next.Interested) {
243                 return false
244         }
245         more := true
246         cancel := roaring.AndNot(&current.Requests, &next.Requests)
247         cancel.Iterate(func(req uint32) bool {
248                 more = p.cancel(req)
249                 return more
250         })
251         if !more {
252                 return false
253         }
254         next.Requests.Iterate(func(req uint32) bool {
255                 // This could happen if the peer chokes us between the next state being generated, and us
256                 // trying to transmit the state.
257                 if p.peerChoking && !p.peerAllowedFast.Contains(bitmap.BitIndex(req/p.t.chunksPerRegularPiece())) {
258                         return true
259                 }
260                 var err error
261                 more, err = p.request(req)
262                 if err != nil {
263                         panic(err)
264                 } /* else {
265                         log.Print(req)
266                 } */
267                 return more
268         })
269         if more {
270                 p.needRequestUpdate = ""
271         }
272         return more
273 }