SPB Git
7.6 KB · 134 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    script += "mkdir -p ~/Library/LaunchAgents; if ! ls ~/Library/LaunchAgents 2>/dev/null | grep -qi pm2; then cmd=$(pm2 startup launchd -u %s --hp %s 2>/dev/null | grep '^sudo' | head -1); if [ -n \"$cmd\" ]; then %s echo \"  pm2 startup: $( ${cmd#sudo } >/dev/null 2>&1 && echo ok || echo 'à faire manuellement')\"; fi; fi\n" % (43        config.user_of(alias), config.home_of(alias), ("echo %s | sudo -S -v 2>/dev/null;" % shlex.quote(pw)) if pw else "")44    rc, out, err = ssh.run(ip, script, timeout=1800)45    if ka_helpers:46        out += ka_helpers_install(alias, ip)47    print(out)48    if err.strip():49        print("  stderr:", err.strip()[-300:])50    info = nodes.probe(alias, ip)51    still = [r for r in want if not info.get("runtimes", {}).get(r)]52    print("  résultat : %s" % ("tout est là" if not still else "manquent encore " + ", ".join(still)))53    return not still545556def bootstrap(alias):57    """Installe Xcode CLT + Homebrew sans GUI. Active un sudo NOPASSWD temporaire (retiré à la fin). Long (plusieurs Go)."""58    ip = nodes.ip_of(alias)59    if not ip:60        raise SystemExit("nœud %s injoignable" % alias)61    pw = _sudo_pw(alias)62    if not pw:63        raise SystemExit("mot de passe sudo requis dans %s" % config.sudo_pw_file(alias))64    script = r'''65export LC_ALL=C66echo %s | sudo -S -p '' sh -c 'echo "%s ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/mld-bootstrap && chmod 440 /etc/sudoers.d/mld-bootstrap'67trap 'sudo rm -f /etc/sudoers.d/mld-bootstrap' EXIT68if ! xcode-select -p >/dev/null 2>&1; then69  echo '  installation Command Line Tools...'70  touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress71  PROD=$(softwareupdate -l 2>&1 | grep -oE 'Label: Command Line Tools for Xcode[^,]*' | sed 's/^Label: //' | sort -V | tail -1)72  echo "  produit: ${PROD:-introuvable}"73  if [ -n "$PROD" ]; then sudo softwareupdate -i "$PROD" --verbose 2>&1 | tail -3; fi74  rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress75  sudo xcode-select --switch /Library/Developer/CommandLineTools 2>/dev/null || true76fi77if [ ! -x /opt/homebrew/bin/brew ]; then78  echo '  installation Homebrew...'79  NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1 | tail -480  grep -q 'opt/homebrew/bin/brew shellenv' ~/.zprofile 2>/dev/null || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile81fi82echo "  CLT: $(xcode-select -p 2>/dev/null || echo absent)  brew: $(/opt/homebrew/bin/brew --version 2>/dev/null | head -1 || echo absent)"83''' % (shlex.quote(pw), config.user_of(alias))84    rc, out, err = ssh.run(ip, script, timeout=5400)85    print(out)86    if err.strip():87        print("  stderr:", err.strip()[-400:])88    return rc == 0899091def gateway_mdns():92    import subprocess93    name = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True, text=True).stdout.strip()94    return (name + ".local") if name else nodes.load_lan()["ips"].get(config.GATEWAY, "")959697def ka_helpers_install(alias, ip):98    """Pousseur Ka (launchd zsh → git push vers spbgit) + alias SSH `gitsrv` → passerelle + clé autorisée sur la passerelle."""99    assets = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets")100    out = ["  ka-helpers sur %s :" % alias]101    home = config.home_of(alias)102    ssh.write_remote_file(ip, "%s/ka-pousseur.sh" % home, open(os.path.join(assets, "ka-pousseur.sh")).read(), mode="755")103    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")104    mdns = gateway_mdns()105    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)106    script = r"""107mkdir -p ~/.ssh ~/ka-guardian-spool; touch ~/.ka-pousseur-repos; chmod 700 ~/.ssh108[ -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_ed25519109# alias gitsrv en TÊTE du config (avant Host *) — remplace un bloc existant110python3 - <<'PYEOF'111import os,re112p=os.path.expanduser('~/.ssh/config'); s=open(p).read() if os.path.exists(p) else ''113s=re.sub(r'(?ms)^Host gitsrv\n(?:[ \t]+.*\n?)*\n?', '', s)114open(p,'w').write(%r + s); os.chmod(p, 0o600); print('  gitsrv -> %s')115PYEOF116cat ~/.ssh/ka_guardian_ed25519.pub117launchctl 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é'118""" % (block, mdns)119    rc, o, e = ssh.run(ip, script, timeout=120)120    pub = [l for l in o.splitlines() if l.startswith("ssh-ed25519")]121    out += ["  " + l for l in o.splitlines() if not l.startswith("ssh-ed25519")]122    if pub:123        ak = os.path.expanduser("~/.ssh/authorized_keys")124        cur = open(ak).read() if os.path.exists(ak) else ""125        if pub[0].split()[1] not in cur:126            with open(ak, "a") as f:127                f.write(pub[0].strip() + "\n")128            out.append("  clé %s autorisée sur la passerelle" % (pub[0].split()[-1] if len(pub[0].split()) > 2 else alias))129        else:130            out.append("  clé déjà autorisée sur la passerelle")131    rc, o, e = ssh.run(ip, "ssh -o BatchMode=yes -o ConnectTimeout=6 gitsrv 'echo ok' 2>&1 | tail -1", timeout=30)132    out.append("  test ssh gitsrv : %s" % (o.strip() or e.strip()[-80:]))133    return "\n".join(out) + "\n"134
Files · b96e6dd1702202861fe5c714c6cb2088c76b5da9
Menu

Theme