/
state.go
380 lines (310 loc) · 8.02 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package torrentd
import (
"bytes"
"fmt"
"math/rand"
"os"
"sync/atomic"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/types/infohash"
"github.com/colinmarc/torrentd/log"
"github.com/colinmarc/torrentd/pb"
"github.com/r3labs/sse/v2"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
const (
stateBucketName = "t"
metainfoBucketName = "mi"
)
type torrentState struct {
infohash infohash.T
ptr atomic.Pointer[pb.Torrent]
lastErr atomic.Pointer[error]
done chan struct{}
}
func (td *Torrentd) loadAll() error {
torrents := make(map[infohash.T][]byte)
metainfos := make(map[infohash.T][]byte)
st := time.Now()
td.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketName))
if b == nil {
return nil
}
mib := tx.Bucket([]byte(metainfoBucketName))
if mib == nil {
return nil
}
return b.ForEach(func(k, v []byte) error {
h := (*infohash.T)(k)
torrents[*h] = v
metainfos[*h] = mib.Get(k)
return nil
})
})
log.Infof("loading %d torrents", len(torrents))
td.torrentsLock.Lock()
defer td.torrentsLock.Unlock()
for h, b := range torrents {
var v pb.Torrent
err := proto.Unmarshal(b, &v)
if err != nil {
log.Error(fmt.Errorf("loading state for %s: %w", h.HexString(), err))
continue
}
mi, err := metainfo.Load(bytes.NewReader(metainfos[h]))
if err != nil {
log.Error(fmt.Errorf("loading metainfo for %s: %w", h.HexString(), err))
continue
}
spec := torrent.TorrentSpecFromMetaInfo(mi)
t, _, err := td.client.AddTorrentSpec(spec)
if err != nil {
log.Error(fmt.Errorf("adding existing torrent %s: %w", v.HashHex, err))
continue
}
log.Debugf("added to underlying client: %s", h.HexString())
td.torrents[t.InfoHash()] = td.watch(t, &v)
go func() {
<-t.GotInfo()
t.DownloadAll()
}()
}
log.Infof("done loading torrents (took %v)", time.Since(st))
return nil
}
// add adds a torrent to the underlying client, and then starts to
// track it.
func (td *Torrentd) add(spec *torrent.TorrentSpec) (*pb.Torrent, error) {
h := spec.InfoHash
// This automatically merges, and also checks for existing piece
// completion data (but not the files themselves).
t, _, err := td.client.AddTorrentSpec(spec)
if err != nil {
return nil, err
}
log.Debugf("added to underlying client: %s", t.InfoHash().HexString())
td.torrentsLock.Lock()
defer td.torrentsLock.Unlock()
if st, ok := td.torrents[h]; ok {
return st.ptr.Load(), nil
}
b := new(bytes.Buffer)
err = t.Metainfo().Write(b)
if err != nil {
log.Error(fmt.Errorf("error marshaling metainfo: %w", err))
}
v := &pb.Torrent{
Hash: h[:],
HashHex: h.HexString(),
Name: spec.DisplayName,
State: pb.TorrentState_INITIALIZING,
Started: timestamppb.New(time.Now()),
}
err = td.save(v, b.Bytes())
if err != nil {
log.Error(fmt.Errorf("error saving torrent state: %w", err))
}
td.torrents[h] = td.watch(t, v)
go func() {
<-t.GotInfo()
t.DownloadAll()
}()
return v, nil
}
// remove removes a torrent from the state and deletes any data. It returns
// true if the torrent was found.
func (td *Torrentd) remove(h infohash.T) bool {
log.Infof("removing torrent: %s", h.HexString())
td.torrentsLock.Lock()
defer td.torrentsLock.Unlock()
watcher := td.torrents[h]
delete(td.torrents, h)
if watcher != nil {
go func() {
// The watcher should finish once the state disappears from the
// underlying client.
<-watcher.done
err := td.cleanup(h)
if err != nil {
log.Error(fmt.Errorf("error during torrent cleanup: %w", err))
}
}()
t, _ := td.client.Torrent(h)
if t != nil {
go t.Drop()
}
return true
} else {
return false
}
}
// save writes the torrent to disk, using protobuf serialization. It also saves
// the metainfo bytes in the same transaction, if provided.
func (td *Torrentd) save(v *pb.Torrent, mi []byte) error {
b, err := proto.Marshal(v)
if err != nil {
return fmt.Errorf("error marshaling torrent state: %w", err)
}
err = td.db.Update(func(tx *bolt.Tx) error {
stb, _ := tx.CreateBucketIfNotExists([]byte(stateBucketName))
err := stb.Put(v.Hash, b)
if err != nil {
return err
}
if mi != nil {
mib, _ := tx.CreateBucketIfNotExists([]byte(metainfoBucketName))
err := mib.Put(v.Hash, mi)
return err
}
return nil
})
if err != nil {
return err
}
log.Debugf("wrote torrent state: %s", v.HashHex)
jsonb, err := protojson.Marshal(v)
if err != nil {
return fmt.Errorf("error marshaling torrent state: %w", err)
}
td.events.Publish("torrents", &sse.Event{
Data: jsonb,
})
return nil
}
func (td *Torrentd) cleanup(h infohash.T) error {
hex := h.HexString()
td.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(stateBucketName))
if bucket != nil {
err := bucket.Delete(h[:])
if err != nil {
return err
}
}
bucket.Delete(h[:])
compBucket := tx.Bucket([]byte(completionBucketKey))
if compBucket != nil {
return tx.DeleteBucket(h[:])
}
return nil
})
// Publish a tombstone to subscribers.
b, err := proto.Marshal(&pb.Torrent{
Hash: h[:],
HashHex: hex,
State: pb.TorrentState_DELETED,
})
if err != nil {
return fmt.Errorf("marshaling tombstone: %w", err)
}
td.events.Publish("torrents", &sse.Event{
Data: b,
})
return os.RemoveAll(td.storagePath(h))
}
func (td *Torrentd) list() []*pb.Torrent {
td.torrentsLock.Lock()
defer td.torrentsLock.Unlock()
var res []*pb.Torrent
for _, state := range td.torrents {
res = append(res, state.ptr.Load())
}
return res
}
func (td *Torrentd) watch(t *torrent.Torrent, v *pb.Torrent) *torrentState {
h := t.InfoHash()
hex := h.HexString()
state := &torrentState{
infohash: h,
done: make(chan struct{}),
}
// Store the initial (or existing) value.
state.ptr.Store(v)
// Store the last error
t.SetOnWriteChunkError(func(err error) {
log.Error(fmt.Errorf("torrent error: %s: %v", hex, err))
state.lastErr.Store(&err)
})
// Periodically poll the client for information about the torrent. We want
// to poll active torrents very frequently and inactive torrents
// infrequently.
go func() {
defer close(state.done)
var sleep time.Duration
Polling:
for {
if sleep > 0 {
select {
case <-time.NewTimer(sleep).C:
case <-td.ctx.Done():
break Polling
}
}
t, ok := td.client.Torrent(h)
if t == nil || !ok {
// The torrent disappeared, or was removed.
break Polling
}
select {
case <-t.GotInfo():
case <-td.ctx.Done():
break Polling
}
info := t.Info()
newv := &pb.Torrent{
Hash: h[:],
HashHex: hex,
Name: info.Name,
Started: v.Started,
TotalSize: t.Length(),
TotalCompleted: t.BytesCompleted(),
// TODO stats
TotalUpload: 0,
TotalDownload: 0,
UploadBps: 0,
DownloadBps: 0,
ConnectedPeers: 0,
Files: []*pb.Torrent_File{},
}
for _, f := range t.Files() {
newv.Files = append(newv.Files, &pb.Torrent_File{
Path: f.DisplayPath(),
Size: f.Length(),
Completed: f.BytesCompleted(),
})
}
if newv.TotalCompleted < newv.TotalSize {
if v.State != pb.TorrentState_DOWNLOADING {
log.Debugf("started downloading %s", newv.HashHex)
}
newv.State = pb.TorrentState_DOWNLOADING
log.Debugf("progress: %s: %d%%", newv.HashHex, (100*newv.TotalCompleted)/newv.TotalSize)
} else {
if v.State != pb.TorrentState_SEEDING {
log.Debugf("seeding %s", newv.HashHex)
}
newv.State = pb.TorrentState_SEEDING
}
err := td.save(newv, nil)
if err != nil {
log.Error(fmt.Errorf("error saving torrent state: %w", err))
}
v = newv
state.ptr.Store(v)
// TODO variable sleep
sleep = jitter(100 * time.Millisecond)
}
}()
return state
}
func jitter(d time.Duration) time.Duration {
r := rand.Float64() * float64(d)
r = 0.5*r + 0.5*float64(d)
return time.Duration(0.5*r + 0.5*float64(d))
}