package fleet import ( "errors" "fmt" "log/slog" "path/filepath" "strings" "time" ) // Mise a jour automatique globale d'un serveur : une planification crontab // par serveur met a jour, une par une, toutes ses stacks connues de la // derniere analyse, sauf les stacks exclues, arretees, et celles qui ont leur // propre planification (la planification de la stack prime). Persistee dans // hostauto.json. // AutoHostBy : auteur des mises a jour lancees par la planification d'un serveur. const AutoHostBy = AutoBy + " serveur" // Delais (variables pour les tests). var ( hostPoll = 2 * time.Second // attente de la fin d'une mise a jour hostBusyMax = 30 * time.Minute // attente maximale d'une connexion occupee ) // HostStackResult : resultat d'une stack lors d'une execution globale. type HostStackResult struct { Target string `json:"target"` User string `json:"user"` Dir string `json:"dir"` Name string `json:"name"` OK bool `json:"ok"` Skipped bool `json:"skipped,omitempty"` // rien a faire (deja a jour, arretee) Message string `json:"message"` } // HostAuto : planification globale d'un serveur. type HostAuto struct { Schedule string `json:"schedule"` By string `json:"by,omitempty"` Since time.Time `json:"since"` LastRun time.Time `json:"lastRun,omitzero"` LastOK bool `json:"lastOk"` LastMessage string `json:"lastMessage,omitempty"` Results []HostStackResult `json:"results,omitempty"` pending, running bool current string } // HostAutoInfo : planification d'un serveur telle qu'affichee. type HostAutoInfo struct { Schedule string `json:"schedule"` By string `json:"by,omitempty"` Since time.Time `json:"since"` Next time.Time `json:"next,omitzero"` LastRun time.Time `json:"lastRun,omitzero"` LastOK bool `json:"lastOk"` LastMessage string `json:"lastMessage,omitempty"` Results []HostStackResult `json:"results,omitempty"` Pending bool `json:"pending,omitempty"` Running bool `json:"running,omitempty"` Current string `json:"current,omitempty"` } func (h *HostAuto) info(now time.Time) *HostAutoInfo { i := &HostAutoInfo{Schedule: h.Schedule, By: h.By, Since: h.Since, LastRun: h.LastRun, LastOK: h.LastOK, LastMessage: h.LastMessage, Results: append([]HostStackResult(nil), h.Results...), Pending: h.pending, Running: h.running, Current: h.current} if c, err := ParseCron(h.Schedule); err == nil { i.Next = c.Next(now) } return i } // applyOutcome : dernier resultat de runApply pour une stack. type applyOutcome struct { res Applied skipped bool } // noteOutcomeLocked est appele par runApply a la fin de chaque mise a jour. func (m *Manager) noteOutcomeLocked(key string, res Applied, skipped bool) { if m.outcomes == nil { m.outcomes = map[string]applyOutcome{} } m.outcomes[key] = applyOutcome{res, skipped} } func (m *Manager) saveHostAutoLocked() error { return writeJSON(filepath.Join(m.dir, "hostauto.json"), m.hostAuto) } func (m *Manager) loadHostAuto() error { if err := readJSON(filepath.Join(m.dir, "hostauto.json"), &m.hostAuto); err != nil { return err } if m.hostAuto == nil { m.hostAuto = map[string]*HostAuto{} } return nil } // dropHostAutoLocked oublie la planification d'un serveur supprime. func (m *Manager) dropHostAutoLocked(serverID string) { if _, ok := m.hostAuto[serverID]; !ok { return } delete(m.hostAuto, serverID) if err := m.saveHostAutoLocked(); err != nil { slog.Error("planifications serveur non enregistrees", "err", err) } } // SetHostAuto programme la mise a jour globale d'un serveur (schedule vide : // la desactive). func (m *Manager) SetHostAuto(serverID, schedule, by string) error { schedule = strings.Join(strings.Fields(schedule), " ") m.mu.Lock() defer m.mu.Unlock() if m.indexLocked(serverID) < 0 { return ErrNotFound } old := m.hostAuto[serverID] if schedule == "" { if old == nil { return nil } delete(m.hostAuto, serverID) if err := m.saveHostAutoLocked(); err != nil { m.hostAuto[serverID] = old return err } return nil } if len(schedule) > 100 { return fmt.Errorf("%w : planification trop longue", ErrInvalid) } if _, err := ParseCron(schedule); err != nil { return err } h := &HostAuto{Schedule: schedule, By: by, Since: time.Now()} if old != nil { // on garde le dernier resultat et l'execution en cours h.LastRun, h.LastOK, h.LastMessage, h.Results = old.LastRun, old.LastOK, old.LastMessage, old.Results h.running, h.current = old.running, old.current } m.hostAuto[serverID] = h if err := m.saveHostAutoLocked(); err != nil { if old != nil { m.hostAuto[serverID] = old } else { delete(m.hostAuto, serverID) } return err } return nil } // hostTick lance les executions globales arrivees a echeance. func (m *Manager) hostTick(now time.Time) { m.mu.Lock() defer m.mu.Unlock() for id, h := range m.hostAuto { if c, err := ParseCron(h.Schedule); err == nil && c.Match(now) { h.pending = true } if !h.pending || h.running { // une execution en cours absorbe l'echeance continue } h.pending = false i := m.indexLocked(id) if i < 0 { delete(m.hostAuto, id) _ = m.saveHostAutoLocked() continue } if !m.servers[i].Enabled { h.LastRun, h.LastOK, h.LastMessage, h.Results = now, false, "ignoree : serveur desactive", nil _ = m.saveHostAutoLocked() continue } h.running = true go m.runHostAuto(id, now) } } type hostJob struct { t Target stack Stack } // hostJobsLocked : stacks a mettre a jour lors d'une execution globale. // withPlanned : inclure les stacks qui ont leur propre planification. func (m *Manager) hostJobsLocked(srv Server, withPlanned bool) []hostJob { var jobs []hostJob for _, t := range srv.Targets { sc := m.scans[Key(srv.ID, t.ID)] if sc == nil { continue } for _, st := range sc.Stacks { key := ExclusionKey(srv.ID, t.ID, st.Dir) if m.excluded[key] || (!withPlanned && m.auto[key] != nil) || st.Status == StatusStopped { continue } jobs = append(jobs, hostJob{t, st}) } } return jobs } // runHostAuto met a jour les stacks d'un serveur, une par une. func (m *Manager) runHostAuto(serverID string, at time.Time) { m.mu.Lock() var jobs []hostJob if i := m.indexLocked(serverID); i >= 0 { jobs = m.hostJobsLocked(m.servers[i], false) } m.mu.Unlock() results := make([]HostStackResult, 0, len(jobs)) for _, j := range jobs { r := HostStackResult{Target: j.t.ID, User: j.t.User, Dir: j.stack.Dir, Name: j.stack.Name} m.mu.Lock() if h := m.hostAuto[serverID]; h != nil { h.current = j.stack.Dir } else { // planification supprimee entre-temps m.mu.Unlock() return } m.mu.Unlock() r.OK, r.Skipped, r.Message = m.applyAndWait(serverID, j.t.ID, j.stack.Dir, AutoHostBy) results = append(results, r) } ok, msg := tally(results) m.mu.Lock() defer m.mu.Unlock() if h := m.hostAuto[serverID]; h != nil { h.running, h.current = false, "" h.LastRun, h.LastOK, h.LastMessage, h.Results = at, ok, msg, results if err := m.saveHostAutoLocked(); err != nil { slog.Error("planifications serveur non enregistrees", "err", err) } } slog.Info("mise a jour globale programmee", "server", serverID, "result", msg) logFailures("mise a jour globale programmee", serverID, results) } // logFailures journalise le detail de chaque stack en echec. func logFailures(what, serverID string, results []HostStackResult) { for _, r := range results { if !r.OK { slog.Warn(what+" : echec", "server", serverID, "dir", r.Dir, "msg", r.Message) } } } // tally resume les resultats d'une execution globale ; les stacks en echec // sont nommees dans le message. func tally(results []HostStackResult) (ok bool, msg string) { ok = true restarted, skipped := 0, 0 var failed []string for _, r := range results { switch { case !r.OK: ok = false failed = append(failed, r.Name) case r.Skipped: skipped++ default: restarted++ } } if len(results) == 0 { return true, "aucune stack a mettre a jour (lancer une analyse ?)" } msg = fmt.Sprintf("%d stack(s) : %d relancee(s), %d sans changement, %d en echec", len(results), restarted, skipped, len(failed)) if len(failed) > 0 { msg += " : " + strings.Join(failed, ", ") } return ok, msg } // applyAndWait lance la mise a jour d'une stack et attend son resultat ; une // connexion occupee (analyse en cours) est attendue jusqu'a hostBusyMax. func (m *Manager) applyAndWait(serverID, targetID, dir, by string) (ok, skipped bool, msg string) { key := ExclusionKey(serverID, targetID, dir) m.mu.Lock() delete(m.outcomes, key) m.mu.Unlock() deadline := time.Now().Add(hostBusyMax) for { err := m.Apply(serverID, targetID, dir, by) if err == nil { break } if !errors.Is(err, ErrBusy) || time.Now().After(deadline) { return false, false, err.Error() } select { case <-m.base.Done(): return false, false, "arret de stackwatch" case <-time.After(hostPoll): } } for { m.mu.Lock() o, done := m.outcomes[key] m.mu.Unlock() if done { return o.res.OK, o.skipped, o.res.Message } select { case <-m.base.Done(): return false, false, "arret de stackwatch" case <-time.After(hostPoll): } } }