Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ GSMSV_INFRA_FAKE=true GSMSV_INFRA_ADDR=127.0.0.1:8080 GSMSV_INFRA_INTERNAL_CIDR=
- 모든 노드에 모든 이미지(`image`)의 템플릿이 있다. 템플릿 디스크가 4GiB라서 `ssd_gb`가 4보다 작으면 작업이 `DISK_SHRINK_NOT_ALLOWED`로 실패한다
- Proxmox 동작 하나에 1초 걸린다. VM 만들기는 6초쯤, 지우기는 1초쯤이다
- 같은 노드의 만들기는 클론 단계를 하나씩 한다. 기다리는 작업의 `queue_position`은 앞에 선 작업 수다
- 노드 현황(`GET /nodes`)의 `total`·`usage`는 명세 예시 값으로 고정이다. `configured`(VM 설정 사양 합계)와 `clone_queue_length`는 만든 VM과 기다리는 작업을 따라 바뀐다. 값은 10초 동안 캐시하고, `?refresh=true`면 바로 다시 읽는다

#### VM 한 줄기

Expand Down Expand Up @@ -80,6 +81,16 @@ curl -s -X DELETE "$BASE/vms/vm-k3m9x2p7q4ta" -H "$AUTH" -H 'Idempotency-Key: op
curl -s "$BASE/vms/vm-k3m9x2p7q4ta" -H "$AUTH"
```

#### 노드 조회

```bash
# 노드 현황. 만들기 직후처럼 지금 값이 필요하면 ?refresh=true
curl -s "$BASE/nodes" -H "$AUTH"

