sessions.json/keys.json/settings.json etaient ecrits directement (Path.write_text) : un crash ou une coupure de courant pendant l'ecriture pouvait laisser un fichier tronque, sans aucun recours. - app/storage/atomic_file.py : ecriture .tmp + flush + fsync + os.replace() (atomique y compris sous Windows). - app/storage/json_store.py : load_json_document()/save_json_document(). Chaque sauvegarde conserve la version precedente dans un .bak ; au chargement, un fichier principal corrompu retombe automatiquement sur ce .bak avant de se rabattre sur des valeurs par defaut. Chaque document porte un schema_version, avec une chaine de migrations (vide pour l'instant) pour faire evoluer le format plus tard sans invalider les fichiers existants. - SessionStore et KeyManager utilisent ce module (schema_version=1) ; un fichier legacy sans schema_version reste charge normalement et n'est reecrit qu'a la prochaine sauvegarde naturelle (comportement de "premiere ecriture" inchange par rapport a avant). - settings.json (theme.py) et known_hosts (known_hosts_manager.py, via paramiko.HostKeys.save() redirige vers un .tmp puis os.replace()) beneficient aussi de l'ecriture atomique. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
86 lines
2.7 KiB
Python
86 lines
2.7 KiB
Python
"""Stockage des sessions SSH (serveurs enregistres) dans un fichier JSON local."""
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
from dataclasses import dataclass, field, asdict
|
|
from pathlib import Path
|
|
|
|
from app.paths import DATA_DIR # noqa: E402 (chemins valables aussi en .exe)
|
|
from app.storage.json_store import load_json_document, save_json_document
|
|
|
|
SESSIONS_FILE = DATA_DIR / "sessions.json"
|
|
SCHEMA_VERSION = 1
|
|
|
|
AUTH_AUTO = "auto" # comme la commande ssh : agent + cles ~/.ssh, mot de passe en secours
|
|
AUTH_KEY = "key" # cle privee explicitement choisie
|
|
AUTH_PASSWORD = "password"
|
|
AUTH_AGENT = "agent"
|
|
|
|
|
|
@dataclass
|
|
class Session:
|
|
id: str = field(default_factory=lambda: str(uuid.uuid4()))
|
|
name: str = ""
|
|
group: str = "" # ex: "Prod/Web" -- sert a construire l'arborescence de dossiers
|
|
host: str = ""
|
|
port: int = 22
|
|
username: str = ""
|
|
auth_type: str = AUTH_AUTO # auto | key | password | agent
|
|
key_path: str = ""
|
|
notes: str = ""
|
|
|
|
def to_dict(self) -> dict:
|
|
return asdict(self)
|
|
|
|
@staticmethod
|
|
def from_dict(data: dict) -> "Session":
|
|
known = {f: data.get(f) for f in Session.__dataclass_fields__ if f in data}
|
|
s = Session()
|
|
for k, v in known.items():
|
|
setattr(s, k, v)
|
|
return s
|
|
|
|
|
|
class SessionStore:
|
|
"""Charge/sauvegarde la liste des sessions depuis data/sessions.json."""
|
|
|
|
def __init__(self, path: Path = SESSIONS_FILE):
|
|
self.path = path
|
|
self.sessions: list[Session] = []
|
|
self.load_warning: str | None = None
|
|
self.load()
|
|
|
|
def load(self) -> None:
|
|
was_missing = not self.path.exists()
|
|
document, warning = load_json_document(
|
|
self.path,
|
|
default={"schema_version": SCHEMA_VERSION, "sessions": []},
|
|
current_version=SCHEMA_VERSION,
|
|
)
|
|
self.load_warning = warning
|
|
self.sessions = [Session.from_dict(s) for s in document.get("sessions", [])]
|
|
if was_missing:
|
|
self.save()
|
|
|
|
def save(self) -> None:
|
|
payload = {"schema_version": SCHEMA_VERSION, "sessions": [s.to_dict() for s in self.sessions]}
|
|
save_json_document(self.path, payload)
|
|
|
|
def add(self, session: Session) -> None:
|
|
self.sessions.append(session)
|
|
self.save()
|
|
|
|
def update(self, session: Session) -> None:
|
|
for i, s in enumerate(self.sessions):
|
|
if s.id == session.id:
|
|
self.sessions[i] = session
|
|
break
|
|
self.save()
|
|
|
|
def delete(self, session_id: str) -> None:
|
|
self.sessions = [s for s in self.sessions if s.id != session_id]
|
|
self.save()
|
|
|
|
def groups(self) -> list[str]:
|
|
return sorted({s.group for s in self.sessions if s.group})
|