SPB Git
9.5 KB · 149 lines python
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 %s || ! 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),55            # nœuds loués (REMOTE_NODES) : LaunchDaemon systématique, la session graphique n'est pas garantie au boot56            "true" if alias in config.REMOTE_NODES else "false", shlex.quote(pw), config.user_of(alias))57    else:58        script += "echo '  pm2 startup: mot de passe sudo absent (%s)'\n" % config.sudo_pw_file(alias)59    rc, out, err = ssh.run(ip, script, timeout=1800)60    if ka_helpers:61        out += ka_helpers_install(alias, ip)62    print(out)63    if err.strip():64        print("  stderr:", err.strip()[-300:])65    info = nodes.probe(alias, ip)66    still = [r for r in want if not info.get("runtimes", {}).get(r)]67    print("  résultat : %s" % ("tout est là" if not still else "manquent encore " + ", ".join(still)))68    return not still697071def bootstrap(alias):72    """Installe Xcode CLT + Homebrew sans GUI. Active un sudo NOPASSWD temporaire (retiré à la fin). Long (plusieurs Go)."""73    ip = nodes.ip_of(alias)74    if not ip:75        raise SystemExit("nœud %s injoignable" % alias)76    pw = _sudo_pw(alias)77    if not pw:78        raise SystemExit("mot de passe sudo requis dans %s" % config.sudo_pw_file(alias))79    script = r'''80export LC_ALL=C81echo %s | sudo -S -p '' sh -c 'echo "%s ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/mld-bootstrap && chmod 440 /etc/sudoers.d/mld-bootstrap'82trap 'sudo rm -f /etc/sudoers.d/mld-bootstrap' EXIT83if ! xcode-select -p >/dev/null 2>&1; then84  echo '  installation Command Line Tools...'85  touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress86  PROD=$(softwareupdate -l 2>&1 | grep -oE 'Label: Command Line Tools for Xcode[^,]*' | sed 's/^Label: //' | sort -V | tail -1)87  echo "  produit: ${PROD:-introuvable}"88  if [ -n "$PROD" ]; then sudo softwareupdate -i "$PROD" --verbose 2>&1 | tail -3; fi89  rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress90  sudo xcode-select --switch /Library/Developer/CommandLineTools 2>/dev/null || true91fi92if [ ! -x /opt/homebrew/bin/brew ]; then93  echo '  installation Homebrew...'94  NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1 | tail -495  grep -q 'opt/homebrew/bin/brew shellenv' ~/.zprofile 2>/dev/null || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile96fi97echo "  CLT: $(xcode-select -p 2>/dev/null || echo absent)  brew: $(/opt/homebrew/bin/brew --version 2>/dev/null | head -1 || echo absent)"98''' % (shlex.quote(pw), config.user_of(alias))99    rc, out, err = ssh.run(ip, script, timeout=5400)100    print(out)101    if err.strip():102        print("  stderr:", err.strip()[-400:])103    return rc == 0104105106def gateway_mdns():107    import subprocess108    name = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True, text=True).stdout.strip()109    return (name + ".local") if name else nodes.load_lan()["ips"].get(config.GATEWAY, "")110111112def ka_helpers_install(alias, ip):113    """Pousseur Ka (launchd zsh → git push vers spbgit) + alias SSH `gitsrv` → passerelle + clé autorisée sur la passerelle."""114    assets = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets")115    out = ["  ka-helpers sur %s :" % alias]116    home = config.home_of(alias)117    ssh.write_remote_file(ip, "%s/ka-pousseur.sh" % home, open(os.path.join(assets, "ka-pousseur.sh")).read(), mode="755")118    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")119    mdns = gateway_mdns()120    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)121    script = r"""122mkdir -p ~/.ssh ~/ka-guardian-spool; touch ~/.ka-pousseur-repos; chmod 700 ~/.ssh123[ -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_ed25519124# alias gitsrv en TÊTE du config (avant Host *) — remplace un bloc existant125python3 - <<'PYEOF'126import os,re127p=os.path.expanduser('~/.ssh/config'); s=open(p).read() if os.path.exists(p) else ''128s=re.sub(r'(?ms)^Host gitsrv\n(?:[ \t]+.*\n?)*\n?', '', s)129open(p,'w').write(%r + s); os.chmod(p, 0o600); print('  gitsrv -> %s')130PYEOF131cat ~/.ssh/ka_guardian_ed25519.pub132launchctl 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é'133""" % (block, mdns)134    rc, o, e = ssh.run(ip, script, timeout=120)135    pub = [l for l in o.splitlines() if l.startswith("ssh-ed25519")]136    out += ["  " + l for l in o.splitlines() if not l.startswith("ssh-ed25519")]137    if pub:138        ak = os.path.expanduser("~/.ssh/authorized_keys")139        cur = open(ak).read() if os.path.exists(ak) else ""140        if pub[0].split()[1] not in cur:141            with open(ak, "a") as f:142                f.write(pub[0].strip() + "\n")143            out.append("  clé %s autorisée sur la passerelle" % (pub[0].split()[-1] if len(pub[0].split()) > 2 else alias))144        else:145            out.append("  clé déjà autorisée sur la passerelle")146    rc, o, e = ssh.run(ip, "ssh -o BatchMode=yes -o ConnectTimeout=6 gitsrv 'echo ok' 2>&1 | tail -1", timeout=30)147    out.append("  test ssh gitsrv : %s" % (o.strip() or e.strip()[-80:]))148    return "\n".join(out) + "\n"149
Files · 45787cb0f5540e86ea4e53a6714968c3ca1137c2
Menu

Theme