"""Encrypted configuration export and sequential, inspectable recovery jobs. No chats, prompts, media, logs, model weights or container layers are read into an export. """ import base64,copy,hashlib,json,os,re,secrets,shutil,sqlite3,tempfile,threading,time,zlib from pathlib import Path,PurePosixPath from auth import atomic_write,validate_record from backup_codec import seal,open_backup from catalog import repo_id,file_role,KINDS from profiles import SCHEMAS,CHAT_GPU_DEFAULTS,chat_parameters,FLOAT_PARAMETERS,ACE_COMPONENTS,qwen_clone_model SETTINGS=('soulx_singer-data/settings.json','xvc-data/settings.json','applio-data/settings.json','separator-profiles.json','profiles.json','reasoning-budget.json','endpoint.json','audio-policy.json','video/comfy-selection.json','models/huggingface.json','video/comfy-client-token','video/original-work/settings.json') MAX_HISTORY=40*1024**2 VERSION=1 # Exact byte hash verified against official Hub metadata, not a filename heuristic. LOCAL_SOURCES={'83ee4f4f205fa514161778c41df1ea14144faa0f713510893b63c2395f5c2d53':dict(repo='unsloth/Qwen3.8-27B-GGUF',revision='4ca720788d1e01f1bff70c033e0d0028fd02e502',file='mmproj-BF16.gguf')} def qwen_voice_alias(model): return qwen_clone_model(model) and model.get('id')==hashlib.sha256((model['repo']+model['revision']+'voice-clone').encode()).hexdigest() def validate(doc): if not isinstance(doc,dict) or doc.get('format')!='athena-deck' or doc.get('version')!=VERSION:raise ValueError('Backup-Version nicht unterstützt.') if set(doc)-{'format','version','created_at','settings','models','credentials','theme','network','services','runtimes','warnings','history','runtime_versions'}:raise ValueError('Unbekannte Backup-Felder.') if not isinstance(doc.get('warnings',[]),list) or len(doc.get('warnings',[]))>100 or any(not isinstance(w,str) or len(w)>1024 for w in doc.get('warnings',[])):raise ValueError('Ungültige Backup-Hinweise.') if 'history' in doc and (not isinstance(doc['history'],str) or len(doc['history'])>56*1024**2):raise ValueError('History im Backup zu groß.') models=doc.get('models');profiles=doc.get('settings',{}).get('profiles.json',[]) if not isinstance(models,list) or len(models)>4096 or not isinstance(profiles,list) or len(profiles)>1000:raise ValueError('Ungültiges Modell-/Profilverzeichnis.') ids=set() for m in models: repo_id(m.get('repo'));f=m.get('file','');parts=PurePosixPath(f).parts if not isinstance(f,str) or not parts or f.startswith('/') or '..' in parts or '\\' in f or len(f)>1024 or any(ord(c)<32 for c in f):raise ValueError('Unsicherer Modell-Dateiname.') local=m.get('source')=='local' if not re.fullmatch('[a-f0-9]{64}' if local else '[a-f0-9]{40}',m.get('revision','')) or m.get('kind') not in KINDS or type(m.get('size')) is not int or not 01024 or sf.startswith('/') or '..' in PurePosixPath(sf).parts or '\\' in sf or any(ord(c)<32 for c in sf):raise ValueError('Ungültige Ersatzquelle.') metadata=m.get('runtime_metadata') if metadata is not None and metadata not in ({'architecture':'rvc'},{'architecture':'xvc'},{'architecture':'seed_vc'},{'architecture':'soulx_singer'}):raise ValueError('Ungültige Stimm-Modellmetadaten.') ids.add(m['id']) pids=set();names=set();api_names=set() for p in profiles: if not isinstance(p,dict) or not re.fullmatch('[a-f0-9]{32}',p.get('id','')) or p['id'] in pids or p.get('name') in names:raise ValueError('Ungültige oder doppelte Profil-ID.') name=p.get('name','');kind=p.get('kind');params=p.get('parameters') if not isinstance(name,str) or not 2<=len(name)<=64 or not re.fullmatch(r'[\w .-]+',name) or not name[0].isalnum() or not name[-1].isalnum() or kind not in SCHEMAS or p.get('model_id') not in ids:raise ValueError('Ungültiges Profil oder Modellreferenz.') api_id=p.get('api_id');aliases=p.get('api_aliases',[]) if api_id is not None and (not isinstance(api_id,str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}',api_id)):raise ValueError('Ungültige API-ID im Backup.') if not isinstance(aliases,list) or len(aliases)>100 or any(not isinstance(a,str) or not 1<=len(a)<=64 or any(ord(c)<32 for c in a) for a in aliases):raise ValueError('Ungültige API-Aliase im Backup.') identities=set([name,*aliases]+([api_id] if api_id else [])) if identities & api_names:raise ValueError('Doppelte API-ID oder Alias im Backup.') api_names.update(identities) if type(p.get('revision')) is not int or not 1<=p['revision']<=1000000:raise ValueError('Ungültige Profilrevision.') if not isinstance(params,dict):raise ValueError('Ungültige Profilparameter.') params=chat_parameters(params) if kind=='chat' else params if set(params)!=(set(SCHEMAS[kind])|(set(CHAT_GPU_DEFAULTS) if kind=='chat' else set(params)&{'video_device','text_encoder_device'} if kind=='video' else set())):raise ValueError('Unbekannte Profilparameter.') for key,(lo,hi,_) in SCHEMAS[kind].items(): value=params[key] if isinstance(value,bool) or not isinstance(value,(int,float)) or not lo<=value<=hi or key not in FLOAT_PARAMETERS and type(value) is not int:raise ValueError('Ungültiger Profilparameter: '+key) if kind=='chat' and params.get('chat_runtime')=='strata': from strata_runtime import model_quant model_quant(next(m for m in models if m['id']==p['model_id'])) if kind=='chat' and (params['ubatch']>params['batch'] or params.get('vision_projector') and params['vision_projector'] not in ids):raise ValueError('Ungültige Chat-Zuordnung.') if kind in ('image','video') and (params['width']%64 or params['height']%64):raise ValueError('Ungültige Bildgröße.') components=p.get('components',{}) if not isinstance(components,dict) or any((k not in ('codec','text_encoder','vae','video_vae','audio_vae','spatial_upsampler','model_config','generation_config','tokenizer','vae_config','manual_text_encoder','manual_vae','manual_tokenizer','manual_configuration','manual_projector','manual_auxiliary','tokenizer_config','special_tokens','chat_template','audio_tokenizer','audio_config','preprocessor') and k not in ACE_COMPONENTS and not re.fullmatch(r'runtime_file_[0-9]{1,2}',k)) or v not in ids for k,v in components.items()):raise ValueError('Ungültige Komponentenreferenz.') presets=p.get('presets',[]) if not isinstance(presets,list) or len(presets)>50:raise ValueError('Ungültige Presets im Backup.') preset_ids=set();preset_names=set() for preset in presets: if not isinstance(preset,dict) or set(preset)!={'id','name','created_at','model_id','parameters'}:raise ValueError('Ungültiges Preset.') pn=preset['name'];pi=preset['id'];pp=preset['parameters'] if not isinstance(pn,str) or not 1<=len(pn)<=64 or any(ord(c)<32 for c in pn) or not isinstance(pi,str) or not re.fullmatch('[a-f0-9]{32}',pi) or pi in preset_ids or pn in preset_names or preset['model_id'] not in ids or type(preset['created_at']) not in (int,float):raise ValueError('Ungültige Preset-Metadaten.') if not isinstance(pp,dict):raise ValueError('Ungültige Preset-Parameter.') pp=chat_parameters(pp) if kind=='chat' else pp if set(pp)!=(set(SCHEMAS[kind])|(set(CHAT_GPU_DEFAULTS) if kind=='chat' else set(pp)&{'video_device','text_encoder_device'} if kind=='video' else set())):raise ValueError('Unbekannte Preset-Parameter.') for key,(lo,hi,_) in SCHEMAS[kind].items(): value=pp[key] if isinstance(value,bool) or not isinstance(value,(int,float)) or not lo<=value<=hi or key not in FLOAT_PARAMETERS and type(value) is not int:raise ValueError('Ungültiger Preset-Parameter: '+key) if kind=='chat' and (pp['ubatch']>pp['batch'] or pp.get('vision_projector') and pp['vision_projector'] not in ids):raise ValueError('Ungültige Preset-Projektorzuordnung.') if kind in ('image','video') and (pp['width']%64 or pp['height']%64):raise ValueError('Ungültige Preset-Bildgröße.') preset_ids.add(pi);preset_names.add(pn) pids.add(p['id']);names.add(name) settings=doc.get('settings') if not isinstance(settings,dict) or set(settings)-set(SETTINGS):raise ValueError('Unbekannte Einstellungsdateien.') if 'reasoning-budget.json' in settings: from api_compat import reasoning_policy reasoning_policy(settings['reasoning-budget.json']) ep=settings.get('endpoint.json',{}) if not isinstance(ep,dict) or set(ep)-{'port','enabled_profiles','autostart','responses_compat','tts_text_enhancer'} or type(ep.get('tts_text_enhancer',False)) is not bool or type(ep.get('responses_compat',False)) is not bool or type(ep.get('port',8120)) is not int or not 1024<=ep.get('port',8120)<=65535 or type(ep.get('autostart',False)) is not bool:raise ValueError('Ungültige Endpunkt-Einstellungen.') enabled=ep.get('enabled_profiles',[]) if not isinstance(enabled,list) or any(p not in pids for p in enabled) or len(set(enabled))!=len(enabled):raise ValueError('Unbekannte Profilfreigabe.') if sum(p['kind']=='image' and p['id'] in enabled for p in profiles)>1:raise ValueError('Nur ein Bildprofil darf freigegeben sein.') policy=settings.get('audio-policy.json',{}) if not isinstance(policy,dict) or set(policy)-{'tts','stt'} or any(not isinstance(v,dict) or set(v)!={'mode','profile_id'} or v['mode'] not in ('auto','warm','per_request') or v['profile_id'] is not None and v['profile_id'] not in pids for v in policy.values()):raise ValueError('Ungültige Audio-Einstellung.') selection=settings.get('video/comfy-selection.json',{}) if isinstance(selection,dict) and selection.get('runtime','comfy') not in ('comfy','original'):raise ValueError('Unbekannte Video-Laufzeit.') if not isinstance(selection,dict) or set(selection)-{'model_id','runtime'} or selection.get('model_id') and selection['model_id'] not in ids:raise ValueError('Ungültige Video-Auswahl.') if 'models/huggingface.json' in settings: hf=settings['models/huggingface.json'] if not isinstance(hf,dict) or set(hf)!={'token'} or hf['token'] is not None and (not isinstance(hf['token'],str) or not re.fullmatch(r'hf_[A-Za-z0-9]{10,252}',hf['token'])):raise ValueError('Ungültiger Hugging-Face-Zugang.') if 'video/comfy-client-token' in settings and not re.fullmatch(r'[A-Za-z0-9_-]{32,256}',settings['video/comfy-client-token'].strip()):raise ValueError('Ungültiger Diensttoken.') if 'video/original-work/settings.json' in settings and (not isinstance(settings['video/original-work/settings.json'],dict) or len(json.dumps(settings['video/original-work/settings.json']))>65536):raise ValueError('Ungültige LTX-Einstellungen.') if 'xvc-data/settings.json' in settings: v=settings['xvc-data/settings.json'] if not isinstance(v,dict) or set(v)!={'device'} or v['device'] not in ('3060','5080'):raise ValueError('Ungültige X-VC-GPU.') if 'seed_vc-data/settings.json' in settings: v=settings['seed_vc-data/settings.json'] if not isinstance(v,dict) or set(v)!={'device'} or v['device'] not in ('3060','5080'):raise ValueError('Ungültige Seed-VC-GPU.') if 'soulx_singer-data/settings.json' in settings: v=settings['soulx_singer-data/settings.json'] if not isinstance(v,dict) or set(v)!={'device'} or v['device'] not in ('3060','5080'):raise ValueError('Ungültige SoulX-Singer-GPU.') if 'applio-data/settings.json' in settings: v=settings['applio-data/settings.json'] if not isinstance(v,dict) or set(v)!={'device'} or v['device'] not in ('3060','5080'):raise ValueError('Ungültige Applio-GPU.') if 'separator-profiles.json' in settings: from separator import validate_profiles validate_profiles(settings['separator-profiles.json']) validate_record(doc.get('credentials')) runtimes=doc.get('runtimes') if not isinstance(runtimes,dict) or set(runtimes)-{'llama','llama_builds','image','tts','enhancers','swarm_nodes','ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','seed_vc','soulx_singer','music_remix','strata','pocket'} or not {'llama','llama_builds','image','tts','enhancers','swarm_nodes'}<=set(runtimes):raise ValueError('Ungültiges Laufzeitrezept.') if any(qwen_voice_alias(m) for m in models) and runtimes.get('tts') is not True:raise ValueError('Qwen-Stimmklon benötigt das vollständige TTS-Laufzeitrezept.') if 'separator' in runtimes: from separator_runtime import MODELS value=runtimes['separator'] if not isinstance(value,dict) or set(value)-{'installed','models','sources'} or not {'installed','models'}<=set(value) or type(value['installed']) is not bool or not isinstance(value['models'],list) or len(value['models'])>len(MODELS) or any(not isinstance(m,str) or m not in MODELS for m in value['models']) or len(set(value['models']))!=len(value['models']):raise ValueError('Ungültiges Audio-Separator-Rezept.') if 'sources' in value: from separator_runtime import SOURCES if value['sources']!={name:SOURCES[name] for name in value['models']}:raise ValueError('Audio-Separator-Quellen stimmen nicht mit dem geprüften Rezept überein.') if 'pocket' in runtimes and type(runtimes['pocket']) is not bool:raise ValueError('Ungültige Pocket-Laufzeit.') if 'strata' in runtimes and type(runtimes['strata']) is not bool:raise ValueError('Ungültige Strata-Laufzeit.') if 'music_remix' in runtimes and type(runtimes['music_remix']) is not bool:raise ValueError('Ungültige Audio-Remix-Laufzeit.') if 'xvc' in runtimes and type(runtimes['xvc']) is not bool:raise ValueError('Ungültige X-VC-Laufzeit.') if 'seed_vc' in runtimes and type(runtimes['seed_vc']) is not bool:raise ValueError('Ungültige Seed-VC-Laufzeit.') if 'soulx_singer' in runtimes and type(runtimes['soulx_singer']) is not bool:raise ValueError('Ungültige SoulX-Singer-Laufzeit.') if 'applio' in runtimes and type(runtimes['applio']) is not bool:raise ValueError('Ungültige Applio-Laufzeit.') if 'acestep' in runtimes and type(runtimes['acestep']) is not bool:raise ValueError('Ungültige ACE-Step-Laufzeit.') if 'omnivoice' in runtimes and type(runtimes['omnivoice']) is not bool:raise ValueError('Ungültige OmniVoice-Laufzeit.') if 'voxcpm' in runtimes and type(runtimes['voxcpm']) is not bool:raise ValueError('Ungültige VoxCPM-Laufzeit.') if 'audio_cpp' in runtimes and type(runtimes['audio_cpp']) is not bool:raise ValueError('Ungültige audio.cpp-Laufzeit.') if 'ltx_original' in runtimes and type(runtimes['ltx_original']) is not bool:raise ValueError('Ungültige LTX-Laufzeit.') if not isinstance(runtimes['llama_builds'],list) or len(runtimes['llama_builds'])>50 or any(not isinstance(b,dict) or set(b)!={'commit','backend'} or not re.fullmatch('[a-f0-9]{40}',b.get('commit','')) or b.get('backend') not in ('CUDA','CPU') for b in runtimes['llama_builds']):raise ValueError('Ungültige Buildrezepte.') if runtimes['llama'] is not None: item=runtimes['llama'] if not isinstance(item,dict) or not re.fullmatch('[a-f0-9]{40}',item.get('commit','')) or item.get('backend') not in ('CUDA','CPU'):raise ValueError('Ungültige llama.cpp-Quelle.') if any(type(runtimes[k]) is not bool for k in ('image','tts','swarm_nodes')) or not isinstance(runtimes['enhancers'],dict) or set(runtimes['enhancers'])-{'t2i','i2i'}:raise ValueError('Ungültiges Laufzeitrezept.') for revision in runtimes['enhancers'].values(): if not isinstance(revision,str) or not re.fullmatch('[a-f0-9]{40}',revision):raise ValueError('Ungültige Aufwerterversion.') network=doc.get('network') if network is not None: if not isinstance(network,dict) or (set(network)-{'config','enabled','mode','allowed_hosts'} or not {'config','enabled','mode'}<=set(network)) or type(network['enabled']) is not bool or network['mode'] not in ('lan','both','tunnel'):raise ValueError('Ungültiger Netzwerkstand.') from network.hosts import validate_hosts validate_hosts(network.get('allowed_hosts',[])) if network['config'] is not None: from network.config import parse_config parse_config(network['config'],native=True) services=doc.get('services') if not isinstance(services,list) or len(services)>50:raise ValueError('Ungültiger Containerbestand.') # Validation is shared with the root helper, which independently revalidates before Docker calls. from deploy.docker_backup import validate as validate_container seen=set() for c in services: validate_container(c) if c['name'] in seen:raise ValueError('Doppelte Containerdefinition.') seen.add(c['name']) if doc.get('theme','deck') not in ('deck','athena-classic'):raise ValueError('Unbekanntes Theme.') return doc class Backup: def __init__(self,server): self.server=server;self.root=server.catalog.root.parent;self.directory=self.root/'recovery';self.directory.mkdir(parents=True,exist_ok=True,mode=0o700) self.lock=threading.RLock();self.cancel=threading.Event();self.plan=None;self.job=None path=self.directory/'job.json' if path.exists(): self.job=json.loads(path.read_text()) if self.job.get('state')=='running':self.job.update(state='interrupted',phase='Restore durch Neustart unterbrochen. Backup erneut importieren; vorhandene Dateien werden geprüft und wiederverwendet.');self._save() def busy(self):return bool(self.job and self.job['state']=='running') def _save(self):atomic_write(self.directory/'job.json',self.job) def status(self): with self.lock:return {'job':copy.deepcopy(self.job),'preview':copy.deepcopy(self.plan['summary']) if self.plan else None,'checkpoints':[p.name for p in sorted(self.directory.glob('before-*.adbackup'),reverse=True)]} def snapshot(self,theme='deck',include_history=True,_during_restore=False): s=self.server if self.busy() and not _during_restore:raise ValueError('Restore läuft. Export erst danach.') settings={} # Explicit allowlist: no recursive backup of process work directories. with s.profiles.lock,s.endpoint.lock,s.catalog.lock: for name in SETTINGS: p=self.root/name if p.is_file():settings[name]=p.read_text().strip() if name.endswith('comfy-client-token') else json.loads(p.read_text()) models=[] for m in s.catalog.status()['entries']: item={k:m[k] for k in ('id','repo','revision','file','size','sha256','kind')} if (architecture:=(m.get('runtime_metadata') or {}).get('architecture')) in ('rvc','xvc','soulx_singer'):item['runtime_metadata']={'architecture':architecture} if m['repo'].startswith('local/'): item['source']='local';item['download_source']=m.get('download_source') or LOCAL_SOURCES.get(m['sha256']) elif m.get('download_source'):item['download_source']=copy.deepcopy(m['download_source']) models.append(item) state=s.runtime.status();active=next((b for b in state['builds'] if b['id']==state['active']),None) llama={'commit':active['commit'],'backend':active['backend']} if active else None warnings=[];services=[] try:services=s.docker.call('backup-export')['services'] except (OSError,ValueError): if s.docker.status().get('services'):raise ValueError('Container-Konfigurationen können ohne aktualisierten Systemhelfer nicht gesichert werden.') warnings.append('Docker-Systemhelfer nicht verfügbar; keine Zusatzdienste gesichert.') network=None if not s.network.disabled: network=s.network.call('backup-export') else:warnings.append('Deck-Netzwerkmodul deaktiviert; fremder WireGuard-Gateway wird nicht gesichert.') document=dict(format='athena-deck',version=VERSION,created_at=time.time(),settings=settings,models=models,credentials=s.credentials.read(),theme=theme,network=network,services=services,runtime_versions=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']),runtimes=dict(audio_cpp=bool(getattr(s,'audio_cpp_runtime',None) and s.audio_cpp_runtime.status()['installed']),ltx_original=bool(getattr(s,'ltx_original_runtime',None) and s.ltx_original_runtime.status()['installed']),llama=llama,llama_builds=[dict(commit=b['commit'],backend=b['backend']) for b in state['builds']],image=s.image_runtime.status()['installed'],tts=s.tts_runtime.status()['installed'],enhancers={task:data['revision'] for task in ('t2i','i2i') if (data:=s.prompt_enhancer.installed(task))},swarm_nodes=(self.root/'video/swarm-comfy-nodes').is_dir()),warnings=warnings) if getattr(s,'pocket_runtime',None): document['runtimes']['pocket']=s.pocket_runtime.status()['installed'];document['runtime_versions']['pocket']=s.pocket_runtime.status()['revision'] if getattr(s,'strata_runtime',None): document['runtimes']['strata']=s.strata_runtime.status()['installed'] document['runtime_versions']['strata']=s.strata_runtime.status()['revision'] if getattr(s,'remix_runtime',None): document['runtimes']['music_remix']=s.remix_runtime.status()['installed'] if document['runtimes']['music_remix']: from remix_runtime import VERSION as REMIX_VERSION document['runtime_versions']['music_remix']=REMIX_VERSION if getattr(s,'separator_runtime',None): from separator_runtime import SOURCES separator=s.separator_runtime.status();document['runtimes']['separator']=dict(installed=separator['installed'],models=[m['id'] for m in separator['models'] if m['installed']],sources={m['id']:SOURCES[m['id']] for m in separator['models'] if m['installed']});document['runtime_versions']['separator']=separator['version'] if getattr(s,'xvc_runtime',None): from xvc_runtime import RECIPE_HASH document['runtimes']['xvc']=s.xvc_runtime.status()['installed'];document['runtime_versions']['xvc']=dict(code=s.xvc_runtime.status()['revision'],assets=RECIPE_HASH) if getattr(s,'soulx_singer_runtime',None): from soulx_singer_runtime import RECIPE_HASH document['runtimes']['soulx_singer']=s.soulx_singer_runtime.status()['installed'];document['runtime_versions']['soulx_singer']=dict(code=s.soulx_singer_runtime.status()['revision'],assets=RECIPE_HASH) if getattr(s,'applio_runtime',None): document['runtimes']['applio']=s.applio_runtime.status()['installed'];document['runtime_versions']['applio']=s.applio_runtime.status()['revision'] if (self.root/'applio-data/logs').exists():document['warnings'].append('Eigene Applio-Stimmen und Trainingsdaten separat sichern. Dieses Konfigurationsbackup enthält sie nicht; nach Restore erst den Applio-Datenbestand zurückspielen.') if getattr(s,'acestep_runtime',None): document['runtimes']['acestep']=s.acestep_runtime.status()['installed'];document['runtime_versions']['acestep']=s.acestep_runtime.status()['version'] if getattr(s,'omnivoice_runtime',None): document['runtimes']['omnivoice']=s.omnivoice_runtime.status()['installed'];document['runtime_versions']['omnivoice']=s.omnivoice_runtime.status()['version'] if getattr(s,'voxcpm_runtime',None): document['runtimes']['voxcpm']=s.voxcpm_runtime.status()['installed'];document['runtime_versions']['voxcpm']=s.voxcpm_runtime.status()['version'] if document['runtimes']['audio_cpp']: from audio_cpp_runtime import REVISION document['runtime_versions']['audio_cpp']=REVISION if document['runtimes']['ltx_original']: from ltx_original_runtime import DESKTOP_REV,LTX_REV document['runtime_versions']['ltx_original']=dict(desktop=DESKTOP_REV,inference=LTX_REV) if include_history: with tempfile.TemporaryDirectory(dir=self.directory) as work: out=Path(work)/'history.sqlite3' with s.dashboard.history._lock,sqlite3.connect(out) as dest:s.dashboard.history._db.backup(dest) if out.stat().st_size>MAX_HISTORY:raise ValueError('Dashboard-History größer als 40 MiB. History separat sichern oder Export ohne History wählen.') document['history']=base64.b64encode(out.read_bytes()).decode() return document def export(self,phrase,theme='deck',history=True):return seal(validate(self.snapshot(theme,history)),phrase) def inspect(self,raw,phrase): doc=validate(open_backup(raw,phrase));s=self.server;blockers=[];warnings=list(doc.get('warnings',[]));existing={m['id']:m for m in s.catalog.status()['entries']} if 'history' in doc:self._restore_history(doc['history'],validate_only=True) missing=[m for m in doc['models'] if m['id'] not in existing];need=sum(m['size'] for m in missing) if missing and need+10*1024**3>shutil.disk_usage(self.root).free:blockers.append('Zu wenig Platz für fehlende Gewichte einschließlich 10 GiB Reserve.') for m in doc['models']: if m.get('source')=='local' and not m.get('download_source'): warnings.append(m['file']+': lokale Datei ohne nachladbare Quelle; separat sichern.') if m['id'] not in existing:blockers.append(m['file']+': lokale Gewichtedatei fehlt und hat keine Downloadquelle.') if m['id'] in existing and existing[m['id']].get('sha256')!=m['sha256']:blockers.append('Vorhandene Modelldatei hat abweichende Prüfsumme: '+m['file']) if doc['runtimes']['llama']: prereq=s.runtime.prerequisites();backend=doc['runtimes']['llama']['backend'] if not prereq['cuda_ready' if backend=='CUDA' else 'cpu_ready']:blockers.append('llama.cpp-Buildwerkzeuge fehlen; Laufzeit-Voraussetzungen installieren.') if doc['network'] and (doc['network'].get('config') or 'allowed_hosts' in doc['network']): if s.network.disabled:blockers.append('Backup enthält Netzwerkeinstellungen: Deck-Netzwerkmodul muss zuerst installiert/angebunden werden. Bestehender Gateway wird nicht übernommen.') elif s.network.status().get('enabled') or s.network.status().get('mode')!='lan':blockers.append('Deck-Tunnel vor Netzwerk-Restore im bestätigten LAN-Modus deaktivieren.') if doc['network']['mode']!='lan':warnings.append('Tunnelzugang wird mit Rückfallzeit aktiviert und muss über den Tunnel bestätigt werden.') versions=doc.get('runtime_versions',{}) if versions.get('pocket'): from pocket_runtime import REVISION as POCKET_REVISION if versions['pocket']!=POCKET_REVISION:blockers.append('Backup verlangt eine andere Pocket-Version. Passende Deck-Version verwenden.') if versions.get('strata'): from strata_runtime import COMMIT if versions['strata']!=COMMIT:blockers.append('Backup verlangt eine andere Strata-Version. Passende Deck-Version verwenden.') if versions.get('acestep'): from acestep_runtime import VERSION as ACE_VERSION if versions['acestep']!=ACE_VERSION:blockers.append('Backup verlangt eine andere ACE-Step-Version. Passende Deck-Version verwenden.') if versions.get('omnivoice'): from omnivoice_runtime import VERSION as OMNIVOICE_VERSION if versions['omnivoice']!=OMNIVOICE_VERSION:blockers.append('Backup verlangt eine andere OmniVoice-Version. Passende Deck-Version verwenden.') if versions.get('voxcpm'): from voxcpm_runtime import VERSION as VOXCPM_VERSION if versions['voxcpm']!=VOXCPM_VERSION:blockers.append('Backup verlangt eine andere VoxCPM-Version. Passende Deck-Version verwenden.') if versions.get('music_remix'): from remix_runtime import VERSION as REMIX_VERSION if versions['music_remix']!=REMIX_VERSION:blockers.append('Backup verlangt eine andere Audio-Remix-Version.') if versions.get('separator'): from separator_runtime import VERSION as SEPARATOR_VERSION if versions['separator']!=SEPARATOR_VERSION:blockers.append('Backup verlangt eine andere Audio-Separator-Version.') if versions.get('audio_cpp'): from audio_cpp_runtime import REVISION if versions['audio_cpp']!=REVISION:blockers.append('Backup verlangt eine andere audio.cpp-Version. Passende Deck-Version verwenden.') if versions.get('ltx_original'): from ltx_original_runtime import DESKTOP_REV,LTX_REV if versions['ltx_original']!=dict(desktop=DESKTOP_REV,inference=LTX_REV):blockers.append('Backup verlangt eine andere originale LTX-Version. Passende Deck-Version verwenden.') if versions.get('xvc'): from xvc_runtime import REVISION as XVC_REVISION,RECIPE_HASH if versions['xvc']!=dict(code=XVC_REVISION,assets=RECIPE_HASH):blockers.append('Backup verlangt eine andere X-VC-Version oder Komponentenquelle.') if doc.get('runtimes',{}).get('seed_vc') or versions.get('seed_vc'): blockers.append('Seed-VC wurde entfernt. Dieses alte Laufzeitrezept wird nicht wieder installiert.') if versions.get('soulx_singer'): from soulx_singer_runtime import REVISION as SOULX_REVISION,RECIPE_HASH if versions['soulx_singer']!=dict(code=SOULX_REVISION,assets=RECIPE_HASH):blockers.append('Backup verlangt eine andere SoulX-Singer-Version oder Komponentenquelle.') if versions.get('applio'): from applio_runtime import REVISION as APPLIO_REVISION if versions['applio']!=APPLIO_REVISION:blockers.append('Backup verlangt eine andere Applio-Version.') if versions and {k:v for k,v in versions.items() if k not in ('ltx_original','audio_cpp','separator','voxcpm','omnivoice','acestep','applio','xvc','seed_vc','soulx_singer','music_remix','strata','pocket')}!=dict(image=dict(comfy=s.image_runtime.status()['comfy_revision'],gguf=s.image_runtime.status()['gguf_revision']),tts=s.tts_runtime.status()['revision']):blockers.append('Backup verlangt andere Bild-/TTS-Laufzeitversionen. Passende Deck-Version oder geprüftes Runtime-Upgrade verwenden.') for c in doc['services']: if not c.get('registry') and not c.get('build_recipe'):warnings.append(c['name']+': Image nur lokal vorhanden; Registry-/Buildquelle fehlt.') ports=s.endpoint.allowed_ports if ports and doc['settings'].get('endpoint.json',{}).get('port',8120) not in ports:blockers.append('API-Port aus Backup ist nicht veröffentlicht. Installer zuerst für diesen Port konfigurieren.') ident=secrets.token_hex(16);summary=dict(id=ident,created_at=doc.get('created_at'),models=[dict(id=m['id'],name=m['file'],bytes=m['size'],present=m['id'] in existing) for m in doc['models']],profiles=[p['name'] for p in doc['settings'].get('profiles.json',[])],services=[dict(name=c['name'],image=c['image'],registry=c.get('registry'),build_recipe=c.get('build_recipe'),restorable=bool(c.get('registry') or c.get('build_recipe')),running=c['running']) for c in doc['services']],download_bytes=need,runtimes=doc['runtimes'],wireguard=bool(doc['network'] and doc['network']['config']),warnings=warnings,blockers=blockers,theme=doc.get('theme','deck')) with self.lock: if self.busy():raise ValueError('Restore läuft bereits.') self.plan={'document':doc,'summary':summary,'expires':time.monotonic()+1800} return summary def inspect_checkpoint(self,name): if not isinstance(name,str) or not re.fullmatch(r'before-[a-f0-9]{32}\.adbackup',name):raise ValueError('Ungültiger Rückfallstand.') p=self.directory/name;key=p.with_suffix('.key') if p.is_symlink() or key.is_symlink() or not p.is_file() or not key.is_file():raise ValueError('Rückfallstand nicht verfügbar.') return self.inspect(p.read_bytes(),key.read_text()) def start(self,data): if not isinstance(data,dict) or set(data)!={'id','services','confirm','restore_credentials'} or data['confirm'] is not True or type(data['restore_credentials']) is not bool or not isinstance(data['services'],list):raise ValueError('Restore-Prüfung und ausdrückliche Bestätigung erforderlich.') with self.lock: if self.busy():raise ValueError('Restore läuft bereits.') if not self.plan or self.plan['expires']MAX_HISTORY:raise ValueError('History im Backup zu groß.') with tempfile.TemporaryDirectory(dir=self.directory) as work: path=Path(work)/'history.sqlite3';path.write_bytes(raw) with sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True) as source: if source.execute('PRAGMA quick_check').fetchone()[0]!='ok':raise ValueError('Ungültige Dashboard-History.') expected={'meta','samples_raw','samples_hourly','slot_samples_raw','slot_samples_hourly','token_totals','token_hourly','model_events'} if {r[0] for r in source.execute("SELECT name FROM sqlite_master WHERE type='table'")}!=expected or source.execute("SELECT COUNT(*) FROM sqlite_master WHERE type IN ('trigger','view')").fetchone()[0]:raise ValueError('Unbekanntes History-Schema.') if not validate_only: with self.server.dashboard.history._lock:source.backup(self.server.dashboard.history._db) def stop(self): with self.lock: self.cancel.set() if self.busy(): self.server.catalog.stop();self.server.runtime.stop();self.server.image_runtime.stop();self.server.tts_runtime.stop();self.server.ltx_original_runtime.stop(); if getattr(self.server,'separator_runtime',None):self.server.separator_runtime.stop() if getattr(self.server,'separator_tests',None):self.server.separator_tests.stop() if getattr(self.server,'music',None):self.server.music.stop() if getattr(self.server,'omnivoice_runtime',None):self.server.omnivoice_runtime.stop() if getattr(self.server,'voxcpm_runtime',None):self.server.voxcpm_runtime.stop() if getattr(self.server,'xvc_runtime',None):self.server.xvc_runtime.stop() if getattr(self.server,'soulx_singer_runtime',None):self.server.soulx_singer_runtime.stop() if getattr(self.server,'applio_runtime',None):self.server.applio_runtime.stop() if getattr(self.server,'acestep_runtime',None):self.server.acestep_runtime.stop() if getattr(self.server,'audio_cpp_runtime',None):self.server.audio_cpp_runtime.stop() self.server.prompt_enhancer.stop() return {'cancellation_requested':True}