"""Чтение данных сервисов через pct (сервис живёт на узле Proxmox).""" import subprocess def pct_exec(ct, args, timeout=25): """Выполнить команду внутри контейнера Proxmox.""" cmd = ["pct", "exec", str(ct), "--"] + args try: out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) if out.returncode != 0: return None, (out.stderr or out.stdout).strip()[:160] return out.stdout.strip(), None except Exception as e: return None, str(e)[:120] def docker_sqlite(ct, container, db, sql, timeout=25): return pct_exec(ct, ["docker", "exec", container, "sqlite3", db, sql], timeout=timeout) class Navidrome: """Музыка: считаем по базе, без пароля.""" def counts(self): out, err = docker_sqlite( 125, "navidrome", "/data/navidrome.db", "select (select count(*) from artist)||'|'||(select count(*) from album)" "||'|'||(select count(*) from media_file)") if err: return None, err try: a, al, m = (int(x) for x in out.split("|")) return {"artists": a, "albums": al, "tracks": m}, None except Exception: return None, f"странный ответ: {out[:60]}" def size(self): out, err = pct_exec(125, ["sh", "-c", "du -sh /opt/music-lxc/music 2>/dev/null | cut -f1"]) return out or "—" class Books: """Книги: библиотека Calibre, читаем через python3 (sqlite3 в модуле).""" DB = "/opt/books/library/metadata.db" _COUNT = ("import sqlite3;" "c=sqlite3.connect('%s');" "print(c.execute('select count(*) from books').fetchone()[0])" % DB) _RECENT = ("import sqlite3,sys;" "c=sqlite3.connect('%s');" "rows=c.execute('select b.title, ifnull((select a.name from authors a " "join books_authors_link l on l.author=a.id where l.book=b.id limit 1), chr(45)) " "from books b order by b.id desc limit ?', (int(sys.argv[1]),)).fetchall();" "[print(r[0]+chr(124)+(r[1] or chr(45))) for r in rows]" % DB) _SEARCH = ("import sqlite3,sys;" "c=sqlite3.connect('%s');" "rows=c.execute('select b.title, ifnull((select a.name from authors a " "join books_authors_link l on l.author=a.id where l.book=b.id limit 1), chr(45)) " "from books b where b.title like ? limit ?', (chr(37)+sys.argv[1]+chr(37), int(sys.argv[2]))).fetchall();" "[print(r[0]+chr(124)+(r[1] or chr(45))) for r in rows]" % DB) def counts(self): out, err = pct_exec(111, ["python3", "-c", self._COUNT]) if err: return None, err try: return {"books": int(out)}, None except ValueError: return None, f"странный ответ: {out[:60]}" def _rows(self, out): rows = [] for line in (out or "").splitlines(): parts = line.split("|") if len(parts) >= 2: rows.append({"title": parts[0], "author": parts[1] or "—"}) return rows def recent(self, limit=8): out, err = pct_exec(111, ["python3", "-c", self._RECENT, str(limit)]) if err: return [], err return self._rows(out), None def search(self, term, limit=8): out, err = pct_exec(111, ["python3", "-c", self._SEARCH, term, str(limit)]) if err: return [], err return self._rows(out), None class ImmichDb: def counts(self): out, err = pct_exec(151, ["su", "-", "postgres", "-c", "psql -d immich_db -tAc \"select (select count(*) from asset)" "||'|'||(select count(*) from album)||'|'||(select count(*) from \\\"user\\\")\""]) if err: return None, err try: a, al, u = (int(x) for x in out.split("|")) return {"assets": a, "albums": al, "users": u}, None except Exception: return None, f"странный ответ: {out[:60]}" class HomeDb: """Home Assistant: читаем реестр сущностей (только чтение).""" def entities(self): out, err = pct_exec(106, ["docker", "exec", "homeassistant", "sh", "-c", "python3 -c \"import json,collections;" "d=json.load(open('/config/.storage/core.entity_registry'))['data']['entities'];" "c=collections.Counter(e['entity_id'].split('.')[0] for e in d);" "print(len(d));print('|'.join(f'{k}={v}' for k,v in c.most_common(10)))\""]) if err: return None, err lines = out.splitlines() try: total = int(lines[0]) except (IndexError, ValueError): return None, "не удалось разобрать ответ" kinds = lines[1] if len(lines) > 1 else "" return {"total": total, "kinds": kinds}, None def states(self): out, err = pct_exec(106, ["docker", "exec", "homeassistant", "sh", "-c", "python3 -c \"import json;" "d=json.load(open('/config/.storage/core.restore_state'))['data'];" "s=[x for x in d if isinstance(x,dict) and 'state' in x];" "print(len(s))\""]) if err: return None, err return {"restored": int(out or 0)}, None class Disks: """Свободное место по узлу и контейнерам.""" def host(self): out, err = pct_exec(10, ["df", "-h", "/"]) if err: return None, err return out.splitlines()[-1] if out else None, None