Skip to content
Open
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
33 changes: 32 additions & 1 deletion tiering/offload/altmount.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import os
import re
import ssl
import threading
import time
import urllib.parse
import uuid
Expand Down Expand Up @@ -262,6 +263,33 @@ def __init__(self, url: str | None = None, apikey: str | None = None, *,
self._timeout = timeout
self._sleep = sleep
self._clock = clock
self._jobs: dict = {} # path an import returned -> the job id this client made for it
self._jobs_mu = threading.Lock()

def job_of(self, remote_path: str):
"""The job id this client used for the import that returned `remote_path`, or None."""
with self._jobs_mu:
return self._jobs.get(remote_path)

def remove(self, job_id: str) -> bool:
"""Remove one import by the job id this client made, through AltMount's SABnzbd
history delete (the same endpoint and key as the import). Only a job id this client
made is accepted (the caller keeps the record of it, so it survives a restart). AltMount
answers true even for an id it does not know."""
if not re.fullmatch(r"[0-9a-f]{32}", str(job_id)):
raise AltMountError("not a job id of ours")
q = urllib.parse.urlencode({"name": "delete", "value": job_id, "del_files": "1"})
body = urllib.parse.urlencode({"mode": "history", "output": "json",
"apikey": self._key}).encode()
conn, resp = self._http.open(
"POST", f"/sabnzbd/api?{q}",
{"Content-Type": "application/x-www-form-urlencoded"}, body)
if not self._json(resp, conn).get("status"):
raise AltMountError("altmount refused the removal")
with self._jobs_mu:
for k in [k for k, v in self._jobs.items() if v == job_id]:
del self._jobs[k]
return True

def _json(self, resp, conn):
try:
Expand Down Expand Up @@ -329,7 +357,10 @@ def import_nzb(self, nzb_bytes: bytes, release_name: str) -> str:
if slot:
st = (slot.get("status") or "").lower()
if st == "completed":
return self._remote_path(slot)
path = self._remote_path(slot)
with self._jobs_mu:
self._jobs[path] = job_id
return path
if st == "failed":
raise ImportFailed("altmount import failed")
if self._clock() >= deadline:
Expand Down
37 changes: 37 additions & 0 deletions tiering/offload/redownload.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,43 @@ def find(self, lib_path: str):
"unmonitored": [e["id"] for e in hit if not e.get("monitored")]}
return None

def locate(self, row):
"""Where the arrs themselves put the row's media item now, by its identity (never by
the path it used to have): {"paths": [share paths of its file], "has_file": bool,
"queued": bool}. None when the row has no identity to ask by. Raises ArrError when an
arr cannot answer (what an arr did not say is not "no file"). A movie is asked by its
imdb id, an episode by its series' tvdb id with its season and episode number."""
kind = row.get("kind")
out = {"paths": [], "has_file": False, "queued": False}
if kind == "movie" and row.get("imdb_id"):
for c in self.radarrs:
for m in c.get("/api/v3/movie", imdbId=str(row["imdb_id"])) or []:
f = m.get("movieFile") if isinstance(m, dict) else None
if f and f.get("path"):
out["paths"].append(self._local(f["path"]))
out["has_file"] = out["has_file"] or bool(m.get("hasFile"))
if c.get("/api/v3/queue/details", movieId=int(m["id"])):
out["queued"] = True
return out
if (kind == "episode" and row.get("tvdb_id") and row.get("season") is not None
and row.get("episode") is not None):
for c in self.sonarrs:
for sr in c.get("/api/v3/series", tvdbId=str(row["tvdb_id"])) or []:
eps = c.get("/api/v3/episode", seriesId=sr["id"],
seasonNumber=int(row["season"]), includeEpisodeFile="true")
for e in eps or []:
if e.get("episodeNumber") != int(row["episode"]):
continue
f = e.get("episodeFile")
if isinstance(f, dict) and f.get("path"):
out["paths"].append(self._local(f["path"]))
out["has_file"] = out["has_file"] or bool(e.get("hasFile"))
if c.get("/api/v3/queue/details", seriesId=sr["id"],
episodeIds=int(e["id"])):
out["queued"] = True
return out
return None

