Page Deploiement: generateur de docker-compose et garage.toml (1 a 9 noeuds, rejoindre un cluster, etapes, CLI) + tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ca1330434e
commit
ea2058b6c1
9 files changed
+686
-2
No files matched your search
@@ -7,8 +7,11 @@ Interface web d'administration pour un cluster [Garage](https://garagehq.deuxfle
|
||||
- **Clés d'accès** : création, import, secret affiché à la demande, exemples de configuration `rclone` et `aws`, permissions par bucket, suppression.
|
||||
- **Cluster** : nœuds, rôles (zone, capacité, étiquettes, passerelle), layout en attente avec prévisualisation, application et annulation, connexion d'un nœud.
|
||||
- **Maintenance** : réparations (`tables`, `blocks`, `scrub`...), tâches de fond, blocs en erreur, snapshot des métadonnées.
|
||||
- **Déploiement** : générateur de `docker-compose.yml` et de `garage.toml` pour un cluster de 1 à 9 nœuds (un serveur par nœud, ou tous sur un hôte pour tester), avec zones, capacités, réplication, secrets générés dans le navigateur, étapes d'assemblage et commandes CLI équivalentes. Il sait aussi préparer des nœuds qui rejoignent un cluster existant (`bootstrap_peers`). Il ne déploie rien lui-même.
|
||||
- **Console** : exécute la CLI `garage` (liste blanche de sous-commandes), avec des raccourcis et un historique.
|
||||
|
||||
Note : passer un cluster existant à plusieurs nœuds *avec réplication* change `replication_factor`, ce que Garage ne supporte pas officiellement sur un cluster en place (voir sa documentation). Le plus sûr est de monter un nouveau cluster et d'y copier les données ; la page Déploiement prépare les fichiers.
|
||||
|
||||
Garage 2.0 ou plus récent est requis : l'interface parle à l'**API d'administration v2** (`/v2/...`).
|
||||
|
||||
## Fonctionnement
|
||||
@@ -70,6 +73,8 @@ MOCK_ADDR=127.0.0.1:13903 go run ./cmd/mockgarage &
|
||||
GARAGE_ADMIN_URL=http://127.0.0.1:13903 GARAGE_ADMIN_TOKEN=test UI_PASSWORD=secret LISTEN_ADDR=127.0.0.1:8080 go run ./cmd/server
|
||||
```
|
||||
|
||||
`npm test` (dans `frontend/`, Node 23+) exécute les tests du générateur de déploiement (`src/deployGen.ts`).
|
||||
|
||||
`npm run dev` (dans `frontend/`) sert le frontend avec rechargement à chaud et proxy vers `:8080`.
|
||||
|
||||
## Licence
|
||||
|
||||
@@ -148,6 +148,8 @@ func handle(token string) http.HandlerFunc {
|
||||
j(w, 200, map[string]any{"layoutVersion": version, "nodes": []any{map[string]any{
|
||||
"id": nodeID, "role": role, "addr": "172.18.0.2:3901", "hostname": "garage", "isUp": true, "lastSeenSecsAgo": nil, "draining": false,
|
||||
"dataPartition": map[string]any{"available": int64(412e9), "total": int64(500e9)}, "metadataPartition": map[string]any{"available": int64(40e9), "total": int64(50e9)}, "garageVersion": "v2.3.0"}}})
|
||||
case "GetNodeInfo":
|
||||
j(w, 200, map[string]any{"success": map[string]any{nodeID: map[string]any{"nodeId": nodeID, "garageVersion": "v2.3.0", "rustVersion": "1.80", "dbEngine": "lmdb", "addr": "172.18.0.2:3901"}}, "error": map[string]any{}})
|
||||
case "GetClusterStatistics":
|
||||
j(w, 200, map[string]any{"freeform": "Storage nodes:\n ID Hostname Zone Capacity Part. DataAvail MetaAvail\n 563e1ac8 garage dc1 500.0 GB 256 412.0 GB 40.0 GB"})
|
||||
case "GetClusterLayout":
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "node --test test/"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.1.0",
|
||||
|
||||
@@ -3,7 +3,8 @@ import { appApi, errMsg, type Config } from "./api";
|
||||
import { BucketPage, Buckets } from "./Buckets";
|
||||
import { Cluster } from "./Cluster";
|
||||
import { Console } from "./Console";
|
||||
import { ClusterIcon, BucketIcon, ConsoleIcon, MaintenanceIcon, OverviewIcon } from "./gicons";
|
||||
import { Deploy } from "./Deploy";
|
||||
import { ClusterIcon, BucketIcon, ConsoleIcon, DeployIcon, MaintenanceIcon, OverviewIcon } from "./gicons";
|
||||
import { KeyIcon, LogoutIcon, MenuIcon, MoonIcon, SunIcon } from "./icons";
|
||||
import { KeyPage, Keys } from "./Keys";
|
||||
import { Login } from "./Login";
|
||||
@@ -78,6 +79,7 @@ const NAV = [
|
||||
["buckets", "Buckets", BucketIcon],
|
||||
["keys", "Clés d'accès", KeyIcon],
|
||||
["cluster", "Cluster", ClusterIcon],
|
||||
["deploy", "Déploiement", DeployIcon],
|
||||
["maintenance", "Maintenance", MaintenanceIcon],
|
||||
["console", "Console", ConsoleIcon],
|
||||
] as const;
|
||||
@@ -108,6 +110,8 @@ function Shell({ cfg, reload }: { cfg: Config; reload: () => void }) {
|
||||
return id ? <KeyPage id={id} key={id} cfg={cfg} /> : <Keys cfg={cfg} />;
|
||||
case "cluster":
|
||||
return <Cluster />;
|
||||
case "deploy":
|
||||
return <Deploy cfg={cfg} />;
|
||||
case "maintenance":
|
||||
return <Maintenance />;
|
||||
case "console":
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { garage, type ClusterStatus, type Config } from "./api";
|
||||
import { MAX_NODES, defaultConfig, defaultNodes, generate, randomHex, randomToken, type Consistency, type DeployConfig, type GenFile, type NodeSpec } from "./deployGen";
|
||||
import { DownloadIcon, RefreshIcon } from "./icons";
|
||||
import { CopyButton, PageHead, useAct } from "./ui";
|
||||
|
||||
const KEY = "garageUiDeploy";
|
||||
|
||||
/** Le formulaire survit à un rechargement de l'onglet (sessionStorage), pas à sa fermeture : il contient des secrets. */
|
||||
function load(cfg: Config): DeployConfig {
|
||||
const base = defaultConfig(cfg.s3Region);
|
||||
try {
|
||||
const s = sessionStorage.getItem(KEY);
|
||||
if (s) return { ...base, ...JSON.parse(s) };
|
||||
} catch {
|
||||
/* stockage indisponible */
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function download(f: GenFile) {
|
||||
const url = URL.createObjectURL(new Blob([f.content], { type: "text/plain" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = f.download;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export function Deploy({ cfg }: { cfg: Config }) {
|
||||
const act = useAct();
|
||||
const [c, setC] = useState(() => load(cfg));
|
||||
const [sel, setSel] = useState(0);
|
||||
const gen = useMemo(() => generate(c), [c]);
|
||||
const file = gen.files[Math.min(sel, gen.files.length - 1)];
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
sessionStorage.setItem(KEY, JSON.stringify(c));
|
||||
} catch {
|
||||
/* stockage indisponible */
|
||||
}
|
||||
}, [c]);
|
||||
|
||||
const set = <K extends keyof DeployConfig>(k: K, v: DeployConfig[K]) => setC((p) => ({ ...p, [k]: v }));
|
||||
const setNode = (i: number, patch: Partial<NodeSpec>) => setC((p) => ({ ...p, nodes: p.nodes.map((n, j) => (j === i ? { ...n, ...patch } : n)) }));
|
||||
const setCount = (raw: number) =>
|
||||
setC((p) => {
|
||||
const n = Math.min(MAX_NODES, Math.max(1, Math.round(raw) || 1));
|
||||
const nodes = n <= p.nodes.length ? p.nodes.slice(0, n) : [...p.nodes, ...defaultNodes(n).slice(p.nodes.length)];
|
||||
// Le facteur suit le nombre de nœuds tant que l'utilisateur ne l'a pas choisi lui-même.
|
||||
const replication = p.replication === Math.min(3, p.nodes.length) ? Math.min(3, n) : p.replication;
|
||||
return { ...p, nodes, replication };
|
||||
});
|
||||
|
||||
/** Pré-remplit l'image et le nœud à rejoindre depuis le cluster que cette interface administre. */
|
||||
const fromCluster = () =>
|
||||
act(async () => {
|
||||
const [st, info] = await Promise.all([
|
||||
garage.get<ClusterStatus>("GetClusterStatus"),
|
||||
garage.get<{ success?: Record<string, { nodeId?: string; addr?: string | null; garageVersion?: string }> }>("GetNodeInfo", { node: "self" }),
|
||||
]);
|
||||
const [key, me] = Object.entries(info.success ?? {})[0] ?? [];
|
||||
const ver = (me?.garageVersion ?? st.nodes[0]?.garageVersion ?? "").match(/\d+\.\d+\.\d+/)?.[0];
|
||||
setC((p) => ({
|
||||
...p,
|
||||
image: ver ? `dxflrs/garage:v${ver}` : p.image,
|
||||
peer: key ? `${me?.nodeId ?? key}@${me?.addr ?? "<hôte>:3901"}` : p.peer,
|
||||
}));
|
||||
}, "Version et nœud à rejoindre repris du cluster actuel : vérifiez l'adresse, puis collez son rpc_secret.");
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<PageHead title="Déploiement">
|
||||
<button onClick={fromCluster} title="Reprendre la version de Garage et le nœud actuel pour étendre ce cluster">
|
||||
Étendre le cluster actuel
|
||||
</button>
|
||||
</PageHead>
|
||||
<p className="muted">
|
||||
Décrivez la topologie voulue : les fichiers <code>docker-compose.yml</code> et <code>garage.toml</code> sont générés au fur et à mesure, avec les étapes pour assembler le cluster. Rien n'est déployé par cet outil.
|
||||
</p>
|
||||
|
||||
<section className="panel">
|
||||
<h3>Topologie</h3>
|
||||
<div className="grid2">
|
||||
<label className="field">
|
||||
<span>Mode</span>
|
||||
<select value={c.mode} onChange={(e) => set("mode", e.target.value as DeployConfig["mode"])}>
|
||||
<option value="hosts">Un serveur par nœud (recommandé)</option>
|
||||
<option value="single">Tous les nœuds sur un seul hôte (test)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Nombre de nœuds</span>
|
||||
<input type="number" min={1} max={MAX_NODES} value={c.nodes.length} onChange={(e) => setCount(Number(e.target.value))} />
|
||||
</label>
|
||||
</div>
|
||||
<div className="table-wrap" style={{ marginTop: "0.8rem" }}>
|
||||
<table className="table form-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nom</th>
|
||||
<th>Zone</th>
|
||||
{c.mode === "hosts" && <th>Adresse (IP ou nom)</th>}
|
||||
<th>Capacité (Go)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{c.nodes.map((n, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input type="text" value={n.name} onChange={(e) => setNode(i, { name: e.target.value })} aria-label={`Nom du nœud ${i + 1}`} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="text" value={n.zone} onChange={(e) => setNode(i, { zone: e.target.value })} aria-label={`Zone du nœud ${i + 1}`} />
|
||||
</td>
|
||||
{c.mode === "hosts" && (
|
||||
<td>
|
||||
<input type="text" value={n.host} placeholder="10.0.0.1x" onChange={(e) => setNode(i, { host: e.target.value })} aria-label={`Adresse du nœud ${i + 1}`} />
|
||||
</td>
|
||||
)}
|
||||
<td>
|
||||
<input type="number" min={0} value={n.capacityGB} onChange={(e) => setNode(i, { capacityGB: Number(e.target.value) })} aria-label={`Capacité du nœud ${i + 1}`} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="panel">
|
||||
<h3>Réglages</h3>
|
||||
<div className="grid2">
|
||||
<label className="field">
|
||||
<span>Facteur de réplication (copies de chaque donnée)</span>
|
||||
<input type="number" min={1} max={MAX_NODES} value={c.replication} onChange={(e) => set("replication", Number(e.target.value))} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Cohérence</span>
|
||||
<select value={c.consistency} onChange={(e) => set("consistency", e.target.value as Consistency)}>
|
||||
<option value="consistent">consistent (défaut)</option>
|
||||
<option value="degraded">degraded</option>
|
||||
<option value="dangerous">dangerous</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Image Docker</span>
|
||||
<input type="text" value={c.image} onChange={(e) => set("image", e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Région S3</span>
|
||||
<input type="text" value={c.s3Region} onChange={(e) => set("s3Region", e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Domaine S3 (facultatif)</span>
|
||||
<input type="text" value={c.s3Root} placeholder=".s3.exemple.org" onChange={(e) => set("s3Root", e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Domaine des sites web (facultatif)</span>
|
||||
<input type="text" value={c.webRoot} placeholder=".web.exemple.org" onChange={(e) => set("webRoot", e.target.value)} />
|
||||
</label>
|
||||
{c.mode === "hosts" && (
|
||||
<>
|
||||
<label className="field">
|
||||
<span>Dossier des métadonnées (sur le serveur)</span>
|
||||
<input type="text" value={c.metaDir} onChange={(e) => set("metaDir", e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Dossier des données (sur le serveur)</span>
|
||||
<input type="text" value={c.dataDir} onChange={(e) => set("dataDir", e.target.value)} />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{c.mode === "hosts" && (
|
||||
<label className="check-row">
|
||||
<input type="checkbox" checked={c.hostNetwork} onChange={(e) => set("hostNetwork", e.target.checked)} />
|
||||
<span>Réseau « host » au lieu de ports publiés (approche de la documentation de Garage)</span>
|
||||
</label>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="panel">
|
||||
<h3>Secrets et cluster à rejoindre</h3>
|
||||
<div className="form">
|
||||
<label className="field">
|
||||
<span>rpc_secret (commun à tous les nœuds)</span>
|
||||
<div className="row">
|
||||
<input type="text" className="grow mono" value={c.rpcSecret} onChange={(e) => set("rpcSecret", e.target.value.trim())} spellCheck={false} />
|
||||
<button className="icon-btn" onClick={() => set("rpcSecret", randomHex())} aria-label="Régénérer" title="Régénérer">
|
||||
<RefreshIcon />
|
||||
</button>
|
||||
<CopyButton text={c.rpcSecret} />
|
||||
</div>
|
||||
</label>
|
||||
<div className="grid2">
|
||||
<label className="field">
|
||||
<span>Jeton d'administration</span>
|
||||
<div className="row">
|
||||
<input type="text" className="grow mono" value={c.adminToken} onChange={(e) => set("adminToken", e.target.value.trim())} spellCheck={false} />
|
||||
<button className="icon-btn" onClick={() => set("adminToken", randomToken())} aria-label="Régénérer" title="Régénérer">
|
||||
<RefreshIcon />
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Jeton des métriques</span>
|
||||
<div className="row">
|
||||
<input type="text" className="grow mono" value={c.metricsToken} onChange={(e) => set("metricsToken", e.target.value.trim())} spellCheck={false} />
|
||||
<button className="icon-btn" onClick={() => set("metricsToken", randomToken())} aria-label="Régénérer" title="Régénérer">
|
||||
<RefreshIcon />
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Nœud existant à rejoindre (facultatif : étendre un cluster en place)</span>
|
||||
<input type="text" className="mono" value={c.peer} placeholder="<identifiant de 64 caractères>@hôte:3901" onChange={(e) => set("peer", e.target.value)} spellCheck={false} />
|
||||
</label>
|
||||
{c.peer.trim() && <p className="muted small-text">Pour étendre un cluster existant, remplacez rpc_secret par celui de ses nœuds (<code>rpc_secret</code> dans leur garage.toml).</p>}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="warns">
|
||||
{gen.warnings.map((w, i) => (
|
||||
<p className={`warnline ${w.level}`} key={i}>
|
||||
{w.text}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<section className="panel">
|
||||
<div className="row">
|
||||
<h3 className="grow">Fichiers générés</h3>
|
||||
<button onClick={() => gen.files.forEach((f, i) => setTimeout(() => download(f), i * 200))}>
|
||||
<DownloadIcon /> Tout télécharger
|
||||
</button>
|
||||
</div>
|
||||
<div className="chips">
|
||||
{gen.files.map((f, i) => (
|
||||
<button key={f.path} className={`chip ${f === file ? "on" : ""}`} onClick={() => setSel(i)}>
|
||||
{f.path}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{file && (
|
||||
<>
|
||||
<div className="row" style={{ margin: "0.3rem 0" }}>
|
||||
<code className="grow">{file.path}</code>
|
||||
<CopyButton text={file.content} label="Copier" />
|
||||
<button onClick={() => download(file)}>
|
||||
<DownloadIcon /> Télécharger
|
||||
</button>
|
||||
</div>
|
||||
<pre className="out tall">{file.content}</pre>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="panel">
|
||||
<h3>Étapes</h3>
|
||||
<ol className="steps">
|
||||
{gen.steps.map((s, i) => (
|
||||
<li key={i}>{s}</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<section className="panel">
|
||||
<div className="row">
|
||||
<h3 className="grow">Commandes équivalentes (CLI)</h3>
|
||||
<CopyButton text={gen.commands} label="Copier" />
|
||||
</div>
|
||||
<p className="muted small-text">
|
||||
Si vous préférez la ligne de commande à la page Cluster. Remplacez les repères <code><ID-…></code> par les identifiants relevés à l'étape précédente.
|
||||
</p>
|
||||
<pre className="out">{gen.commands}</pre>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
// Générateur de déploiement : fonction pure, sans dépendance (testée avec `npm test`).
|
||||
// Produit les fichiers (docker-compose.yml, garage.toml), les avertissements, les étapes et les
|
||||
// commandes équivalentes à partir d'une description de la topologie. Rien n'est envoyé au serveur.
|
||||
|
||||
export type Mode = "hosts" | "single";
|
||||
export type Consistency = "consistent" | "degraded" | "dangerous";
|
||||
|
||||
export interface NodeSpec {
|
||||
name: string;
|
||||
zone: string;
|
||||
/** Adresse (IP ou nom, sans port) à laquelle les autres nœuds joignent celui-ci. */
|
||||
host: string;
|
||||
capacityGB: number;
|
||||
}
|
||||
|
||||
export interface DeployConfig {
|
||||
/** hosts : un serveur par nœud (production). single : tous les nœuds sur un seul hôte (test). */
|
||||
mode: Mode;
|
||||
nodes: NodeSpec[];
|
||||
replication: number;
|
||||
consistency: Consistency;
|
||||
image: string;
|
||||
s3Region: string;
|
||||
rpcSecret: string;
|
||||
adminToken: string;
|
||||
metricsToken: string;
|
||||
/** id@hôte:port d'un nœud d'un cluster existant à rejoindre (facultatif). */
|
||||
peer: string;
|
||||
s3Root: string;
|
||||
webRoot: string;
|
||||
/** Dossiers sur l'hôte (modes « un serveur par nœud »). */
|
||||
metaDir: string;
|
||||
dataDir: string;
|
||||
hostNetwork: boolean;
|
||||
}
|
||||
|
||||
export interface GenFile {
|
||||
/** Chemin d'affichage, ex. « garage-1/garage.toml ». */
|
||||
path: string;
|
||||
/** Nom proposé au téléchargement (unique, à renommer sur le serveur). */
|
||||
download: string;
|
||||
content: string;
|
||||
lang: "yaml" | "toml";
|
||||
}
|
||||
|
||||
export interface Warn {
|
||||
level: "bad" | "warn" | "info";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface Generated {
|
||||
files: GenFile[];
|
||||
warnings: Warn[];
|
||||
steps: string[];
|
||||
commands: string;
|
||||
}
|
||||
|
||||
export const MAX_NODES = 9;
|
||||
|
||||
export const slug = (s: string) =>
|
||||
s
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "") || "garage";
|
||||
|
||||
/** Chaîne TOML / YAML entre guillemets (JSON.stringify est valide dans les deux). */
|
||||
const q = (s: string) => JSON.stringify(s);
|
||||
|
||||
const hostPort = (h: string, port: number) => `${h.includes(":") && !h.startsWith("[") ? `[${h}]` : h}:${port}`;
|
||||
|
||||
function randomBytes(n: number): Uint8Array {
|
||||
const b = new Uint8Array(n);
|
||||
crypto.getRandomValues(b);
|
||||
return b;
|
||||
}
|
||||
/** 32 octets en hexadécimal : format de rpc_secret. */
|
||||
export const randomHex = (n = 32) => Array.from(randomBytes(n), (x) => x.toString(16).padStart(2, "0")).join("");
|
||||
/** 32 octets en base64 : format des jetons d'administration. */
|
||||
export const randomToken = (n = 32) => btoa(String.fromCharCode(...randomBytes(n)));
|
||||
|
||||
export function defaultNodes(n: number): NodeSpec[] {
|
||||
return Array.from({ length: n }, (_, i) => ({ name: `garage-${i + 1}`, zone: `dc${i + 1}`, host: "", capacityGB: 500 }));
|
||||
}
|
||||
|
||||
export function defaultConfig(s3Region = "garage", image = "dxflrs/garage:v2.3.0"): DeployConfig {
|
||||
return {
|
||||
mode: "hosts",
|
||||
nodes: defaultNodes(3),
|
||||
replication: 3,
|
||||
consistency: "consistent",
|
||||
image,
|
||||
s3Region,
|
||||
rpcSecret: randomHex(),
|
||||
adminToken: randomToken(),
|
||||
metricsToken: randomToken(),
|
||||
peer: "",
|
||||
s3Root: "",
|
||||
webRoot: "",
|
||||
metaDir: "./meta",
|
||||
dataDir: "./data",
|
||||
hostNetwork: false,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Fichiers ------------------------------------------------------------------------
|
||||
|
||||
function tomlFor(c: DeployConfig, rpcAddr: string): string {
|
||||
const L: string[] = [
|
||||
`# Généré par Garage UI. rpc_secret et admin_token sont des secrets : chmod 600 sur ce fichier.`,
|
||||
`metadata_dir = "/var/lib/garage/meta"`,
|
||||
`data_dir = "/var/lib/garage/data"`,
|
||||
`db_engine = "lmdb"`,
|
||||
`metadata_auto_snapshot_interval = "6h"`,
|
||||
``,
|
||||
`# Doit être IDENTIQUE sur tous les nœuds du cluster.`,
|
||||
`replication_factor = ${c.replication}`,
|
||||
`consistency_mode = ${q(c.consistency)}`,
|
||||
`compression_level = 2`,
|
||||
``,
|
||||
`rpc_bind_addr = "0.0.0.0:3901"`,
|
||||
`rpc_public_addr = ${q(rpcAddr)}`,
|
||||
`rpc_secret = ${q(c.rpcSecret)}`,
|
||||
];
|
||||
if (c.peer.trim()) L.push(`bootstrap_peers = [${q(c.peer.trim())}]`);
|
||||
L.push(``, `[s3_api]`, `s3_region = ${q(c.s3Region)}`, `api_bind_addr = "0.0.0.0:3900"`);
|
||||
if (c.s3Root.trim()) L.push(`root_domain = ${q(c.s3Root.trim())}`);
|
||||
L.push(``, `[s3_web]`, `bind_addr = "0.0.0.0:3902"`);
|
||||
if (c.webRoot.trim()) L.push(`root_domain = ${q(c.webRoot.trim())}`);
|
||||
L.push(`index = "index.html"`, ``, `[admin]`, `# Port d'administration : à n'ouvrir qu'à Garage UI.`, `api_bind_addr = "0.0.0.0:3903"`);
|
||||
L.push(`admin_token = ${q(c.adminToken)}`, `metrics_token = ${q(c.metricsToken)}`, ``);
|
||||
return L.join("\n");
|
||||
}
|
||||
|
||||
function composeHost(c: DeployConfig, n: NodeSpec): string {
|
||||
const L = [
|
||||
`# Nœud ${n.name} (zone ${n.zone}). À enregistrer sur son serveur avec garage.toml, dans le même dossier.`,
|
||||
`services:`,
|
||||
` garage:`,
|
||||
` image: ${q(c.image)}`,
|
||||
` container_name: ${slug(n.name)}`,
|
||||
` restart: unless-stopped`,
|
||||
];
|
||||
if (c.hostNetwork) L.push(` network_mode: host`);
|
||||
else L.push(` ports:`, ` - "3900:3900" # API S3`, ` - "3901:3901" # RPC entre nœuds`, ` - "3902:3902" # sites web`, ` - "3903:3903" # administration (Garage UI)`);
|
||||
L.push(` volumes:`, ` - ./garage.toml:/etc/garage.toml:ro`, ` - ${q(`${c.metaDir}:/var/lib/garage/meta`)}`, ` - ${q(`${c.dataDir}:/var/lib/garage/data`)}`, ``);
|
||||
return L.join("\n");
|
||||
}
|
||||
|
||||
function composeSingle(c: DeployConfig): string {
|
||||
const L = [
|
||||
`# Test : tous les nœuds sur un même hôte. Aucune tolérance à la panne de cet hôte ou de son disque.`,
|
||||
`services:`,
|
||||
];
|
||||
c.nodes.forEach((n, i) => {
|
||||
const s = slug(n.name);
|
||||
const p = (base: number) => base + 10 * i;
|
||||
L.push(
|
||||
` ${s}:`,
|
||||
` image: ${q(c.image)}`,
|
||||
` container_name: ${s}`,
|
||||
` restart: unless-stopped`,
|
||||
` ports:`,
|
||||
` - "${p(3900)}:3900" # API S3`,
|
||||
` - "${p(3901)}:3901" # RPC (les nœuds se parlent par le réseau Docker)`,
|
||||
` - "${p(3902)}:3902" # sites web`,
|
||||
` - "${p(3903)}:3903" # administration`,
|
||||
` volumes:`,
|
||||
` - ./${s}.toml:/etc/garage.toml:ro`,
|
||||
` - ./${s}/meta:/var/lib/garage/meta`,
|
||||
` - ./${s}/data:/var/lib/garage/data`,
|
||||
``,
|
||||
);
|
||||
});
|
||||
return L.join("\n");
|
||||
}
|
||||
|
||||
// --- Génération ------------------------------------------------------------------------
|
||||
|
||||
export function generate(c: DeployConfig): Generated {
|
||||
const files: GenFile[] = [];
|
||||
const warnings: Warn[] = [];
|
||||
const W = (level: Warn["level"], text: string) => warnings.push({ level, text });
|
||||
const single = c.mode === "single";
|
||||
const names = c.nodes.map((n) => slug(n.name));
|
||||
const addr = (n: NodeSpec) => (single ? hostPort(slug(n.name), 3901) : n.host.trim() ? hostPort(n.host.trim(), 3901) : `<ADRESSE-DE-${slug(n.name).toUpperCase()}>:3901`);
|
||||
|
||||
// Fichiers
|
||||
if (single) {
|
||||
files.push({ path: "docker-compose.yml", download: "docker-compose.yml", content: composeSingle(c), lang: "yaml" });
|
||||
c.nodes.forEach((n) => files.push({ path: `${slug(n.name)}.toml`, download: `${slug(n.name)}.toml`, content: tomlFor(c, addr(n)), lang: "toml" }));
|
||||
} else {
|
||||
c.nodes.forEach((n) => {
|
||||
const s = slug(n.name);
|
||||
files.push({ path: `${s}/docker-compose.yml`, download: `${s}_docker-compose.yml`, content: composeHost(c, n), lang: "yaml" });
|
||||
files.push({ path: `${s}/garage.toml`, download: `${s}_garage.toml`, content: tomlFor(c, addr(n)), lang: "toml" });
|
||||
});
|
||||
}
|
||||
|
||||
// Avertissements
|
||||
const count = c.nodes.length;
|
||||
const zones = new Set(c.nodes.map((n) => n.zone.trim()));
|
||||
if (!c.peer.trim() && c.replication > count) W("bad", `Le facteur de réplication (${c.replication}) dépasse le nombre de nœuds (${count}) : le cluster ne pourra pas écrire de données.`);
|
||||
if (c.replication < 1) W("bad", "Le facteur de réplication doit être au moins 1.");
|
||||
if (c.replication === 1) W("warn", "Réplication à 1 : aucune redondance. La panne d'un nœud rend ses données indisponibles. À réserver aux tests.");
|
||||
if (c.replication > 1 && zones.size < Math.min(c.replication, count)) W("warn", `Seulement ${zones.size} zone(s) pour ${c.replication} copies : Garage ne pourra pas toujours placer les copies dans des zones différentes. Une zone par serveur (ou par site) est recommandée.`);
|
||||
if (new Set(names).size !== names.length) W("bad", "Deux nœuds ont le même nom (une fois normalisé) : les noms doivent être uniques.");
|
||||
if (c.nodes.some((n) => !n.zone.trim())) W("bad", "Chaque nœud doit avoir une zone.");
|
||||
if (single) W("warn", "Tous les nœuds sur le même hôte : la réplication ne protège pas de la perte de cet hôte ni de son disque. Pour apprendre ou tester uniquement.");
|
||||
else {
|
||||
const missing = c.nodes.filter((n) => !n.host.trim()).map((n) => n.name);
|
||||
if (missing.length) W("bad", `Adresse manquante pour : ${missing.join(", ")}. Les fichiers contiennent un repère <ADRESSE-DE-…> à remplacer.`);
|
||||
const hosts = c.nodes.map((n) => n.host.trim()).filter(Boolean);
|
||||
if (new Set(hosts).size !== hosts.length) W("warn", "Plusieurs nœuds ont la même adresse : sur un même hôte, utilisez plutôt le mode « tous les nœuds sur un hôte » ou des ports différents.");
|
||||
}
|
||||
if (c.peer.trim()) {
|
||||
W("info", "Rejoindre un cluster existant : replication_factor doit être identique à celui des nœuds déjà en place, et rpc_secret aussi. Changer le facteur d'un cluster existant n'est pas officiellement supporté par Garage (voir la documentation, « replication_factor »).");
|
||||
if (!/^[0-9a-f]{64}@.+:\d+$/i.test(c.peer.trim())) W("bad", "Le nœud à rejoindre doit être de la forme <identifiant de 64 caractères>@<hôte>:<port>.");
|
||||
}
|
||||
if (!/^[0-9a-f]{64}$/i.test(c.rpcSecret)) W("bad", "rpc_secret doit être une chaîne hexadécimale de 64 caractères (32 octets).");
|
||||
if (c.nodes.some((n) => !(n.capacityGB > 0))) W("warn", "Capacité à renseigner pour chaque nœud : elle sert à l'assignation des rôles.");
|
||||
W("info", "Les secrets sont générés dans votre navigateur et ne sont pas envoyés au serveur de Garage UI. Gardez ces fichiers privés. Le port 3903 (administration) ne doit être joignable que par Garage UI.");
|
||||
|
||||
// Étapes
|
||||
const steps: string[] = [];
|
||||
steps.push(
|
||||
single
|
||||
? "Enregistrez docker-compose.yml et les fichiers .toml dans un même dossier, puis lancez : docker compose up -d."
|
||||
: `Sur chaque serveur : créez un dossier, enregistrez-y docker-compose.yml et garage.toml (téléchargés sous le nom <nœud>_… : renommez-les), puis lancez : docker compose up -d.`,
|
||||
);
|
||||
if (c.peer.trim()) {
|
||||
steps.push("Les nouveaux nœuds contactent le cluster existant au démarrage (bootstrap_peers) : ils apparaissent dans la page Cluster, sans rôle.");
|
||||
} else {
|
||||
steps.push("Relevez l'identifiant de chaque nœud (commande ci-dessous), puis connectez-les entre eux : page Cluster, « Connecter un nœud » (id@adresse:3901). Une connexion par nœud suffit, les autres se découvrent ensuite.");
|
||||
}
|
||||
steps.push("Page Cluster : assignez à chaque nœud sa zone et sa capacité (icône +), puis « Appliquer ». Garage calcule la répartition et rééquilibre les données.");
|
||||
steps.push("Vérifiez : tous les nœuds en ligne, partitions saines sur la Vue d'ensemble. Le rééquilibrage peut durer (page Maintenance : tâches de fond).");
|
||||
|
||||
// Commandes équivalentes (CLI)
|
||||
const first = names[0] ?? "garage-1";
|
||||
const C: string[] = [];
|
||||
if (!c.peer.trim()) {
|
||||
C.push("# 1. Identifiant de chaque nœud (id@adresse)");
|
||||
names.forEach((s) => C.push(`docker exec ${s} /garage node id`));
|
||||
C.push("", `# 2. Connexion (depuis ${first} ; une fois par autre nœud)`);
|
||||
names.slice(1).forEach((s) => C.push(`docker exec ${first} /garage node connect <ID-${s}>@${addr(c.nodes[names.indexOf(s)])}`));
|
||||
C.push("");
|
||||
}
|
||||
C.push(`# ${c.peer.trim() ? "1" : "3"}. Rôles : zone (-z), capacité en octets (-c)`);
|
||||
c.nodes.forEach((n) => C.push(`docker exec ${first} /garage layout assign -z ${n.zone.trim() || "<zone>"} -c ${Math.round((n.capacityGB || 0) * 1e9)} <ID-${slug(n.name)}>`));
|
||||
C.push("", `# ${c.peer.trim() ? "2" : "4"}. Vérifier puis appliquer (--version : version actuelle du layout + 1, soit 1 pour un cluster neuf)`);
|
||||
C.push(`docker exec ${first} /garage layout show`, `docker exec ${first} /garage layout apply --version ${c.peer.trim() ? "<N+1>" : 1}`);
|
||||
|
||||
return { files, warnings, steps, commands: C.join("\n") };
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export const OverviewIcon = pap(P.Pie);
|
||||
export const BucketIcon = pap(P.Archive);
|
||||
export const MaintenanceIcon = pap(P.Gears);
|
||||
export const GlobeIcon = pap(P.Globe);
|
||||
export const DeployIcon = pap(P.Code);
|
||||
|
||||
/** Lucide « server » */
|
||||
export const ClusterIcon = icon(
|
||||
|
||||
@@ -1072,3 +1072,37 @@ pre.out {
|
||||
.panel > .bar {
|
||||
margin-bottom: 0.8rem;
|
||||
}
|
||||
|
||||
/* --- Déploiement ------------------------------------------------------------------------------ */
|
||||
.form-table input {
|
||||
width: 100%;
|
||||
}
|
||||
.warns {
|
||||
margin-bottom: 1.2rem;
|
||||
}
|
||||
.warnline {
|
||||
margin: 0.4rem 0;
|
||||
padding: 0.55rem 0.8rem;
|
||||
border-radius: var(--radius-sm);
|
||||
border-left: 4px solid var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
.warnline.warn {
|
||||
border-left-color: var(--warn);
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.warnline.bad {
|
||||
border-left-color: var(--danger);
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
}
|
||||
pre.out.tall {
|
||||
max-height: 30rem;
|
||||
}
|
||||
.steps {
|
||||
margin: 0;
|
||||
padding-left: 1.3rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Tests du générateur : `npm test` (Node 23+ exécute les .ts directement).
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { defaultConfig, defaultNodes, generate, slug } from "../src/deployGen.ts";
|
||||
|
||||
const base = () => {
|
||||
const c = defaultConfig("garage-west-naoned-1", "dxflrs/garage:v2.3.0");
|
||||
c.nodes = defaultNodes(3).map((n, i) => ({ ...n, host: `10.0.0.${11 + i}` }));
|
||||
return c;
|
||||
};
|
||||
const byPath = (g, p) => g.files.find((f) => f.path === p)?.content ?? assert.fail(`fichier absent : ${p}`);
|
||||
const has = (g, level, re) => g.warnings.some((w) => w.level === level && re.test(w.text));
|
||||
|
||||
test("3 serveurs : un compose et un toml par nœud, réplication 3, secret commun", () => {
|
||||
const g = generate(base());
|
||||
assert.equal(g.files.length, 6);
|
||||
const t1 = byPath(g, "garage-1/garage.toml");
|
||||
const t2 = byPath(g, "garage-2/garage.toml");
|
||||
assert.match(t1, /replication_factor = 3/);
|
||||
assert.match(t1, /rpc_public_addr = "10\.0\.0\.11:3901"/);
|
||||
assert.match(t2, /rpc_public_addr = "10\.0\.0\.12:3901"/);
|
||||
const secret = (t) => t.match(/rpc_secret = "([0-9a-f]{64})"/)?.[1];
|
||||
assert.ok(secret(t1) && secret(t1) === secret(t2));
|
||||
assert.match(t1, /s3_region = "garage-west-naoned-1"/);
|
||||
assert.doesNotMatch(t1, /bootstrap_peers/);
|
||||
assert.match(byPath(g, "garage-1/docker-compose.yml"), /image: "dxflrs\/garage:v2\.3\.0"/);
|
||||
assert.ok(!g.warnings.some((w) => w.level === "bad"), JSON.stringify(g.warnings));
|
||||
});
|
||||
|
||||
test("réplication supérieure au nombre de nœuds : erreur", () => {
|
||||
const c = base();
|
||||
c.replication = 4;
|
||||
assert.ok(has(generate(c), "bad", /dépasse le nombre de nœuds/));
|
||||
});
|
||||
|
||||
test("adresse manquante : erreur et repère dans le fichier", () => {
|
||||
const c = base();
|
||||
c.nodes[1].host = "";
|
||||
const g = generate(c);
|
||||
assert.ok(has(g, "bad", /Adresse manquante pour : garage-2/));
|
||||
assert.match(byPath(g, "garage-2/garage.toml"), /<ADRESSE-DE-GARAGE-2>:3901/);
|
||||
});
|
||||
|
||||
test("mode un seul hôte : ports décalés, adresses RPC par nom de service, avertissement", () => {
|
||||
const c = base();
|
||||
c.mode = "single";
|
||||
const g = generate(c);
|
||||
const compose = byPath(g, "docker-compose.yml");
|
||||
assert.match(compose, /"3900:3900"/);
|
||||
assert.match(compose, /"3910:3900"/);
|
||||
assert.match(compose, /"3920:3900"/);
|
||||
assert.match(byPath(g, "garage-3.toml"), /rpc_public_addr = "garage-3:3901"/);
|
||||
assert.ok(has(g, "warn", /même hôte/));
|
||||
});
|
||||
|
||||
test("rejoindre un cluster : bootstrap_peers, mise en garde sur le facteur, format vérifié", () => {
|
||||
const c = base();
|
||||
c.peer = `${"ab".repeat(32)}@10.0.0.2:3901`;
|
||||
const g = generate(c);
|
||||
assert.match(byPath(g, "garage-1/garage.toml"), /bootstrap_peers = \["abab[0-9a-f]+@10\.0\.0\.2:3901"\]/);
|
||||
assert.ok(has(g, "info", /identique/));
|
||||
assert.ok(!has(g, "bad", /identifiant de 64/));
|
||||
c.peer = "garage:3901";
|
||||
assert.ok(has(generate(c), "bad", /identifiant de 64/));
|
||||
});
|
||||
|
||||
test("réplication 1 et zones insuffisantes : avertissements", () => {
|
||||
const c = base();
|
||||
c.replication = 1;
|
||||
assert.ok(has(generate(c), "warn", /aucune redondance/));
|
||||
c.replication = 3;
|
||||
c.nodes.forEach((n) => (n.zone = "dc1"));
|
||||
assert.ok(has(generate(c), "warn", /zone\(s\) pour 3 copies/));
|
||||
});
|
||||
|
||||
test("réseau host, domaines, IPv6, secrets entre guillemets", () => {
|
||||
const c = base();
|
||||
c.hostNetwork = true;
|
||||
c.s3Root = ".s3.exemple.org";
|
||||
c.nodes[0].host = "fd00::1";
|
||||
const g = generate(c);
|
||||
const compose = byPath(g, "garage-1/docker-compose.yml");
|
||||
assert.match(compose, /network_mode: host/);
|
||||
assert.doesNotMatch(compose, /ports:/);
|
||||
const t1 = byPath(g, "garage-1/garage.toml");
|
||||
assert.match(t1, /root_domain = "\.s3\.exemple\.org"/);
|
||||
assert.match(t1, /rpc_public_addr = "\[fd00::1\]:3901"/);
|
||||
});
|
||||
|
||||
test("commandes CLI : capacités en octets, version de layout", () => {
|
||||
const g = generate(base());
|
||||
assert.match(g.commands, /layout assign -z dc1 -c 500000000000 <ID-garage-1>/);
|
||||
assert.match(g.commands, /layout apply --version 1/);
|
||||
assert.match(g.commands, /node connect <ID-garage-2>@10\.0\.0\.12:3901/);
|
||||
});
|
||||
|
||||
test("slug", () => {
|
||||
assert.equal(slug("Garage Nœud 1"), "garage-n-ud-1");
|
||||
assert.equal(slug("***"), "garage");
|
||||
});
|
||||
Reference in new issue
Block a user