package fleet import ( "bufio" "bytes" "context" _ "embed" "errors" "fmt" "os" "os/exec" "path/filepath" "strconv" "strings" ) //go:embed remote.sh var remoteScript string // Runner exécute le script distant pour une cible et transmet chaque ligne de // sortie à onLine. Une erreur signale un échec de connexion ou d'exécution ; // les erreurs « métier » (docker absent...) passent par des lignes E. type Runner interface { Run(ctx context.Context, host string, port int, user string, args []string, onLine func(string)) error } // SSH joint les serveurs avec le client `ssh` du système : clé dédiée, hôtes // inconnus acceptés à la première connexion puis épinglés (known_hosts). type SSH struct { KeyFile string KnownHosts string Timeout int // secondes pour établir la connexion } // quote protège un argument pour le shell distant. func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } // Command renvoie la commande distante : le script est passé en argument de // `sh -c` pour laisser l'entrée standard libre (docker ne doit pas la lire). func remoteCommand(args []string) string { parts := []string{"sh", "-c", quote(remoteScript), "stackwatch"} for _, a := range args { parts = append(parts, quote(a)) } return strings.Join(parts, " ") } func (s SSH) sshArgs(host string, port int, user string) []string { to := s.Timeout if to <= 0 { to = 10 } return []string{ "-i", s.KeyFile, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "UserKnownHostsFile=" + s.KnownHosts, "-o", "ConnectTimeout=" + strconv.Itoa(to), "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", "-o", "LogLevel=ERROR", "-p", strconv.Itoa(port), "-l", user, } } func (s SSH) Run(ctx context.Context, host string, port int, user string, args []string, onLine func(string)) error { argv := append(s.sshArgs(host, port, user), "--", host, remoteCommand(args)) cmd := exec.CommandContext(ctx, "ssh", argv...) var stderr bytes.Buffer cmd.Stderr = &limitWriter{w: &stderr, max: 4096} out, err := cmd.StdoutPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } sc := bufio.NewScanner(out) sc.Buffer(make([]byte, 64<<10), 4<<20) lines := 0 for sc.Scan() { lines++ onLine(sc.Text()) } werr := cmd.Wait() if ctx.Err() != nil { return fmt.Errorf("interrompu : %w", ctx.Err()) } if werr != nil && lines == 0 { msg := strings.TrimSpace(stderr.String()) if msg == "" { msg = werr.Error() } return errors.New(msg) } return nil } type limitWriter struct { w *bytes.Buffer max int } func (l *limitWriter) Write(p []byte) (int, error) { if room := l.max - l.w.Len(); room > 0 { if len(p) > room { l.w.Write(p[:room]) } else { l.w.Write(p) } } return len(p), nil } // EnsureKey crée la clé SSH de stackwatch (ed25519, sans phrase de passe) si // elle n'existe pas, et renvoie le chemin de la clé privée et la clé publique. func EnsureKey(dir, override string) (keyFile, pub string, err error) { keyFile = override if keyFile == "" { if err = os.MkdirAll(dir, 0o700); err != nil { return } keyFile = filepath.Join(dir, "id_ed25519") if _, serr := os.Stat(keyFile); errors.Is(serr, os.ErrNotExist) { out, kerr := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "stackwatch", "-f", keyFile).CombinedOutput() if kerr != nil { return "", "", fmt.Errorf("ssh-keygen : %v : %s", kerr, strings.TrimSpace(string(out))) } } } out, kerr := exec.Command("ssh-keygen", "-y", "-f", keyFile).Output() if kerr != nil { return "", "", fmt.Errorf("clé publique illisible (%s) : %v", keyFile, kerr) } return keyFile, strings.TrimSpace(string(out)) + "\n", nil }