fastframes-voice / housekeeping.py
fffiloni's picture
Add a read-only segment timeline and protect temporary studio media
8ef249c verified
Raw History Blame Contribute Delete
2.53 kB
"""Reclaim abandoned temporary takes and share disk headroom between renders."""
import logging
import shutil
import threading
import time
import gallery
import takes
IDLE_SECONDS = 90 * 60
MIN_FREE = 512 * 1024**2
with takes.connection() as db:
db.execute("CREATE TABLE reservations (id TEXT PRIMARY KEY, bytes INTEGER NOT NULL)")
def reserve(key, size):
with takes.connection() as db:
db.execute("BEGIN IMMEDIATE")
reserved = db.execute("SELECT coalesce(sum(bytes),0) FROM reservations").fetchone()[0]
if size + reserved + MIN_FREE > shutil.disk_usage(takes.ROOT).free:
return False
db.execute("INSERT INTO reservations VALUES (?,?)", (key,size))
return True
def release(key):
with takes.connection() as db:
db.execute("DELETE FROM reservations WHERE id=?", (key,))
def sweep():
cutoff = int(time.time()) - IDLE_SECONDS
with takes.connection() as db:
owners = db.execute("""SELECT owner FROM takes WHERE touched<? AND phase NOT IN ('live','interpreting')
UNION SELECT session FROM media WHERE touched<?""",(cutoff,cutoff)).fetchall()
for (owner,) in owners:
with gallery.lock_for(owner), takes.connection() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT id,touched,phase FROM takes WHERE owner=?", (owner,)).fetchone()
if row and (row["touched"] >= cutoff or row["phase"] in ("live","interpreting")):
continue
paths = takes.remove_owner(db,owner) if row else []
expired = db.execute("SELECT path FROM media WHERE session=? AND touched<?",(owner,cutoff)).fetchall()
db.execute("DELETE FROM media WHERE session=? AND touched<?",(owner,cutoff))
db.commit()
for path in paths:
shutil.rmtree(path,ignore_errors=True)
for (relative,) in expired:
if relative.startswith("viewing/"):
file = takes.ROOT / relative
file.unlink(missing_ok=True)
try:
file.parent.rmdir()
except OSError:
pass
def start():
def periodic():
while True:
time.sleep(60)
try:
sweep()
except Exception:
logging.getLogger("studio").exception("Temporary session cleanup failed")
threading.Thread(target=periodic,name="temporary-take-cleanup",daemon=True).start()