Add legacy user data migration and encrypted twice-daily backups

This commit is contained in:
Mikei386 committed 2026-10-06 15:48:06 +02:00
1 parent c359a15cdf
commit 84b235df27
12 files changed
+589 -6

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
[Unit]
Description=Athena Deck encrypted configuration and private media backup
Requires=docker.service
After=docker.service
ConditionPathIsDirectory=/data/athena-deck/backups
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /opt/athena-deck-maintenance/scheduled_backup.py
User=root
UMask=0077
Nice=15
IOSchedulingClass=idle
TimeoutStartSec=infinity
+11
View File
@@ -0,0 +1,11 @@
[Unit]
Description=Athena Deck backup twice daily (German time)
[Timer]
OnCalendar=*-*-* 08:00:00 Europe/Berlin
OnCalendar=*-*-* 20:00:00 Europe/Berlin
Persistent=true
Unit=athena-deck-backup.service
[Install]
WantedBy=timers.target
+62
View File
@@ -0,0 +1,62 @@
"""Authenticated streaming media archive. Key is the first stdin line, never argv.
Run in Deck's existing Python runtime (cryptography already installed).
"""
import hashlib,io,json,os,sys,tarfile
from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
MAGIC=b'ATHENA-MEDIA-GCM1\n'
CHUNK=1024*1024
def derive(key,salt):return hashlib.scrypt(key,salt=salt,n=32768,r=8,p=1,maxmem=64*1024**2,dklen=32)
def encrypt(source,target,key):
salt=os.urandom(16);nonce=os.urandom(12);head=MAGIC+salt+nonce
enc=Cipher(algorithms.AES(derive(key,salt)),modes.GCM(nonce)).encryptor();enc.authenticate_additional_data(head)
target.write(head)
while b:=source.read(CHUNK):target.write(enc.update(b))
target.write(enc.finalize());target.write(enc.tag)
class Decrypted(io.RawIOBase):
def __init__(self,source,key):
self.source=source;head=source.read(len(MAGIC)+28)
if not head.startswith(MAGIC) or len(head)!=len(MAGIC)+28:raise ValueError('Kein Medienbackup')
self.dec=Cipher(algorithms.AES(derive(key,head[len(MAGIC):len(MAGIC)+16])),modes.GCM(head[-12:])).decryptor();self.dec.authenticate_additional_data(head);self.tail=b'';self.buffer=b'';self.done=False
def readable(self):return True
def read(self,size=-1):
if size<0:
result=[]
while b:=self.read(CHUNK):result.append(b)
return b''.join(result)
while len(self.buffer)<size and not self.done:
block=self.source.read(CHUNK)
if block:
data=self.tail+block;self.tail=data[-16:];self.buffer+=self.dec.update(data[:-16])
else:
if len(self.tail)!=16:raise ValueError('Archiv abgeschnitten')
self.buffer+=self.dec.finalize_with_tag(self.tail);self.done=True
out=self.buffer[:size];self.buffer=self.buffer[size:];return out
def verify(source,key):
stream=Decrypted(source,key);hashes={};manifest=None
with tarfile.open(fileobj=stream,mode='r|gz') as archive:
for member in archive:
if not member.isfile():raise ValueError('Nur reguläre Dateien erlaubt')
if member.name.startswith('/') or '..' in member.name.split('/'):raise ValueError('Unsicherer Archivpfad')
f=archive.extractfile(member)
if member.name=='MANIFEST.json':manifest=json.load(f);continue
h=hashlib.sha256()
while b:=f.read(CHUNK):h.update(b)
hashes[member.name]=dict(sha256=h.hexdigest(),size=member.size)
# Drain to authenticate even when tar ended before the ciphertext did.
while stream.read(CHUNK):pass
if manifest is None or hashes!=manifest['files']:raise ValueError('Dateiprüfsummen stimmen nicht')
return {'verified_files':len(hashes),'verified_bytes':sum(x['size'] for x in hashes.values())}
if __name__=='__main__':
key=sys.stdin.buffer.readline(257).strip()
if not 16<=len(key)<=256:raise ValueError('Ungültiger Sicherungsschlüssel')
if sys.argv[1]=='encrypt':encrypt(sys.stdin.buffer,sys.stdout.buffer,key)
elif sys.argv[1]=='verify':print(json.dumps(verify(sys.stdin.buffer,key)))
elif sys.argv[1]=='decrypt':
stream=Decrypted(sys.stdin.buffer,key)
while block:=stream.read(CHUNK):sys.stdout.buffer.write(block)
else:raise ValueError('Unbekannte Aktion')
+23
View File
@@ -0,0 +1,23 @@
"""Install Athena's explicit host backup timer without restarting Deck."""
import os,shutil,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parent
HOST=Path('/opt/athena-deck-maintenance')
STATE=Path('/opt/athena-deck-dev/runtime/state')
def main():
if os.geteuid()!=0 or not STATE.is_dir():raise SystemExit('Auf Athena als root mit vorhandener Deck-Installation ausführen.')
HOST.mkdir(mode=0o700,exist_ok=True);maintenance=STATE/'maintenance';maintenance.mkdir(exist_ok=True)
for name in ('scheduled_backup.py','restore_userdata.py','migrate_legacy_userdata.py'):
p=HOST/name;shutil.copyfile(ROOT/name,p);p.chmod(0o600)
for name in ('read_backup_snapshot.py','backup_stream.py'):
p=maintenance/name;shutil.copyfile(ROOT/name,p);p.chmod(0o644)
# Existing container user needs only the helper sources, never the host recovery key.
os.chown(maintenance,65534,65534)
Path('/data/athena-deck/backups').mkdir(parents=True,exist_ok=True,mode=0o700)
for name in ('athena-deck-backup.service','athena-deck-backup.timer'):
shutil.copyfile(ROOT/name,Path('/etc/systemd/system')/name)
subprocess.run(['systemctl','daemon-reload'],check=True)
subprocess.run(['systemctl','enable','--now','athena-deck-backup.timer'],check=True)
print('Backup-Zeitplan installiert: 08:00 und 20:00 Europe/Berlin; Deck nicht neu gestartet.')
if __name__=='__main__':main()
+90
View File
@@ -0,0 +1,90 @@
"""Non-destructive legacy media/history migration; no profile or service changes."""
import argparse,hashlib,json,os,shutil,sqlite3,tempfile,time
from pathlib import Path
def digest(p):
h=hashlib.sha256()
with p.open('rb') as f:
while b:=f.read(4*1024**2):h.update(b)
return h.hexdigest()
def copy_tree(source,target,records):
if not source.exists():return
for p in sorted(source.rglob('*')):
rel=p.relative_to(source);q=target/rel
if p.is_symlink():raise ValueError('Symlink in Nutzdaten: '+str(p))
if p.is_dir():q.mkdir(parents=True,exist_ok=True);continue
if not p.is_file() or p.name.endswith(('-wal','-shm')):continue
q.parent.mkdir(parents=True,exist_ok=True)
temporary=q.with_name(q.name+'.migration-partial')
if p.suffix in ('.db','.sqlite3'):
if temporary.exists():temporary.unlink()
with sqlite3.connect('file:'+str(p)+'?mode=ro',uri=True) as a,sqlite3.connect(temporary) as b:
a.backup(b)
if b.execute('PRAGMA integrity_check').fetchone()[0]!='ok':raise ValueError('SQLite beschädigt')
sha=digest(temporary)
else:sha=digest(p)
if q.exists():
if digest(q)!=sha:
temporary.unlink(missing_ok=True)
raise ValueError('Zielkonflikt; nichts überschrieben: '+str(q))
temporary.unlink(missing_ok=True)
else:
if p.suffix not in ('.db','.sqlite3'):shutil.copy2(p,temporary)
if digest(temporary)!=sha:raise ValueError('Kopie beschädigt')
temporary.replace(q);q.chmod(0o600)
records.append({'source':str(p),'target':str(q),'sha256':digest(q),'size':q.stat().st_size})
def merge_jobs(source,target,state):
if not source.exists():return {'imported':0}
remap={'/data/models/':'/var/lib/deck/applio-data/logs/','/data/uploads/':'/var/lib/deck/applio-data/datasets/.mikes-applio-ui/uploads/','/data/results/':'/var/lib/deck/applio-data/datasets/.mikes-applio-ui/results/','/app/logs/':'/var/lib/deck/applio-data/logs/','/app/assets/datasets/':'/var/lib/deck/applio-data/datasets/'}
with sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True) as old,sqlite3.connect(target,timeout=30) as new:
old.row_factory=sqlite3.Row
columns=[x[1] for x in old.execute('pragma table_info(jobs)')]
if columns!=[x[1] for x in new.execute('pragma table_info(jobs)')]:raise ValueError('Applio-Schema abweichend')
count=0;missing=[]
for row in old.execute('select * from jobs'):
d=dict(row)
existing=new.execute('select 1 from jobs where id=?',(d['id'],)).fetchone()
if existing:
for field in ('input_files','output_files'):
paths=json.loads(new.execute('select '+field+' from jobs where id=?',(d['id'],)).fetchone()[0]);changed=False
for i,path in enumerate(paths):
for prefix,dest in remap.items():
if path.startswith(prefix):paths[i]=dest+path[len(prefix):];changed=True;break
if changed:new.execute('update jobs set '+field+'=? where id=?',(json.dumps(paths),d['id']))
continue
for key in ('input_files','output_files'):
paths=json.loads(d[key]);mapped=[]
for p in paths:
for prefix,dest in remap.items():
if p.startswith(prefix):p=dest+p[len(prefix):];break
mapped.append(p)
host=Path(str(state)+p[len('/var/lib/deck'):]) if p.startswith('/var/lib/deck/') else Path(p)
if not host.is_file():missing.append({'job':d['id'],'field':key,'path':p})
d[key]=json.dumps(mapped)
# Imported jobs are history, never resume old queued/running work.
if d['status'] in ('wartend','laufend','queued','running'):
d['status']='abgebrochen';d['phase']='Historischer Auftrag; bei Übernahme nicht fortgesetzt';d['cancelled']=1
new.execute('insert into jobs ('+','.join(columns)+') values ('+','.join('?' for _ in columns)+')',[d[c] for c in columns]);count+=1
if new.execute('pragma integrity_check').fetchone()[0]!='ok':raise ValueError('Ziel-Datenbank beschädigt')
return {'imported':count,'missing_references':missing}
def run(state,ladypoly):
state=Path(state);archive=state/'legacy-userdata';archive.mkdir(exist_ok=True,mode=0o700);records=[]
sources=[('/data/music/ace-step-ui','ace-step-ui'),('/data/music/acestep','acestep-runs'),('/data/voice/xvc/output','xvc-output'),('/data/voice/omnivoice/output','omnivoice-output'),('/data/voice/studio/profiles','voice-profiles'),('/data/voice/applio/mikes-applio-ui','applio-ui'),('/var/lib/docker/volumes/mike-ai_router-images/_data','router-images'),('/var/lib/docker/volumes/mike-ai_router-state/_data','router-state')]
for source,name in sources:
copy_tree(Path(source),archive/name,records);print('Preserved:',name,flush=True)
copy_tree(Path('/data/music/yue2'),Path(ladypoly)/'outputs',records)
# Fill gaps in previously copied training datasets and outputs, retaining new files.
for name in ('datasets','logs'):
copy_tree(Path('/data/voice/applio')/name,state/'applio-data'/name,records)
result=merge_jobs(Path('/data/voice/applio/mikes-applio-ui/jobs/jobs.db'),state/'applio-data/jobs/jobs.db',state)
for root in (archive,state/'applio-data',Path(ladypoly)/'outputs'):
for p in [root,*root.rglob('*')]:
if not p.is_symlink():os.chown(p,65534,65534)
manifest={'created_at':time.time(),'files':records,'applio':result,'legacy_ui_note':'ACE-Step-Playlists/DB erhalten; vollständige UI weiterhin zurückgestellt.'}
out=archive/'migration-manifest.json';tmp=out.with_suffix('.tmp');tmp.write_text(json.dumps(manifest,ensure_ascii=False,indent=2));tmp.chmod(0o600);tmp.replace(out)
print(json.dumps({'files':len(records),'bytes':sum(r['size'] for r in records),'applio_jobs':result['imported'],'missing_references':len(result.get('missing_references',[]))}))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--state',required=True);p.add_argument('--ladypoly',required=True);a=p.parse_args();run(a.state,a.ladypoly)
+62
View File
@@ -0,0 +1,62 @@
"""Read-only host maintenance export using Deck's existing backup schema.
No Server construction, worker startup, installation or state write.
Run inside the installed Deck container, with passphrase on stdin.
"""
import hashlib,json,sqlite3,sys,threading
from pathlib import Path
from types import SimpleNamespace
sys.path.insert(0,'/app')
from backup import Backup,SETTINGS,validate
from backup_codec import seal,open_backup
from auth import CredentialStore
from image_runtime import ImageRuntime
from tts_runtime import TTSRuntime
from prompt_enhancer import PromptEnhancer
from docker_support import DockerSupport
from network.client import NetworkClient
def fingerprint(root):
paths=[root/n for n in SETTINGS]+list((root/'models').glob('*/entry.json'))+[root/'runtime/state.json',root/'auth.json',root/'recovery/job.json']+list(root.glob('*runtime/active.json'))
return {str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths if p.is_file()}
def snapshot(root):
before=fingerprint(root)
job=root/'recovery/job.json'
if job.exists() and json.loads(job.read_text()).get('state')=='running':raise ValueError('Restore läuft; Sicherung wird verschoben.')
class Inventory:
def __init__(self):self.root=root/'models';self.lock=threading.RLock()
def status(self):return {'entries':[dict(json.loads(p.read_text()),id=p.parent.name) for p in self.root.glob('*/entry.json')]}
# Allocate passive runtime readers without invoking constructors that may resume jobs.
def reader(cls,name):
r=cls.__new__(cls);r.root=root/name;r.lock=threading.RLock();r.job=None;r.image_runtime=image;return r
image=ImageRuntime(root/'image-runtime');catalog=Inventory()
state=json.loads((root/'runtime/state.json').read_text())
s=SimpleNamespace(catalog=catalog,profiles=SimpleNamespace(lock=threading.RLock()),endpoint=SimpleNamespace(lock=threading.RLock()),runtime=SimpleNamespace(status=lambda:state),image_runtime=image,tts_runtime=reader(TTSRuntime,'tts-runtime'),docker=DockerSupport(),network=NetworkClient(),credentials=CredentialStore(root/'auth.json'))
s.prompt_enhancer=PromptEnhancer(root/'prompt-enhancers',catalog,s.profiles,image)
from audio_cpp_runtime import AudioCppRuntime
from ltx_original_runtime import LTXOriginalRuntime
from separator_runtime import SeparatorRuntime
from remix_runtime import RemixRuntime
from xvc_runtime import XVCRuntime
from applio_runtime import ApplioRuntime
from acestep_runtime import AceStepRuntime
from omnivoice_runtime import OmniVoiceRuntime
from voxcpm_runtime import VoxCPMRuntime
for attr,cls,name in [('audio_cpp_runtime',AudioCppRuntime,'audio-cpp-runtime'),('ltx_original_runtime',LTXOriginalRuntime,'ltx-original-runtime'),('separator_runtime',SeparatorRuntime,'separator-runtime'),('remix_runtime',RemixRuntime,'music-remix-runtime'),('xvc_runtime',XVCRuntime,'xvc-runtime'),('applio_runtime',ApplioRuntime,'applio-runtime'),('acestep_runtime',AceStepRuntime,'acestep-runtime'),('omnivoice_runtime',OmniVoiceRuntime,'omnivoice-runtime'),('voxcpm_runtime',VoxCPMRuntime,'voxcpm-runtime')]:setattr(s,attr,reader(cls,name))
b=Backup.__new__(Backup);b.server=s;b.root=root;b.job=None
doc=b.snapshot(include_history=False)
doc['warnings'].append('Vollständige Dashboard-Historie liegt im separaten Nutzdatenarchiv.')
if before!=fingerprint(root):raise ValueError('Konfiguration während Export geändert; erneut versuchen.')
# This deployed OmniVoice tag uses the same maintained voice-web build recipe.
# Export the canonical recipe name accepted by the existing Restore UI.
for service in doc['services']:
if service.get('build_recipe')=='voice-web' and service.get('image')=='athena-voice-web:0.2.1-deck-random':
service['image']='athena-voice-web:0.2.1-deck2'
service['registry']=None
doc['warnings'].append('OmniVoice: lokales Image deck-random wird beim Neuaufbau aus dem gepflegten voice-web-Rezept als deck2 gebaut. Bestehenden anders benannten Container nicht automatisch ersetzen.')
return validate(doc)
if __name__=='__main__':
key=sys.stdin.buffer.readline().decode().strip();doc=snapshot(Path('/var/lib/deck'));raw=seal(doc,key)
assert open_backup(raw,key)==doc
sys.stdout.buffer.write(raw)
+45
View File
@@ -0,0 +1,45 @@
"""Verify and recover media into a NEW host directory; never overwrite live data.
Requires the running Deck container with maintenance/backup_stream.py.
"""
import argparse,json,os,shutil,subprocess,tarfile,tempfile,threading
from pathlib import Path
from scheduled_backup import command,KEY
def feed(process,archive,secret,errors):
try:
process.stdin.write(secret)
with archive.open('rb') as f:shutil.copyfileobj(f,process.stdin,1024*1024)
except BaseException as e:errors.append(e)
finally:process.stdin.close()
def restore(archive,target,keyfile):
if target.exists() or target.is_symlink():raise ValueError('Ziel muss neu und leer sein; bestehende Daten werden nicht überschrieben')
secret=keyfile.read_bytes().strip()+b'\n'
check=subprocess.Popen(command('backup_stream.py','verify'),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
errors=[];thread=threading.Thread(target=feed,args=(check,archive,secret,errors));thread.start();out,err=check.stdout.read(),check.stderr.read();thread.join()
if check.wait() or errors:raise ValueError('Archiv oder Schlüssel ungültig; nichts wiederhergestellt')
target.parent.mkdir(parents=True,exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.userdata-restore-',dir=target.parent) as temporary:
stage=Path(temporary)/'data';stage.mkdir(mode=0o700)
process=subprocess.Popen(command('backup_stream.py','decrypt'),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
errors=[];thread=threading.Thread(target=feed,args=(process,archive,secret,errors));thread.start()
try:
with tarfile.open(fileobj=process.stdout,mode='r|gz') as tar:
for member in tar:
if not member.isfile() or member.name.startswith('/') or '..' in member.name.split('/'):raise ValueError('Unsicherer Archivpfad')
dest=stage/member.name
if dest.exists():raise ValueError('Doppelter Archivpfad')
dest.parent.mkdir(parents=True,exist_ok=True)
with dest.open('xb') as f:shutil.copyfileobj(tar.extractfile(member),f,1024*1024)
dest.chmod(0o600)
# Drain the decrypted stream so AES-GCM final authentication runs.
while process.stdout.read(1024*1024):pass
thread.join();err=process.stderr.read()
if process.wait() or errors:raise ValueError('Wiederherstellung unvollständig')
stage.rename(target)
finally:
if process.poll() is None:process.kill();process.wait()
thread.join()
return json.loads(out)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('archive',type=Path);p.add_argument('target',type=Path);p.add_argument('--key',type=Path,default=KEY);a=p.parse_args();print(json.dumps(restore(a.archive,a.target,a.key)))
+108
View File
@@ -0,0 +1,108 @@
"""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=('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<estimate+10*1024**3:raise ValueError('Zu wenig Platz für neue Sicherung; alte Sicherungen bleiben erhalten')
atomic_json(DEST/'status.json',dict(state='running',started=time.time(),generation=stamp))
config=subprocess.run(command('read_backup_snapshot.py'),input=secret,capture_output=True)
if config.returncode:raise ValueError('Deck-Konfigurationsexport fehlgeschlagen: '+config.stderr.decode()[-600:])
p=pending/'athena-deck.adbackup';p.write_bytes(config.stdout);p.chmod(0o600)
result=media(pending/'userdata.tar.gz.agcm',secret)
atomic_json(pending/'manifest.json',dict(generation=stamp,config_sha256=hashlib.sha256(config.stdout).hexdigest(),**result))
pending.rename(DEST/stamp)
# Retain three verified generations; never delete the last good one on failure.
generations=sorted(p for p in DEST.iterdir() if p.is_dir() and re.fullmatch(r'[0-9]{8}-[0-9]{6}',p.name) and (p/'manifest.json').is_file())
for old in generations[:-3]:shutil.rmtree(old)
atomic_json(DEST/'status.json',dict(state='complete',finished=time.time(),generation=stamp,retained=min(3,len(generations)),**result))
print(json.dumps(dict(state='complete',generation=stamp,**result)))
except BaseException as e:
shutil.rmtree(pending,ignore_errors=True);atomic_json(DEST/'status.json',dict(state='failed',finished=time.time(),error=str(e)));raise
if __name__=='__main__':run()