// Package fleet suit les mises à jour des stacks docker compose de plusieurs // serveurs, joints en SSH : liste de serveurs, analyses (pull + comparaison des // images), mise à jour d'une stack. package fleet import ( "errors" "fmt" "path" "regexp" "strings" "time" ) // Statuts d'une stack. const ( StatusUpToDate = "uptodate" // toutes les images sont à jour StatusUpdates = "updates" // au moins une image a une nouvelle version StatusStopped = "stopped" // aucun conteneur en cours StatusError = "error" // fichier invalide, pull en échec... ) // Server est un serveur joint en SSH. Chaque Target est une connexion SSH sous // un utilisateur donné, avec les racines à parcourir : /home pour un compte qui // lit tout, ou /home/alice pour des stacks qui n'ont que les droits d'alice. type Server struct { ID string `json:"id"` Name string `json:"name"` Host string `json:"host"` Port int `json:"port"` Note string `json:"note,omitempty"` Enabled bool `json:"enabled"` Targets []Target `json:"targets"` } // Target : utilisateur SSH et racines (profondeur : niveaux de sous-répertoires // explorés sous chaque racine, 1 = /home/). type Target struct { ID string `json:"id"` User string `json:"user"` Roots []string `json:"roots"` Depth int `json:"depth"` } // Service : un conteneur d'une stack. type Service struct { Name string `json:"name"` Image string `json:"image"` Running string `json:"running"` // identifiant (12 caractères) de l'image en cours Latest string `json:"latest"` // identifiant de l'image tirée State string `json:"state"` // ok, update ou unknown } // Stack : une stack trouvée sous une racine. type Stack struct { Dir string `json:"dir"` Name string `json:"name"` File string `json:"file"` Status string `json:"status"` Error string `json:"error,omitempty"` Services []Service `json:"services,omitempty"` // Applied : dernière mise à jour lancée depuis stackwatch. Applied *Applied `json:"applied,omitempty"` } // Applied : résultat d'une mise à jour déclenchée depuis l'interface. type Applied struct { At time.Time `json:"at"` By string `json:"by"` OK bool `json:"ok"` Message string `json:"message"` } // Scan : dernier résultat (ou analyse en cours) d'une cible. type Scan struct { Running bool `json:"running"` Task string `json:"task,omitempty"` // scan ou apply, pendant Running Current string `json:"current,omitempty"` // stack en cours de traitement Started time.Time `json:"started,omitzero"` Finished time.Time `json:"finished,omitzero"` Error string `json:"error,omitempty"` // Warnings : racines illisibles ou introuvables. Warnings []string `json:"warnings,omitempty"` Stacks []Stack `json:"stacks"` Docker string `json:"docker,omitempty"` Compose string `json:"compose,omitempty"` } // Summary compte les stacks de toutes les cibles. type Summary struct { Servers int `json:"servers"` Stacks int `json:"stacks"` Updates int `json:"updates"` Errors int `json:"errors"` Stopped int `json:"stopped"` Unreachable int `json:"unreachable"` Scanning int `json:"scanning"` } var ( ErrNotFound = errors.New("introuvable") ErrInvalid = errors.New("valeur invalide") ErrBusy = errors.New("analyse ou mise à jour déjà en cours") hostRe = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._:-]*[A-Za-z0-9])?$`) userRe = regexp.MustCompile(`^[a-z_][a-z0-9_.-]{0,31}$`) // Chemins absolus simples : pas de guillemets, d'espaces ni de caractères de shell. pathRe = regexp.MustCompile(`^/[A-Za-z0-9._@+/-]*$`) ) // Validate normalise et contrôle un serveur ; les cibles sans identifiant en reçoivent un. func (s *Server) Validate() error { s.Name = strings.TrimSpace(s.Name) s.Host = strings.TrimSpace(s.Host) s.Note = strings.TrimSpace(s.Note) if s.Name == "" || len(s.Name) > 80 { return fmt.Errorf("%w : nom (1 à 80 caractères)", ErrInvalid) } if len(s.Host) > 253 || !hostRe.MatchString(s.Host) { return fmt.Errorf("%w : hôte (nom DNS ou adresse IP)", ErrInvalid) } if s.Port == 0 { s.Port = 22 } if s.Port < 1 || s.Port > 65535 { return fmt.Errorf("%w : port", ErrInvalid) } if len(s.Note) > 300 { return fmt.Errorf("%w : note trop longue", ErrInvalid) } if len(s.Targets) == 0 { return fmt.Errorf("%w : au moins une connexion (utilisateur et racines)", ErrInvalid) } if len(s.Targets) > 20 { return fmt.Errorf("%w : 20 connexions au maximum", ErrInvalid) } seen := map[string]bool{} for i := range s.Targets { t := &s.Targets[i] if err := t.validate(); err != nil { return err } if t.ID == "" { t.ID = newID() } if seen[t.ID] { return fmt.Errorf("%w : connexion en double", ErrInvalid) } seen[t.ID] = true } return nil } func (t *Target) validate() error { t.User = strings.TrimSpace(t.User) if !userRe.MatchString(t.User) { return fmt.Errorf("%w : utilisateur SSH %q", ErrInvalid, t.User) } if t.Depth == 0 { t.Depth = 1 } if t.Depth < 0 || t.Depth > 4 { return fmt.Errorf("%w : profondeur (1 à 4)", ErrInvalid) } if len(t.Roots) > 20 { return fmt.Errorf("%w : 20 racines au maximum par connexion", ErrInvalid) } roots := make([]string, 0, len(t.Roots)) for _, r := range t.Roots { r = strings.TrimSpace(r) if r == "" { continue } if !pathRe.MatchString(r) || strings.Contains(r, "..") { return fmt.Errorf("%w : racine %q (chemin absolu, sans espace ni caractère spécial)", ErrInvalid, r) } if r != "/" { r = path.Clean(r) } roots = append(roots, r) } if len(roots) == 0 { roots = []string{"/home"} } t.Roots = roots return nil } // Key identifie une cible dans les résultats. func Key(serverID, targetID string) string { return serverID + "/" + targetID } // Counts renvoie le nombre de services en retard sur le total. func (st Stack) Counts() (outdated, total int) { for _, s := range st.Services { total++ if s.State == "update" { outdated++ } } return }