"""`mld prepare ` : installe les runtimes manquants (Homebrew), active pm2 au démarrage, pose le marqueur, raccorde le nœud au MacLustr Tunnel (wg1 → BHS64) et applique `mld harden` (résilience coupure/MAJ).""" import os import shlex from . import config, nodes, ssh def _sudo_pw(alias=None): pwf = config.sudo_pw_file(alias) if os.path.exists(pwf): return open(pwf).read().strip() return None def prepare(alias, runtimes=None, ka_helpers=False, tunnel_peer=True, harden=True): ip = nodes.ip_of(alias) if not ip: raise SystemExit("nœud %s injoignable" % alias) info = nodes.probe(alias, ip) have = info.get("runtimes", {}) want = runtimes or ["node", "pnpm", "pm2", "python@3.14", "python@3.13", "uv", "git"] print("prepare %s (%s) — présents : %s" % (alias, ip, ", ".join(k for k, v in have.items() if v))) if not have.get("brew"): print(" ✗ Homebrew absent : bootstrap requis (Xcode CLT). Lancer d'abord : mld bootstrap %s" % alias) return False missing = [r for r in want if not have.get(r)] script = "" for r in missing: if r in config.BREW_FORMULAE: fallback = " || npm install -g pm2 >/dev/null 2>&1" if r == "pm2" else "" script += "echo ' brew install %s'; brew install -q %s >/dev/null 2>&1%s || echo ' ! échec %s'\n" % (r, config.BREW_FORMULAE[r], fallback, r) elif r in config.BREW_CASKS: script += "echo ' brew install --cask %s'; brew install -q --cask %s >/dev/null 2>&1 || echo ' ! échec %s'\n" % (r, config.BREW_CASKS[r], r) # marqueur script += "[ -f ~/.maclustr-node ] || echo %s > ~/.maclustr-node\n" % alias # pm2 startup (launchd) — nécessite sudo pw = _sudo_pw(alias) # pm2 startup doit tourner sous sudo (écrit le plist + launchctl load) ; l'ancien `${cmd#sudo }` le lançait sans sudo → « à faire manuellement » if pw: # `pm2 ls` d'abord (crée ~/.pm2 sous l'utilisateur), puis chown après le startup sous sudo : sinon root laisse des fichiers dans ~/.pm2 → EACCES pm2.log script += ("mkdir -p ~/Library/LaunchAgents; pm2 ls >/dev/null 2>&1; if ! ls ~/Library/LaunchAgents 2>/dev/null | grep -qi pm2; then " "if echo %s | sudo -S -p '' env PATH=\"$PATH\" pm2 startup launchd -u %s --hp %s >/dev/null 2>&1; then echo ' pm2 startup: ok'; else echo ' pm2 startup: ÉCHEC'; fi; fi\n" "echo %s | sudo -S -p '' chown -R %s ~/.pm2 2>/dev/null\n" "launchctl list 2>/dev/null | grep -qi pm2 || launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/pm2.*.plist >/dev/null 2>&1; " "launchctl list 2>/dev/null | grep -qi pm2 && echo ' pm2 launchd: chargé' || echo ' pm2 launchd: NON chargé'\n" # nœud sans session graphique (loué, M2U64…) : le domaine gui n'existe pas au boot → LaunchDaemon système avec UserName "if %s || ! launchctl print gui/$(id -u) >/dev/null 2>&1; then P=$(ls ~/Library/LaunchAgents/pm2.*.plist 2>/dev/null | head -1); " "if [ -n \"$P\" ]; then L=$(/usr/libexec/PlistBuddy -c 'Print :Label' \"$P\"); D=/Library/LaunchDaemons/$(basename \"$P\"); " "echo %s | sudo -S -p '' sh -c \"cp '$P' '$D' && /usr/libexec/PlistBuddy -c 'Delete :UserName' '$D' 2>/dev/null; /usr/libexec/PlistBuddy -c 'Add :UserName string %s' '$D' && chown root:wheel '$D' && chmod 644 '$D' && launchctl bootout system/$L 2>/dev/null; launchctl bootstrap system '$D' 2>/dev/null; launchctl print system/$L >/dev/null 2>&1 && echo ' pm2 LaunchDaemon (pas de session graphique) : chargé' || echo ' pm2 LaunchDaemon : NON chargé'\"; fi; fi\n") % ( shlex.quote(pw), config.user_of(alias), config.home_of(alias), shlex.quote(pw), config.user_of(alias), # nœuds loués (REMOTE_NODES) : LaunchDaemon systématique, la session graphique n'est pas garantie au boot "true" if alias in config.REMOTE_NODES else "false", shlex.quote(pw), config.user_of(alias)) else: script += "echo ' pm2 startup: mot de passe sudo absent (%s)'\n" % config.sudo_pw_file(alias) rc, out, err = ssh.run(ip, script, timeout=1800) if ka_helpers: out += ka_helpers_install(alias, ip) print(out) if err.strip(): print(" stderr:", err.strip()[-300:]) # MacLustr Tunnel : raccorde le nœud au hub BHS64 (wg1) s'il ne l'est pas — nécessaire pour exposer un site if tunnel_peer: from . import tunnel try: tunnel.ensure_peer(alias, log=print) except tunnel.TunnelError as e: print(" tunnel : %s" % e) # résilience (auto-login, pas de veille, redémarrage après coupure, MAJ macOS/Tailscale off) if harden: from . import harden as _harden _harden.harden(alias) info = nodes.probe(alias, ip) still = [r for r in want if not info.get("runtimes", {}).get(r)] print(" résultat : %s" % ("tout est là" if not still else "manquent encore " + ", ".join(still))) return not still def bootstrap(alias): """Installe Xcode CLT + Homebrew sans GUI. Active un sudo NOPASSWD temporaire (retiré à la fin). Long (plusieurs Go).""" ip = nodes.ip_of(alias) if not ip: raise SystemExit("nœud %s injoignable" % alias) pw = _sudo_pw(alias) if not pw: raise SystemExit("mot de passe sudo requis dans %s" % config.sudo_pw_file(alias)) script = r''' export LC_ALL=C echo %s | sudo -S -p '' sh -c 'echo "%s ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/mld-bootstrap && chmod 440 /etc/sudoers.d/mld-bootstrap' trap 'sudo rm -f /etc/sudoers.d/mld-bootstrap' EXIT if ! xcode-select -p >/dev/null 2>&1; then echo ' installation Command Line Tools...' touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress PROD=$(softwareupdate -l 2>&1 | grep -oE 'Label: Command Line Tools for Xcode[^,]*' | sed 's/^Label: //' | sort -V | tail -1) echo " produit: ${PROD:-introuvable}" if [ -n "$PROD" ]; then sudo softwareupdate -i "$PROD" --verbose 2>&1 | tail -3; fi rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress sudo xcode-select --switch /Library/Developer/CommandLineTools 2>/dev/null || true fi if [ ! -x /opt/homebrew/bin/brew ]; then echo ' installation Homebrew...' NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1 | tail -4 grep -q 'opt/homebrew/bin/brew shellenv' ~/.zprofile 2>/dev/null || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile fi echo " CLT: $(xcode-select -p 2>/dev/null || echo absent) brew: $(/opt/homebrew/bin/brew --version 2>/dev/null | head -1 || echo absent)" ''' % (shlex.quote(pw), config.user_of(alias)) rc, out, err = ssh.run(ip, script, timeout=5400) print(out) if err.strip(): print(" stderr:", err.strip()[-400:]) return rc == 0 def gateway_mdns(): import subprocess name = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True, text=True).stdout.strip() return (name + ".local") if name else nodes.load_lan()["ips"].get(config.GATEWAY, "") def ka_helpers_install(alias, ip): """Pousseur Ka (launchd zsh → git push vers spbgit) + alias SSH `gitsrv` → passerelle + clé autorisée sur la passerelle.""" assets = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets") out = [" ka-helpers sur %s :" % alias] home = config.home_of(alias) ssh.write_remote_file(ip, "%s/ka-pousseur.sh" % home, open(os.path.join(assets, "ka-pousseur.sh")).read(), mode="755") ssh.write_remote_file(ip, "%s/Library/LaunchAgents/com.ka.pousseur.plist" % home, open(os.path.join(assets, "com.ka.pousseur.plist")).read(), mode="644") mdns = gateway_mdns() block = "Host gitsrv\n HostName %s\n User %s\n IdentityFile ~/.ssh/ka_guardian_ed25519\n IdentitiesOnly yes\n ControlMaster no\n ControlPath none\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n LogLevel ERROR\n\n" % (mdns, config.USER) script = r""" mkdir -p ~/.ssh ~/ka-guardian-spool; touch ~/.ka-pousseur-repos; chmod 700 ~/.ssh [ -f ~/.ssh/ka_guardian_ed25519 ] || ssh-keygen -q -t ed25519 -N '' -C "ka-guardian@$(cat ~/.maclustr-node 2>/dev/null || hostname -s)" -f ~/.ssh/ka_guardian_ed25519 # alias gitsrv en TÊTE du config (avant Host *) — remplace un bloc existant python3 - <<'PYEOF' import os,re p=os.path.expanduser('~/.ssh/config'); s=open(p).read() if os.path.exists(p) else '' s=re.sub(r'(?ms)^Host gitsrv\n(?:[ \t]+.*\n?)*\n?', '', s) open(p,'w').write(%r + s); os.chmod(p, 0o600); print(' gitsrv -> %s') PYEOF cat ~/.ssh/ka_guardian_ed25519.pub launchctl bootout gui/$(id -u)/com.ka.pousseur >/dev/null 2>&1; launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.ka.pousseur.plist && echo ' pousseur launchd chargé' """ % (block, mdns) rc, o, e = ssh.run(ip, script, timeout=120) pub = [l for l in o.splitlines() if l.startswith("ssh-ed25519")] out += [" " + l for l in o.splitlines() if not l.startswith("ssh-ed25519")] if pub: ak = os.path.expanduser("~/.ssh/authorized_keys") cur = open(ak).read() if os.path.exists(ak) else "" if pub[0].split()[1] not in cur: with open(ak, "a") as f: f.write(pub[0].strip() + "\n") out.append(" clé %s autorisée sur la passerelle" % (pub[0].split()[-1] if len(pub[0].split()) > 2 else alias)) else: out.append(" clé déjà autorisée sur la passerelle") rc, o, e = ssh.run(ip, "ssh -o BatchMode=yes -o ConnectTimeout=6 gitsrv 'echo ok' 2>&1 | tail -1", timeout=30) out.append(" test ssh gitsrv : %s" % (o.strip() or e.strip()[-80:])) return "\n".join(out) + "\n"