tstor/src/sources/torrent/daemon.go

359 lines
8.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 (
2024-03-28 13:09:42 +00:00
"bufio"
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"
"log/slog"
2024-01-28 20:22:49 +00:00
"os"
"path/filepath"
"strings"
2024-03-28 13:09:42 +00:00
"sync"
"time"
2023-10-16 09:18:40 +00:00
2024-06-14 22:14:44 +00:00
"git.kmsign.ru/royalcat/tstor/pkg/ctxbilly"
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"
"github.com/royalcat/ctxio"
2024-03-28 13:09:42 +00:00
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"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"
"github.com/go-git/go-billy/v5/util"
2024-03-19 21:30:37 +00:00
"github.com/royalcat/kv"
2023-10-16 09:18:40 +00:00
)
2024-07-08 21:19:04 +00:00
var tracer = otel.Tracer("git.kmsign.ru/royalcat/tstor/sources/torrent",
trace.WithInstrumentationAttributes(attribute.String("component", "torrent-daemon")),
)
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
fis *fileItemStore
dirsAquire kv.Store[string, DirAquire]
fileProperties kv.Store[string, FileProperties]
2024-01-28 20:22:49 +00:00
loadMutex sync.Mutex
2024-01-28 20:22:49 +00:00
torrentLoaded chan struct{}
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-06-14 22:14:44 +00:00
func NewService(sourceFs billy.Filesystem, conf config.TorrentClient) (*Daemon, error) {
s := &Daemon{
log: rlog.Component("torrent-service"),
sourceFs: sourceFs,
torrentLoaded: make(chan struct{}),
loadMutex: sync.Mutex{},
}
err := os.MkdirAll(conf.MetadataFolder, 0744)
if err != nil {
return nil, fmt.Errorf("error creating metadata folder: %w", err)
}
2024-05-19 21:36:22 +00:00
s.fis, err = newFileItemStore(filepath.Join(conf.MetadataFolder, "items"), 2*time.Hour)
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)
2024-06-16 21:34:46 +00:00
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-06-02 21:20:43 +00:00
s.client, err = newClient(s.Storage, s.fis, &conf, id)
if err != nil {
return nil, fmt.Errorf("error starting torrent client: %w", err)
}
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
go func() {
2024-03-28 13:09:42 +00:00
ctx := context.Background()
err := s.loadTorrentFiles(ctx)
2024-01-28 20:22:49 +00:00
if err != nil {
2024-04-17 08:36:14 +00:00
s.log.Error(ctx, "initial torrent load failed", rlog.Error(err))
2024-01-28 20:22:49 +00:00
}
close(s.torrentLoaded)
}()
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-06-25 21:39:30 +00:00
func (s *Daemon) loadTorrent(ctx context.Context, f vfs.File) (*Controller, error) {
2024-07-08 21:19:04 +00:00
ctx, span := tracer.Start(ctx, "loadTorrent")
2024-03-28 13:09:42 +00:00
defer span.End()
2024-04-17 08:36:14 +00:00
log := s.log
2024-03-28 13:09:42 +00:00
stat, err := f.Info()
2024-01-07 17:09:56 +00:00
if err != nil {
2024-01-28 20:22:49 +00:00
return nil, fmt.Errorf("call stat failed: %w", err)
2024-01-07 17:09:56 +00:00
}
2024-03-28 13:09:42 +00:00
span.SetAttributes(attribute.String("filename", stat.Name()))
mi, err := metainfo.Load(bufio.NewReader(ctxio.IoReader(ctx, f)))
2024-01-28 20:22:49 +00:00
if err != nil {
return nil, fmt.Errorf("loading torrent metadata from file %s, error: %w", stat.Name(), err)
}
2024-03-28 13:09:42 +00:00
t, ok := s.client.Torrent(mi.HashInfoBytes())
2024-01-07 17:09:56 +00:00
if !ok {
2024-03-28 13:09:42 +00:00
span.AddEvent("torrent not found, loading from file")
2024-04-17 08:36:14 +00:00
log.Info(ctx, "torrent not found, loading from file")
2024-03-28 13:09:42 +00:00
2024-01-28 20:22:49 +00:00
spec, err := torrent.TorrentSpecFromMetaInfoErr(mi)
2024-01-07 17:09:56 +00:00
if err != nil {
2024-01-28 20:22:49 +00:00
return nil, fmt.Errorf("parse spec from metadata: %w", err)
}
infoBytes := spec.InfoBytes
if !isValidInfoHashBytes(infoBytes) {
2024-04-17 08:36:14 +00:00
log.Warn(ctx, "info loaded from spec not valid")
2024-01-28 20:22:49 +00:00
infoBytes = nil
2024-01-07 17:09:56 +00:00
}
2024-01-28 20:22:49 +00:00
if len(infoBytes) == 0 {
2024-04-17 08:36:14 +00:00
log.Info(ctx, "no info loaded from file, try to load from cache")
2024-01-28 20:22:49 +00:00
infoBytes, err = s.infoBytes.GetBytes(spec.InfoHash)
2024-05-19 21:24:09 +00:00
if err != nil && err != errNotFound {
2024-01-28 20:22:49 +00:00
return nil, fmt.Errorf("get info bytes from database: %w", err)
}
}
t, _ = s.client.AddTorrentOpt(torrent.AddTorrentOpts{
2024-01-28 20:22:49 +00:00
InfoHash: spec.InfoHash,
Storage: s.Storage,
InfoBytes: infoBytes,
ChunkSize: spec.ChunkSize,
})
t.AllowDataDownload()
2024-02-22 22:54:56 +00:00
t.AllowDataUpload()
2024-01-28 20:22:49 +00:00
2024-03-28 13:09:42 +00:00
span.AddEvent("torrent added to client")
2024-01-07 17:09:56 +00:00
select {
case <-ctx.Done():
2024-03-28 13:09:42 +00:00
return nil, ctx.Err()
2024-01-07 17:09:56 +00:00
case <-t.GotInfo():
2024-01-28 20:22:49 +00:00
err := s.infoBytes.Set(t.InfoHash(), t.Metainfo())
if err != nil {
2024-04-17 08:36:14 +00:00
log.Error(ctx, "error setting info bytes for torrent",
slog.String("torrent-name", t.Name()),
rlog.Error(err),
)
2024-01-28 20:22:49 +00:00
}
2024-03-28 13:09:42 +00:00
}
span.AddEvent("got info")
2024-01-28 20:22:49 +00:00
2024-06-14 22:14:44 +00:00
// info := t.Info()
// if info == nil {
// return nil, fmt.Errorf("info is nil")
// }
// compatable, _, err := s.checkTorrentCompatable(ctx, spec.InfoHash, *info)
// if err != nil {
// return nil, err
// }
// if !compatable {
// return nil, fmt.Errorf(
// "torrent with name '%s' not compatable existing infohash: %s, new: %s",
// t.Name(), t.InfoHash().HexString(), spec.InfoHash.HexString(),
// )
// }
2024-01-07 17:09:56 +00:00
}
2024-06-16 21:34:46 +00:00
ctl := s.newController(t)
2024-01-07 17:09:56 +00:00
2024-06-14 22:14:44 +00:00
err = ctl.initializeTorrentPriories(ctx)
2024-03-19 21:30:37 +00:00
if err != nil {
2024-06-14 22:14:44 +00:00
log.Error(ctx, "error initializing torrent priorities", rlog.Error(err))
2024-02-22 22:54:56 +00:00
}
2024-06-14 22:14:44 +00:00
return ctl, nil
2024-03-19 21:30:37 +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-06-14 22:14:44 +00:00
func (s *Daemon) Stats() (*Stats, error) {
2024-01-28 20:22:49 +00:00
return &Stats{}, nil
}
2024-06-14 22:14:44 +00:00
func (s *Daemon) GetStats() torrent.ConnStats {
return s.client.ConnStats()
2024-01-28 20:22:49 +00:00
}
2024-03-28 13:09:42 +00:00
const loadWorkers = 5
2024-06-14 22:14:44 +00:00
func (s *Daemon) loadTorrentFiles(ctx context.Context) error {
2024-03-28 13:09:42 +00:00
ctx, span := tracer.Start(ctx, "loadTorrentFiles", trace.WithAttributes(
attribute.Int("workers", loadWorkers),
))
defer span.End()
2024-04-17 08:36:14 +00:00
log := s.log
2024-03-28 13:09:42 +00:00
2024-07-08 21:19:04 +00:00
loaderPaths := make(chan string, loadWorkers*5)
2024-03-28 13:09:42 +00:00
wg := sync.WaitGroup{}
defer func() {
close(loaderPaths)
wg.Wait()
}()
loaderWorker := func() {
for path := range loaderPaths {
2024-06-14 22:14:44 +00:00
info, err := s.sourceFs.Stat(path)
if err != nil {
log.Error(ctx, "error stat torrent file", slog.String("filename", path), rlog.Error(err))
continue
}
file, err := s.sourceFs.Open(path)
2024-03-28 13:09:42 +00:00
if err != nil {
2024-04-17 08:36:14 +00:00
log.Error(ctx, "error opening torrent file", slog.String("filename", path), rlog.Error(err))
2024-03-28 13:09:42 +00:00
continue
}
2024-06-14 22:14:44 +00:00
defer file.Close()
vfile := vfs.NewCtxBillyFile(info, ctxbilly.WrapFile(file))
2024-03-28 13:09:42 +00:00
2024-06-25 21:39:30 +00:00
_, err = s.loadTorrent(ctx, vfile)
2024-03-28 13:09:42 +00:00
if err != nil {
2024-04-17 08:36:14 +00:00
log.Error(ctx, "failed adding torrent", rlog.Error(err))
2024-03-28 13:09:42 +00:00
}
}
wg.Done()
}
2024-06-14 22:14:44 +00:00
wg.Add(loadWorkers)
2024-03-28 13:09:42 +00:00
for range loadWorkers {
go loaderWorker()
}
2024-06-14 22:14:44 +00:00
return util.Walk(s.sourceFs, "", func(path string, info os.FileInfo, err error) error {
2023-12-21 23:15:39 +00:00
if err != nil {
2024-01-28 20:22:49 +00:00
return fmt.Errorf("fs walk error: %w", err)
2023-12-21 23:15:39 +00:00
}
2024-01-28 20:22:49 +00:00
if ctx.Err() != nil {
return ctx.Err()
}
if info.IsDir() {
return nil
2023-12-21 23:15:39 +00:00
}
2024-01-28 20:22:49 +00:00
if strings.HasSuffix(path, ".torrent") {
2024-03-28 13:09:42 +00:00
loaderPaths <- path
2023-12-21 23:15:39 +00:00
}
2023-10-18 09:52:48 +00:00
2024-01-28 20:22:49 +00:00
return nil
})
2023-10-16 09:18:40 +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-06-14 22:14:44 +00:00
func (s *Daemon) ListTorrents(ctx context.Context) ([]*Controller, error) {
2024-01-28 20:22:49 +00:00
<-s.torrentLoaded
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) {
2024-01-28 20:22:49 +00:00
<-s.torrentLoaded
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
}