Files
ucvl-home-vision/recording_archive.py
T

349 lines
22 KiB
Python

"""Ordered, durable Baidu recording archive; delete local bytes only after readback."""
import datetime as dt
import hashlib
import json
import math
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
import threading
import time
import recording_format
ID = r'[a-f0-9]{16}'
NAME = re.compile(r'\d{4}-\d\d-\d\d_\d\d-\d\d-\d\d-\d{6}\.mp4')
ZONE = dt.timezone(dt.timedelta(hours=8))
class Archive:
def __init__(self, app):
self.a = app
self.guard = threading.Lock()
self.phase = ''
self.error = ''
self.scanned = 0
self.progress = {}
self.last_retry = 0
def initialize(self):
a = self.a
with a.LOCK, a.DB:
a.DB.executescript('''CREATE TABLE IF NOT EXISTS recording_archive (
id TEXT PRIMARY KEY, family TEXT NOT NULL, camera TEXT NOT NULL,
root TEXT NOT NULL, path TEXT NOT NULL, started REAL NOT NULL,
duration REAL NOT NULL, size INTEGER NOT NULL, fingerprint TEXT NOT NULL,
sha256 TEXT NOT NULL DEFAULT '', remote TEXT NOT NULL DEFAULT '', fs_id TEXT NOT NULL DEFAULT '',
state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
retry_at REAL NOT NULL DEFAULT 0, error TEXT NOT NULL DEFAULT '',
verified_at REAL NOT NULL DEFAULT 0, UNIQUE(root,path));
CREATE INDEX IF NOT EXISTS recording_archive_time ON recording_archive(state,started);
CREATE INDEX IF NOT EXISTS recording_archive_scope ON recording_archive(family,camera,started);''')
columns = {r[1] for r in a.DB.execute('PRAGMA table_info(recording_archive)')}
for column, kind in [('released_bytes','INTEGER'),('released_at','REAL')]:
if column not in columns:
a.DB.execute('ALTER TABLE recording_archive ADD COLUMN '+column+' '+kind+' NOT NULL DEFAULT 0')
if 'metadata' not in columns:
a.DB.execute("ALTER TABLE recording_archive ADD COLUMN metadata TEXT NOT NULL DEFAULT ''")
if 'archive_size' not in columns:
a.DB.execute('ALTER TABLE recording_archive ADD COLUMN archive_size INTEGER NOT NULL DEFAULT 0')
# Snapshot legacy ownership once. A later device transfer must not
# reassign historic footage to the receiving household.
if a.setting('recording_legacy_owners') is None:
a.set_setting('recording_legacy_owners', {c['id']:a.HOUSEHOLDS.family_of(c) for c in a.objects('cameras')})
if not a.setting('recording_instance'):
a.set_setting('recording_instance', secrets.token_hex(8))
def roots(self):
roots = {'current':self.a.RECORDINGS.resolve()}
legacy = os.environ.get('VISION_LEGACY_RECORDINGS', '')
if legacy and Path(legacy).resolve() != self.a.RECORDINGS.resolve():
roots['legacy'] = Path(legacy).resolve()
return roots
@staticmethod
def fingerprint(path):
s = path.stat()
return json.dumps([s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns])
def local(self, row):
root = self.roots().get(row['root'])
if root is None: raise self.a.Problem('录像目录已变化,保留队列等待管理员检查', 409)
p = root / row['path']
if p.is_symlink() or p.resolve() != p.absolute() or not p.resolve().is_relative_to(root.resolve()):
raise self.a.Problem('录像路径不安全,未操作文件', 409)
return p
def enqueue(self, root_key, relative, family, camera, duration):
if not re.fullmatch(ID, family) or not re.fullmatch(ID, camera): return
p = self.local(dict(root=root_key, path=relative))
root = self.roots()[root_key]
allowed = [root/family/('cam_'+camera+'_main')]
if root_key == 'legacy' or self.a.setting('recording_legacy_owners',{}).get(camera)==family:
allowed.append(root/('cam_'+camera+'_main'))
if p.parent not in allowed or not NAME.fullmatch(p.name) or not p.is_file(): return
if not math.isfinite(duration) or not 0 < duration <= 86400 or p.stat().st_size <= 0: return
# MediaMTX uses the host local timezone in its default strftime path.
started = dt.datetime.strptime(p.stem, '%Y-%m-%d_%H-%M-%S-%f').timestamp()
key = hashlib.sha256((root_key+'/'+relative).encode()).hexdigest()[:32]
with self.a.LOCK, self.a.DB:
self.a.DB.execute('INSERT OR IGNORE INTO recording_archive (id,family,camera,root,path,started,duration,size,fingerprint) VALUES (?,?,?,?,?,?,?,?,?)',
(key,family,camera,root_key,relative,started,duration,p.stat().st_size,self.fingerprint(p)))
def consume(self):
folder = self.a.DATA/'recording-tickets'
if not folder.exists(): return
for p in sorted(folder.glob('*.json'))[:256]:
if p.is_symlink() or p.stat().st_size > 4096: continue
try:
body = json.loads(p.read_text(encoding='utf8'))
self.enqueue('current',body['path'],body['family'],body['camera'],float(body['duration']))
p.unlink()
except (OSError, ValueError, KeyError, TypeError):
self.error = '部分录像完成通知无法读取,原文件已保留'
def recover(self):
"""Crash/upgrade recovery: never infer closure from age alone."""
if os.name != 'posix' or not Path('/proc').is_dir(): return
# Require visibility of the media writer's descriptors. Fail closed if
# it exists but /proc permissions prevent inspecting its open files.
opened = set()
try:
for proc in Path('/proc').iterdir():
if not proc.name.isdigit(): continue
try:
if proc.joinpath('comm').read_text().strip() != 'mediamtx': continue
for fd in proc.joinpath('fd').iterdir():
try: opened.add(os.readlink(fd))
except FileNotFoundError: pass
except FileNotFoundError: pass
except (PermissionError, OSError):
self.error = '无法核对录制中文件,暂缓恢复旧片段'; return
owners = self.a.setting('recording_legacy_owners',{})
candidates = [(p.name,root_key,root,p) for root_key,root in self.roots().items() for p in root.rglob('*.mp4')]
for _, root_key, root, p in sorted(candidates):
if p.is_symlink() or not NAME.fullmatch(p.name): continue
relative = str(p.relative_to(root))
with self.a.LOCK:
if self.a.DB.execute('SELECT 1 FROM recording_archive WHERE root=? AND path=?',(root_key,relative)).fetchone(): continue
try:
if str(p) in opened or time.time()-p.stat().st_mtime < 60: continue
match = re.fullmatch('cam_('+ID+')_main',p.parent.name)
if not match: continue
camera = match[1]
family = p.parent.parent.name if re.fullmatch(ID,p.parent.parent.name) else owners.get(camera,'')
before = self.fingerprint(p)
result = subprocess.run(['ffprobe','-v','error','-show_entries','format=duration','-of','json',str(p)],capture_output=True,timeout=15,check=True)
duration = float(json.loads(result.stdout)['format']['duration'])
if self.fingerprint(p) != before: continue
self.enqueue(root_key,relative,family,camera,duration)
except (OSError,ValueError,KeyError,subprocess.SubprocessError): continue
def update(self, key, **values):
with self.a.LOCK, self.a.DB:
self.a.DB.execute('UPDATE recording_archive SET '+','.join(k+'=?' for k in values)+' WHERE id=?',(*values.values(),key))
def row(self, key):
with self.a.LOCK:
r = self.a.DB.execute('SELECT * FROM recording_archive WHERE id=?',(key,)).fetchone()
return dict(r) if r else None
def prepared_file(self, row):
return self.a.DATA/'recording-prepared'/(row['id']+'.mp4')
def prepare(self, row, source):
# An already assigned old path stays immutable across retries/upgrades.
if row['remote'] and not row['metadata']: return source,row
target = self.prepared_file(row)
target.parent.mkdir(mode=0o700,exist_ok=True)
if target.is_symlink(): raise self.a.Problem('录像准备路径异常,原文件已保留')
family=self.a.get_object('households',row['family']) or {}
camera=self.a.get_object('cameras',row['camera']) or {}
saved=json.loads(row['metadata']) if row['metadata'] else {}
family_name=saved.get('familyName',family.get('name','家庭')); camera_name=saved.get('cameraName',camera.get('name','摄像头'))
if not target.exists() or not row['metadata']:
if shutil.disk_usage(target.parent).free < max(row['size']*2,512*1024*1024):
raise self.a.Problem('写入录像时间属性所需临时空间不足,原片段已保留')
temp=target.with_suffix('.partial.mp4')
try:
meta=recording_format.prepare(source,temp,row,family_name,camera_name)
temp.replace(target)
finally: temp.unlink(missing_ok=True)
if self.fingerprint(source)!=row['fingerprint']:
target.unlink(missing_ok=True)
raise self.a.Problem('录像准备期间原片段发生变化,已暂停上传')
# Persist path with metadata before a cloud request, for retry safety.
remote=row['remote'] or recording_format.remote_path(self.a.BAIDU.public_config()['appFolder'],
self.a.setting('recording_instance'),row,family_name,camera_name)
self.update(row['id'],metadata=json.dumps(meta,ensure_ascii=False),archive_size=target.stat().st_size,remote=remote)
row=self.row(row['id'])
return target,row
def process_one(self):
if not self.guard.acquire(blocking=False): return False
row = None
try:
with self.a.LOCK:
r = self.a.DB.execute("SELECT * FROM recording_archive WHERE state IN ('pending','verified') ORDER BY started,id LIMIT 1").fetchone()
if not r: return False
row = dict(r)
if row['retry_at'] > time.time(): return False
p = self.local(row)
if row['state']=='verified' and not p.exists():
self.prepared_file(row).unlink(missing_ok=True)
self.update(row['id'],state='cloud',error='',released_bytes=row['size'],released_at=row['released_at'] or time.time()); return True
if self.fingerprint(p) != row['fingerprint']:
raise self.a.Problem('片段在入队后发生变化,已保留本地文件,需核查')
def report(stage, done=0, total=0):
self.progress = dict(id=row['id'],stage=stage,done=done,total=total,
percent=round(min(100,100*done/total),1) if total else None)
report('preparing')
upload_file,row=self.prepare(row,p)
archive_size=row['archive_size'] or row['size']
self.phase = '上传 '+dt.datetime.fromtimestamp(row['started'],ZONE).strftime('%m-%d %H:%M')+' · '+row['camera']
digest = hashlib.sha256()
with upload_file.open('rb') as source:
while block := source.read(1024*1024): digest.update(block)
sha = digest.hexdigest()
if row['sha256'] and row['sha256'] != sha: raise self.a.Problem('本地片段校验不一致,未删除')
remote = row['remote']
self.update(row['id'],sha256=sha,remote=remote)
if row['state'] != 'verified':
result = self.a.BAIDU.upload('shared',upload_file,remote,progress=lambda n,total:report('uploading',n,total))
if result.get('path') != remote or result.get('size') != archive_size or not result.get('fs_id'):
raise self.a.Problem('网盘上传结果不完整,本地录像已保留')
self.phase = '校验云端片段 · '+row['camera']
report('verifying',0,archive_size)
self.a.BAIDU.verify_file(remote,result['fs_id'],archive_size,sha,progress=lambda n,total:report('verifying',n,total))
self.update(row['id'],state='verified',fs_id=str(result['fs_id']),verified_at=time.time(),error='')
else:
# Recheck cloud after a crash before retrying the local deletion.
report('verifying',0,archive_size)
self.a.BAIDU.verify_file(remote,row['fs_id'],archive_size,sha,progress=lambda n,total:report('verifying',n,total))
if self.fingerprint(p) != row['fingerprint']: raise self.a.Problem('上传期间片段发生变化,未删除本地文件')
report('cleaning')
p.unlink()
self.prepared_file(row).unlink(missing_ok=True)
self.update(row['id'],state='cloud',retry_at=0,error='',released_bytes=row['size'],released_at=time.time())
self.error = ''
return True
except Exception as exc:
# Never expose credential-bearing HTTP/transport exception details.
message = str(exc) if isinstance(exc,self.a.Problem) else '上传或校验未完成,本地片段已保留,将自动重试'
self.error = message
if row:
attempts = row['attempts']+1
self.update(row['id'],attempts=attempts,retry_at=time.time()+min(1800,15*2**min(attempts,7)),error=message)
return False
finally:
self.phase = ''; self.progress = {}; self.guard.release()
def status(self):
with self.a.LOCK:
rows = list(self.a.DB.execute('SELECT state,count(*) AS n,coalesce(sum(size),0) AS bytes FROM recording_archive GROUP BY state'))
oldest = self.a.DB.execute("SELECT started,error,retry_at FROM recording_archive WHERE state IN ('pending','verified') ORDER BY started LIMIT 1").fetchone()
counts = {r['state']:r['n'] for r in rows}
return dict(pending=counts.get('pending',0)+counts.get('verified',0),uploaded=counts.get('cloud',0),
pendingGB=round(sum(r['bytes'] for r in rows if r['state'] in ('pending','verified'))/1e9,2),
phase=self.phase,error=self.error or (oldest['error'] if oldest else ''),retryAt=oldest['retry_at'] if oldest else 0)
def tasks(self, user, query):
"""Platform operations only; do not expose other households to managers."""
if user['role'] != 'admin': raise self.a.Problem('上传任务总览仅超级管理员可查看',403)
state = query.get('state','pending')
if state not in ('all','pending','retry','cloud','expired'): raise self.a.Problem('任务状态不正确')
try: page = int(query.get('page','1'))
except (TypeError,ValueError): raise self.a.Problem('页码不正确')
if not 1 <= page <= 1000000: raise self.a.Problem('页码不正确')
where = []; values = []
if state=='pending': where.append("state IN ('pending','verified')")
elif state=='retry': where.append("state IN ('pending','verified') AND error<>''")
elif state!='all': where.append('state=?');values.append(state)
for key in ('family','camera'):
if query.get(key):
if not re.fullmatch(ID,query[key]): raise self.a.Problem('筛选对象不正确')
where.append(key+'=?');values.append(query[key])
sql = ' WHERE '+' AND '.join(where) if where else ''
with self.a.LOCK:
count = self.a.DB.execute('SELECT count(*) FROM recording_archive'+sql,values).fetchone()[0]
page = min(page,max(1,math.ceil(count/20)))
rows = self.a.DB.execute("SELECT * FROM recording_archive"+sql+" ORDER BY CASE WHEN state IN ('pending','verified') THEN 0 ELSE 1 END, CASE WHEN state IN ('pending','verified') THEN started ELSE -started END,id LIMIT 20 OFFSET ?",(*values,(page-1)*20)).fetchall()
totals = dict(self.a.DB.execute("SELECT coalesce(sum(CASE WHEN state IN ('pending','verified') THEN size ELSE 0 END),0) pendingBytes, sum(CASE WHEN state IN ('pending','verified') THEN 1 ELSE 0 END) pendingCount, coalesce(sum(released_bytes),0) releasedBytes, coalesce(sum(CASE WHEN released_at>? THEN released_bytes ELSE 0 END),0) releasedTodayBytes, coalesce(sum(CASE WHEN state='cloud' THEN CASE WHEN archive_size>0 THEN archive_size ELSE size END ELSE 0 END),0) cloudBytes, sum(CASE WHEN state='cloud' THEN 1 ELSE 0 END) cloudCount FROM recording_archive",(dt.datetime.combine(dt.datetime.now(ZONE).date(),dt.time.min,tzinfo=ZONE).timestamp(),)).fetchone())
homes = {h['id']:h['name'] for h in self.a.objects('households')}
cameras = {c['id']:c['name'] for c in self.a.objects('cameras')}
scopes = self.a.DB.execute('SELECT DISTINCT family,camera FROM recording_archive ORDER BY family,camera').fetchall()
active = dict(self.progress)
items = [dict(id=r['id'],name=Path(r['remote'] or r['path']).name,familyId=r['family'],familyName=homes.get(r['family'],'已移除家庭'),
cameraId=r['camera'],cameraName=cameras.get(r['camera'],'已移除摄像机'),started=r['started'],duration=r['duration'],
ended=r['started']+r['duration'],metadata=json.loads(r['metadata']) if r['metadata'] else {},
archiveSize=r['archive_size'] or r['size'],size=r['size'],state=r['state'],attempts=r['attempts'],error=r['error'],retryAt=r['retry_at'],
verifiedAt=r['verified_at'],releasedAt=r['released_at'],releasedBytes=r['released_bytes'],remotePath=r['remote']) for r in rows]
return dict(items=items,page=page,total=count,pages=max(1,math.ceil(count/20)),totals={k:v or 0 for k,v in totals.items()},
active=active,updatedAt=time.time(),status=self.status(),
families=[dict(id=k,name=homes.get(k,'已移除家庭')) for k in sorted({r['family'] for r in scopes})],
cameras=[dict(id=r['camera'],familyId=r['family'],name=cameras.get(r['camera'],'已移除摄像机')) for r in scopes])
def retry(self, user):
if user['role'] != 'admin': raise self.a.Problem('仅超级管理员可重试上传队列',403)
if not self.guard.acquire(blocking=False): raise self.a.Problem('当前片段正在处理,请等待完成',409)
try:
now=time.time()
if now-self.last_retry<10: raise self.a.Problem('请稍等后再重试',429)
with self.a.LOCK,self.a.DB:
row=self.a.DB.execute("SELECT id FROM recording_archive WHERE state IN ('pending','verified') ORDER BY started,id LIMIT 1").fetchone()
if not row: return dict(ok=True)
self.a.DB.execute('UPDATE recording_archive SET retry_at=0 WHERE id=?',(row['id'],))
self.last_retry=now
self.a.audit('重试最早待上传录像',user['username'])
return dict(ok=True)
finally: self.guard.release()
def listing(self, camera, start, end):
family = self.a.HOUSEHOLDS.family_of(camera)
with self.a.LOCK:
rows = self.a.DB.execute("SELECT id,started,duration,state FROM recording_archive WHERE camera=? AND family=? AND state IN ('cloud','verified') AND started<? AND started+duration>? ORDER BY started LIMIT 3000",(camera['id'],family,end,start)).fetchall()
return [dict(id=r['id'],start=dt.datetime.fromtimestamp(r['started'],dt.timezone.utc).isoformat(),duration=r['duration'],source='baidu') for r in rows]
def authorized(self, user, key):
row = self.row(key)
if not row or row['state'] not in ('cloud','verified'): raise self.a.Problem('云端录像不存在',404)
camera = self.a.ACCOUNTS.camera(user,self.a.get_object('cameras',row['camera']))
if self.a.HOUSEHOLDS.family_of(camera) != row['family']: raise self.a.Problem('历史录像属于设备转移前的家庭,未授权访问',403)
return row
def watch(self):
while True:
try:
self.consume()
if time.time()-self.scanned > 60:
self.recover(); self.scanned = time.time()
if self.process_one():
self.prune()
continue
except Exception:
self.error = '录像队列暂不可用,原文件已保留'
time.sleep(5)
def prune(self):
# Only this instance's indexed, verified cloud recordings are eligible.
# Pending files never expire, including during a long cloud outage.
days = self.a.setting('storage',{}).get('retentionDays',30)
cutoff = time.time()-days*86400
with self.a.LOCK:
rows = [dict(r) for r in self.a.DB.execute("SELECT * FROM recording_archive WHERE state='cloud' AND started+duration<? ORDER BY started LIMIT 10",(cutoff,))]
for row in rows:
if not recording_format.valid_path(row['remote'],self.a.BAIDU.public_config()['appFolder'],self.a.setting('recording_instance'),row): continue
self.a.BAIDU.delete_recording_file(row['remote'])
self.update(row['id'],state='expired')
def quota(self, policy):
"""A dedicated filesystem enforces the limit even if Python stops."""
root = self.a.RECORDINGS
configured = int(os.environ.get('VISION_RECORDING_QUOTA_BYTES','0'))
ready = (os.name=='posix' and configured>0 and root.is_mount()
and root.stat().st_dev != self.a.DATA.stat().st_dev
and shutil.disk_usage(root).total <= configured <= policy['maxGB']*1e9)
return ready, configured