Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 35 additions & 21 deletions src/downloader/downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,12 @@ type Downloader interface {
// albumMigrator is implemented by downloaders that fetch a whole release and
// so have files to migrate beyond the one the monitor tracks. It is optional:
// a downloader that only ever grabs a single file simply does not implement it.
//
// MoveAlbumSiblings returns how many files are still in flight. The monitor
// calls it again while that is above zero, because the recommended track
// normally finishes ahead of the rest of its release.
type albumMigrator interface {
MoveAlbumSiblings(trackDir, destDir string, track *models.Track, keepPermissions bool)
MoveAlbumSiblings(trackDir, destDir string, track *models.Track, keepPermissions bool) int
}

// albumMigrators returns the registered downloaders that migrate whole
Expand Down Expand Up @@ -266,7 +270,11 @@ func buildTrackPath(template string, track *models.Track) string {
return filepath.Clean(result)
}

func (c *DownloadClient) MoveDownload(srcDir, destDir, trackPath string, track *models.Track) error {
// MoveDownload moves the recommended track into the library and returns the
// directory it landed in. Album siblings are migrated by the monitor rather
// than here: they usually have not finished downloading yet, so they need
// revisiting long after this returns.
func (c *DownloadClient) MoveDownload(srcDir, destDir, trackPath string, track *models.Track) (string, error) {
trackDir := filepath.Join(srcDir, trackPath)
srcFile := filepath.Join(trackDir, track.File)

Expand All @@ -282,7 +290,7 @@ func (c *DownloadClient) MoveDownload(srcDir, destDir, trackPath string, track *

in, err := os.Open(srcFile)
if err != nil {
return fmt.Errorf("couldn't open source file: %s", err.Error())
return "", fmt.Errorf("couldn't open source file: %s", err.Error())
}

defer func() {
Expand All @@ -304,18 +312,18 @@ func (c *DownloadClient) MoveDownload(srcDir, destDir, trackPath string, track *
dstFile = filepath.Join(destDir, relativePath)
} else {
if err = os.MkdirAll(destDir, os.ModePerm); err != nil {
return fmt.Errorf("couldn't make download directory: %s", err.Error())
return "", fmt.Errorf("couldn't make download directory: %s", err.Error())
}

dstFile = filepath.Join(destDir, track.File)
}
if err = os.MkdirAll(filepath.Dir(dstFile), os.ModePerm); err != nil {
return fmt.Errorf("couldn't make destination directory: %s", err.Error())
return "", fmt.Errorf("couldn't make destination directory: %s", err.Error())
}

out, err := os.Create(dstFile)
if err != nil {
return fmt.Errorf("couldn't create destination file: %s", err.Error())
return "", fmt.Errorf("couldn't create destination file: %s", err.Error())
}

defer func() {
Expand All @@ -325,42 +333,48 @@ func (c *DownloadClient) MoveDownload(srcDir, destDir, trackPath string, track *
}()

if _, err = io.Copy(out, in); err != nil {
return fmt.Errorf("copy failed: %s", err.Error())
return "", fmt.Errorf("copy failed: %s", err.Error())
}

if err = out.Sync(); err != nil {
return fmt.Errorf("sync failed: %s", err.Error())
return "", fmt.Errorf("sync failed: %s", err.Error())
}

if c.Cfg.KeepPermissions {
info, err := os.Stat(srcFile)
if err != nil {
return fmt.Errorf("stat error: %s", err.Error())
return "", fmt.Errorf("stat error: %s", err.Error())
}
if err = os.Chmod(dstFile, info.Mode()); err != nil {
return fmt.Errorf("chmod failed: %s", err.Error())
return "", fmt.Errorf("chmod failed: %s", err.Error())
}
}

if err = os.Remove(srcFile); err != nil {
return fmt.Errorf("failed to delete original file: %s", err.Error())
return "", fmt.Errorf("failed to delete original file: %s", err.Error())
}

// Siblings move before the emptiness check below, so a directory still
// holding an unfinished album track is not removed out from under it.
for _, m := range c.albumMigrators() {
m.MoveAlbumSiblings(trackDir, filepath.Dir(dstFile), track, c.Cfg.KeepPermissions)
// A directory still holding album siblings is left alone; the monitor
// removes it once it has migrated the last of them.
if err = removeDirIfEmpty(trackDir); err != nil {
return "", err
}

isEmpty, err := isDirEmpty(trackDir)
return filepath.Dir(dstFile), nil
}

// removeDirIfEmpty cleans up a download directory once nothing is left in it.
func removeDirIfEmpty(dir string) error {
isEmpty, err := isDirEmpty(dir)
if err != nil {
return fmt.Errorf("couldn't check if directory is empty: %s", err.Error())
} else if isEmpty {
if err = os.Remove(trackDir); err != nil {
return fmt.Errorf("failed to remove empty directory: %s", err.Error())
}
}

if !isEmpty {
return nil
}
if err = os.Remove(dir); err != nil {
return fmt.Errorf("failed to remove empty directory: %s", err.Error())
}
return nil
}

Expand Down
87 changes: 83 additions & 4 deletions src/downloader/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"explo/src/models"
"fmt"
"log/slog"
"path/filepath"
"strings"
"time"
)
Expand Down Expand Up @@ -34,10 +35,26 @@ type FileStatus struct {
PercentComplete float64 `json:"percentComplete"`
}

// pendingAlbum is a release whose recommended track has already been migrated
// but whose remaining files are still downloading. The monitor revisits these
// each tick, because the recommended track is queued first and so normally
// finishes well ahead of its siblings.
type pendingAlbum struct {
track *models.Track
trackDir string
destDir string
// remaining is the count the migrator last reported. Progress is measured
// against this rather than against the migrator's own bookkeeping, so the
// deadline depends only on what the interface returns.
remaining int
lastChange time.Time
}

func (c *DownloadClient) MonitorDownloads(tracks []*models.Track, m Monitor) error {
var successDownloads int

progressMap := make(map[string]*DownloadMonitor)
pendingAlbums := make(map[string]*pendingAlbum)
monCfg, err := m.GetConf()
if err != nil {
return err
Expand Down Expand Up @@ -89,10 +106,17 @@ func (c *DownloadClient) MonitorDownloads(tracks []*models.Track, m Monitor) err
var path string
track.File, path = parsePath(track.File)
if monCfg.MigrateDownload {
if err = c.MoveDownload(monCfg.FromDir, monCfg.ToDir, path, track); err != nil {
destDir, err := c.MoveDownload(monCfg.FromDir, monCfg.ToDir, path, track)
if err != nil {
slog.Error("error while moving file", "err", err.Error())
} else {
slog.Info("track moved successfully", "service", monCfg.Service)
c.trackAlbum(pendingAlbums, key, &pendingAlbum{
track: track,
trackDir: filepath.Join(monCfg.FromDir, path),
destDir: destDir,
lastChange: currentTime,
}, monCfg)
}
}
delete(progressMap, key)
Expand All @@ -117,8 +141,11 @@ func (c *DownloadClient) MonitorDownloads(tracks []*models.Track, m Monitor) err
continue
}
}
// Exit condition: all tracks have been processed or skipped
if tracksProcessed(tracks, progressMap) {
c.migratePendingAlbums(pendingAlbums, monCfg, time.Now().Local())

// Exit condition: all tracks have been processed or skipped, and
// every release has finished being migrated
if tracksProcessed(tracks, progressMap) && len(pendingAlbums) == 0 {
slog.Info("[monitor] Finished", "service", monCfg.Service, "downloaded files", successDownloads, "total tracks", len(tracks))
return nil
}
Expand All @@ -137,4 +164,56 @@ func tracksProcessed(tracks []*models.Track, progressMap map[string]*DownloadMon
}
}
return true
}
}
// trackAlbum records a release for later migration, migrating whatever has
// already finished. Releases with nothing left over are never recorded, so a
// single-track download costs nothing.
func (c *DownloadClient) trackAlbum(pending map[string]*pendingAlbum, key string, album *pendingAlbum, monCfg MonitorConfig) {
if remaining := c.migrateAlbum(album); remaining > 0 {
album.remaining = remaining
pending[key] = album
slog.Info("[monitor] waiting for the rest of the release", "service", monCfg.Service,
"album", album.track.Album, "files", remaining)
}
}

// migrateAlbum moves whatever of one release has finished, returning how many
// of its files are still in flight.
func (c *DownloadClient) migrateAlbum(album *pendingAlbum) int {
var remaining int
for _, m := range c.albumMigrators() {
remaining += m.MoveAlbumSiblings(album.trackDir, album.destDir, album.track, c.Cfg.KeepPermissions)
}
return remaining
}

// migratePendingAlbums revisits every release still waiting on files. A release
// that stops making progress is abandoned on the same deadline a stalled track
// is, so the monitor cannot be held open by a peer that has gone away.
func (c *DownloadClient) migratePendingAlbums(pending map[string]*pendingAlbum, monCfg MonitorConfig, now time.Time) {
for key, album := range pending {
before := album.remaining
remaining := c.migrateAlbum(album)
album.remaining = remaining

if remaining == 0 {
delete(pending, key)
if err := removeDirIfEmpty(album.trackDir); err != nil {
slog.Debug("couldn't clean up release directory", "context", err.Error())
}
slog.Info("[monitor] release fully migrated", "service", monCfg.Service, "album", album.track.Album)
continue
}

if remaining < before {
album.lastChange = now
continue
}

if now.Sub(album.lastChange) > monCfg.MonitorDuration {
delete(pending, key)
slog.Warn("[monitor] giving up on the rest of the release", "service", monCfg.Service,
"album", album.track.Album, "files left in place", remaining)
}
}
}
Loading
Loading