diff --git a/.env.example b/.env.example index 54c8f0e..cac4700 100644 --- a/.env.example +++ b/.env.example @@ -8,6 +8,8 @@ UI_PASSWORD= # Affichage des exemples de configuration client (rclone, aws cli). GARAGE_S3_ENDPOINT=https://s3.example.org GARAGE_S3_REGION=garage +# API S3 vue du serveur garage-ui, pour vider un bucket (défaut : hôte de GARAGE_ADMIN_URL, port 3900). +# GARAGE_S3_API_URL=http://garage:3900 # Console CLI (facultatif) : chemin du binaire garage et secret RPC du cluster. GARAGE_BIN=/garage # hôte:port suffit, l'identifiant du noeud est ajouté automatiquement. diff --git a/README.md b/README.md index 65e1cb2..a46b411 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Interface web d'administration pour un cluster [Garage](https://garagehq.deuxfleurs.fr/) (stockage S3 auto-hébergé), dans la même charte que [Up And Down](https://github.com/vLab-BZH/upandown) : thème clair et sombre, icônes [Papicons](https://github.com/PapillonApp/papicons), même feuille de style. - **Vue d'ensemble** : santé du cluster, partitions, nœuds et occupation des disques, plus gros buckets. -- **Buckets** : création, alias globaux, clés autorisées (lecture, écriture, propriétaire), quotas (taille, nombre d'objets), site web statique, nettoyage des envois multipart inachevés, suppression. +- **Buckets** : création, alias globaux, clés autorisées (lecture, écriture, propriétaire), quotas (taille, nombre d'objets), site web statique, nettoyage des envois multipart inachevés, vidage (tous les objets et envois inachevés, avec avancement), suppression. - **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. @@ -22,6 +22,8 @@ Un seul binaire Go (bibliothèque standard, aucune dépendance) qui embarque le 2. il relaie `/api/garage/v2/*` vers l'API d'administration de Garage en ajoutant le jeton : **le jeton n'atteint jamais le navigateur**, et seuls les chemins `/v2/` sont relayés ; 3. il exécute, pour la console, le binaire `garage` avec une liste blanche de sous-commandes (`status`, `stats`, `repair`, `worker`, `block`, `meta`, `layout`, `bucket`, `key`, `node`), sans shell, avec délai maximal et sortie plafonnée. +Le vidage d'un bucket est la seule fonction qui sort de ce rôle de relais : l'API d'administration ne sait pas supprimer d'objets, le serveur passe donc par l'API S3 (`GARAGE_S3_API_URL`). Il crée une clé temporaire (`garage-ui-vidage-...`), lui donne lecture et écriture sur le bucket, supprime les objets par lots de 1000 (`DeleteObjects`), nettoie les envois multipart inachevés (`CleanupIncompleteUploads`, sans limite d'âge), puis supprime la clé, même en cas d'erreur ou d'interruption. Garage n'implémente pas le versioning S3 : il n'y a pas de versions à purger. + Cette interface donne les pleins pouvoirs sur le cluster : ne l'exposez que derrière HTTPS et une authentification (la vôtre, ou un reverse proxy avec `UI_PASSWORD` vide). ## Démarrage @@ -54,7 +56,8 @@ La console CLI utilise `GARAGE_RPC_HOST` (`hôte:3901`) et `GARAGE_RPC_SECRET` ( | `SESSION_SECRET` / `SESSION_TTL` | aléatoire / `24h` | Signature et durée de la session | | `PUBLIC_URL` | | URL publique (`https://...` : cookie `Secure`) | | `TITLE` | `Garage UI` | Titre affiché | -| `GARAGE_S3_ENDPOINT` / `GARAGE_S3_REGION` | | Exemples de configuration client | +| `GARAGE_S3_ENDPOINT` / `GARAGE_S3_REGION` | / `garage` | Exemples de configuration client ; la région sert aussi à signer les requêtes S3 du vidage (`s3_region` de `garage.toml`) | +| `GARAGE_S3_API_URL` | `http://:3900` | API S3 vue du serveur, pour le vidage des buckets (`api_bind_addr` de `[s3_api]`) | | `GARAGE_BIN` / `GARAGE_CONFIG` | `/garage` si présent | CLI : binaire et fichier `garage.toml` (`-c`) | | `GARAGE_RPC_HOST` / `GARAGE_RPC_SECRET` | `:3901` / | CLI : adresse RPC (`hôte:port` ou `id@hôte:port`) et secret | | `LISTEN_ADDR` | `:8080` | Écoute | diff --git a/cmd/mockgarage/main.go b/cmd/mockgarage/main.go index 9c95a44..f2a5158 100644 --- a/cmd/mockgarage/main.go +++ b/cmd/mockgarage/main.go @@ -6,10 +6,13 @@ package main import ( "encoding/json" + "encoding/xml" "fmt" + "io" "log" "net/http" "os" + "sort" "strings" "sync" "time" @@ -33,6 +36,18 @@ type bucket struct { MaxSize *int64 MaxObjs *int64 Keys map[string]perm + Names map[string]bool // objets côté S3, créés à la première requête S3 (Objects noms factices) +} + +// s3Names renvoie les objets du bucket, générés à partir de Objects au premier appel. +func (b *bucket) s3Names() map[string]bool { + if b.Names == nil { + b.Names = map[string]bool{} + for i := 0; i < b.Objects; i++ { + b.Names[fmt.Sprintf("donnees/objet-%06d.bin", i)] = true + } + } + return b.Names } type key struct { @@ -330,6 +345,85 @@ func handle(token string) http.HandlerFunc { } } +// handleS3 imite juste ce dont le vidage a besoin : ListObjectsV2 et DeleteObjects, en style path. +// La signature n'est pas vérifiée, seule la présence d'une clé connue l'est. +func handleS3(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + auth := r.Header.Get("Authorization") + known := false + for id := range keys { + if strings.Contains(auth, "Credential="+id+"/") { + known = true + } + } + if !known { + w.WriteHeader(403) + fmt.Fprint(w, `InvalidAccessKeyIdclé inconnue`) + return + } + name := strings.Trim(r.URL.Path, "/") + var b *bucket + for _, x := range buckets { + for _, a := range x.Aliases { + if a == name { + b = x + } + } + } + if b == nil { + w.WriteHeader(404) + fmt.Fprint(w, `NoSuchBucketbucket introuvable`) + return + } + q := r.URL.Query() + names := b.s3Names() + log.Printf("S3 %s /%s?%s", r.Method, name, r.URL.RawQuery) + switch { + case r.Method == "GET" && q.Get("list-type") == "2": + var all []string + for k := range names { + if k > q.Get("continuation-token") { + all = append(all, k) + } + } + sort.Strings(all) + trunc := len(all) > 1000 + if trunc { + all = all[:1000] + } + fmt.Fprint(w, ``) + for _, k := range all { + fmt.Fprintf(w, `%s`, k) + } + if trunc { + fmt.Fprintf(w, `true%s`, all[len(all)-1]) + } + fmt.Fprint(w, ``) + case r.Method == "POST" && q.Has("delete"): + var in struct { + Objects []struct{ Key string } `xml:"Object"` + } + data, _ := io.ReadAll(r.Body) + _ = xml.Unmarshal(data, &in) + for _, o := range in.Objects { + if names[o.Key] { + delete(names, o.Key) + b.Objects-- + if b.Objects > 0 { + b.Bytes -= b.Bytes / int64(b.Objects+1) + } else { + b.Bytes = 0 + } + } + } + time.Sleep(300 * time.Millisecond) // pour voir l'avancement dans l'interface + fmt.Fprint(w, ``) + default: + w.WriteHeader(501) + } +} + func main() { token := "test" if v := os.Getenv("MOCK_TOKEN"); v != "" { @@ -339,7 +433,12 @@ func main() { if v := os.Getenv("MOCK_ADDR"); v != "" { addr = v } - log.Printf("mockgarage sur %s (jeton %q)", addr, token) + s3Addr := ":3900" + if v := os.Getenv("MOCK_S3_ADDR"); v != "" { + s3Addr = v + } + log.Printf("mockgarage sur %s (jeton %q), S3 sur %s", addr, token, s3Addr) + go func() { log.Fatal(http.ListenAndServe(s3Addr, http.HandlerFunc(handleS3))) }() http.Handle("/v2/", handle(token)) log.Fatal(http.ListenAndServe(addr, nil)) } diff --git a/cmd/server/main.go b/cmd/server/main.go index c10f54f..5f90e32 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -51,6 +51,7 @@ type config struct { title string s3Endpoint string s3Region string + s3URL *url.URL // API S3 vue du serveur (vidage des buckets), distincte de l'endpoint public cliBin string cliConfig string rpcHost string // GARAGE_RPC_HOST : [identifiant@]hôte:port @@ -91,6 +92,10 @@ func loadConfig() (*config, error) { return nil, fmt.Errorf("GARAGE_ADMIN_URL invalide") } c.adminURL = u + s3 := env("GARAGE_S3_API_URL", "http://"+u.Hostname()+":3900") + if c.s3URL, err = url.Parse(s3); err != nil || c.s3URL.Host == "" { + return nil, fmt.Errorf("GARAGE_S3_API_URL invalide") + } if d, err := time.ParseDuration(env("SESSION_TTL", "24h")); err == nil && d > 0 { c.sessionTTL = d } @@ -437,6 +442,7 @@ func (c *config) routes() http.Handler { mux.HandleFunc("POST /api/login", c.handleLogin) mux.HandleFunc("POST /api/logout", c.handleLogout) mux.HandleFunc("POST /api/cli", c.guard(c.handleCLI)) + mux.HandleFunc("POST /api/buckets/empty", c.guard(c.handleEmptyBucket)) mux.Handle("/api/garage/", c.guard(c.garageProxy().ServeHTTP)) mux.Handle("/", spa()) return mux diff --git a/docker-compose.yml b/docker-compose.yml index 91011c2..a3a40cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,6 +18,8 @@ services: # Exemples de configuration client affichés sur la page d'une clé. GARAGE_S3_ENDPOINT: ${GARAGE_S3_ENDPOINT:-} GARAGE_S3_REGION: ${GARAGE_S3_REGION:-garage} + # API S3 interne, utilisée pour vider un bucket (clé temporaire créée puis supprimée). + GARAGE_S3_API_URL: ${GARAGE_S3_API_URL:-http://garage:3900} # Console CLI : le binaire garage est dans l'image ; il lui faut l'adresse RPC et le secret. GARAGE_RPC_HOST: ${GARAGE_RPC_HOST:-garage:3901} GARAGE_RPC_SECRET: ${GARAGE_RPC_SECRET:-} diff --git a/frontend/src/Buckets.tsx b/frontend/src/Buckets.tsx index 151751d..4097298 100644 --- a/frontend/src/Buckets.tsx +++ b/frontend/src/Buckets.tsx @@ -1,9 +1,9 @@ -import { useState } from "react"; -import { garage, getBucket, bucketName, type BucketInfo, type BucketListItem, type KeyListItem, type Perm } from "./api"; +import { useRef, useState } from "react"; +import { garage, getBucket, bucketName, emptyBucket, errMsg, type BucketInfo, type EmptyProgress, type BucketListItem, type KeyListItem, type Perm } from "./api"; import { GIB, fmtDate, fmtNum, fmtSize } from "./format"; import { BucketIcon, GlobeIcon } from "./gicons"; -import { CloseIcon, PlusIcon, RefreshIcon, TrashIcon } from "./icons"; -import { Confirm, CopyButton, Loading, Modal, Mono, PageHead, Status, UsageBar, useAct, useLoad } from "./ui"; +import { CloseIcon, PlusIcon, RefreshIcon, TrashFullIcon, TrashIcon } from "./icons"; +import { Confirm, CopyButton, Loading, Modal, Mono, PageHead, Status, UsageBar, useAct, useLoad, useNotify } from "./ui"; // --- Liste ------------------------------------------------------------------------- @@ -138,6 +138,7 @@ export function BucketPage({ id }: { id: string }) { const { data: b, error, loading, reload } = useLoad(() => getBucket(id), [id]); const keys = useLoad(() => garage.get("ListKeys"), []); const [confirmDelete, setConfirmDelete] = useState(false); + const [emptying, setEmptying] = useState(false); const [alias, setAlias] = useState(""); const [addKey, setAddKey] = useState(""); @@ -152,6 +153,14 @@ export function BucketPage({ id }: { id: string }) { return (
+ @@ -291,12 +300,29 @@ export function BucketPage({ id }: { id: string }) { + {emptying && ( + { + setEmptying(false); + reload(); + }} + /> + )} + {confirmDelete && ( - Le bucket {name} sera supprimé définitivement. Garage refuse de supprimer un bucket qui contient encore des objets. + Le bucket {name} sera supprimé définitivement. Garage refuse de supprimer un bucket qui contient encore des objets + {b.objects > 0 && ( + <> + {" "} + : celui-ci en contient {fmtNum(b.objects)}, videz-le d'abord (bouton « Vider ») + + )} + .

} confirmLabel="Supprimer" @@ -312,6 +338,90 @@ export function BucketPage({ id }: { id: string }) { ); } +/** Vidage : confirmation par saisie du nom, puis avancement lot par lot. */ +function EmptyBucket({ b, onClose }: { b: BucketInfo; onClose: () => void }) { + const notify = useNotify(); + const name = bucketName(b); + const [typed, setTyped] = useState(""); + const [p, setP] = useState(null); + const [running, setRunning] = useState(false); + const [error, setError] = useState(""); + const abort = useRef(null); + const finished = p?.phase === "done"; + // Le compteur d'objets de Garage est approximatif (mis à jour en tâche de fond) : borné à 99 % avant la fin. + const pct = finished ? 100 : Math.min(99, Math.round(((p?.deleted ?? 0) / Math.max(b.objects, 1)) * 100)); + + const start = async () => { + setRunning(true); + setError(""); + abort.current = new AbortController(); + try { + const r = await emptyBucket(b.id, setP, abort.current.signal); + notify(`Bucket « ${name} » vidé : ${fmtNum(r.deleted)} objets supprimés`, r.failed ? undefined : "ok"); + } catch (e) { + setError(abort.current.signal.aborted ? "Vidage interrompu." : errMsg(e)); + } finally { + setRunning(false); + } + }; + const close = () => { + if (running && !confirm("Interrompre le vidage en cours ? Les objets déjà supprimés le restent.")) return; + abort.current?.abort(); + onClose(); + }; + + return ( + +
+

+ Tous les objets du bucket {name} ({fmtNum(b.objects)} objets, {fmtSize(b.bytes)}) seront supprimés définitivement, ainsi que les envois + multipart inachevés. Le bucket, ses alias, clés, quotas et réglages sont conservés. +

+

+ Garage n'a pas de versioning S3 ni de corbeille : cette action est irréversible. L'interface passe par l'API S3 avec une clé temporaire, supprimée à la fin. +

+
+ {!p && !running && ( + + )} + {(p || running) && ( +
+
+ +
+

+ {finished ? "Terminé :" : p?.phase === "uploads" ? "Nettoyage des envois inachevés…" : "Suppression en cours…"} {fmtNum(p?.deleted ?? 0)} objets supprimés + {p?.failed ? `, ${fmtNum(p.failed)} en échec` : ""} + {finished && p?.uploadsDeleted ? `, ${fmtNum(p.uploadsDeleted)} envois inachevés nettoyés` : ""}. +

+ {p?.errors?.length ? ( +
    + {p.errors.map((e) => ( +
  • {e}
  • + ))} +
+ ) : null} +
+ )} + {error &&

{error}

} +
+ + + {!finished && ( + + )} +
+
+ ); +} + function QuotaForm({ b, onSave }: { b: BucketInfo; onSave: (q: { maxSize: number | null; maxObjects: number | null }) => void }) { const [size, setSize] = useState(b.quotas?.maxSize ? String(+(b.quotas.maxSize / GIB).toFixed(2)) : ""); const [objs, setObjs] = useState(b.quotas?.maxObjects ? String(b.quotas.maxObjects) : ""); diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 7652ff5..86aaec1 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -173,6 +173,54 @@ export const appApi = { cli: (args: string[]) => req<{ exitCode: number; output: string; ms: number }>("/api/cli", { method: "POST", body: JSON.stringify({ args }) }), }; +/** Avancement du vidage d'un bucket (une ligne NDJSON par lot de 1000 objets). */ +export interface EmptyProgress { + phase: "start" | "objects" | "uploads" | "done" | "error"; + deleted: number; + failed: number; + uploadsDeleted?: number; + errors?: string[]; + message?: string; +} + +/** + * Vide un bucket (objets puis envois multipart inachevés). Le serveur passe par l'API S3 avec une + * clé temporaire, et diffuse l'avancement : onProgress est appelé à chaque lot. + */ +export async function emptyBucket(id: string, onProgress: (p: EmptyProgress) => void, signal?: AbortSignal): Promise { + const r = await fetch(`/api/buckets/empty${qs({ id })}`, { method: "POST", credentials: "same-origin", headers: { "X-Requested-With": "garage-ui" }, signal }); + if (!r.ok || !r.body) { + let msg = r.statusText; + try { + msg = (await r.json()).message || msg; + } catch { + /* réponse non JSON */ + } + throw new ApiError(r.status, msg); + } + const reader = r.body.getReader(); + const dec = new TextDecoder(); + let buf = ""; + let last: EmptyProgress | null = null; + for (;;) { + const { value, done } = await reader.read(); + if (value) buf += dec.decode(value, { stream: true }); + let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + last = JSON.parse(line) as EmptyProgress; + onProgress(last); + } + if (done) break; + } + if (!last) throw new ApiError(502, "Réponse vide du serveur"); + if (last.phase === "error") throw new ApiError(502, last.message || "Échec du vidage"); + if (last.phase !== "done") throw new ApiError(502, `Vidage interrompu après ${last.deleted} objets supprimés`); + return last; +} + export const bucketName = (b: { id: string; globalAliases?: string[]; localAliases?: { alias: string }[] }) => b.globalAliases?.[0] ?? b.localAliases?.[0]?.alias ?? b.id.slice(0, 12);