Console: l'identifiant du noeud est ajoute automatiquement a GARAGE_RPC_HOST (GetNodeInfo)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
cedricandClaude Sonnet 5.5 committed 2026-11-21 13:03:32 +01:00
1 parent 17b98b6cf3
commit ca1330434e
4 files changed
+122 -7

No files matched your search

+2 -1
View File
@@ -10,5 +10,6 @@ GARAGE_S3_ENDPOINT=https://s3.example.org
GARAGE_S3_REGION=garage GARAGE_S3_REGION=garage
# Console CLI (facultatif) : chemin du binaire garage et secret RPC du cluster. # Console CLI (facultatif) : chemin du binaire garage et secret RPC du cluster.
GARAGE_BIN=/garage GARAGE_BIN=/garage
GARAGE_RPC_HOST= # hôte:port suffit, l'identifiant du noeud est ajouté automatiquement.
GARAGE_RPC_HOST=garage:3901
GARAGE_RPC_SECRET= GARAGE_RPC_SECRET=
+2 -2
View File
@@ -39,7 +39,7 @@ docker compose up -d --build
# http://localhost:8088 # http://localhost:8088
``` ```
La console CLI utilise `GARAGE_RPC_HOST` (adresse RPC, port 3901) et `GARAGE_RPC_SECRET` (le `rpc_secret` de `garage.toml`). Sans `GARAGE_BIN`, la page Console est désactivée ; les autres pages n'en ont pas besoin. La console CLI utilise `GARAGE_RPC_HOST` (`hôte:3901`) et `GARAGE_RPC_SECRET` (le `rpc_secret` de `garage.toml`). La CLI exige l'adresse au format `<identifiant du nœud>@<hôte>:<port>` : l'identifiant est demandé automatiquement à Garage (`GetNodeInfo`), inutile de le copier ; vous pouvez aussi le fournir vous-même. Sans `GARAGE_BIN`, la page Console est désactivée ; les autres pages n'en ont pas besoin.
## Variables ## Variables
@@ -53,7 +53,7 @@ La console CLI utilise `GARAGE_RPC_HOST` (adresse RPC, port 3901) et `GARAGE_RPC
| `TITLE` | `Garage UI` | Titre affiché | | `TITLE` | `Garage UI` | Titre affiché |
| `GARAGE_S3_ENDPOINT` / `GARAGE_S3_REGION` | | Exemples de configuration client | | `GARAGE_S3_ENDPOINT` / `GARAGE_S3_REGION` | | Exemples de configuration client |
| `GARAGE_BIN` / `GARAGE_CONFIG` | `/garage` si présent | CLI : binaire et fichier `garage.toml` (`-c`) | | `GARAGE_BIN` / `GARAGE_CONFIG` | `/garage` si présent | CLI : binaire et fichier `garage.toml` (`-c`) |
| `GARAGE_RPC_HOST` / `GARAGE_RPC_SECRET` | | CLI : adresse et secret RPC | | `GARAGE_RPC_HOST` / `GARAGE_RPC_SECRET` | `<hôte admin>:3901` / | CLI : adresse RPC (`hôte:port` ou `id@hôte:port`) et secret |
| `LISTEN_ADDR` | `:8080` | Écoute | | `LISTEN_ADDR` | `:8080` | Écoute |
## Développement ## Développement
+74 -3
View File
@@ -28,6 +28,7 @@ import (
"path" "path"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"github.com/vLab-BZH/garage-ui/web" "github.com/vLab-BZH/garage-ui/web"
@@ -52,10 +53,14 @@ type config struct {
s3Region string s3Region string
cliBin string cliBin string
cliConfig string cliConfig string
rpcHost string // GARAGE_RPC_HOST : [identifiant@]hôte:port
publicURL string publicURL string
sessionTTL time.Duration sessionTTL time.Duration
cliTimeout time.Duration cliTimeout time.Duration
transport http.RoundTripper // nil : transport par défaut (les tests y mettent un faux Garage) transport http.RoundTripper // nil : transport par défaut (les tests y mettent un faux Garage)
rpcMu sync.Mutex
rpcResolved string // rpcHost complété par l'identifiant du nœud, une fois connu
} }
func env(k, def string) string { func env(k, def string) string {
@@ -76,6 +81,7 @@ func loadConfig() (*config, error) {
s3Region: env("GARAGE_S3_REGION", "garage"), s3Region: env("GARAGE_S3_REGION", "garage"),
cliBin: env("GARAGE_BIN", ""), cliBin: env("GARAGE_BIN", ""),
cliConfig: env("GARAGE_CONFIG", ""), cliConfig: env("GARAGE_CONFIG", ""),
rpcHost: env("GARAGE_RPC_HOST", ""),
publicURL: env("PUBLIC_URL", ""), publicURL: env("PUBLIC_URL", ""),
sessionTTL: 24 * time.Hour, sessionTTL: 24 * time.Hour,
cliTimeout: 120 * time.Second, cliTimeout: 120 * time.Second,
@@ -270,6 +276,66 @@ func (b *limitedBuf) Write(p []byte) (int, error) {
return len(p), nil return len(p), nil
} }
// selfNodeID demande à l'API d'administration l'identifiant complet du nœud qui répond.
func (c *config) selfNodeID(ctx context.Context) (string, error) {
u := *c.adminURL
u.Path = strings.TrimRight(u.Path, "/") + "/v2/GetNodeInfo"
u.RawQuery = "node=self"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+c.adminToken)
cl := &http.Client{Transport: c.transport, Timeout: 10 * time.Second}
resp, err := cl.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GetNodeInfo : HTTP %d", resp.StatusCode)
}
var out struct {
Success map[string]struct {
NodeID string `json:"nodeId"`
} `json:"success"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil {
return "", err
}
for id, n := range out.Success {
if n.NodeID != "" {
return n.NodeID, nil
}
return id, nil
}
return "", errors.New("GetNodeInfo : aucun nœud dans la réponse")
}
// resolveRPCHost renvoie l'adresse RPC au format exigé par la CLI : <identifiant complet>@<hôte>:<port>.
// GARAGE_RPC_HOST peut donner seulement hôte:port (l'identifiant est alors demandé à Garage, une fois),
// ou rester vide (hôte de l'API d'administration, port 3901).
func (c *config) resolveRPCHost(ctx context.Context) (string, error) {
host := c.rpcHost
if host == "" {
host = c.adminURL.Hostname() + ":3901"
}
if strings.Contains(host, "@") {
return host, nil
}
c.rpcMu.Lock()
defer c.rpcMu.Unlock()
if c.rpcResolved != "" {
return c.rpcResolved, nil
}
id, err := c.selfNodeID(ctx)
if err != nil {
return "", err
}
c.rpcResolved = id + "@" + host
return c.rpcResolved, nil
}
func (c *config) handleCLI(w http.ResponseWriter, r *http.Request) { func (c *config) handleCLI(w http.ResponseWriter, r *http.Request) {
if c.cliBin == "" { if c.cliBin == "" {
writeErr(w, http.StatusNotImplemented, "Console CLI non configurée (GARAGE_BIN)") writeErr(w, http.StatusNotImplemented, "Console CLI non configurée (GARAGE_BIN)")
@@ -299,17 +365,22 @@ func (c *config) handleCLI(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), c.cliTimeout) ctx, cancel := context.WithTimeout(r.Context(), c.cliTimeout)
defer cancel() defer cancel()
cmd := exec.CommandContext(ctx, c.cliBin, args...) cmd := exec.CommandContext(ctx, c.cliBin, args...)
rpcHost, err := c.resolveRPCHost(ctx)
if err != nil {
writeErr(w, http.StatusBadGateway, "Impossible de déterminer l'identifiant du nœud Garage : "+err.Error())
return
}
var env []string var env []string
for _, e := range os.Environ() { for _, e := range os.Environ() {
if !strings.HasPrefix(e, "UI_") && !strings.HasPrefix(e, "SESSION_") { if !strings.HasPrefix(e, "UI_") && !strings.HasPrefix(e, "SESSION_") && !strings.HasPrefix(e, "GARAGE_RPC_HOST=") {
env = append(env, e) env = append(env, e)
} }
} }
cmd.Env = env cmd.Env = append(env, "GARAGE_RPC_HOST="+rpcHost)
out := &limitedBuf{} out := &limitedBuf{}
cmd.Stdout, cmd.Stderr = out, out cmd.Stdout, cmd.Stderr = out, out
start := time.Now() start := time.Now()
err := cmd.Run() err = cmd.Run()
code := 0 code := 0
var ee *exec.ExitError var ee *exec.ExitError
switch { switch {
+44 -1
View File
@@ -125,7 +125,9 @@ func TestMutationNeedsCSRFHeader(t *testing.T) {
func TestCLIWhitelist(t *testing.T) { func TestCLIWhitelist(t *testing.T) {
g, _ := fakeGarage(t) g, _ := fakeGarage(t)
h := newTestConfig(t, g).routes() c := newTestConfig(t, g)
c.rpcHost = "ff00@garage.test:3901" // déjà complet : la résolution a son propre test
h := c.routes()
ck := login(t, h) ck := login(t, h)
call := func(body string) *httptest.ResponseRecorder { call := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/cli", strings.NewReader(body)) req := httptest.NewRequest("POST", "/api/cli", strings.NewReader(body))
@@ -144,3 +146,44 @@ func TestCLIWhitelist(t *testing.T) {
} }
} }
} }
func TestResolveRPCHost(t *testing.T) {
calls := 0
rt := roundTripFunc(func(r *http.Request) (*http.Response, error) {
calls++
rec := httptest.NewRecorder()
if r.URL.Path != "/v2/GetNodeInfo" || r.URL.Query().Get("node") != "self" || r.Header.Get("Authorization") != "Bearer tok" {
rec.WriteHeader(400)
return rec.Result(), nil
}
_, _ = rec.WriteString(`{"success":{"abc123":{"nodeId":"abc123"}},"error":{}}`)
return rec.Result(), nil
})
c := newTestConfig(t, rt)
c.rpcHost = "garage:3901"
for i := 0; i < 2; i++ { // le second appel doit venir du cache
got, err := c.resolveRPCHost(t.Context())
if err != nil || got != "abc123@garage:3901" {
t.Fatalf("résolu : %q, %v", got, err)
}
}
if calls != 1 {
t.Fatalf("%d appels à GetNodeInfo, attendu 1 (cache)", calls)
}
// Déjà au bon format : aucun appel.
c2 := newTestConfig(t, rt)
c2.rpcHost = "ff00@10.0.0.2:3901"
before := calls
if got, _ := c2.resolveRPCHost(t.Context()); got != "ff00@10.0.0.2:3901" || calls != before {
t.Fatalf("hôte complet modifié ou appel inutile : %q", got)
}
// Vide : hôte de l'API d'administration, port 3901.
c3 := newTestConfig(t, rt)
c3.rpcHost = ""
if got, _ := c3.resolveRPCHost(t.Context()); got != "abc123@garage.test:3901" {
t.Fatalf("hôte par défaut : %q", got)
}
}