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:
1 parent
17b98b6cf3
commit
ca1330434e
4 files changed
+122
-7
No files matched your search
+74
-3
@@ -28,6 +28,7 @@ import (
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/vLab-BZH/garage-ui/web"
|
||||
@@ -52,10 +53,14 @@ type config struct {
|
||||
s3Region string
|
||||
cliBin string
|
||||
cliConfig string
|
||||
rpcHost string // GARAGE_RPC_HOST : [identifiant@]hôte:port
|
||||
publicURL string
|
||||
sessionTTL time.Duration
|
||||
cliTimeout time.Duration
|
||||
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 {
|
||||
@@ -76,6 +81,7 @@ func loadConfig() (*config, error) {
|
||||
s3Region: env("GARAGE_S3_REGION", "garage"),
|
||||
cliBin: env("GARAGE_BIN", ""),
|
||||
cliConfig: env("GARAGE_CONFIG", ""),
|
||||
rpcHost: env("GARAGE_RPC_HOST", ""),
|
||||
publicURL: env("PUBLIC_URL", ""),
|
||||
sessionTTL: 24 * time.Hour,
|
||||
cliTimeout: 120 * time.Second,
|
||||
@@ -270,6 +276,66 @@ func (b *limitedBuf) Write(p []byte) (int, error) {
|
||||
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) {
|
||||
if c.cliBin == "" {
|
||||
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)
|
||||
defer cancel()
|
||||
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
|
||||
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)
|
||||
}
|
||||
}
|
||||
cmd.Env = env
|
||||
cmd.Env = append(env, "GARAGE_RPC_HOST="+rpcHost)
|
||||
out := &limitedBuf{}
|
||||
cmd.Stdout, cmd.Stderr = out, out
|
||||
start := time.Now()
|
||||
err := cmd.Run()
|
||||
err = cmd.Run()
|
||||
code := 0
|
||||
var ee *exec.ExitError
|
||||
switch {
|
||||
|
||||
+44
-1
@@ -125,7 +125,9 @@ func TestMutationNeedsCSRFHeader(t *testing.T) {
|
||||
|
||||
func TestCLIWhitelist(t *testing.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)
|
||||
call := func(body string) *httptest.ResponseRecorder {
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user