# 그 노드에 실제로 있는 VM. 캐시를 쓰지 않는다. 맡지 않은 노드는 404
curl -s "$BASE/nodes/node-a/vms" -H "$AUTH"
```

#### 오류 흉내 (`X-Fake-Fail`)

요청 헤더에 `X-Fake-Fail: {code}`를 실으면 그 code의 오류로 답한다 (예: `UPSTREAM_UNAVAILABLE`이면 503). code 목록은 내부 API 규약 5.3이고, 목록에 없는 값이면 400 `INVALID_REQUEST`다. 헬스 체크는 이 헤더를 보지 않는다.
Expand Down
6 changes: 5 additions & 1 deletion cmd/engine/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

"github.com/GSMSV/GSMSV-Infra-V2/internal/api"
"github.com/GSMSV/GSMSV-Infra-V2/internal/job"
"github.com/GSMSV/GSMSV-Infra-V2/internal/node"
"github.com/GSMSV/GSMSV-Infra-V2/internal/proxmox"
"github.com/GSMSV/GSMSV-Infra-V2/internal/vm"
)
Expand Down Expand Up @@ -87,12 +88,15 @@ const fakeStepDelay = time.Second
func fakeHandler(secret string, internal netip.Prefix) http.Handler {
up := func(context.Context) error { return nil }
jobs := job.NewManager(time.Now)
px := proxmox.NewFake(fakeStepDelay, fakeNodes...)
vms := vm.New(px, jobs, internal)
return api.New(api.Config{
Secret: secret,
BootID: job.NewID("boot-"),
Checks: map[string]func(context.Context) error{"proxmox": up, "gateway": up, "caddy": up, "kubernetes": up},
Fake: true,
Jobs: jobs,
VMs: vm.New(proxmox.NewFake(fakeStepDelay, fakeNodes...), jobs, internal),
VMs: vms,
Nodes: node.New(px, vms.CloneQueue, time.Now),
})
}
5 changes: 5 additions & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

"github.com/GSMSV/GSMSV-Infra-V2/internal/job"
"github.com/GSMSV/GSMSV-Infra-V2/internal/node"
"github.com/GSMSV/GSMSV-Infra-V2/internal/vm"
)

Expand All @@ -28,6 +29,8 @@ type Config struct {
Jobs *job.Manager
// VMs는 VM 엔드포인트가 부르는 VM 서비스다.
VMs *vm.Service
// Nodes는 노드 조회 엔드포인트가 부르는 노드 서비스다.
Nodes *node.Service
}

// opaqueIDPattern은 job_id와 Idempotency-Key의 모양이다 (명세 JobId·IdempotencyKey).
Expand All @@ -44,6 +47,8 @@ func New(cfg Config) http.Handler {
mux.Handle("POST /vms", createVM(cfg.VMs))
mux.Handle("GET /vms/{vm_id}", getVM(cfg.VMs))
mux.Handle("DELETE /vms/{vm_id}", deleteVM(cfg.VMs))
mux.Handle("GET /nodes", listNodes(cfg.Nodes))
mux.Handle("GET /nodes/{node}/vms", listNodeVMs(cfg.Nodes))
var protected http.Handler = mux
if cfg.Fake {
protected = fakeFail(protected)
Expand Down
39 changes: 39 additions & 0 deletions internal/api/node.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package api

import (
"context"
"net/http"

"github.com/GSMSV/GSMSV-Infra-V2/internal/job"
"github.com/GSMSV/GSMSV-Infra-V2/internal/node"
)

func listNodes(nodes *node.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var refresh bool
switch r.URL.Query().Get("refresh") {
case "", "false":
case "true":
refresh = true
default:
writeErr(w, r, job.Invalid("INVALID_REQUEST", job.Field{Field: "refresh", Reason: "invalid_format"}))
return
}
ctx, cancel := context.WithTimeout(r.Context(), syncTimeout)
defer cancel()
writeJSON(w, http.StatusOK, map[string]any{"items": nodes.List(ctx, refresh)})
}
}

func listNodeVMs(nodes *node.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), syncTimeout)
defer cancel()
l, err := nodes.VMs(ctx, r.PathValue("node"))
if err != nil {
writeErr(w, r, err)
return
}
writeJSON(w, http.StatusOK, l)
}
}
252 changes: 252 additions & 0 deletions internal/api/node_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
package api_test

import (
"context"
"net/http"
"net/http/httptest"
"reflect"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"

"github.com/GSMSV/GSMSV-Infra-V2/internal/proxmox"
)

// countingStatus는 NodeStatus를 부른 횟수를 센다. 캐시가 Proxmox를 다시 부르지 않는지 본다.
type countingStatus struct {
*proxmox.Fake
calls atomic.Int64
}

func (c *countingStatus) NodeStatus(ctx context.Context, name string) (proxmox.NodeStatus, error) {
c.calls.Add(1)
return c.Fake.NodeStatus(ctx, name)
}

// hangingNode는 hung 노드의 NodeStatus가 ctx가 끝날 때까지 답하지 않는 Proxmox다.
type hangingNode struct {
*proxmox.Fake
hung string
}

func (h hangingNode) NodeStatus(ctx context.Context, name string) (proxmox.NodeStatus, error) {
if name == h.hung {
<-ctx.Done()
return proxmox.NodeStatus{}, ctx.Err()
}
return h.Fake.NodeStatus(ctx, name)
}

// stallOnce는 처음 불린 NodeStatus 하나만 ctx가 끝날 때까지 답하지 않는 Proxmox다.
type stallOnce struct {
*proxmox.Fake
stalled atomic.Bool
}

func (s *stallOnce) NodeStatus(ctx context.Context, name string) (proxmox.NodeStatus, error) {
if s.stalled.CompareAndSwap(false, true) {
<-ctx.Done()
return proxmox.NodeStatus{}, ctx.Err()
}
return s.Fake.NodeStatus(ctx, name)
}

// 가짜 노드의 총량·실사용량은 명세 listNodes 예시 값이다.
var (
fakeTotal = map[string]any{"cpu_cores": float64(16), "cpu_threads": float64(32), "memory_mb": float64(131072), "ssd_gb": float64(1800)}
fakeUsage = map[string]any{"cpu_percent": 23.5, "memory_used_mb": float64(61440), "uptime_sec": float64(1209600)}
)

// nodeItem은 GET /nodes 응답에서 name 노드의 항목이다.
func nodeItem(t *testing.T, body map[string]any, name string) map[string]any {
t.Helper()
items, _ := body["items"].([]any)
for _, it := range items {
if m := it.(map[string]any); m["node"] == name {
return m
}
}
t.Fatalf("node %s not in %v", name, body)
return nil
}

func TestListNodes(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
px := &countingStatus{Fake: newFake()}
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 101}, Name: vmID, Running: true, VCPU: 2, MemoryMB: 4096, DiskGB: 20})
// 꺼진 VM과 관리 밖 VM도 합계에 넣는다.
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 150}, Name: "monitoring", VCPU: 4, MemoryMB: 8192, DiskGB: 50})
// 템플릿은 디스크만 넣는다.
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 9000}, Name: "ubuntu-template", VCPU: 1, MemoryMB: 512, DiskGB: 4, Template: true})
h := vmAPI(px)

rec, body := call(t, h, "GET", "/nodes", authed(nil))
want := map[string]any{"items": []any{
map[string]any{
"node": "node-a", "online": true, "observed_at": "2000-01-01T00:00:00Z", "total": fakeTotal, "usage": fakeUsage,
"configured": map[string]any{"vcpu": float64(6), "memory_mb": float64(12288), "ssd_gb": float64(74)},
"clone_queue_length": float64(0),
},
map[string]any{
"node": "node-b", "online": true, "observed_at": "2000-01-01T00:00:00Z", "total": fakeTotal, "usage": fakeUsage,
"configured": map[string]any{"vcpu": float64(0), "memory_mb": float64(0), "ssd_gb": float64(0)},
"clone_queue_length": float64(0),
},
}}
if rec.Code != http.StatusOK || !reflect.DeepEqual(body, want) {
t.Fatalf("got %d %v, want 200 %v", rec.Code, body, want)
}
if got := px.calls.Load(); got != 2 {
t.Fatalf("NodeStatus calls = %d, want 2 (one per node)", got)
}

// 10초 안에는 캐시 값을 주고 Proxmox를 부르지 않는다 (경계 7.4).
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 102}, Name: "vm-2b3c4d5e6f7g", VCPU: 1, MemoryMB: 1024, DiskGB: 10})
time.Sleep(9 * time.Second)
_, body = call(t, h, "GET", "/nodes", authed(nil))
if c := nodeItem(t, body, "node-a")["configured"].(map[string]any); c["vcpu"] != float64(6) || px.calls.Load() != 2 {
t.Fatalf("within ttl: configured %v, calls %d; want cached vcpu 6 and no new call", c, px.calls.Load())
}

// 10초가 지나면 다시 묻는다. 동시에 몰려도 노드마다 한 번만 묻는다.
time.Sleep(time.Second)
var wg sync.WaitGroup
for range 20 {
wg.Go(func() { call(t, h, "GET", "/nodes", authed(nil)) })
}
wg.Wait()
_, body = call(t, h, "GET", "/nodes", authed(nil))
a := nodeItem(t, body, "node-a")
if a["configured"].(map[string]any)["vcpu"] != float64(7) || a["observed_at"] != "2000-01-01T00:00:10Z" || px.calls.Load() != 4 {
t.Fatalf("after ttl: node-a %v, calls %d; want vcpu 7 observed at 10s and 4 calls", a, px.calls.Load())
}

// refresh=true면 캐시를 무시한다.
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-b", VMID: 101}, Name: "vm-3c4d5e6f7g8h", VCPU: 2, MemoryMB: 2048, DiskGB: 20})
_, body = call(t, h, "GET", "/nodes?refresh=true", authed(nil))
if c := nodeItem(t, body, "node-b")["configured"].(map[string]any); c["vcpu"] != float64(2) || px.calls.Load() != 6 {
t.Fatalf("refresh: configured %v, calls %d; want vcpu 2 and 6 calls", c, px.calls.Load())
}

rec, body = call(t, h, "GET", "/nodes?refresh=yes", authed(nil))
wantError(t, rec, body, http.StatusBadRequest, "INVALID_REQUEST", false)
wantFieldDetail(t, body, "refresh", "invalid_format")
})
}

func TestListNodesOffline(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
px := newFake()
h := vmAPI(hangingNode{Fake: px, hung: "node-b"})

// 답하지 않는 노드가 있어도 8초 안에 200으로 답하고, 그 노드만 online: false다 (명세 listNodes).
start := time.Now()
rec, body := call(t, h, "GET", "/nodes", authed(nil))
if elapsed := time.Since(start); elapsed >= 8*time.Second {
t.Fatalf("took %v, contract 6 requires under 8s", elapsed)
}
want := map[string]any{
"node": "node-b", "online": false, "observed_at": nodeItem(t, body, "node-b")["observed_at"],
"total": nil, "usage": nil, "configured": nil, "clone_queue_length": float64(0),
}
if rec.Code != http.StatusOK || !reflect.DeepEqual(nodeItem(t, body, "node-b"), want) || nodeItem(t, body, "node-a")["online"] != true {
t.Fatalf("got %d %v, want 200 with node-b %v and node-a online", rec.Code, body, want)
}

// 모든 노드에 닿지 않아도 503이 아니라 200이다.
px.SetDown("node-a", true)
rec, body = call(t, h, "GET", "/nodes?refresh=true", authed(nil))
if rec.Code != http.StatusOK || nodeItem(t, body, "node-a")["online"] != false || nodeItem(t, body, "node-b")["online"] != false {
t.Fatalf("all down: got %d %v, want 200 with every node offline", rec.Code, body)
}
})
}

func TestListNodesCanceledRequestNotCached(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
h := vmAPI(&stallOnce{Fake: newFake()})
ctx, cancel := context.WithCancel(context.Background())
req := httptest.NewRequestWithContext(ctx, "GET", "/nodes", nil)
for k, v := range authed(nil) {
req.Header.Set(k, v)
}
// 응답 전에 클라이언트가 끊는다.
time.AfterFunc(time.Second, cancel)
h.ServeHTTP(httptest.NewRecorder(), req)

// 끊긴 요청 때문에 멈춘 노드가 다음 요청에서 offline으로 남지 않는다.
_, body := call(t, h, "GET", "/nodes", authed(nil))
if nodeItem(t, body, "node-a")["online"] != true || nodeItem(t, body, "node-b")["online"] != true {
t.Fatalf("after canceled request: %v, want every node online", body)
}
})
}

func TestCloneQueueLength(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
h := vmAPI(newFake())
ids := []string{vmID, "vm-2b3c4d5e6f7g", "vm-3c4d5e6f7g8h"}
var jobs []string
for i, id := range ids {
rec, body := create(t, h, "op-"+id, createBody(func(b map[string]any) { b["id"], b["vmid"] = id, 101+i }), nil)
jobs = append(jobs, accepted(t, rec, body, i))
}
// 지금 클론 중인 첫째는 세지 않는다 (명세 clone_queue_length). 셋째의 queue_position(2)과 기준이 다르다.
_, body := call(t, h, "GET", "/nodes", authed(nil))
if a, b := nodeItem(t, body, "node-a")["clone_queue_length"], nodeItem(t, body, "node-b")["clone_queue_length"]; a != float64(2) || b != float64(0) {
t.Fatalf("clone_queue_length node-a %v node-b %v, want 2 and 0", a, b)
}
for _, j := range jobs {
follow(t, h, j)
}
// 캐시 안이어도 클론 줄은 지금 값이다.
_, body = call(t, h, "GET", "/nodes", authed(nil))
if a := nodeItem(t, body, "node-a")["clone_queue_length"]; a != float64(0) {
t.Fatalf("after all clones: clone_queue_length %v, want 0", a)
}
})
}

func TestListNodeVMs(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
px := newFake()
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 9000}, Name: "ubuntu-template", DiskGB: 4, Template: true})
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 150}, Name: "monitoring", VCPU: 4})
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-a", VMID: 101}, Name: vmID, Running: true})
h := vmAPI(px)

rec, body := call(t, h, "GET", "/nodes/node-a/vms", authed(nil))
want := map[string]any{"node": "node-a", "observed_at": "2000-01-01T00:00:00Z", "items": []any{
map[string]any{"vmid": float64(101), "name": vmID, "template": false},
map[string]any{"vmid": float64(150), "name": "monitoring", "template": false},
map[string]any{"vmid": float64(9000), "name": "ubuntu-template", "template": true},
}}
if rec.Code != http.StatusOK || !reflect.DeepEqual(body, want) {
t.Fatalf("got %d %v, want 200 %v", rec.Code, body, want)
}

// VM이 없으면 null이 아니라 빈 목록이다.
if _, body := call(t, h, "GET", "/nodes/node-b/vms", authed(nil)); !reflect.DeepEqual(body["items"], []any{}) {
t.Fatalf("empty node: items = %v, want []", body["items"])
}

// 캐시를 쓰지 않는다. 방금 생긴 VM도 바로 보인다.
px.Put(proxmox.VM{Ref: proxmox.Ref{Node: "node-b", VMID: 101}, Name: "vm-2b3c4d5e6f7g"})
if _, body := call(t, h, "GET", "/nodes/node-b/vms", authed(nil)); len(body["items"].([]any)) != 1 {
t.Fatalf("new vm not listed: %v", body)
}

rec, body = call(t, h, "GET", "/nodes/node-z/vms", authed(nil))
wantError(t, rec, body, http.StatusNotFound, "RESOURCE_NOT_FOUND", false)

rec, body = call(t, h, "GET", "/nodes/node_a/vms", authed(nil))
wantError(t, rec, body, http.StatusBadRequest, "INVALID_REQUEST", false)
wantFieldDetail(t, body, "node", "invalid_format")

px.SetDown("node-a", true)
rec, body = call(t, h, "GET", "/nodes/node-a/vms", authed(nil))
wantError(t, rec, body, http.StatusServiceUnavailable, "UPSTREAM_UNAVAILABLE", true)
})
}
6 changes: 4 additions & 2 deletions internal/api/vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (

"github.com/GSMSV/GSMSV-Infra-V2/internal/api"
"github.com/GSMSV/GSMSV-Infra-V2/internal/job"
"github.com/GSMSV/GSMSV-Infra-V2/internal/node"
"github.com/GSMSV/GSMSV-Infra-V2/internal/proxmox"
"github.com/GSMSV/GSMSV-Infra-V2/internal/vm"
)
Expand All @@ -35,10 +36,11 @@ const (
// newFake는 node-a·node-b를 맡고, 바꾸는 동작 하나에 1초 걸리는 가짜 Proxmox다.
func newFake() *proxmox.Fake { return proxmox.NewFake(time.Second, "node-a", "node-b") }

// vmAPI는 px에 붙은 가짜 모드 내부 API다. 내부 대역은 192.0.2.0/24다.
// vmAPI는 px에 붙은 가짜 모드 내부 API다 (VM·노드 엔드포인트). 내부 대역은 192.0.2.0/24다.
func vmAPI(px proxmox.Client) http.Handler {
jobs := job.NewManager(time.Now)
return api.New(api.Config{Secret: secret, Fake: true, Jobs: jobs, VMs: vm.New(px, jobs, netip.MustParsePrefix("192.0.2.0/24"))})
vms := vm.New(px, jobs, netip.MustParsePrefix("192.0.2.0/24"))
return api.New(api.Config{Secret: secret, Fake: true, Jobs: jobs, VMs: vms, Nodes: node.New(px, vms.CloneQueue, time.Now)})
}

// createBody는 명세 createVm 예시 본문이다. change가 있으면 칸을 바꾼다.
Expand Down
Loading