def _client(self, item):
pool = self.radarrs if item["kind"] == "radarr" else self.sonarrs
try:
Expand Down
5 changes: 5 additions & 0 deletions tiering/offload/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,11 @@ def _adopt_renamed(state, db, apply, local, cand, resolve, mount, out) -> bool:
if apply and not state.update_if(db, id, row["state"], lib_path=local):
out["renamed"] -= 1
out["renamed_skipped"] += 1
elif apply and getattr(state, "note_only_follow", None) and row.get("lib_path"):
try: # a TIERING_ONLY_PATHS entry follows the row to its new path (and only that one)
state.note_only_follow(db, row["lib_path"], local)
except Exception as e: # noqa: BLE001
log.warning("register: the allowlist could not follow row %s (%s)", id, type(e).__name__)
return True


Expand Down
176 changes: 173 additions & 3 deletions tiering/offload/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,14 @@
REGISTER_BAD_FRAC = 0.05 # missing_local + ambiguous over this share of listed fails register (on_pool is not counted)
RESTORED_NOTE = "restored from the restore path" # ops.RESTORED_NOTE
ORPHAN_NOTES = ("L replaced", RESTORED_NOTE) # failed rows whose stub the orphan cleanup may remove
GONE_NOTE = "L gone: removed by the arr or the user" # kept apart from ORPHAN_NOTES: its stub is not removed
GONE_DAYS = 7.0 # L missing this long, with the arr saying it has no file for the item (TIERING_L_GONE_DAYS; 0: never)
GONE_LOOKUP_EVERY = 3600.0 # a row whose L is missing is looked up in the arrs this often
GONE_LOOKUPS_PER_PASS = 10 # arr lookups for missing L per pass: a few calls each, never a sweep
GONE_MASS = 25 # this many rows past the grace at once look like an unmounted disk, not deletions: act on none
# ops events, alerted once per id
ALERT_EVENTS = ("promote_short_remote", "takeover_orphan", "substitute_hash_failed")
ONCE_KINDS = ALERT_EVENTS + ("l_missing", "promote_stuck", "lost_file") # alerted once per id, ever
ONCE_KINDS = ALERT_EVENTS + ("l_missing", "l_gone", "promote_stuck", "lost_file") # alerted once per id, ever
BACKOFF_MAX = 6 * 3600.0 # promote retry delay: RETRY_DELAY doubling, capped here
FAIL_ALERT_AFTER = 3 # failures in a row per id before an alert
REGISTER_KEYS = ("listed", "missing_local", "ambiguous", "errors") # required in the result
Expand Down Expand Up @@ -219,6 +224,7 @@ class Config:
check_max_h: float = CHECK_MAX_H
auto_redownload: bool = True # TIERING_AUTO_REDOWNLOAD (only acts with apply)
redownload_max: int = REDOWNLOAD_MAX
l_gone_days: float = GONE_DAYS
auto_switch: bool = True # TIERING_AUTO_SWITCH: move watchers to the restore path on an unrepairable chunk

@classmethod
Expand Down Expand Up @@ -294,6 +300,7 @@ def from_env(cls, env=None) -> "Config":
auto_switch=e.get("TIERING_AUTO_SWITCH", "1").strip().lower()
not in ("0", "false", "no", "off"),
redownload_max=max(1, int(e.get("TIERING_REDOWNLOAD_MAX_PER_NIGHT") or REDOWNLOAD_MAX)),
l_gone_days=max(0.0, float(e.get("TIERING_L_GONE_DAYS") or GONE_DAYS)),
)


Expand Down Expand Up @@ -668,6 +675,11 @@ def __init__(self, cfg: Config, deps: Deps, clock=time.time, sleep=time.sleep):
self.errors = 0
self.counts: dict = {}
self.only_blocked = False
self._gone_verdict: dict = {} # id -> the arrs' last answer for a row whose L is missing
self._gone_due: list = []
self._gone_cache = None
self.gone_next: dict = {} # id -> when its missing L is looked up in the arrs again
self.only_follow: dict = {} # path -> allowlist entry it descends from (state.note_only_follow)
self.heartbeat_path = cfg.db + ".heartbeat"

# ---- small helpers
Expand All @@ -677,13 +689,26 @@ def _may_demote(self, row) -> bool:
if self.only_blocked: # the allowlist file could not be read this pass: no demotes
return False
only = self.cfg.only_paths
return not only or _norm_only(str(row.get("lib_path") or "")) in only
if not only:
return True
p = _norm_only(str(row.get("lib_path") or ""))
# a row that moved (a substitute with another extension, an arr rename) keeps the
# entry of the path it came from; the entry must still be on the list
return p in only or self.only_follow.get(p) in only

