Mise a jour automatique globale programmee par serveur
- planification crontab par serveur (hostauto.json) : toutes les stacks de la
derniere analyse, une par une, hors exclues, arretees et stacks ayant leur
propre planification (celle de la stack prime)
- attente d'une connexion occupee (30 min max), resultat par stack conserve
- API PUT /api/servers/{id}/auto {"schedule"} ; vue de fleet : servers[].auto
- interface : bouton horloge par serveur (dialogue de planification), badge,
section Serveurs dans la vue "Mises a jour auto", statut bleu pendant l'execution
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LNfwm6UCYFyvNQNSF5i9Gy
This commit is contained in:
1 parent
ef259ae27a
commit
eac873266c
10 files changed
+824
-109
No files matched your search
@@ -0,0 +1,298 @@
|
||||
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.
|
||||
func (m *Manager) hostJobsLocked(srv Server) []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] || 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])
|
||||
}
|
||||
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)
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
ok, restarted, skipped, failed := true, 0, 0, 0
|
||||
for _, r := range results {
|
||||
switch {
|
||||
case !r.OK:
|
||||
ok = false
|
||||
failed++
|
||||
case r.Skipped:
|
||||
skipped++
|
||||
default:
|
||||
restarted++
|
||||
}
|
||||
}
|
||||
msg := fmt.Sprintf("%d stack(s) : %d relancee(s), %d sans changement, %d en echec", len(results), restarted, skipped, failed)
|
||||
if len(results) == 0 {
|
||||
msg = "aucune stack a mettre a jour (lancer une analyse ?)"
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// 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 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, AutoHostBy)
|
||||
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):
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user