346 lines
12 KiB
Go
346 lines
12 KiB
Go
// mockgarage : faux serveur d'administration Garage v2 (en mémoire), pour développer et tester
|
|
// l'interface sans cluster. Ce n'est PAS Garage : il imite seulement la forme des réponses.
|
|
//
|
|
// go run ./cmd/mockgarage # écoute sur :3903, jeton « test »
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type perm struct {
|
|
Read bool `json:"read"`
|
|
Write bool `json:"write"`
|
|
Owner bool `json:"owner"`
|
|
}
|
|
|
|
type bucket struct {
|
|
ID string
|
|
Created string
|
|
Aliases []string
|
|
Objects int
|
|
Bytes int64
|
|
Site bool
|
|
Index string
|
|
ErrDoc *string
|
|
MaxSize *int64
|
|
MaxObjs *int64
|
|
Keys map[string]perm
|
|
}
|
|
|
|
type key struct {
|
|
ID, Name, Secret, Created string
|
|
Expiration *string
|
|
CreateBucket bool
|
|
}
|
|
|
|
var (
|
|
mu sync.Mutex
|
|
buckets = map[string]*bucket{}
|
|
keys = map[string]*key{}
|
|
nodeID = "563e1ac825ee3323aa441e72c26d1030d6d4414aeb3697544d1d7e0c3d8da3a2"
|
|
staged bool
|
|
version = 1
|
|
)
|
|
|
|
func init() {
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
keys["GK31c2f218a2e44f485b94239e"] = &key{ID: "GK31c2f218a2e44f485b94239e", Name: "sauvegardes-proxmox", Secret: strings.Repeat("ab12", 16), Created: now, CreateBucket: true}
|
|
keys["GKb5d1c6ef0a9d4a3f9c8e1b22"] = &key{ID: "GKb5d1c6ef0a9d4a3f9c8e1b22", Name: "lecture-seule", Secret: strings.Repeat("cd34", 16), Created: now}
|
|
gb := int64(1 << 30)
|
|
q := 50 * gb
|
|
buckets["b1"] = &bucket{ID: "9a1f0c3e5b7d2f48a6c1e9d0b3a5f7c2e4d6b8a0c2e4f6a8b0d2c4e6f8a0b2c4", Created: now, Aliases: []string{"proxmox-backups"}, Objects: 1284, Bytes: 38 * gb, MaxSize: &q,
|
|
Keys: map[string]perm{"GK31c2f218a2e44f485b94239e": {true, true, true}}}
|
|
buckets["b2"] = &bucket{ID: "1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d", Created: now, Aliases: []string{"site-vitrine", "www"}, Objects: 42, Bytes: 12 << 20, Site: true, Index: "index.html",
|
|
Keys: map[string]perm{"GKb5d1c6ef0a9d4a3f9c8e1b22": {true, false, false}}}
|
|
buckets["b3"] = &bucket{ID: "7f6e5d4c3b2a19080f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a6978", Created: now, Aliases: []string{"vide"}, Keys: map[string]perm{}}
|
|
}
|
|
|
|
func j(w http.ResponseWriter, code int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func gerr(w http.ResponseWriter, code int, msg string) {
|
|
j(w, code, map[string]any{"code": "MockError", "message": msg, "region": "garage", "path": ""})
|
|
}
|
|
|
|
func findBucket(id string) *bucket {
|
|
for _, b := range buckets {
|
|
if b.ID == id {
|
|
return b
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (b *bucket) info() map[string]any {
|
|
ks := []map[string]any{}
|
|
for id, p := range b.Keys {
|
|
if k := keys[id]; k != nil {
|
|
ks = append(ks, map[string]any{"accessKeyId": id, "name": k.Name, "permissions": p, "bucketLocalAliases": []string{}})
|
|
}
|
|
}
|
|
var wc any
|
|
if b.Site {
|
|
wc = map[string]any{"indexDocument": b.Index, "errorDocument": b.ErrDoc}
|
|
}
|
|
return map[string]any{
|
|
"id": b.ID, "created": b.Created, "globalAliases": b.Aliases, "websiteAccess": b.Site, "websiteConfig": wc,
|
|
"keys": ks, "objects": b.Objects, "bytes": b.Bytes, "unfinishedUploads": 0, "unfinishedMultipartUploads": 2,
|
|
"unfinishedMultipartUploadParts": 5, "unfinishedMultipartUploadBytes": 30 << 20,
|
|
"quotas": map[string]any{"maxSize": b.MaxSize, "maxObjects": b.MaxObjs},
|
|
}
|
|
}
|
|
|
|
func (k *key) info(secret bool) map[string]any {
|
|
bs := []map[string]any{}
|
|
for _, b := range buckets {
|
|
if p, ok := b.Keys[k.ID]; ok {
|
|
bs = append(bs, map[string]any{"id": b.ID, "globalAliases": b.Aliases, "localAliases": []string{}, "permissions": p})
|
|
}
|
|
}
|
|
var s any
|
|
if secret {
|
|
s = k.Secret
|
|
}
|
|
return map[string]any{"accessKeyId": k.ID, "name": k.Name, "created": k.Created, "expiration": k.Expiration, "expired": false,
|
|
"secretAccessKey": s, "permissions": map[string]bool{"createBucket": k.CreateBucket}, "buckets": bs}
|
|
}
|
|
|
|
func handle(token string) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "Bearer "+token {
|
|
gerr(w, 403, "jeton d'administration invalide")
|
|
return
|
|
}
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
op := strings.TrimPrefix(r.URL.Path, "/v2/")
|
|
q := r.URL.Query()
|
|
var body map[string]any
|
|
var arr []any
|
|
raw := json.NewDecoder(r.Body)
|
|
var anyBody any
|
|
_ = raw.Decode(&anyBody)
|
|
switch v := anyBody.(type) {
|
|
case map[string]any:
|
|
body = v
|
|
case []any:
|
|
arr = v
|
|
}
|
|
str := func(k string) string { s, _ := body[k].(string); return s }
|
|
log.Printf("%s %s", r.Method, op)
|
|
|
|
switch op {
|
|
case "GetClusterHealth":
|
|
j(w, 200, map[string]any{"status": "healthy", "knownNodes": 1, "connectedNodes": 1, "storageNodes": 1, "storageNodesUp": 1, "partitions": 256, "partitionsQuorum": 256, "partitionsAllOk": 256})
|
|
case "GetClusterStatus":
|
|
var role any = map[string]any{"zone": "dc1", "tags": []string{"lab"}, "capacity": int64(500e9)}
|
|
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":
|
|
st := []any{}
|
|
if staged {
|
|
st = append(st, map[string]any{"id": nodeID, "zone": "dc1", "tags": []string{"lab"}, "capacity": int64(800e9)})
|
|
}
|
|
j(w, 200, map[string]any{"version": version, "roles": []any{map[string]any{"id": nodeID, "zone": "dc1", "tags": []string{"lab"}, "capacity": int64(500e9)}}, "partitionSize": 67108864, "stagedRoleChanges": st})
|
|
case "UpdateClusterLayout":
|
|
staged = true
|
|
j(w, 200, map[string]any{"version": version})
|
|
case "PreviewClusterLayoutChanges":
|
|
j(w, 200, map[string]any{"message": []string{"==== NEW CLUSTER LAYOUT ====", "capacité 800 GB sur dc1", "(aperçu simulé)"}})
|
|
case "ApplyClusterLayout":
|
|
staged, version = false, version+1
|
|
j(w, 200, map[string]any{"message": []string{"ok"}})
|
|
case "RevertClusterLayout":
|
|
staged = false
|
|
j(w, 200, map[string]any{"version": version})
|
|
case "ConnectClusterNodes":
|
|
j(w, 200, []any{map[string]any{"success": len(arr) > 0 && strings.Contains(fmt.Sprint(arr[0]), "@")}})
|
|
case "ListBuckets":
|
|
out := []any{}
|
|
for _, b := range buckets {
|
|
out = append(out, map[string]any{"id": b.ID, "created": b.Created, "globalAliases": b.Aliases, "localAliases": []any{}})
|
|
}
|
|
j(w, 200, out)
|
|
case "GetBucketInfo":
|
|
if b := findBucket(q.Get("id")); b != nil {
|
|
j(w, 200, b.info())
|
|
return
|
|
}
|
|
gerr(w, 404, "bucket introuvable")
|
|
case "CreateBucket":
|
|
id := fmt.Sprintf("%064x", time.Now().UnixNano())
|
|
b := &bucket{ID: id, Created: time.Now().UTC().Format(time.RFC3339), Aliases: []string{str("globalAlias")}, Keys: map[string]perm{}}
|
|
buckets[id] = b
|
|
j(w, 200, b.info())
|
|
case "DeleteBucket":
|
|
b := findBucket(q.Get("id"))
|
|
switch {
|
|
case b == nil:
|
|
gerr(w, 404, "bucket introuvable")
|
|
case b.Objects > 0:
|
|
gerr(w, 409, "le bucket n'est pas vide")
|
|
default:
|
|
for k, x := range buckets {
|
|
if x == b {
|
|
delete(buckets, k)
|
|
}
|
|
}
|
|
w.WriteHeader(204)
|
|
}
|
|
case "UpdateBucket":
|
|
b := findBucket(q.Get("id"))
|
|
if b == nil {
|
|
gerr(w, 404, "bucket introuvable")
|
|
return
|
|
}
|
|
if wa, ok := body["websiteAccess"].(map[string]any); ok {
|
|
b.Site, _ = wa["enabled"].(bool)
|
|
b.Index, _ = wa["indexDocument"].(string)
|
|
}
|
|
if qu, ok := body["quotas"].(map[string]any); ok {
|
|
b.MaxSize, b.MaxObjs = nil, nil
|
|
if f, ok := qu["maxSize"].(float64); ok {
|
|
n := int64(f)
|
|
b.MaxSize = &n
|
|
}
|
|
if f, ok := qu["maxObjects"].(float64); ok {
|
|
n := int64(f)
|
|
b.MaxObjs = &n
|
|
}
|
|
}
|
|
j(w, 200, b.info())
|
|
case "AddBucketAlias", "RemoveBucketAlias":
|
|
b := findBucket(str("bucketId"))
|
|
if b == nil {
|
|
gerr(w, 404, "bucket introuvable")
|
|
return
|
|
}
|
|
a := str("globalAlias")
|
|
if op == "AddBucketAlias" {
|
|
b.Aliases = append(b.Aliases, a)
|
|
} else {
|
|
out := b.Aliases[:0:0]
|
|
for _, x := range b.Aliases {
|
|
if x != a {
|
|
out = append(out, x)
|
|
}
|
|
}
|
|
b.Aliases = out
|
|
}
|
|
j(w, 200, b.info())
|
|
case "AllowBucketKey", "DenyBucketKey":
|
|
b := findBucket(str("bucketId"))
|
|
if b == nil {
|
|
gerr(w, 404, "bucket introuvable")
|
|
return
|
|
}
|
|
p := b.Keys[str("accessKeyId")]
|
|
pm, _ := body["permissions"].(map[string]any)
|
|
on := op == "AllowBucketKey"
|
|
if pm["read"] == true {
|
|
p.Read = on
|
|
}
|
|
if pm["write"] == true {
|
|
p.Write = on
|
|
}
|
|
if pm["owner"] == true {
|
|
p.Owner = on
|
|
}
|
|
b.Keys[str("accessKeyId")] = p
|
|
j(w, 200, b.info())
|
|
case "CleanupIncompleteUploads":
|
|
j(w, 200, map[string]any{"uploadsDeleted": 2})
|
|
case "ListKeys":
|
|
out := []any{}
|
|
for _, k := range keys {
|
|
out = append(out, map[string]any{"id": k.ID, "name": k.Name, "created": k.Created, "expiration": k.Expiration, "expired": false})
|
|
}
|
|
j(w, 200, out)
|
|
case "GetKeyInfo":
|
|
if k := keys[q.Get("id")]; k != nil {
|
|
j(w, 200, k.info(q.Get("showSecretKey") == "true"))
|
|
return
|
|
}
|
|
gerr(w, 404, "clé introuvable")
|
|
case "CreateKey", "ImportKey":
|
|
id := str("accessKeyId")
|
|
sec := str("secretAccessKey")
|
|
if id == "" {
|
|
id = fmt.Sprintf("GK%024x", time.Now().UnixNano())
|
|
sec = fmt.Sprintf("%064x", time.Now().UnixNano())
|
|
}
|
|
k := &key{ID: id, Name: str("name"), Secret: sec, Created: time.Now().UTC().Format(time.RFC3339)}
|
|
keys[id] = k
|
|
j(w, 200, k.info(true))
|
|
case "UpdateKey":
|
|
k := keys[q.Get("id")]
|
|
if k == nil {
|
|
gerr(w, 404, "clé introuvable")
|
|
return
|
|
}
|
|
if n := str("name"); n != "" {
|
|
k.Name = n
|
|
}
|
|
if a, ok := body["allow"].(map[string]any); ok && a["createBucket"] == true {
|
|
k.CreateBucket = true
|
|
}
|
|
if d, ok := body["deny"].(map[string]any); ok && d["createBucket"] == true {
|
|
k.CreateBucket = false
|
|
}
|
|
j(w, 200, k.info(false))
|
|
case "DeleteKey":
|
|
delete(keys, q.Get("id"))
|
|
for _, b := range buckets {
|
|
delete(b.Keys, q.Get("id"))
|
|
}
|
|
w.WriteHeader(204)
|
|
case "ListWorkers":
|
|
j(w, 200, map[string]any{"success": map[string]any{nodeID: []any{
|
|
map[string]any{"id": 1, "name": "Block resync worker #1", "state": "idle", "errors": 0, "consecutiveErrors": 0, "queueLength": 0},
|
|
map[string]any{"id": 2, "name": "Block scrub worker", "state": "busy", "errors": 0, "consecutiveErrors": 0, "progress": "42.0%"},
|
|
map[string]any{"id": 3, "name": "object sync", "state": map[string]any{"throttled": map[string]any{"durationSecs": 5}}, "errors": 1, "consecutiveErrors": 1, "lastError": map[string]any{"message": "timeout", "secsAgo": 90}},
|
|
}}, "error": map[string]any{}})
|
|
case "ListBlockErrors":
|
|
if r.Method != http.MethodGet { // comme le vrai Garage : GET uniquement
|
|
gerr(w, 400, "Unknown API endpoint: "+r.Method+" /v2/"+op)
|
|
return
|
|
}
|
|
j(w, 200, map[string]any{"success": map[string]any{nodeID: []any{}}, "error": map[string]any{}})
|
|
case "LaunchRepairOperation", "CreateMetadataSnapshot", "RetryBlockResync":
|
|
j(w, 200, map[string]any{"success": map[string]any{nodeID: nil}, "error": map[string]any{}})
|
|
default:
|
|
gerr(w, 404, "opération inconnue : "+op)
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
token := "test"
|
|
if v := os.Getenv("MOCK_TOKEN"); v != "" {
|
|
token = v
|
|
}
|
|
addr := ":3903"
|
|
if v := os.Getenv("MOCK_ADDR"); v != "" {
|
|
addr = v
|
|
}
|
|
log.Printf("mockgarage sur %s (jeton %q)", addr, token)
|
|
http.Handle("/v2/", handle(token))
|
|
log.Fatal(http.ListenAndServe(addr, nil))
|
|
}
|