def refresh_only_paths(self):
"""Start of each pass: an `@file` allowlist is read again. A file that cannot be read,
or that holds no paths, blocks every demote this pass (never opens them up). The log
holds the count only, never a path."""
self.only_blocked = False
if not self.cfg.only_spec and not self.cfg.only_paths:
return
try:
f = getattr(self.state, "only_follow", None)
self.only_follow = dict(f(self.db())) if f else {}
except Exception as e: # noqa: BLE001 # no pairs: only the listed paths count
self.only_follow = {}
log.warning("TIERING_ONLY_PATHS: moved paths not readable (%s)", type(e).__name__)
if not self.cfg.only_spec:
return
try:
Expand Down Expand Up @@ -1185,14 +1210,155 @@ def _rebase_atime(self, db, id):

# ---- reconcile and bad chunks

def _arrs(self):
"""The arr clients (redownload.Arrs), or None when none are set or one cannot be built."""
if self.deps.arrs is None:
return None
try:
return self.deps.arrs()
except Exception as e: # noqa: BLE001
log.error("arr clients not usable: %s", type(e).__name__)
return None

def _gone_clear(self, db, id):
"""L is back (or the row moved on): its missing-since mark goes."""
self.gone_next.pop(id, None)
if self.cfg.apply and id in self._gone_load(db):
g = dict(self._gone_load(db))
g.pop(id, None)
self._kv_set(db, "l_gone_since", g)
self._gone_cache = g

def _gone_load(self, db) -> dict:
if getattr(self, "_gone_cache", None) is None:
g = self._kv_get(db, "l_gone_since", {})
self._gone_cache = {str(k): float(v) for k, v in g.items()} if isinstance(g, dict) else {}
return self._gone_cache

def _l_gone(self, db, row, now, budget) -> bool:
"""An offloaded row whose L is missing from its recorded path. Asks the arrs where
they have the item now (by its identity, never a guess at a name): if the file
there is the tierfs symlink of this id, the row's lib_path follows it. Else, with
the arr answering that it has no file and nothing queued, the row is marked gone
once L has been missing for TIERING_L_GONE_DAYS. Nothing else is touched: no stub,
no remote data, no link. Returns True when it used one of the pass's lookups."""
id, cfg = row["id"], self.cfg
arrs = self._arrs()
if arrs is None or not hasattr(arrs, "locate"):
self._once("l_missing", id, lib_path=row.get("lib_path"))
return False
gone = self._gone_load(db)
if id not in gone:
gone[id] = now
self._kv_set(db, "l_gone_since", gone) # (a dry run keeps it in memory only)
since = gone.get(id, now)
used = False
if now >= self.gone_next.get(id, 0.0):
if budget[0] <= 0:
return False # this pass's lookups are spent; the next pass goes on
self.gone_next[id] = now + GONE_LOOKUP_EVERY
used = True
try:
loc = arrs.locate(row)
except Exception as e: # noqa: BLE001 # an arr that does not answer says nothing
log.warning("%s: L is missing and an arr did not answer (%s)", id, type(e).__name__)
loc = None
if loc is not None and self._l_moved(db, row, loc):
self._gone_clear(db, id)
return used
self._gone_verdict[id] = loc # kept for the grace check below
self._once("l_missing", id, lib_path=row.get("lib_path"))
loc = self._gone_verdict.get(id)
days = cfg.l_gone_days
if (days > 0 and loc is not None and not loc["paths"] and not loc["has_file"]
and not loc["queued"] and now - since >= days * DAY):
self._gone_due.append((row, since, loc))
return used

def _l_moved(self, db, row, loc) -> bool:
"""The arr's file for this row is a tierfs symlink of this id at another path: follow it."""
id = row["id"]
for share in loc["paths"]:
if share == row.get("lib_path"):
continue
found = self._find_disk({"lib_path": share})
if len(found) != 1:
continue
try:
got = os.readlink(found[0])
except OSError:
continue
ext = os.path.splitext(share)[1]
if os.path.basename(got) != f"{id}{ext}":
continue
other = self.state.by_path(db, share)
if other is not None and other["id"] != id:
log.warning("%s: its link is at a path another row holds; not moving it", id)
return False
if not self.cfg.apply:
log.warning("dry run: would point %s at the path the arr has its link at", id)
return True
old = row.get("lib_path")
if not self.state.update_if(db, id, "offloaded", lib_path=share):
return False
self.state.log_event(db, id, "l_moved", {"from": old, "to": share})
log.warning("%s: the arr moved its link; lib_path follows", id)
try:
self.state.note_only_follow(db, old, share)
except Exception as e: # noqa: BLE001
log.warning("%s: the allowlist could not follow the row (%s)", id, type(e).__name__)
return True
return False

