tstor/daemons/torrent/daemon.go

227 lines
5.1 KiB
Go
Raw Normal View History

2024-05-19 21:24:09 +00:00
package torrent
2023-10-16 09:18:40 +00:00
import (
2023-12-21 23:15:39 +00:00
"context"
2024-05-13 16:56:20 +00:00
"errors"
2023-12-21 23:15:39 +00:00
"fmt"
2024-01-28 20:22:49 +00:00
"os"
"path/filepath"
2024-03-28 13:09:42 +00:00
"sync"
"time"
2023-10-16 09:18:40 +00:00
2024-03-28 13:09:42 +00:00
"git.kmsign.ru/royalcat/tstor/pkg/rlog"
2024-03-19 21:30:37 +00:00
"git.kmsign.ru/royalcat/tstor/src/config"
2024-06-16 21:34:46 +00:00
"git.kmsign.ru/royalcat/tstor/src/tkv"
2024-06-02 19:53:33 +00:00
"git.kmsign.ru/royalcat/tstor/src/vfs"
2024-03-28 13:09:42 +00:00
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
2024-08-15 08:23:44 +00:00
"go.opentelemetry.io/otel/metric"
2024-03-28 13:09:42 +00:00
"go.opentelemetry.io/otel/trace"
2024-03-19 21:30:37 +00:00
"golang.org/x/exp/maps"
2024-01-28 20:22:49 +00:00
2023-10-16 09:18:40 +00:00
"github.com/anacrolix/torrent"
2024-01-28 20:22:49 +00:00
"github.com/anacrolix/torrent/bencode"
2023-10-16 09:18:40 +00:00
"github.com/anacrolix/torrent/metainfo"
2024-01-28 20:22:49 +00:00
"github.com/anacrolix/torrent/types/infohash"
"github.com/go-git/go-billy/v5"
2024-03-19 21:30:37 +00:00
"github.com/royalcat/kv"
2023-10-16 09:18:40 +00:00
)
2024-10-26 22:19:16 +00:00
const instrument = "git.kmsign.ru/royalcat/tstor/daemons/torrent"
2024-08-15 08:23:44 +00:00
var (
tracer = otel.Tracer(instrument, trace.WithInstrumentationAttributes(attribute.String("component", "torrent-daemon")))
meter = otel.Meter(instrument, metric.WithInstrumentationAttributes(attribute.String("component", "torrent-daemon")))
2024-07-08 21:19:04 +00:00
)
2024-03-28 13:09:42 +00:00
2024-03-19 21:30:37 +00:00
type DirAquire struct {
Name string
Hashes []infohash.T
}
2024-06-14 22:14:44 +00:00
type Daemon struct {
2024-06-16 21:34:46 +00:00
client *torrent.Client
infoBytes *infoBytesStore
Storage *fileStorage
2024-07-10 09:26:17 +00:00
fis *dhtFileItemStore
2024-06-16 21:34:46 +00:00
dirsAquire kv.Store[string, DirAquire]
fileProperties kv.Store[string, FileProperties]
2024-07-16 20:58:06 +00:00
statsStore *statsStore
2024-01-28 20:22:49 +00:00
loadMutex sync.Mutex
2023-10-16 09:18:40 +00:00
sourceFs billy.Filesystem
2024-03-19 21:30:37 +00:00
2024-04-17 08:36:14 +00:00
log *rlog.Logger
2023-10-16 09:18:40 +00:00
}
2024-08-15 08:23:44 +00:00
const dhtTTL = 180 * 24 * time.Hour
2024-07-16 20:58:06 +00:00
func NewDaemon(sourceFs billy.Filesystem, conf config.TorrentClient) (*Daemon, error) {
2024-06-14 22:14:44 +00:00
s := &Daemon{
log: rlog.Component("torrent-service"),
sourceFs: sourceFs,
loadMutex: sync.Mutex{},
}
err := os.MkdirAll(conf.MetadataFolder, 0744)
if err != nil {
return nil, fmt.Errorf("error creating metadata folder: %w", err)
}
2024-07-16 20:58:06 +00:00
s.fis, err = newDHTStore(filepath.Join(conf.MetadataFolder, "dht-item-store"), dhtTTL)
if err != nil {
return nil, fmt.Errorf("error starting item store: %w", err)
}
2024-05-19 21:24:09 +00:00
s.Storage, _, err = setupStorage(conf)
2024-03-19 21:30:37 +00:00
if err != nil {
return nil, err
}
2024-06-16 21:34:46 +00:00
s.fileProperties, err = tkv.NewKV[string, FileProperties](conf.MetadataFolder, "file-properties")
if err != nil {
return nil, err
}
2024-05-19 21:24:09 +00:00
s.infoBytes, err = newInfoBytesStore(conf.MetadataFolder)
if err != nil {
return nil, err
}
2024-05-19 21:36:22 +00:00
id, err := getOrCreatePeerID(filepath.Join(conf.MetadataFolder, "ID"))
if err != nil {
return nil, fmt.Errorf("error creating node ID: %w", err)
}
2024-07-16 20:58:06 +00:00
s.statsStore, err = newStatsStore(conf.MetadataFolder, time.Hour*24*30)
if err != nil {
return nil, err
}
2024-08-15 08:23:44 +00:00
clientConfig := newClientConfig(s.Storage, s.fis, &conf, id)
s.client, err = torrent.NewClient(clientConfig)
if err != nil {
2024-08-15 08:23:44 +00:00
return nil, err
}
2024-08-15 08:23:44 +00:00
// TODO move to config
s.client.AddDhtNodes([]string{
"router.bittorrent.com:6881",
"router.utorrent.com:6881",
"dht.transmissionbt.com:6881",
"router.bitcomet.com:6881",
"dht.aelitis.com6881",
})
2024-06-02 21:20:43 +00:00
s.client.AddDhtNodes(conf.DHTNodes)
2024-06-16 21:34:46 +00:00
s.dirsAquire, err = tkv.NewKV[string, DirAquire](conf.MetadataFolder, "dir-acquire")
if err != nil {
return nil, err
2023-10-16 09:18:40 +00:00
}
2024-01-28 20:22:49 +00:00
2024-08-31 23:00:13 +00:00
// go func() {
// ctx := context.Background()
// err := s.backgroudFileLoad(ctx)
// if err != nil {
// s.log.Error(ctx, "initial torrent load failed", rlog.Error(err))
// }
// }()
2024-01-28 20:22:49 +00:00
2024-07-16 20:58:06 +00:00
go func() {
2024-08-15 08:23:44 +00:00
ctx := context.Background()
2024-07-16 20:58:06 +00:00
const period = time.Second * 10
2024-08-15 08:23:44 +00:00
err := registerTorrentMetrics(s.client)
if err != nil {
s.log.Error(ctx, "error registering torrent metrics", rlog.Error(err))
}
err = registerDhtMetrics(s.client)
if err != nil {
s.log.Error(ctx, "error registering dht metrics", rlog.Error(err))
}
2024-07-16 20:58:06 +00:00
timer := time.NewTicker(period)
for {
select {
case <-s.client.Closed():
return
case <-timer.C:
2024-08-15 08:23:44 +00:00
s.updateStats(ctx)
2024-07-16 20:58:06 +00:00
}
}
}()
2024-03-19 21:30:37 +00:00
return s, nil
2023-10-16 09:18:40 +00:00
}
2024-06-14 22:14:44 +00:00
var _ vfs.FsFactory = (*Daemon)(nil).NewTorrentFs
2023-10-16 09:18:40 +00:00
2024-06-14 22:14:44 +00:00
func (s *Daemon) Close(ctx context.Context) error {
2024-05-13 16:56:20 +00:00
return errors.Join(append(
s.client.Close(),
2024-05-13 16:56:20 +00:00
s.Storage.Close(),
s.dirsAquire.Close(ctx),
2024-06-16 21:34:46 +00:00
// s.excludedFiles.Close(ctx),
s.infoBytes.Close(),
s.fis.Close(),
2024-05-13 16:56:20 +00:00
)...)
2024-03-17 21:00:34 +00:00
}
2024-01-28 20:22:49 +00:00
func isValidInfoHashBytes(d []byte) bool {
var info metainfo.Info
err := bencode.Unmarshal(d, &info)
return err == nil
}
2024-07-10 09:26:17 +00:00
func (s *Daemon) Stats() torrent.ConnStats {
2024-07-16 20:58:06 +00:00
return s.client.Stats().ConnStats
2024-01-28 20:22:49 +00:00
}
2024-06-16 21:34:46 +00:00
func storeByTorrent[K kv.Bytes, V any](s kv.Store[K, V], infohash infohash.T) kv.Store[K, V] {
return kv.PrefixBytes[K, V](s, K(infohash.HexString()+"/"))
}
func (s *Daemon) newController(t *torrent.Torrent) *Controller {
return newController(t,
storeByTorrent(s.fileProperties, t.InfoHash()),
s.Storage,
2024-07-10 09:26:17 +00:00
s.log,
2024-06-16 21:34:46 +00:00
)
}
2024-06-14 22:14:44 +00:00
func (s *Daemon) ListTorrents(ctx context.Context) ([]*Controller, error) {
2024-05-19 21:24:09 +00:00
out := []*Controller{}
for _, v := range s.client.Torrents() {
2024-06-16 21:34:46 +00:00
out = append(out, s.newController(v))
2024-01-28 20:22:49 +00:00
}
return out, nil
2023-10-16 09:18:40 +00:00
}
2024-01-07 17:09:56 +00:00
2024-06-14 22:14:44 +00:00
func (s *Daemon) GetTorrent(infohashHex string) (*Controller, error) {
t, ok := s.client.Torrent(infohash.FromHexString(infohashHex))
2024-01-28 20:22:49 +00:00
if !ok {
return nil, nil
}
2024-06-16 21:34:46 +00:00
return s.newController(t), nil
2024-01-07 17:09:56 +00:00
}
2024-03-19 21:30:37 +00:00
func slicesUnique[S ~[]E, E comparable](in S) S {
m := map[E]struct{}{}
for _, v := range in {
m[v] = struct{}{}
}
return maps.Keys(m)
}
func apply[I, O any](in []I, f func(e I) O) []O {
out := []O{}
for _, v := range in {
out = append(out, f(v))
}
return out
}