From 5ef34c27e273b5ac505d78baf221e6e9824e2278 Mon Sep 17 00:00:00 2001 From: whiyoung Date: Wed, 2 Dec 2026 15:01:28 +0900 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=EB=85=B8=EB=93=9C=20=ED=98=84?= =?UTF-8?q?=ED=99=A9=C2=B7=EB=85=B8=EB=93=9C=EB=B3=84=20VM=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=20=EC=A1=B0=ED=9A=8C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 11 ++ cmd/engine/main.go | 6 +- internal/api/api.go | 5 + internal/api/node.go | 39 +++++++ internal/api/node_test.go | 217 ++++++++++++++++++++++++++++++++++++ internal/api/vm_test.go | 6 +- internal/job/manager.go | 15 +++ internal/node/doc.go | 4 + internal/node/node.go | 161 ++++++++++++++++++++++++++ internal/proxmox/fake.go | 41 +++++++ internal/proxmox/proxmox.go | 20 ++++ internal/vm/vm.go | 15 ++- 12 files changed, 533 insertions(+), 7 deletions(-) create mode 100644 internal/api/node.go create mode 100644 internal/api/node_test.go create mode 100644 internal/node/doc.go create mode 100644 internal/node/node.go diff --git a/README.md b/README.md index 31861b4..6fd385d 100644 --- a/README.md +++ b/README.md @@ -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 한 줄기 @@ -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`다. 헬스 체크는 이 헤더를 보지 않는다. diff --git a/cmd/engine/main.go b/cmd/engine/main.go index b511b74..33a74a8 100644 --- a/cmd/engine/main.go +++ b/cmd/engine/main.go @@ -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" ) @@ -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), }) } diff --git a/internal/api/api.go b/internal/api/api.go index bace235..fd6b1c4 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -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" ) @@ -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). @@ -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) diff --git a/internal/api/node.go b/internal/api/node.go new file mode 100644 index 0000000..e4d9085 --- /dev/null +++ b/internal/api/node.go @@ -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) + } +} diff --git a/internal/api/node_test.go b/internal/api/node_test.go new file mode 100644 index 0000000..7dd0758 --- /dev/null +++ b/internal/api/node_test.go @@ -0,0 +1,217 @@ +package api_test + +import ( + "context" + "net/http" + "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) +} + +// 가짜 노드의 총량·실사용량은 명세 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 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) + }) +} diff --git a/internal/api/vm_test.go b/internal/api/vm_test.go index e29e775..5eb8873 100644 --- a/internal/api/vm_test.go +++ b/internal/api/vm_test.go @@ -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" ) @@ -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가 있으면 칸을 바꾼다. diff --git a/internal/job/manager.go b/internal/job/manager.go index daf5c0d..813831e 100644 --- a/internal/job/manager.go +++ b/internal/job/manager.go @@ -7,6 +7,7 @@ import ( "maps" "runtime/debug" "slices" + "strings" "sync" "time" ) @@ -125,6 +126,20 @@ func (m *Manager) prior(key, fingerprint, resourceID string) (Job, bool, error) return Job{}, false, nil } +// Waiting은 이름이 prefix로 시작하는 줄들에서 차례를 기다리는 작업 수다. +// 줄마다 맨 앞([0], 지금 첫 단계를 하는 작업)은 세지 않는다. +func (m *Manager) Waiting(prefix string) int { + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + for name, line := range m.lines { + if strings.HasPrefix(name, prefix) { + n += len(line) - 1 + } + } + return n +} + // view는 바깥에 줄 작업 복사본이다. queued면 queue_position을 지금 줄 위치로 채운다. m.mu를 쥐고 부른다. func (m *Manager) view(e *entry) Job { j := e.job diff --git a/internal/node/doc.go b/internal/node/doc.go new file mode 100644 index 0000000..488c197 --- /dev/null +++ b/internal/node/doc.go @@ -0,0 +1,4 @@ +// Package node는 Infra가 맡은 Proxmox 노드의 현황과 노드에 실제로 있는 VM을 준다 (내부 API 13.8). +// +// 노드의 여유(할당 기준)는 계산하지 않는다. 할당 합계와 상한은 Server가 정한다 (경계 4장 레드라인). +package node diff --git a/internal/node/node.go b/internal/node/node.go new file mode 100644 index 0000000..31819e5 --- /dev/null +++ b/internal/node/node.go @@ -0,0 +1,161 @@ +package node + +import ( + "context" + "log/slog" + "math" + "regexp" + "slices" + "sync" + "time" + + "github.com/GSMSV/GSMSV-Infra-V2/internal/job" + "github.com/GSMSV/GSMSV-Infra-V2/internal/proxmox" +) + +// NamePattern은 명세 NodeName의 정규식이다. +var NamePattern = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$`) + +// cacheTTL은 노드 현황을 다시 묻지 않고 주는 시간이다. Proxmox가 약 10초마다 값을 갱신한다 (경계 7.4). +const cacheTTL = 10 * time.Second + +// Status는 명세 NodeStatus다. 닿지 않은 노드는 Total·Usage·Configured가 nil이다. +type Status struct { + Node string `json:"node"` + Online bool `json:"online"` + ObservedAt time.Time `json:"observed_at"` + Total *Total `json:"total"` + Usage *Usage `json:"usage"` + Configured *Configured `json:"configured"` + CloneQueueLength int `json:"clone_queue_length"` +} + +// Total은 명세 NodeTotal이다. +type Total struct { + CPUCores int `json:"cpu_cores"` + CPUThreads int `json:"cpu_threads"` + MemoryMB int `json:"memory_mb"` + SSDGB int `json:"ssd_gb"` +} + +// Usage는 명세 NodeUsage다. +type Usage struct { + CPUPercent float64 `json:"cpu_percent"` + MemoryUsedMB int `json:"memory_used_mb"` + UptimeSec int `json:"uptime_sec"` +} + +// Configured는 명세 NodeConfigured다. +type Configured struct { + VCPU int `json:"vcpu"` + MemoryMB int `json:"memory_mb"` + SSDGB int `json:"ssd_gb"` +} + +// VMList는 명세 NodeVmList다. +type VMList struct { + Node string `json:"node"` + ObservedAt time.Time `json:"observed_at"` + Items []VM `json:"items"` +} + +// VM은 명세 NodeVm이다. +type VM struct { + VMID int `json:"vmid"` + Name string `json:"name"` + Template bool `json:"template"` +} + +// Service는 노드 조회를 Proxmox 호출로 옮긴다. +type Service struct { + px proxmox.Client + queue func(node string) int + now func() time.Time + + // mu는 캐시를 지키고, 캐시를 다시 채우는 요청을 한 번에 하나만 돌게 한다. + // 그래서 오래된 캐시에 요청이 몰려도 노드마다 한 번만 묻는다 (경계 7.4). + mu sync.Mutex + cache map[string]Status // 노드 → 마지막으로 물은 값. clone_queue_length는 담지 않는다 +} + +// New는 px로 노드를 묻는 Service를 만든다. queue는 노드의 클론 줄에서 기다리는 작업 수를 준다. +func New(px proxmox.Client, queue func(node string) int, now func() time.Time) *Service { + return &Service{px: px, queue: queue, now: now, cache: map[string]Status{}} +} + +// List는 맡은 노드 전부의 현황이다 (명세 listNodes). 캐시가 cacheTTL보다 오래됐거나 refresh면 그 노드를 다시 묻는다. +// 닿지 않거나 ctx 안에 답하지 않은 노드는 online: false로 넣고, 전체를 실패로 답하지 않는다. +func (s *Service) List(ctx context.Context, refresh bool) []Status { + s.mu.Lock() + defer s.mu.Unlock() + names := s.px.Nodes() + now := s.now() + out := make([]Status, len(names)) + var wg sync.WaitGroup + for i, name := range names { + if c, ok := s.cache[name]; ok && !refresh && now.Sub(c.ObservedAt) < cacheTTL { + out[i] = c + continue + } + wg.Go(func() { out[i] = s.observe(ctx, name) }) + } + wg.Wait() + for i := range out { + s.cache[out[i].Node] = out[i] + // 클론 줄은 Infra 메모리의 값이라 캐시하지 않고 늘 지금 값을 준다. + out[i].CloneQueueLength = s.queue(out[i].Node) + } + return out +} + +// observe는 노드 하나를 묻는다. 실패하면 이유를 로그에 남기고 online: false로 준다. +func (s *Service) observe(ctx context.Context, name string) Status { + ns, err := s.px.NodeStatus(ctx, name) + var vms []proxmox.VM + if err == nil { + vms, err = s.px.VMs(ctx, name) + } + st := Status{Node: name, ObservedAt: s.now().UTC()} + if err != nil { + slog.Warn("node unreachable", "node", name, "err", err) + return st + } + st.Online = true + st.Total = &Total{CPUCores: ns.CPUCores, CPUThreads: ns.CPUThreads, MemoryMB: ns.MemoryMB, SSDGB: ns.SSDGB} + st.Usage = &Usage{CPUPercent: math.Round(ns.CPUPercent*10) / 10, MemoryUsedMB: ns.MemoryUsedMB, UptimeSec: ns.UptimeSec} + st.Configured = configured(vms) + return st +} + +// configured는 노드에 있는 모든 VM의 설정 사양 합계다. 꺼진 VM도 넣고, 템플릿은 디스크만 넣는다 (명세 NodeConfigured). +func configured(vms []proxmox.VM) *Configured { + c := &Configured{} + for _, v := range vms { + c.SSDGB += v.DiskGB + if !v.Template { + c.VCPU += v.VCPU + c.MemoryMB += v.MemoryMB + } + } + return c +} + +// VMs는 nodeName에 실제로 있는 VM이다 (명세 listNodeVms). 고아 VM을 찾는 데 쓰여서 캐시를 쓰지 않는다. +// 맡지 않은 노드면 RESOURCE_NOT_FOUND, 닿지 않으면 UPSTREAM_UNAVAILABLE이다. +func (s *Service) VMs(ctx context.Context, nodeName string) (VMList, error) { + if !NamePattern.MatchString(nodeName) { + return VMList{}, job.Invalid("INVALID_REQUEST", job.Field{Field: "node", Reason: "invalid_format"}) + } + if !slices.Contains(s.px.Nodes(), nodeName) { + return VMList{}, &job.Error{Code: "RESOURCE_NOT_FOUND"} + } + vms, err := s.px.VMs(ctx, nodeName) + if err != nil { + return VMList{}, err + } + l := VMList{Node: nodeName, ObservedAt: s.now().UTC(), Items: make([]VM, 0, len(vms))} + for _, v := range vms { + l.Items = append(l.Items, VM{VMID: v.VMID, Name: v.Name, Template: v.Template}) + } + return l, nil +} diff --git a/internal/proxmox/fake.go b/internal/proxmox/fake.go index 4fce162..41bbe96 100644 --- a/internal/proxmox/fake.go +++ b/internal/proxmox/fake.go @@ -117,6 +117,47 @@ func (f *Fake) Find(_ context.Context, name string) (VM, error) { return VM{}, &job.Error{Code: "RESOURCE_NOT_FOUND"} } +// fakeNodeStatus는 가짜 노드 하나의 총량·실사용량이다. 값은 명세 listNodes 예시와 같다. +var fakeNodeStatus = NodeStatus{ + CPUCores: 16, CPUThreads: 32, MemoryMB: 131072, SSDGB: 1800, + CPUPercent: 23.5, MemoryUsedMB: 61440, UptimeSec: 1209600, +} + +func (f *Fake) NodeStatus(_ context.Context, node string) (NodeStatus, error) { + f.mu.Lock() + defer f.mu.Unlock() + if _, err := f.reachable(node); err != nil { + return NodeStatus{}, err + } + return fakeNodeStatus, nil +} + +func (f *Fake) VMs(_ context.Context, node string) ([]VM, error) { + f.mu.Lock() + defer f.mu.Unlock() + n, err := f.reachable(node) + if err != nil { + return nil, err + } + vms := make([]VM, 0, len(n.vms)) + for _, id := range slices.Sorted(maps.Keys(n.vms)) { + vms = append(vms, *n.vms[id]) + } + return vms, nil +} + +// reachable은 맡은 노드 중 닿는 node를 준다. f.mu를 쥐고 부른다. +func (f *Fake) reachable(node string) (*fakeNode, error) { + n, ok := f.nodes[node] + switch { + case !ok: + return nil, &job.Error{Code: "RESOURCE_NOT_FOUND"} + case n.down: + return nil, &job.Error{Code: "UPSTREAM_UNAVAILABLE"} + } + return n, nil +} + // op은 바꾸는 가짜 동작 하나다. delay만큼 걸린 뒤, X-Fake-Fail code가 이 동작의 것이면 그 code로 // 실패하고, 아니면 노드에 apply를 한다. func (f *Fake) op(ctx context.Context, name string, node string, apply func(n *fakeNode) error) error { diff --git a/internal/proxmox/proxmox.go b/internal/proxmox/proxmox.go index 71d5323..7f13da1 100644 --- a/internal/proxmox/proxmox.go +++ b/internal/proxmox/proxmox.go @@ -29,6 +29,22 @@ type VM struct { Pending bool // Snapshots는 이 VM에 있는 스냅샷 이름이다. Proxmox에서 직접 만든 것도 들어 있다. Snapshots []string + // Template은 클론의 원본이 되는 템플릿인지다. + Template bool +} + +// NodeStatus는 노드 하나의 물리 총량과 Proxmox가 모아 둔 실사용량이다. +type NodeStatus struct { + // CPUCores는 물리 코어 수, CPUThreads는 논리 스레드 수다. + CPUCores int + CPUThreads int + MemoryMB int + // SSDGB는 VM 디스크를 두는 저장소 풀의 크기(GiB)다. + SSDGB int + // CPUPercent는 노드 전체 CPU 사용률(0~100)이다. + CPUPercent float64 + MemoryUsedMB int + UptimeSec int } // Config는 Configure가 VM에 넣는 값이다. @@ -52,6 +68,10 @@ type Client interface { // Find는 이름이 name인 VM을 맡은 노드에서 찾는다. 모든 노드가 답했는데 없을 때만 // RESOURCE_NOT_FOUND이고, 닿지 않는 노드가 있으면 UPSTREAM_UNAVAILABLE이다 (규약 2.1). Find(ctx context.Context, name string) (VM, error) + // NodeStatus는 node의 총량과 실사용량이다. 닿지 않으면 UPSTREAM_UNAVAILABLE이다. + NodeStatus(ctx context.Context, node string) (NodeStatus, error) + // VMs는 node에 실제로 있는 VM 전부다. 관리 밖 VM과 템플릿도 넣는다. 닿지 않으면 UPSTREAM_UNAVAILABLE이다. + VMs(ctx context.Context, node string) ([]VM, error) // Clone은 ref의 노드에 있는 image 템플릿을 ref 자리로 복제하고 name을 붙인다. // VMID_TAKEN, TEMPLATE_NOT_FOUND, NODE_CAPACITY로 실패할 수 있다. Clone(ctx context.Context, ref Ref, image, name string) error diff --git a/internal/vm/vm.go b/internal/vm/vm.go index 49b3393..622bab9 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -10,6 +10,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/proxmox" "github.com/GSMSV/GSMSV-Infra-V2/internal/resourceid" ) @@ -18,9 +19,8 @@ import ( // shortcut: 실제 Proxmox에서 재기 전의 임시값이다. 계획서 ③의 실제 Proxmox 시험에서 잰 값으로 바꾼다 (규약 12장) const guestInitTimeout = 10 * time.Minute -// 명세 VmCreateRequest·VmCloudInit의 정규식이다. +// 명세 VmCreateRequest·VmCloudInit의 정규식이다. 노드 이름은 node.NamePattern이다. var ( - nodePattern = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$`) imagePattern = regexp.MustCompile(`^[a-z0-9]+([.-][a-z0-9]+)*$`) userPattern = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}$`) hashPattern = regexp.MustCompile(`^\$6\$(rounds=[0-9]+\$)?[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}$`) @@ -73,7 +73,7 @@ func (s *Service) Create(ctx context.Context, key string, r CreateRequest) (job. return s.jobs.Submit(ctx, key, fingerprint("vm.create", r), job.Spec{ Type: "vm.create", ResourceID: r.ID, - Line: r.Node + "/" + s.px.Storage(r.Node, r.Image), + Line: cloneLine(r.Node, s.px.Storage(r.Node, r.Image)), // 키 기억을 잃은 뒤 다시 온 요청도 막는다 (규약 4.3). Precheck: func(ctx context.Context) error { _, err := s.px.Find(ctx, r.ID) @@ -108,6 +108,13 @@ func (s *Service) Create(ctx context.Context, key string, r CreateRequest) (job. }) } +// cloneLine은 VM 만들기의 클론 줄 이름이다. 같은 노드·저장소의 클론은 한 줄로 선다. +func cloneLine(nodeName, storage string) string { return nodeName + "/" + storage } + +// CloneQueue는 nodeName의 클론 줄들에서 차례를 기다리는 만들기 작업 수다. 지금 클론 중인 작업은 세지 않는다 +// (명세 NodeStatus.clone_queue_length). +func (s *Service) CloneQueue(nodeName string) int { return s.jobs.Waiting(cloneLine(nodeName, "")) } + // check는 r을 명세 형식과 이 엔진의 설정(맡은 노드, 내부 대역)으로 검사하고 내부 IP를 준다. // 틀린 칸은 모두 details.fields[]에 담는다. 값은 담지 않는다 (password_hash가 오류 본문에 나가지 않게). func (s *Service) check(r CreateRequest) (netip.Addr, error) { @@ -133,7 +140,7 @@ func (s *Service) check(r CreateRequest) (netip.Addr, error) { } } - if match("node", r.Node, nodePattern) && !slices.Contains(s.px.Nodes(), r.Node) { + if match("node", r.Node, node.NamePattern) && !slices.Contains(s.px.Nodes(), r.Node) { add("node", "unknown") } within("vmid", r.VMID, 100, 999999999) From fa2e42e59ed4ed3eea871fbb7df49af57d1b934f Mon Sep 17 00:00:00 2001 From: whiyoung Date: Wed, 2 Dec 2026 15:05:22 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20=EB=81=8A=EA=B8=B4=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD=EC=9D=98=20=EB=85=B8=EB=93=9C=20=EA=B4=80=EC=B8=A1?= =?UTF-8?q?=EC=9D=84=20=EC=BA=90=EC=8B=9C=EC=97=90=20=EB=82=A8=EA=B8=B0?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/api/node_test.go | 35 +++++++++++++++++++++++++++++++++++ internal/node/node.go | 7 ++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/internal/api/node_test.go b/internal/api/node_test.go index 7dd0758..f813c48 100644 --- a/internal/api/node_test.go +++ b/internal/api/node_test.go @@ -3,6 +3,7 @@ package api_test import ( "context" "net/http" + "net/http/httptest" "reflect" "sync" "sync/atomic" @@ -38,6 +39,20 @@ func (h hangingNode) NodeStatus(ctx context.Context, name string) (proxmox.NodeS 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)} @@ -149,6 +164,26 @@ func TestListNodesOffline(t *testing.T) { }) } +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()) diff --git a/internal/node/node.go b/internal/node/node.go index 31819e5..afa12c5 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -2,6 +2,7 @@ package node import ( "context" + "errors" "log/slog" "math" "regexp" @@ -100,8 +101,12 @@ func (s *Service) List(ctx context.Context, refresh bool) []Status { wg.Go(func() { out[i] = s.observe(ctx, name) }) } wg.Wait() + // 요청이 끊겨 멈춘 관측은 노드 상태가 아니라서 캐시에 남기지 않는다. 시간 초과(답하지 않는 노드)는 남긴다. + keep := !errors.Is(ctx.Err(), context.Canceled) for i := range out { - s.cache[out[i].Node] = out[i] + if keep { + s.cache[out[i].Node] = out[i] + } // 클론 줄은 Infra 메모리의 값이라 캐시하지 않고 늘 지금 값을 준다. out[i].CloneQueueLength = s.queue(out[i].Node) }