spb/maclustr-dispatch
Public
1"""`mld prepare <nœud>` : installe les runtimes manquants (Homebrew), copie la config ngrok, active pm2 au démarrage, pose le marqueur."""2import os3import shlex4from . import config, nodes, ssh567def _sudo_pw(alias=None):8 pwf = config.sudo_pw_file(alias)9 if os.path.exists(pwf):10 return open(pwf).read().strip()11 return None121314def prepare(alias, runtimes=None, ka_helpers=False):15 ip = nodes.ip_of(alias)16 if not ip:17 raise SystemExit("nœud %s injoignable" % alias)18 info = nodes.probe(alias, ip)19 have = info.get("runtimes", {})20 want = runtimes or ["node", "pnpm", "pm2", "ngrok", "python@3.14", "python@3.13", "uv", "git"]21 print("prepare %s (%s) — présents : %s" % (alias, ip, ", ".join(k for k, v in have.items() if v)))22 if not have.get("brew"):23 print(" ✗ Homebrew absent : bootstrap requis (Xcode CLT). Lancer d'abord : mld bootstrap %s" % alias)24 return False25 missing = [r for r in want if not have.get(r)]26 script = ""27 for r in missing:28 if r in config.BREW_FORMULAE:29 fallback = " || npm install -g pm2 >/dev/null 2>&1" if r == "pm2" else ""30 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)31 elif r in config.BREW_CASKS:32 script += "echo ' brew install --cask ngrok'; brew install -q --cask ngrok >/dev/null 2>&1 || brew install -q ngrok/ngrok/ngrok >/dev/null 2>&1 || echo ' ! échec ngrok'\n"33 # config ngrok (authtoken) depuis la passerelle34 if "ngrok" in missing or not have.get("ngrok"):35 if os.path.exists(config.NGROK_CFG):36 rc0, _, _ = ssh.write_remote_file(ip, "%s/Library/Application Support/ngrok/ngrok.yml" % config.home_of(alias), open(config.NGROK_CFG).read(), mode="600")37 script += "echo ' ngrok.yml %s'\n" % ("copié" if rc0 == 0 else "ÉCHEC de copie")38 # marqueur39 script += "[ -f ~/.maclustr-node ] || echo %s > ~/.maclustr-node\n" % alias40 # pm2 startup (launchd) — nécessite sudo41 pw = _sudo_pw(alias)42 # pm2 startup doit tourner sous sudo (écrit le plist + launchctl load) ; l'ancien `${cmd#sudo }` le lançait sans sudo → « à faire manuellement »43 if pw:44 script += ("mkdir -p ~/Library/LaunchAgents; if ! ls ~/Library/LaunchAgents 2>/dev/null | grep -qi pm2; then "45 "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"46 "launchctl list 2>/dev/null | grep -qi pm2 || launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/pm2.*.plist >/dev/null 2>&1; "47 "launchctl list 2>/dev/null | grep -qi pm2 && echo ' pm2 launchd: chargé' || echo ' pm2 launchd: NON chargé'\n"48 # nœud sans session graphique (loué, M2U64…) : le domaine gui n'existe pas au boot → LaunchDaemon système avec UserName49 "if ! launchctl print gui/$(id -u) >/dev/null 2>&1; then P=$(ls ~/Library/LaunchAgents/pm2.*.plist 2>/dev/null | head -1); "50 "if [ -n \"$P\" ]; then L=$(/usr/libexec/PlistBuddy -c 'Print :Label' \"$P\"); D=/Library/LaunchDaemons/$(basename \"$P\"); "51 "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") % (52 shlex.quote(pw), config.user_of(alias), config.home_of(alias), shlex.quote(pw), config.user_of(alias))53 else:54 script += "echo ' pm2 startup: mot de passe sudo absent (%s)'\n" % config.sudo_pw_file(alias)55 rc, out, err = ssh.run(ip, script, timeout=1800)56 if ka_helpers:57 out += ka_helpers_install(alias, ip)58 print(out)59 if err.strip():60 print(" stderr:", err.strip()[-300:])61 info = nodes.probe(alias, ip)62 still = [r for r in want if not info.get("runtimes", {}).get(r)]63 print(" résultat : %s" % ("tout est là" if not still else "manquent encore " + ", ".join(still)))64 return not still656667def bootstrap(alias):68 """Installe Xcode CLT + Homebrew sans GUI. Active un sudo NOPASSWD temporaire (retiré à la fin). Long (plusieurs Go)."""69 ip = nodes.ip_of(alias)70 if not ip:71 raise SystemExit("nœud %s injoignable" % alias)72 pw = _sudo_pw(alias)73 if not pw:74 raise SystemExit("mot de passe sudo requis dans %s" % config.sudo_pw_file(alias))75 script = r'''76export LC_ALL=C77echo %s | sudo -S -p '' sh -c 'echo "%s ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/mld-bootstrap && chmod 440 /etc/sudoers.d/mld-bootstrap'78trap 'sudo rm -f /etc/sudoers.d/mld-bootstrap' EXIT79if ! xcode-select -p >/dev/null 2>&1; then80 echo ' installation Command Line Tools...'81 touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress82 PROD=$(softwareupdate -l 2>&1 | grep -oE 'Label: Command Line Tools for Xcode[^,]*' | sed 's/^Label: //' | sort -V | tail -1)83 echo " produit: ${PROD:-introuvable}"84 if [ -n "$PROD" ]; then sudo softwareupdate -i "$PROD" --verbose 2>&1 | tail -3; fi85 rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress86 sudo xcode-select --switch /Library/Developer/CommandLineTools 2>/dev/null || true87fi88if [ ! -x /opt/homebrew/bin/brew ]; then89 echo ' installation Homebrew...'90 NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1 | tail -491 grep -q 'opt/homebrew/bin/brew shellenv' ~/.zprofile 2>/dev/null || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile92fi93echo " CLT: $(xcode-select -p 2>/dev/null || echo absent) brew: $(/opt/homebrew/bin/brew --version 2>/dev/null | head -1 || echo absent)"94''' % (shlex.quote(pw), config.user_of(alias))95 rc, out, err = ssh.run(ip, script, timeout=5400)96 print(out)97 if err.strip():98 print(" stderr:", err.strip()[-400:])99 return rc == 0100101102def gateway_mdns():103 import subprocess104 name = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True, text=True).stdout.strip()105 return (name + ".local") if name else nodes.load_lan()["ips"].get(config.GATEWAY, "")106107108def ka_helpers_install(alias, ip):109 """Pousseur Ka (launchd zsh → git push vers spbgit) + alias SSH `gitsrv` → passerelle + clé autorisée sur la passerelle."""110 assets = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets")111 out = [" ka-helpers sur %s :" % alias]112 home = config.home_of(alias)113 ssh.write_remote_file(ip, "%s/ka-pousseur.sh" % home, open(os.path.join(assets, "ka-pousseur.sh")).read(), mode="755")114 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")115 mdns = gateway_mdns()116 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)117 script = r"""118mkdir -p ~/.ssh ~/ka-guardian-spool; touch ~/.ka-pousseur-repos; chmod 700 ~/.ssh119[ -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_ed25519120# alias gitsrv en TÊTE du config (avant Host *) — remplace un bloc existant121python3 - <<'PYEOF'122import os,re123p=os.path.expanduser('~/.ssh/config'); s=open(p).read() if os.path.exists(p) else ''124s=re.sub(r'(?ms)^Host gitsrv\n(?:[ \t]+.*\n?)*\n?', '', s)125open(p,'w').write(%r + s); os.chmod(p, 0o600); print(' gitsrv -> %s')126PYEOF127cat ~/.ssh/ka_guardian_ed25519.pub128launchctl 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é'129""" % (block, mdns)130 rc, o, e = ssh.run(ip, script, timeout=120)131 pub = [l for l in o.splitlines() if l.startswith("ssh-ed25519")]132 out += [" " + l for l in o.splitlines() if not l.startswith("ssh-ed25519")]133 if pub:134 ak = os.path.expanduser("~/.ssh/authorized_keys")135 cur = open(ak).read() if os.path.exists(ak) else ""136 if pub[0].split()[1] not in cur:137 with open(ak, "a") as f:138 f.write(pub[0].strip() + "\n")139 out.append(" clé %s autorisée sur la passerelle" % (pub[0].split()[-1] if len(pub[0].split()) > 2 else alias))140 else:141 out.append(" clé déjà autorisée sur la passerelle")142 rc, o, e = ssh.run(ip, "ssh -o BatchMode=yes -o ConnectTimeout=6 gitsrv 'echo ok' 2>&1 | tail -1", timeout=30)143 out.append(" test ssh gitsrv : %s" % (o.strip() or e.strip()[-80:]))144 return "\n".join(out) + "\n"145