def _gone_finish(self, db, now):
"""The rows `_l_gone` found past the grace: mark them gone, once each, and alert. Many
at once is not a set of deletions (a disk that is not mounted looks the same): none."""
due, self._gone_due = self._gone_due, []
if not due:
return
if len(due) >= GONE_MASS:
self._once("l_gone_mass", "all", rows=len(due))
log.error("%d rows have had no L for over %g days; this looks like a missing "
"disk, not deletions: none is marked", len(due), self.cfg.l_gone_days)
return
for row, since, _loc in due:
id = row["id"]
if id in self.promote_running or id in self.demote_running:
continue
arrs = self._arrs() # the verdict is asked again now, not taken from an hour ago
try:
loc = arrs.locate(row)
except Exception as e: # noqa: BLE001
log.warning("%s: not marked gone: an arr did not answer (%s)", id, type(e).__name__)
continue
if (loc is None or loc["paths"] or loc["has_file"] or loc["queued"]
or self._find_disk(row)):
continue
if not self.cfg.apply:
log.warning("dry run: would mark %s gone, no L for %.1f days", id,
(now - since) / DAY)
continue
if self.state.update_if(db, id, "offloaded", state="failed", restore_note=GONE_NOTE):
self.state.log_event(db, id, "l_gone", {
"since": since, "days": round((now - since) / DAY, 1),
"reason": "no link for this id in the arr's path and the arr has no file "
"or queue entry for the item"})
self._once("l_gone", id, days=round((now - since) / DAY, 1))
self._gone_clear(db, id)
log.warning("%s: its L is gone; no longer managed (stub and remote data kept)", id)

def _reconcile(self, db, rows, now):
budget = [GONE_LOOKUPS_PER_PASS]
self._gone_due: list = []
for row in rows:
if row["state"] != "offloaded" or row["id"] in self.promote_running:
continue
found = self._find_disk(row)
if not found: # L is gone from every disk: alert, never fail the row for it
self._once("l_missing", row["id"], lib_path=row.get("lib_path"))
if self._l_gone(db, row, now, budget):
budget[0] -= 1
continue
self._gone_clear(db, row["id"])
if len(found) > 1:
self._log_skip(row, found)
continue
Expand All @@ -1212,6 +1378,10 @@ def _reconcile(self, db, rows, now):
restore_note="L replaced"):
self.state.log_event(db, row["id"], "l_replaced", {"lib_path": row.get("lib_path")})
log.warning("%s: L replaced, no longer managed", row["id"])
self._gone_finish(db, now)
live = {r["id"] for r in rows if r["state"] == "offloaded"}
for id in [i for i in self._gone_load(db) if i not in live]:
self._gone_clear(db, id) # the row moved on (promoted, failed, gone): no mark

# ---- orphan stub cleanup

Expand Down
24 changes: 24 additions & 0 deletions tiering/offload/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,30 @@ def kv_set(db, key, value) -> None:
(key, json.dumps(value, sort_keys=True)))


def _only_norm(p) -> str:
p = str(p or "").strip()
return p.rstrip("/") if len(p) > 1 else p


def only_follow(db) -> dict:
"""{library path: the TIERING_ONLY_PATHS entry it descends from}, for a row whose library
path changed (a substitute with another extension, an arr rename). It grants nothing by
itself: the runner honours a pair only while its entry is still on the allowlist."""
d = kv_get(db, "only_follow", {})
return d if isinstance(d, dict) else {}


def note_only_follow(db, old, new) -> None:
"""The row at `old` now lives at `new`: the allowlist entry that covered `old` covers `new`
(and only `new`). A chain of moves keeps pointing at the first path."""
old, new = _only_norm(old), _only_norm(new)
if not old or not new or old == new:
return
d = only_follow(db)
d[new] = d.get(old, old)
kv_set(db, "only_follow", d)


def last_plays(db) -> dict:
"""{rating_key: last play time} the runner has seen, kept so a wiped Plex history
cannot make a played file look idle."""
Expand Down
Loading