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 # `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.log45 script += ("mkdir -p ~/Library/LaunchAgents; pm2 ls >/dev/null 2>&1; if ! ls ~/Library/LaunchAgents 2>/dev/null | grep -qi pm2; then "46 "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"47 "echo %s | sudo -S -p '' chown -R %s ~/.pm2 2>/dev/null\n"48 "launchctl list 2>/dev/null | grep -qi pm2 || launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/pm2.*.plist >/dev/null 2>&1; "49 "launchctl list 2>/dev/null | grep -qi pm2 && echo ' pm2 launchd: chargé' || echo ' pm2 launchd: NON chargé'\n"50 # nœud sans session graphique (loué, M2U64…) : le domaine gui n'existe pas au boot → LaunchDaemon système avec UserName51 "if ! launchctl print gui/$(id -u) >/dev/null 2>&1; then P=$(ls ~/Library/LaunchAgents/pm2.*.plist 2>/dev/null | head -1); "52 "if [ -n \"$P\" ]; then L=$(/usr/libexec/PlistBuddy -c 'Print :Label' \"$P\"); D=/Library/LaunchDaemons/$(basename \"$P\"); "53 "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") % (54 shlex.quote(pw), config.user_of(alias), config.home_of(alias), shlex.quote(pw), config.user_of(alias), shlex.quote(pw), config.user_of(alias))55 else:56 script += "echo ' pm2 startup: mot de passe sudo absent (%s)'\n" % config.sudo_pw_file(alias)57 rc, out, err = ssh.run(ip, script, timeout=1800)58 if ka_helpers:59 out += ka_helpers_install(alias, ip)60 print(out)61 if err.strip():62 print(" stderr:", err.strip()[-300:])63 info = nodes.probe(alias, ip)64 still = [r for r in want if not info.get("runtimes", {}).get(r)]65 print(" résultat : %s" % ("tout est là" if not still else "manquent encore " + ", ".join(still)))66 return not still676869def bootstrap(alias):70 """Installe Xcode CLT + Homebrew sans GUI. Active un sudo NOPASSWD temporaire (retiré à la fin). Long (plusieurs Go)."""71 ip = nodes.ip_of(alias)72 if not ip:73 raise SystemExit("nœud %s injoignable" % alias)74 pw = _sudo_pw(alias)75 if not pw:76 raise SystemExit("mot de passe sudo requis dans %s" % config.sudo_pw_file(alias))77 script = r'''78export LC_ALL=C79echo %s | sudo -S -p '' sh -c 'echo "%s ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/mld-bootstrap && chmod 440 /etc/sudoers.d/mld-bootstrap'80trap 'sudo rm -f /etc/sudoers.d/mld-bootstrap' EXIT81if ! xcode-select -p >/dev/null 2>&1; then82 echo ' installation Command Line Tools...'83 touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress84 PROD=$(softwareupdate -l 2>&1 | grep -oE 'Label: Command Line Tools for Xcode[^,]*' | sed 's/^Label: //' | sort -V | tail -1)85 echo " produit: ${PROD:-introuvable}"86 if [ -n "$PROD" ]; then sudo softwareupdate -i "$PROD" --verbose 2>&1 | tail -3; fi87 rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress88 sudo xcode-select --switch /Library/Developer/CommandLineTools 2>/dev/null || true89fi90if [ ! -x /opt/homebrew/bin/brew ]; then91 echo ' installation Homebrew...'92 NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1 | tail -493 grep -q 'opt/homebrew/bin/brew shellenv' ~/.zprofile 2>/dev/null || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile94fi95echo " CLT: $(xcode-select -p 2>/dev/null || echo absent) brew: $(/opt/homebrew/bin/brew --version 2>/dev/null | head -1 || echo absent)"96''' % (shlex.quote(pw), config.user_of(alias))97 rc, out, err = ssh.run(ip, script, timeout=5400)98 print(out)99 if err.strip():100 print(" stderr:", err.strip()[-400:])101 return rc == 0102103104def gateway_mdns():105 import subprocess106 name = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True, text=True).stdout.strip()107 return (name + ".local") if name else nodes.load_lan()["ips"].get(config.GATEWAY, "")108109110def ka_helpers_install(alias, ip):111 """Pousseur Ka (launchd zsh → git push vers spbgit) + alias SSH `gitsrv` → passerelle + clé autorisée sur la passerelle."""112 assets = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets")113 out = [" ka-helpers sur %s :" % alias]114 home = config.home_of(alias)115 ssh.write_remote_file(ip, "%s/ka-pousseur.sh" % home, open(os.path.join(assets, "ka-pousseur.sh")).read(), mode="755")116 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")117 mdns = gateway_mdns()118 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)119 script = r"""120mkdir -p ~/.ssh ~/ka-guardian-spool; touch ~/.ka-pousseur-repos; chmod 700 ~/.ssh121[ -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_ed25519122# alias gitsrv en TÊTE du config (avant Host *) — remplace un bloc existant123python3 - <<'PYEOF'124import os,re125p=os.path.expanduser('~/.ssh/config'); s=open(p).read() if os.path.exists(p) else ''126s=re.sub(r'(?ms)^Host gitsrv\n(?:[ \t]+.*\n?)*\n?', '', s)127open(p,'w').write(%r + s); os.chmod(p, 0o600); print(' gitsrv -> %s')128PYEOF129cat ~/.ssh/ka_guardian_ed25519.pub130launchctl 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é'131""" % (block, mdns)132 rc, o, e = ssh.run(ip, script, timeout=120)133 pub = [l for l in o.splitlines() if l.startswith("ssh-ed25519")]134 out += [" " + l for l in o.splitlines() if not l.startswith("ssh-ed25519")]135 if pub:136 ak = os.path.expanduser("~/.ssh/authorized_keys")137 cur = open(ak).read() if os.path.exists(ak) else ""138 if pub[0].split()[1] not in cur:139 with open(ak, "a") as f:140 f.write(pub[0].strip() + "\n")141 out.append(" clé %s autorisée sur la passerelle" % (pub[0].split()[-1] if len(pub[0].split()) > 2 else alias))142 else:143 out.append(" clé déjà autorisée sur la passerelle")144 rc, o, e = ssh.run(ip, "ssh -o BatchMode=yes -o ConnectTimeout=6 gitsrv 'echo ok' 2>&1 | tail -1", timeout=30)145 out.append(" test ssh gitsrv : %s" % (o.strip() or e.strip()[-80:]))146 return "\n".join(out) + "\n"147