File size: 3,544 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Public site cleanup, every few minutes in a background thread of the API server:



* songs older than `public.keep_songs_hours` are deleted with their stems and mixes (unless a job still runs);

* usage rows older than the daily limits look at are forgotten;

* song folders without a database row (e.g. after the server was stopped mid-upload) are removed.

"""

from __future__ import annotations

import logging
import shutil
import threading
import time
from datetime import timedelta

from sqlmodel import Session, col, select

from stemdeck import quotas
from stemdeck.db import get_engine
from stemdeck.library import SONG_ID, remove_song
from stemdeck.models import ACTIVE_JOB_STATUSES, Job, Song, utcnow
from stemdeck.settings import get_config, get_settings

log = logging.getLogger(__name__)

INTERVAL_SEC = 600.0
MAX_STDOUT_LOG_BYTES = 20 * 1024 * 1024  # worker-stdout.log is appended to by every worker and never rotated
ORPHAN_GRACE_SEC = 3 * 3600.0  # an upload in progress has a folder but no row yet; leave young folders alone


def expire_songs(session: Session, keep_hours: float) -> int:
    cutoff = utcnow() - timedelta(hours=keep_hours)
    expired = session.exec(select(Song).where(col(Song.created_at) < cutoff)).all()
    removed = 0
    for song in expired:
        busy = session.exec(select(Job).where(Job.song_id == song.id,
                                              col(Job.status).in_(ACTIVE_JOB_STATUSES))).first()
        if busy is None:
            remove_song(session, song.id)
            removed += 1
    return removed


def remove_orphan_folders(session: Session) -> int:
    songs_dir = get_settings().songs_dir
    known = set(session.exec(select(Song.id)).all())
    cutoff = time.time() - ORPHAN_GRACE_SEC
    removed = 0
    for folder in songs_dir.iterdir():
        if folder.is_dir() and SONG_ID.fullmatch(folder.name) and folder.name not in known:
            try:
                too_young = folder.stat().st_mtime > cutoff
            except OSError:
                continue
            if not too_young:
                shutil.rmtree(folder, ignore_errors=True)
                removed += 1
    return removed


def trim_worker_stdout_log() -> None:
    log_file = get_settings().logs_dir / "worker-stdout.log"
    try:
        if log_file.stat().st_size > MAX_STDOUT_LOG_BYTES:
            log_file.write_bytes(b"")
    except OSError:
        return


def run_once() -> None:
    trim_worker_stdout_log()
    with Session(get_engine()) as session:
        songs = expire_songs(session, get_config().public.keep_songs_hours)
        usage = quotas.purge_old_usage(session)
        folders = remove_orphan_folders(session)
    if songs or usage or folders:
        log.info("cleanup: %d expired songs, %d usage rows, %d orphan folders removed", songs, usage, folders)


class Housekeeper:
    def __init__(self) -> None:
        self._stop = threading.Event()
        self._thread = threading.Thread(target=self._loop, name="housekeeping", daemon=True)

    def start(self) -> None:
        self._thread.start()

    def stop(self) -> None:
        self._stop.set()

    def _loop(self) -> None:
        while not self._stop.is_set():
            try:
                run_once()
            except Exception:  # noqa: BLE001 - never let cleanup take the server down
                log.exception("cleanup failed")
            self._stop.wait(INTERVAL_SEC)


housekeeper = Housekeeper()