"""Host timer: encrypted Deck configuration + explicit user data, atomic generations. No browser credentials, model loading, service restart or bulk runtime backup. """ import fcntl,hashlib,io,json,os,re,secrets,shutil,sqlite3,subprocess,tarfile,tempfile,time from pathlib import Path STATE=Path('/opt/athena-deck-dev/runtime/state') DEST=Path('/data/athena-deck/backups') KEY=Path('/etc/athena-deck-backup/recovery.key') CONTAINER='athena-deck-dev' SCRIPT='/var/lib/deck/maintenance/' def atomic_json(path,data): tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(data,indent=2));tmp.chmod(0o600);tmp.replace(path) def command(script,*args):return ['docker','exec','-i',CONTAINER,'python3',SCRIPT+script,*args] def key(): KEY.parent.mkdir(parents=True,exist_ok=True,mode=0o700) if not KEY.exists(): fd=os.open(KEY,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600) with os.fdopen(fd,'w') as f:f.write(secrets.token_urlsafe(48)+'\n') if KEY.is_symlink() or KEY.stat().st_mode&0o077:raise ValueError('Schlüsseldatei muss privat sein') return KEY.read_bytes().strip()+b'\n' def sources(): names=('articulino-jobs','seedvc-jobs','humaneness-jobs','qwen-native-jobs','speech-voices','pocket-jobs','soulx_singer-data','legacy-userdata','applio-data','xvc-data','voice-tests','music-jobs','acestep-jobs','separator-tests','image-tests','tts-tests') roots=[(STATE/n,'deck/'+n) for n in names]+[(STATE/'video/original-work/outputs','deck/video/original-work/outputs'),(STATE/'video/original-work/remote-inputs','deck/video/original-work/remote-inputs'),(STATE/'video/original-work/deskweb','deck/video/original-work/deskweb'),(Path('/opt/athena-ladypoly/data'),'services/ladypoly'),(Path('/opt/athena-deck-docker-apps'),'services/web-studios')] # Private locally-trained voices have no public replacement source. for p in (STATE/'models').glob('*/entry.json'): if json.loads(p.read_text()).get('repo','').startswith('local/mikes-applio'):roots.append((p.parent,'deck/models/'+p.parent.name)) return roots def files(roots): for root,name in roots: if not root.exists():continue for p in sorted(root.rglob('*')): # Per-job package directories contain runtime/model links, not user media. if name in ('deck/music-jobs','deck/acestep-jobs','deck/voice-tests','deck/tts-tests') and 'package' in p.relative_to(root).parts:continue if name=='deck/image-tests' and 'models' in p.relative_to(root).parts:continue if p.is_symlink():raise ValueError('Symlink im Nutzdatenbestand: '+str(p)) if p.is_file() and not p.name.endswith(('-wal','-shm')):yield p,name+'/'+p.relative_to(root).as_posix() class Hashed: def __init__(self,f):self.f=f;self.hash=hashlib.sha256() def read(self,n):b=self.f.read(n);self.hash.update(b);return b def media(target,secret): proc=subprocess.Popen(command('backup_stream.py','encrypt'),stdin=subprocess.PIPE,stdout=target.open('wb'),stderr=subprocess.PIPE) manifest={} try: proc.stdin.write(secret) with tempfile.TemporaryDirectory(dir=DEST) as scratch,tarfile.open(fileobj=proc.stdin,mode='w|gz',compresslevel=1) as archive: entries=list(files(sources()))+[(STATE/'dashboard-history.sqlite3','deck/dashboard-history.sqlite3')] for source,name in entries: if not source.exists():continue original=source if source.suffix in ('.db','.sqlite3'): source=Path(scratch)/hashlib.sha256(name.encode()).hexdigest() with sqlite3.connect('file:'+str(original)+'?mode=ro',uri=True) as old,sqlite3.connect(source) as new: old.backup(new) if new.execute('pragma integrity_check').fetchone()[0]!='ok':raise ValueError('SQLite-Sicherung beschädigt') before=source.stat();info=tarfile.TarInfo(name);info.size=before.st_size;info.mode=0o600;info.mtime=before.st_mtime with source.open('rb') as f: reader=Hashed(f);archive.addfile(info,reader) after=source.stat() if (before.st_size,before.st_mtime_ns)!=(after.st_size,after.st_mtime_ns):raise ValueError('Nutzdatei während Sicherung verändert; neuer Lauf erforderlich') manifest[name]={'size':info.size,'sha256':reader.hash.hexdigest()} if len(manifest)%250==0:print('Archived files:',len(manifest),flush=True) data=json.dumps({'files':manifest,'created_at':time.time()}).encode();info=tarfile.TarInfo('MANIFEST.json');info.size=len(data);info.mode=0o600;archive.addfile(info,io.BytesIO(data)) proc.stdin.close();error=proc.stderr.read();rc=proc.wait() if rc:raise ValueError('Medienverschlüsselung fehlgeschlagen') except BaseException: proc.kill();proc.wait();raise target.chmod(0o600) verifier=subprocess.Popen(command('backup_stream.py','verify'),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) try: verifier.stdin.write(secret) with target.open('rb') as f:shutil.copyfileobj(f,verifier.stdin,1024*1024) verifier.stdin.close();result=verifier.stdout.read();error=verifier.stderr.read() if verifier.wait():raise ValueError('Medienarchiv-Prüfung fehlgeschlagen') return json.loads(result) finally: if verifier.poll() is None:verifier.kill();verifier.wait() def run(): DEST.mkdir(parents=True,exist_ok=True,mode=0o700);os.chmod(DEST,0o700) with (DEST/'backup.lock').open('w') as lock: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);secret=key() stamp=time.strftime('%Y%m%d-%H%M%S');pending=DEST/('.pending-'+stamp);pending.mkdir(mode=0o700) try: estimate=sum(p.stat().st_size for p,_ in files(sources())) if shutil.disk_usage(DEST).free