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
@@ -183,6 +183,7 @@ func (m *Manager) runAuto(ctx context.Context) {
|
||||
|
||||
func (m *Manager) autoTick(now time.Time) {
|
||||
now = now.Truncate(time.Minute)
|
||||
m.hostTick(now)
|
||||
var due []string
|
||||
m.mu.Lock()
|
||||
for key, e := range m.auto {
|
||||
|
||||
@@ -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):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHostAuto(t *testing.T) {
|
||||
hostPoll = 5 * time.Millisecond
|
||||
dir := t.TempDir()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
m, err := Open(ctx, dir, exclTestRunner{}, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv, err := m.Add(Server{Name: "s1", Host: "h1", Enabled: true, Targets: []Target{{User: "root"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tid := srv.Targets[0].ID
|
||||
m.scans[Key(srv.ID, tid)] = &Scan{Stacks: []Stack{
|
||||
{Dir: "/home/a", Name: "a", Status: StatusUpdates},
|
||||
{Dir: "/home/b", Name: "b", Status: StatusUpToDate},
|
||||
{Dir: "/home/c", Name: "c", Status: StatusUpdates},
|
||||
{Dir: "/home/d", Name: "d", Status: StatusStopped},
|
||||
}}
|
||||
if err := m.SetExcluded(srv.ID, tid, "/home/b", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetAuto(srv.ID, tid, "/home/c", "0 0 1 1 *", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := m.SetHostAuto(srv.ID, "* 25 * * *", "test"); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("planification invalide : %v", err)
|
||||
}
|
||||
if err := m.SetHostAuto("inconnu", "@daily", "test"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("serveur inconnu : %v", err)
|
||||
}
|
||||
if err := m.SetHostAuto(srv.ID, "0 3 * * *", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := m.Snapshot()[0]; v.Auto == nil || v.Auto.Schedule != "0 3 * * *" || v.Auto.Next.IsZero() {
|
||||
t.Fatalf("planification non affichee : %+v", v.Auto)
|
||||
}
|
||||
|
||||
// Echeance : seule /home/a est traitee (b exclue, c planifiee a part, d arretee).
|
||||
m.hostTick(time.Date(2026, 1, 1, 3, 0, 0, 0, time.Local))
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
var h HostAuto
|
||||
for {
|
||||
m.mu.Lock()
|
||||
h = *m.hostAuto[srv.ID]
|
||||
m.mu.Unlock()
|
||||
if !h.running {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("execution non terminee")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if len(h.Results) != 1 || h.Results[0].Dir != "/home/a" || h.LastRun.IsZero() {
|
||||
t.Fatalf("resultats : %+v", h)
|
||||
}
|
||||
if h.LastOK || h.Results[0].OK { // exclTestRunner ne repond rien
|
||||
t.Fatalf("echec attendu : %+v", h)
|
||||
}
|
||||
|
||||
// Persistance.
|
||||
m2, err := Open(ctx, dir, exclTestRunner{}, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e := m2.hostAuto[srv.ID]; e == nil || e.Schedule != "0 3 * * *" || len(e.Results) != 1 {
|
||||
t.Fatal("planification non relue")
|
||||
}
|
||||
|
||||
// Desactivation, puis suppression du serveur.
|
||||
if err := m.SetHostAuto(srv.ID, "", "test"); err != nil || m.hostAuto[srv.ID] != nil {
|
||||
t.Fatalf("desactivation : %v", err)
|
||||
}
|
||||
if err := m.SetHostAuto(srv.ID, "@daily", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.Delete(srv.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(m.hostAuto) != 0 {
|
||||
t.Fatalf("planifications restantes : %v", m.hostAuto)
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ type Manager struct {
|
||||
scans map[string]*Scan
|
||||
excluded map[string]bool // ExclusionKey -> stack exclue des mises à jour
|
||||
auto map[string]*AutoEntry
|
||||
hostAuto map[string]*HostAuto
|
||||
outcomes map[string]applyOutcome
|
||||
watchers sync.WaitGroup
|
||||
}
|
||||
|
||||
@@ -53,6 +55,9 @@ func Open(ctx context.Context, dir string, r Runner, parallel int) (*Manager, er
|
||||
if err := m.loadAuto(); err != nil {
|
||||
return nil, fmt.Errorf("autoupdate.json : %w", err)
|
||||
}
|
||||
if err := m.loadHostAuto(); err != nil {
|
||||
return nil, fmt.Errorf("hostauto.json : %w", err)
|
||||
}
|
||||
if err := readJSON(filepath.Join(dir, "state.json"), &m.scans); err != nil {
|
||||
slog.Warn("state.json illisible, résultats ignorés", "err", err)
|
||||
m.scans = map[string]*Scan{}
|
||||
@@ -105,6 +110,8 @@ func (m *Manager) saveStateLocked() {
|
||||
type View struct {
|
||||
Server
|
||||
Scans map[string]Scan `json:"scans"`
|
||||
// Auto : mise a jour globale programmee du serveur.
|
||||
Auto *HostAutoInfo `json:"auto,omitempty"`
|
||||
}
|
||||
|
||||
func copyScan(s *Scan) Scan {
|
||||
@@ -121,6 +128,9 @@ func (m *Manager) Snapshot() []View {
|
||||
out := make([]View, 0, len(m.servers))
|
||||
for _, s := range m.servers {
|
||||
v := View{Server: s, Scans: map[string]Scan{}}
|
||||
if h := m.hostAuto[s.ID]; h != nil {
|
||||
v.Auto = h.info(time.Now())
|
||||
}
|
||||
v.Targets = append([]Target(nil), s.Targets...)
|
||||
for _, t := range s.Targets {
|
||||
if sc, ok := m.scans[Key(s.ID, t.ID)]; ok {
|
||||
@@ -271,6 +281,7 @@ func (m *Manager) Delete(id string) error {
|
||||
delete(m.scans, Key(id, t.ID))
|
||||
m.dropExclusionsLocked(Key(id, t.ID))
|
||||
}
|
||||
m.dropHostAutoLocked(id)
|
||||
m.saveStateLocked()
|
||||
return nil
|
||||
}
|
||||
@@ -493,7 +504,7 @@ func (m *Manager) runApply(srv Server, t Target, dir, by string) {
|
||||
// Planification : autoapply ne relance la stack que si une image a change
|
||||
// ("skip" sinon : stack laissee telle quelle).
|
||||
mode, skipped := "apply", false
|
||||
if by == AutoBy {
|
||||
if strings.HasPrefix(by, AutoBy) { // stack ou serveur
|
||||
mode = "autoapply"
|
||||
}
|
||||
err := m.Runner.Run(ctx, srv.Host, srv.Port, t.User, []string{mode, dir}, func(line string) {
|
||||
@@ -533,6 +544,7 @@ func (m *Manager) runApply(srv Server, t Target, dir, by string) {
|
||||
if by == AutoBy {
|
||||
m.recordAutoLocked(ExclusionKey(srv.ID, t.ID, dir), res.At, res.OK, res.Message)
|
||||
}
|
||||
m.noteOutcomeLocked(ExclusionKey(srv.ID, t.ID, dir), res, skipped)
|
||||
sc.Running, sc.Task, sc.Current = false, "", ""
|
||||
m.saveStateLocked()
|
||||
slog.Info("mise à jour de stack", "server", srv.Name, "user", t.User, "dir", dir, "by", by, "ok", res.OK, "msg", res.Message)
|
||||
|
||||
Reference in new issue
Block a user