Bouton "Tout mettre a jour" : mise a jour globale de toutes les stacks
- POST /api/update-all (administrateur) : toutes les stacks de tous les serveurs actifs, hors exclues et arretees, en mode autoapply (pull, puis down + up -d seulement si une image a change) ; serveurs en parallele, stacks d'un meme serveur une par une ; 409 si deja en cours - etat en memoire expose dans /api/fleet (updateAll : progression, resultats) - interface : bouton dans la barre du haut (progression n/total), dialogue de lancement avec le resultat par stack, echecs en tete - hostJobsLocked/applyAndWait/tally factorises avec la planification serveur Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LNfwm2CJxCZs4b8wVW7zkh
This commit is contained in:
1 parent
eac873266c
commit
b5aad6dbd3
9 files changed
+365
-29
No files matched your search
@@ -14,6 +14,9 @@ Même interface et même authentification qu'[Up And Down](../upandown) (local,
|
|||||||
- Statuts : **À jour**, **Mise à jour** (au moins une image plus récente), **Arrêtée**, **Erreur**
|
- Statuts : **À jour**, **Mise à jour** (au moins une image plus récente), **Arrêtée**, **Erreur**
|
||||||
(fichier invalide, pull refusé...). Les répertoires cachés et `node_modules` sont ignorés.
|
(fichier invalide, pull refusé...). Les répertoires cachés et `node_modules` sont ignorés.
|
||||||
- Bouton **Mettre à jour** (administrateurs, après confirmation) : `pull`, `down`, `up -d` de la stack.
|
- Bouton **Mettre à jour** (administrateurs, après confirmation) : `pull`, `down`, `up -d` de la stack.
|
||||||
|
- Bouton **Tout mettre à jour** (barre du haut, administrateurs) : toutes les stacks de tous les
|
||||||
|
serveurs actifs, hors exclues et arrêtées ; `pull` puis `down` + `up -d` seulement si une image a
|
||||||
|
changé. Serveurs en parallèle, stacks d'un même serveur une par une ; résultat par stack dans le dialogue.
|
||||||
- Analyse automatique toutes les `CHECK_INTERVAL` (6 h par défaut), ou à la demande
|
- Analyse automatique toutes les `CHECK_INTERVAL` (6 h par défaut), ou à la demande
|
||||||
(par stack, connexion, serveur, ou **Tout vérifier**).
|
(par stack, connexion, serveur, ou **Tout vérifier**).
|
||||||
|
|
||||||
|
|||||||
+14
-4
@@ -2,11 +2,12 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
|||||||
import { api, type Fleet, type Me } from "./api";
|
import { api, type Fleet, type Me } from "./api";
|
||||||
import { ActionMenu } from "./ActionMenu";
|
import { ActionMenu } from "./ActionMenu";
|
||||||
import { FleetView } from "./FleetView";
|
import { FleetView } from "./FleetView";
|
||||||
|
import { UpdateAllDialog } from "./AutoUpdate";
|
||||||
import { KeyDialog, ServerDialog } from "./ServerDialog";
|
import { KeyDialog, ServerDialog } from "./ServerDialog";
|
||||||
import { Login } from "./Login";
|
import { Login } from "./Login";
|
||||||
import { SettingsDialog } from "./SettingsDialog";
|
import { SettingsDialog } from "./SettingsDialog";
|
||||||
import { initials } from "./format";
|
import { initials } from "./format";
|
||||||
import { LogoutIcon, MenuIcon, MoonIcon, PlusIcon, RefreshIcon, ServerIcon, SettingsIcon, ShieldIcon, StackIcon, SunIcon, UserIcon, UsersIcon, KeyIcon } from "./icons";
|
import { CloudUpIcon, LogoutIcon, MenuIcon, MoonIcon, PlusIcon, RefreshIcon, ServerIcon, SettingsIcon, ShieldIcon, StackIcon, SunIcon, UserIcon, UsersIcon, KeyIcon } from "./icons";
|
||||||
|
|
||||||
type Theme = "light" | "dark";
|
type Theme = "light" | "dark";
|
||||||
|
|
||||||
@@ -68,6 +69,7 @@ function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
|
|||||||
const [userMenu, setUserMenu] = useState<HTMLElement | null>(null);
|
const [userMenu, setUserMenu] = useState<HTMLElement | null>(null);
|
||||||
const [serverDialog, setServerDialog] = useState<{ id?: string } | null>(null);
|
const [serverDialog, setServerDialog] = useState<{ id?: string } | null>(null);
|
||||||
const [keyDialog, setKeyDialog] = useState(false);
|
const [keyDialog, setKeyDialog] = useState(false);
|
||||||
|
const [updateAllDialog, setUpdateAllDialog] = useState(false);
|
||||||
const title = me.title || "Stackwatch";
|
const title = me.title || "Stackwatch";
|
||||||
const user = me.user!;
|
const user = me.user!;
|
||||||
|
|
||||||
@@ -97,7 +99,8 @@ function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Rafraîchissement : rapide pendant une analyse, lent sinon.
|
// Rafraîchissement : rapide pendant une analyse, lent sinon.
|
||||||
const busy = !!fleet && fleet.summary.scanning > 0;
|
const updating = !!fleet?.updateAll?.running;
|
||||||
|
const busy = !!fleet && (fleet.summary.scanning > 0 || updating);
|
||||||
const loadRef = useRef(load);
|
const loadRef = useRef(load);
|
||||||
loadRef.current = load;
|
loadRef.current = load;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -156,9 +159,15 @@ function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
|
|||||||
</a>
|
</a>
|
||||||
<div className="topbar-tools">
|
<div className="topbar-tools">
|
||||||
<button className="ex-btn" onClick={() => run(api.checkAll)} disabled={!servers.length || busy} title="Analyser tous les serveurs">
|
<button className="ex-btn" onClick={() => run(api.checkAll)} disabled={!servers.length || busy} title="Analyser tous les serveurs">
|
||||||
<RefreshIcon className={busy ? "spin" : ""} />
|
<RefreshIcon className={busy && !updating ? "spin" : ""} />
|
||||||
<span className="hide-sm">{busy ? "Analyse…" : "Tout vérifier"}</span>
|
<span className="hide-sm">{busy && !updating ? "Analyse…" : "Tout vérifier"}</span>
|
||||||
</button>
|
</button>
|
||||||
|
{me.admin && (
|
||||||
|
<button className="ex-btn" onClick={() => setUpdateAllDialog(true)} disabled={!servers.length} title="Mettre a jour toutes les stacks de tous les serveurs (hors exclues et arretees)">
|
||||||
|
{updating ? <RefreshIcon className="spin" /> : <CloudUpIcon />}
|
||||||
|
<span className="hide-sm">{updating ? `Mise à jour ${fleet?.updateAll?.done ?? 0}/${fleet?.updateAll?.total ?? 0}…` : "Tout mettre à jour"}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label={theme === "dark" ? "Thème clair" : "Thème sombre"} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
|
<button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label={theme === "dark" ? "Thème clair" : "Thème sombre"} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
|
||||||
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
||||||
</button>
|
</button>
|
||||||
@@ -264,6 +273,7 @@ function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{settings && <SettingsDialog me={me} initialTab={settings} onClose={() => setSettings(null)} onChanged={reloadMe} />}
|
{settings && <SettingsDialog me={me} initialTab={settings} onClose={() => setSettings(null)} onChanged={reloadMe} />}
|
||||||
|
{updateAllDialog && <UpdateAllDialog status={fleet?.updateAll} onClose={() => setUpdateAllDialog(false)} onStart={() => run(api.updateAll)} />}
|
||||||
{keyDialog && fleet && <KeyDialog publicKey={fleet.publicKey ?? ""} onClose={() => setKeyDialog(false)} />}
|
{keyDialog && fleet && <KeyDialog publicKey={fleet.publicKey ?? ""} onClose={() => setKeyDialog(false)} />}
|
||||||
{serverDialog && (
|
{serverDialog && (
|
||||||
<ServerDialog
|
<ServerDialog
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// Mises a jour automatiques programmees (crontab) : par stack (detail de la
|
// Mises a jour automatiques programmees (crontab) : par stack (detail de la
|
||||||
// stack) et globale par serveur (dialogue du serveur), badges et vue de suivi.
|
// stack) et globale par serveur (dialogue du serveur), badges et vue de suivi.
|
||||||
import { useEffect, useState, type ReactNode } from "react";
|
import { useEffect, useState, type ReactNode } from "react";
|
||||||
import { api, type AutoInfo, type HostAutoInfo, type Me, type Scan, type Server, type Stack, type Target } from "./api";
|
import { api, type AutoInfo, type HostAutoInfo, type UpdateAll, type Me, type Scan, type Server, type Stack, type Target } from "./api";
|
||||||
import { fmtDate, fmtRelative } from "./format";
|
import { fmtDate, fmtRelative } from "./format";
|
||||||
import { CheckIcon, ClockIcon, RefreshIcon, WarningIcon } from "./icons";
|
import { CheckIcon, ClockIcon, CloudUpIcon, RefreshIcon, WarningIcon } from "./icons";
|
||||||
|
|
||||||
export const AUTO_PRESETS: [string, string][] = [
|
export const AUTO_PRESETS: [string, string][] = [
|
||||||
["0 4 * * *", "Chaque nuit a 4 h"],
|
["0 4 * * *", "Chaque nuit a 4 h"],
|
||||||
@@ -192,6 +192,73 @@ export function AutoEditor({ stack, busy, tz, hostSchedule, onSave }: EditorProp
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface UpdateAllProps {
|
||||||
|
status?: UpdateAll;
|
||||||
|
onStart: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mise a jour de toutes les stacks de tous les serveurs : confirmation, progression et dernier resultat. */
|
||||||
|
export function UpdateAllDialog({ status, onStart, onClose }: UpdateAllProps) {
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
const running = !!status?.running;
|
||||||
|
const results = [...(status?.results ?? [])].sort((a, b) => Number(a.ok) - Number(b.ok) || Number(!!a.skipped) - Number(!!b.skipped) || a.server.localeCompare(b.server) || a.name.localeCompare(b.name));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal" role="dialog" aria-modal="true" aria-label="Mettre a jour toutes les stacks" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h3>Mettre a jour toutes les stacks</h3>
|
||||||
|
<div className="modal-text">
|
||||||
|
<p className="muted small-text">
|
||||||
|
Toutes les stacks de tous les serveurs actifs sont mises a jour : pull, puis down + up -d seulement si une image a change. Les serveurs sont traites en parallele, les stacks d'un meme serveur
|
||||||
|
une par une. Sont ignorees : les stacks exclues et les stacks arretees.
|
||||||
|
</p>
|
||||||
|
{status && (
|
||||||
|
<div className="small-text">
|
||||||
|
{running ? (
|
||||||
|
<span className="status-pill st-applying">
|
||||||
|
<RefreshIcon size={13} className="spin" /> En cours : {status.done}/{status.total} stack(s)
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className={`auto-last ${status.ok ? "ok" : "ko"}`}>
|
||||||
|
{status.ok ? <CheckIcon size={13} /> : <WarningIcon size={13} />}
|
||||||
|
<span>
|
||||||
|
Derniere execution {fmtRelative(status.finished ?? status.started)}
|
||||||
|
{status.by ? ` (${status.by})` : ""}
|
||||||
|
{status.message ? ` : ${status.message}` : ""}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{results.length > 0 && (
|
||||||
|
<ul className="auto-results small-text">
|
||||||
|
{results.map((r) => (
|
||||||
|
<li key={`${r.serverId}:${r.target}:${r.dir}`} className={r.ok ? (r.skipped ? "muted" : "ok") : "ko"}>
|
||||||
|
{r.ok ? <CheckIcon size={12} /> : <WarningIcon size={12} />} <strong>{r.server}</strong> / <strong>{r.name}</strong> <span className="muted">({r.user})</span> : {r.message}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="modal-actions">
|
||||||
|
<span className="spacer" />
|
||||||
|
<button onClick={onClose}>Fermer</button>
|
||||||
|
<button className="primary" disabled={running} onClick={onStart}>
|
||||||
|
<CloudUpIcon />
|
||||||
|
Lancer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
interface HostDialogProps {
|
interface HostDialogProps {
|
||||||
server: Server;
|
server: Server;
|
||||||
tz?: string;
|
tz?: string;
|
||||||
|
|||||||
@@ -116,6 +116,25 @@ export interface HostAutoInfo {
|
|||||||
current?: string;
|
current?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resultat d'une stack lors d'une mise a jour globale (bouton). */
|
||||||
|
export interface GlobalStackResult extends HostStackResult {
|
||||||
|
serverId: string;
|
||||||
|
server: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mise a jour globale de toutes les stacks (en cours ou derniere executee). */
|
||||||
|
export interface UpdateAll {
|
||||||
|
by?: string;
|
||||||
|
started: string;
|
||||||
|
finished?: string;
|
||||||
|
running: boolean;
|
||||||
|
total: number;
|
||||||
|
done: number;
|
||||||
|
ok: boolean;
|
||||||
|
message?: string;
|
||||||
|
results?: GlobalStackResult[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface Scan {
|
export interface Scan {
|
||||||
running: boolean;
|
running: boolean;
|
||||||
task?: "scan" | "apply";
|
task?: "scan" | "apply";
|
||||||
@@ -168,6 +187,8 @@ export interface Fleet {
|
|||||||
tz?: string;
|
tz?: string;
|
||||||
/** Administrateur : clé publique SSH à autoriser sur les serveurs. */
|
/** Administrateur : clé publique SSH à autoriser sur les serveurs. */
|
||||||
publicKey?: string;
|
publicKey?: string;
|
||||||
|
/** Mise a jour globale en cours ou derniere executee (absente : aucune depuis le demarrage). */
|
||||||
|
updateAll?: UpdateAll;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PingResult {
|
export interface PingResult {
|
||||||
@@ -236,6 +257,9 @@ export const api = {
|
|||||||
await request("/api/check", { method: "POST" });
|
await request("/api/check", { method: "POST" });
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/** Met a jour toutes les stacks de tous les serveurs actifs (hors exclues et arretees). */
|
||||||
|
updateAll: async (): Promise<{ stacks: number }> => (await request("/api/update-all", { method: "POST" })).json(),
|
||||||
|
|
||||||
check: async (serverId: string, targetId?: string): Promise<void> => {
|
check: async (serverId: string, targetId?: string): Promise<void> => {
|
||||||
await request(`/api/servers/${q(serverId)}/check${targetId ? `?target=${q(targetId)}` : ""}`, { method: "POST" });
|
await request(`/api/servers/${q(serverId)}/check${targetId ? `?target=${q(targetId)}` : ""}`, { method: "POST" });
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// GET /api/fleet serveurs, connexions, stacks, résumé ; clé publique SSH (administrateur)
|
// GET /api/fleet serveurs, connexions, stacks, résumé ; clé publique SSH (administrateur)
|
||||||
// GET /api/summary compteurs (stacks, mises à jour, erreurs...)
|
// GET /api/summary compteurs (stacks, mises à jour, erreurs...)
|
||||||
// POST /api/check analyse de tous les serveurs actifs
|
// POST /api/check analyse de tous les serveurs actifs
|
||||||
|
// POST /api/update-all (administrateur) mise a jour de toutes les stacks de tous les serveurs actifs (hors exclues et arretees)
|
||||||
// POST /api/servers/{id}/check[?target=t] analyse d'un serveur (ou d'une de ses connexions)
|
// POST /api/servers/{id}/check[?target=t] analyse d'un serveur (ou d'une de ses connexions)
|
||||||
// POST /api/servers (administrateur) ajout d'un serveur
|
// POST /api/servers (administrateur) ajout d'un serveur
|
||||||
// PUT /api/servers/{id} (administrateur) modification
|
// PUT /api/servers/{id} (administrateur) modification
|
||||||
@@ -94,6 +95,7 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("GET /api/fleet", h.getFleet)
|
mux.HandleFunc("GET /api/fleet", h.getFleet)
|
||||||
mux.HandleFunc("GET /api/summary", h.summary)
|
mux.HandleFunc("GET /api/summary", h.summary)
|
||||||
mux.HandleFunc("POST /api/check", h.checkAll)
|
mux.HandleFunc("POST /api/check", h.checkAll)
|
||||||
|
mux.HandleFunc("POST /api/update-all", h.updateAll)
|
||||||
mux.HandleFunc("POST /api/servers", h.addServer)
|
mux.HandleFunc("POST /api/servers", h.addServer)
|
||||||
mux.HandleFunc("PUT /api/servers/{id}", h.updateServer)
|
mux.HandleFunc("PUT /api/servers/{id}", h.updateServer)
|
||||||
mux.HandleFunc("DELETE /api/servers/{id}", h.deleteServer)
|
mux.HandleFunc("DELETE /api/servers/{id}", h.deleteServer)
|
||||||
@@ -163,6 +165,9 @@ func (h *Handler) getFleet(w http.ResponseWriter, r *http.Request) {
|
|||||||
"interval": int(h.Interval.Seconds()),
|
"interval": int(h.Interval.Seconds()),
|
||||||
"tz": tzName(),
|
"tz": tzName(),
|
||||||
}
|
}
|
||||||
|
if g := h.Fleet.UpdateAllStatus(); g != nil {
|
||||||
|
resp["updateAll"] = g
|
||||||
|
}
|
||||||
if h.isAdmin(r) {
|
if h.isAdmin(r) {
|
||||||
resp["publicKey"] = h.PublicKey
|
resp["publicKey"] = h.PublicKey
|
||||||
}
|
}
|
||||||
@@ -179,6 +184,18 @@ func (h *Handler) checkAll(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusAccepted, map[string]int{"started": n})
|
writeJSON(w, http.StatusAccepted, map[string]int{"started": n})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) updateAll(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !h.admin(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := h.Fleet.UpdateAll(UserID(r))
|
||||||
|
if err != nil {
|
||||||
|
fail(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusAccepted, map[string]int{"stacks": n})
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) checkServer(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) checkServer(w http.ResponseWriter, r *http.Request) {
|
||||||
n, err := h.Fleet.Check(r.PathValue("id"), r.URL.Query().Get("target"))
|
n, err := h.Fleet.Check(r.PathValue("id"), r.URL.Query().Get("target"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+29
-22
@@ -190,7 +190,8 @@ type hostJob struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// hostJobsLocked : stacks a mettre a jour lors d'une execution globale.
|
// hostJobsLocked : stacks a mettre a jour lors d'une execution globale.
|
||||||
func (m *Manager) hostJobsLocked(srv Server) []hostJob {
|
// withPlanned : inclure les stacks qui ont leur propre planification.
|
||||||
|
func (m *Manager) hostJobsLocked(srv Server, withPlanned bool) []hostJob {
|
||||||
var jobs []hostJob
|
var jobs []hostJob
|
||||||
for _, t := range srv.Targets {
|
for _, t := range srv.Targets {
|
||||||
sc := m.scans[Key(srv.ID, t.ID)]
|
sc := m.scans[Key(srv.ID, t.ID)]
|
||||||
@@ -199,7 +200,7 @@ func (m *Manager) hostJobsLocked(srv Server) []hostJob {
|
|||||||
}
|
}
|
||||||
for _, st := range sc.Stacks {
|
for _, st := range sc.Stacks {
|
||||||
key := ExclusionKey(srv.ID, t.ID, st.Dir)
|
key := ExclusionKey(srv.ID, t.ID, st.Dir)
|
||||||
if m.excluded[key] || m.auto[key] != nil || st.Status == StatusStopped {
|
if m.excluded[key] || (!withPlanned && m.auto[key] != nil) || st.Status == StatusStopped {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
jobs = append(jobs, hostJob{t, st})
|
jobs = append(jobs, hostJob{t, st})
|
||||||
@@ -213,7 +214,7 @@ func (m *Manager) runHostAuto(serverID string, at time.Time) {
|
|||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
var jobs []hostJob
|
var jobs []hostJob
|
||||||
if i := m.indexLocked(serverID); i >= 0 {
|
if i := m.indexLocked(serverID); i >= 0 {
|
||||||
jobs = m.hostJobsLocked(m.servers[i])
|
jobs = m.hostJobsLocked(m.servers[i], false)
|
||||||
}
|
}
|
||||||
m.mu.Unlock()
|
m.mu.Unlock()
|
||||||
|
|
||||||
@@ -228,26 +229,11 @@ func (m *Manager) runHostAuto(serverID string, at time.Time) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
m.mu.Unlock()
|
m.mu.Unlock()
|
||||||
r.OK, r.Skipped, r.Message = m.applyAndWait(serverID, j.t.ID, j.stack.Dir)
|
r.OK, r.Skipped, r.Message = m.applyAndWait(serverID, j.t.ID, j.stack.Dir, AutoHostBy)
|
||||||
results = append(results, r)
|
results = append(results, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
ok, restarted, skipped, failed := true, 0, 0, 0
|
ok, msg := tally(results)
|
||||||
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()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
if h := m.hostAuto[serverID]; h != nil {
|
if h := m.hostAuto[serverID]; h != nil {
|
||||||
@@ -260,16 +246,37 @@ func (m *Manager) runHostAuto(serverID string, at time.Time) {
|
|||||||
slog.Info("mise a jour globale programmee", "server", serverID, "result", msg)
|
slog.Info("mise a jour globale programmee", "server", serverID, "result", msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tally resume les resultats d'une execution globale.
|
||||||
|
func tally(results []HostStackResult) (ok bool, msg string) {
|
||||||
|
ok = true
|
||||||
|
restarted, skipped, failed := 0, 0, 0
|
||||||
|
for _, r := range results {
|
||||||
|
switch {
|
||||||
|
case !r.OK:
|
||||||
|
ok = false
|
||||||
|
failed++
|
||||||
|
case r.Skipped:
|
||||||
|
skipped++
|
||||||
|
default:
|
||||||
|
restarted++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(results) == 0 {
|
||||||
|
return true, "aucune stack a mettre a jour (lancer une analyse ?)"
|
||||||
|
}
|
||||||
|
return ok, fmt.Sprintf("%d stack(s) : %d relancee(s), %d sans changement, %d en echec", len(results), restarted, skipped, failed)
|
||||||
|
}
|
||||||
|
|
||||||
// applyAndWait lance la mise a jour d'une stack et attend son resultat ; une
|
// applyAndWait lance la mise a jour d'une stack et attend son resultat ; une
|
||||||
// connexion occupee (analyse en cours) est attendue jusqu'a hostBusyMax.
|
// connexion occupee (analyse en cours) est attendue jusqu'a hostBusyMax.
|
||||||
func (m *Manager) applyAndWait(serverID, targetID, dir string) (ok, skipped bool, msg string) {
|
func (m *Manager) applyAndWait(serverID, targetID, dir, by string) (ok, skipped bool, msg string) {
|
||||||
key := ExclusionKey(serverID, targetID, dir)
|
key := ExclusionKey(serverID, targetID, dir)
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
delete(m.outcomes, key)
|
delete(m.outcomes, key)
|
||||||
m.mu.Unlock()
|
m.mu.Unlock()
|
||||||
deadline := time.Now().Add(hostBusyMax)
|
deadline := time.Now().Add(hostBusyMax)
|
||||||
for {
|
for {
|
||||||
err := m.Apply(serverID, targetID, dir, AutoHostBy)
|
err := m.Apply(serverID, targetID, dir, by)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ type Manager struct {
|
|||||||
auto map[string]*AutoEntry
|
auto map[string]*AutoEntry
|
||||||
hostAuto map[string]*HostAuto
|
hostAuto map[string]*HostAuto
|
||||||
outcomes map[string]applyOutcome
|
outcomes map[string]applyOutcome
|
||||||
|
global *UpdateAll // derniere mise a jour globale (bouton), en memoire
|
||||||
watchers sync.WaitGroup
|
watchers sync.WaitGroup
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -504,7 +505,7 @@ func (m *Manager) runApply(srv Server, t Target, dir, by string) {
|
|||||||
// Planification : autoapply ne relance la stack que si une image a change
|
// Planification : autoapply ne relance la stack que si une image a change
|
||||||
// ("skip" sinon : stack laissee telle quelle).
|
// ("skip" sinon : stack laissee telle quelle).
|
||||||
mode, skipped := "apply", false
|
mode, skipped := "apply", false
|
||||||
if strings.HasPrefix(by, AutoBy) { // stack ou serveur
|
if strings.HasPrefix(by, AutoBy) || strings.HasPrefix(by, GlobalBy) { // stack, serveur ou bouton global
|
||||||
mode = "autoapply"
|
mode = "autoapply"
|
||||||
}
|
}
|
||||||
err := m.Runner.Run(ctx, srv.Host, srv.Port, t.User, []string{mode, dir}, func(line string) {
|
err := m.Runner.Run(ctx, srv.Host, srv.Port, t.User, []string{mode, dir}, func(line string) {
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package fleet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Mise a jour globale a la demande (bouton « Tout mettre a jour ») : toutes
|
||||||
|
// les stacks de tous les serveurs actifs, sauf les stacks exclues et
|
||||||
|
// arretees, avec la logique de la mise a jour programmee (pull, puis down +
|
||||||
|
// up -d seulement si une image a change). Les serveurs sont traites en
|
||||||
|
// parallele (dans la limite du parallelisme global), les stacks d'un meme
|
||||||
|
// serveur une par une. Le dernier resultat est garde en memoire.
|
||||||
|
|
||||||
|
// GlobalBy : auteur des mises a jour lancees par le bouton global.
|
||||||
|
const GlobalBy = "mise a jour globale"
|
||||||
|
|
||||||
|
// GlobalStackResult : resultat d'une stack lors d'une mise a jour globale.
|
||||||
|
type GlobalStackResult struct {
|
||||||
|
ServerID string `json:"serverId"`
|
||||||
|
Server string `json:"server"`
|
||||||
|
HostStackResult
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateAll : mise a jour globale en cours ou derniere executee.
|
||||||
|
type UpdateAll struct {
|
||||||
|
By string `json:"by,omitempty"`
|
||||||
|
Started time.Time `json:"started"`
|
||||||
|
Finished time.Time `json:"finished,omitzero"`
|
||||||
|
Running bool `json:"running"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Done int `json:"done"`
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Results []GlobalStackResult `json:"results,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateAllStatus renvoie une copie de la mise a jour globale (nil : aucune).
|
||||||
|
func (m *Manager) UpdateAllStatus() *UpdateAll {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if m.global == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
g := *m.global
|
||||||
|
g.Results = append([]GlobalStackResult(nil), m.global.Results...)
|
||||||
|
return &g
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateAll lance la mise a jour de toutes les stacks de tous les serveurs
|
||||||
|
// actifs ; elle se poursuit en arriere-plan. Renvoie le nombre de stacks
|
||||||
|
// concernees.
|
||||||
|
func (m *Manager) UpdateAll(user string) (int, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
if m.global != nil && m.global.Running {
|
||||||
|
m.mu.Unlock()
|
||||||
|
return 0, fmt.Errorf("%w : une mise a jour globale est deja en cours", ErrBusy)
|
||||||
|
}
|
||||||
|
type plan struct {
|
||||||
|
srv Server
|
||||||
|
jobs []hostJob
|
||||||
|
}
|
||||||
|
var plans []plan
|
||||||
|
total := 0
|
||||||
|
for _, s := range m.servers {
|
||||||
|
if !s.Enabled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if jobs := m.hostJobsLocked(s, true); len(jobs) > 0 {
|
||||||
|
plans = append(plans, plan{s, jobs})
|
||||||
|
total += len(jobs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if total == 0 {
|
||||||
|
m.mu.Unlock()
|
||||||
|
return 0, fmt.Errorf("%w : aucune stack a mettre a jour (lancer une analyse ?)", ErrInvalid)
|
||||||
|
}
|
||||||
|
g := &UpdateAll{By: user, Started: time.Now(), Running: true, Total: total}
|
||||||
|
m.global = g
|
||||||
|
m.mu.Unlock()
|
||||||
|
|
||||||
|
by := GlobalBy
|
||||||
|
if user != "" {
|
||||||
|
by += " (" + user + ")"
|
||||||
|
}
|
||||||
|
slog.Info("mise a jour globale lancee", "stacks", total, "by", user)
|
||||||
|
go func() {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for _, p := range plans {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for _, j := range p.jobs {
|
||||||
|
r := GlobalStackResult{ServerID: p.srv.ID, Server: p.srv.Name,
|
||||||
|
HostStackResult: HostStackResult{Target: j.t.ID, User: j.t.User, Dir: j.stack.Dir, Name: j.stack.Name}}
|
||||||
|
r.OK, r.Skipped, r.Message = m.applyAndWait(p.srv.ID, j.t.ID, j.stack.Dir, by)
|
||||||
|
m.mu.Lock()
|
||||||
|
g.Results = append(g.Results, r)
|
||||||
|
g.Done++
|
||||||
|
m.mu.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
m.mu.Lock()
|
||||||
|
res := make([]HostStackResult, len(g.Results))
|
||||||
|
for i, r := range g.Results {
|
||||||
|
res[i] = r.HostStackResult
|
||||||
|
}
|
||||||
|
g.OK, g.Message = tally(res)
|
||||||
|
g.Running, g.Finished = false, time.Now()
|
||||||
|
msg := g.Message
|
||||||
|
m.mu.Unlock()
|
||||||
|
slog.Info("mise a jour globale terminee", "result", msg, "by", user)
|
||||||
|
}()
|
||||||
|
return total, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package fleet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// modeRunner repond « A ok » et note le mode et le repertoire demandes.
|
||||||
|
type modeRunner struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
calls []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *modeRunner) Run(_ context.Context, _ string, _ int, _ string, args []string, out func(string)) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.calls = append(r.calls, args[0]+" "+args[1])
|
||||||
|
r.mu.Unlock()
|
||||||
|
out("A\tok\tnouvelle image : stack relancee (down + up -d)")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateAll(t *testing.T) {
|
||||||
|
hostPoll = 5 * time.Millisecond
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
run := &modeRunner{}
|
||||||
|
m, err := Open(ctx, t.TempDir(), run, 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := m.UpdateAll("test"); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Fatalf("aucune stack : %v", err)
|
||||||
|
}
|
||||||
|
s1, _ := m.Add(Server{Name: "s1", Host: "h1", Enabled: true, Targets: []Target{{User: "root"}}})
|
||||||
|
s2, _ := m.Add(Server{Name: "s2", Host: "h2", Enabled: true, Targets: []Target{{User: "root"}}})
|
||||||
|
s3, _ := m.Add(Server{Name: "s3", Host: "h3", Enabled: false, Targets: []Target{{User: "root"}}})
|
||||||
|
t1, t2, t3 := s1.Targets[0].ID, s2.Targets[0].ID, s3.Targets[0].ID
|
||||||
|
m.scans[Key(s1.ID, t1)] = &Scan{Stacks: []Stack{
|
||||||
|
{Dir: "/home/a", Name: "a", Status: StatusUpdates},
|
||||||
|
{Dir: "/home/b", Name: "b", Status: StatusUpToDate},
|
||||||
|
{Dir: "/home/c", Name: "c", Status: StatusUpToDate},
|
||||||
|
{Dir: "/home/d", Name: "d", Status: StatusStopped},
|
||||||
|
}}
|
||||||
|
m.scans[Key(s2.ID, t2)] = &Scan{Stacks: []Stack{{Dir: "/srv/e", Name: "e", Status: StatusUpdates}}}
|
||||||
|
m.scans[Key(s3.ID, t3)] = &Scan{Stacks: []Stack{{Dir: "/srv/f", Name: "f", Status: StatusUpdates}}}
|
||||||
|
if err := m.SetExcluded(s1.ID, t1, "/home/b", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := m.SetAuto(s1.ID, t1, "/home/c", "0 0 1 1 *", "test"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// a, c (planifiee a part, incluse) et e ; b exclue, d arretee, f serveur desactive.
|
||||||
|
n, err := m.UpdateAll("cedric")
|
||||||
|
if err != nil || n != 3 {
|
||||||
|
t.Fatalf("lancement : %d %v", n, err)
|
||||||
|
}
|
||||||
|
if _, err := m.UpdateAll("cedric"); !errors.Is(err, ErrBusy) {
|
||||||
|
t.Fatalf("double lancement : %v", err)
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
var g *UpdateAll
|
||||||
|
for {
|
||||||
|
if g = m.UpdateAllStatus(); !g.Running {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("execution non terminee")
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
}
|
||||||
|
if g.Done != 3 || len(g.Results) != 3 || !g.OK || g.Finished.IsZero() {
|
||||||
|
t.Fatalf("resultat : %+v", g)
|
||||||
|
}
|
||||||
|
run.mu.Lock()
|
||||||
|
for _, c := range run.calls {
|
||||||
|
if c[:10] != "autoapply " {
|
||||||
|
t.Fatalf("mode attendu autoapply : %v", run.calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run.mu.Unlock()
|
||||||
|
if st := m.Snapshot()[0].Scans[t1].Stacks[0]; st.Status != StatusUpToDate || st.Applied == nil || st.Applied.By != "mise a jour globale (cedric)" {
|
||||||
|
t.Fatalf("stack a : %+v", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user