nvidia-smi sampler; OpenAPI spec, HTTP API and /metrics
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c3e915afaa
commit
29fafa8b3e
9 files changed
+2301
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# oapi-codegen v2 config: models, a net/http (Go 1.22 ServeMux) strict server, a typed client, and the embedded spec.
|
||||
package: api
|
||||
output: internal/api/api.gen.go
|
||||
generate:
|
||||
models: true
|
||||
std-http-server: true
|
||||
strict-server: true
|
||||
client: true
|
||||
embedded-spec: true
|
||||
@@ -0,0 +1,154 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: gpu-broker
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Hands out GPU memory on yveltal (GTX 1060 = GPU 0, GTX 1080 = GPU 1) so jobs don't fight over it.
|
||||
|
||||
A client asks for a lease with the VRAM it needs. The broker grants a GPU with room, or queues
|
||||
the request (realtime > interactive > batch, first come first served within a priority). When
|
||||
`max_wait_s` passes, a request with `cpu_fallback` is told to use the CPU instead. Leases expire
|
||||
unless renewed (`ttl_s` in the status); release them when done.
|
||||
|
||||
Listens on 127.0.0.1 only; no authentication.
|
||||
servers:
|
||||
- url: http://127.0.0.1:8130
|
||||
paths:
|
||||
/v1/health:
|
||||
get:
|
||||
operationId: health
|
||||
responses:
|
||||
"200":
|
||||
description: The broker is up and has a recent VRAM sample.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: "#/components/schemas/Health"}
|
||||
/v1/leases:
|
||||
post:
|
||||
operationId: acquireLease
|
||||
description: Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: "#/components/schemas/LeaseRequest"}
|
||||
responses:
|
||||
"200":
|
||||
description: Granted (a GPU, or the CPU).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: "#/components/schemas/Grant"}
|
||||
"400": {$ref: "#/components/responses/Problem"}
|
||||
"413": {$ref: "#/components/responses/Problem"}
|
||||
"503": {$ref: "#/components/responses/Problem"}
|
||||
/v1/leases/{id}/renew:
|
||||
post:
|
||||
operationId: renewLease
|
||||
parameters: [{$ref: "#/components/parameters/LeaseId"}]
|
||||
responses:
|
||||
"204": {description: Renewed.}
|
||||
"404": {$ref: "#/components/responses/Problem"}
|
||||
/v1/leases/{id}:
|
||||
delete:
|
||||
operationId: releaseLease
|
||||
parameters: [{$ref: "#/components/parameters/LeaseId"}]
|
||||
responses:
|
||||
"204": {description: Released (also when it had already expired).}
|
||||
/v1/status:
|
||||
get:
|
||||
operationId: status
|
||||
responses:
|
||||
"200":
|
||||
description: GPUs, leases and the queue.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: "#/components/schemas/Status"}
|
||||
components:
|
||||
parameters:
|
||||
LeaseId:
|
||||
name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string}
|
||||
responses:
|
||||
Problem:
|
||||
description: Error.
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: "#/components/schemas/Problem"}
|
||||
schemas:
|
||||
Problem:
|
||||
type: object
|
||||
required: [error]
|
||||
properties:
|
||||
error: {type: string}
|
||||
Health:
|
||||
type: object
|
||||
required: [status]
|
||||
properties:
|
||||
status: {type: string, enum: [ok, no_sample]}
|
||||
Priority:
|
||||
type: string
|
||||
enum: [batch, interactive, realtime]
|
||||
LeaseRequest:
|
||||
type: object
|
||||
required: [client, priority, vram_mb]
|
||||
properties:
|
||||
client: {type: string, description: "Who is asking, e.g. ollama-proxy, genres-guess."}
|
||||
priority: {$ref: "#/components/schemas/Priority"}
|
||||
vram_mb: {type: integer, minimum: 1}
|
||||
max_wait_s: {type: integer, minimum: 0, description: "0 or absent: wait as long as it takes."}
|
||||
cpu_fallback: {type: boolean, default: false}
|
||||
prefer:
|
||||
type: array
|
||||
items: {type: integer}
|
||||
description: GPU indexes to try first.
|
||||
Grant:
|
||||
type: object
|
||||
required: [device, gpu]
|
||||
properties:
|
||||
device: {type: string, enum: [gpu, cpu]}
|
||||
gpu: {type: integer, description: "GPU index, -1 for the CPU."}
|
||||
lease_id: {type: string, description: Absent for CPU grants.}
|
||||
expires_at: {type: string, format: date-time}
|
||||
Status:
|
||||
type: object
|
||||
required: [gpus, leases, waiting, ttl_s]
|
||||
properties:
|
||||
ttl_s: {type: integer}
|
||||
gpus:
|
||||
type: array
|
||||
items: {$ref: "#/components/schemas/GpuStatus"}
|
||||
leases:
|
||||
type: array
|
||||
items: {$ref: "#/components/schemas/LeaseInfo"}
|
||||
waiting:
|
||||
type: array
|
||||
items: {$ref: "#/components/schemas/WaitInfo"}
|
||||
GpuStatus:
|
||||
type: object
|
||||
required: [index, total_mb, used_mb, reserve_mb, free_mb]
|
||||
properties:
|
||||
index: {type: integer}
|
||||
total_mb: {type: integer}
|
||||
used_mb: {type: integer}
|
||||
reserve_mb: {type: integer}
|
||||
free_mb: {type: integer}
|
||||
LeaseInfo:
|
||||
type: object
|
||||
required: [id, client, gpu, vram_mb, granted_at, expires_at]
|
||||
properties:
|
||||
id: {type: string}
|
||||
client: {type: string}
|
||||
gpu: {type: integer}
|
||||
vram_mb: {type: integer}
|
||||
granted_at: {type: string, format: date-time}
|
||||
expires_at: {type: string, format: date-time}
|
||||
WaitInfo:
|
||||
type: object
|
||||
required: [client, priority, vram_mb, since]
|
||||
properties:
|
||||
client: {type: string}
|
||||
priority: {$ref: "#/components/schemas/Priority"}
|
||||
vram_mb: {type: integer}
|
||||
since: {type: string, format: date-time}
|
||||
@@ -1,3 +1,20 @@
|
||||
module gitea.godemperordoge.org/ziadarafat/gpu-broker
|
||||
|
||||
go 1.27.3
|
||||
|
||||
require (
|
||||
github.com/getkin/kin-openapi v0.152.0
|
||||
github.com/oapi-codegen/runtime v1.8.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.22.5 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/oasdiff/yaml v0.1.1 // indirect
|
||||
github.com/oasdiff/yaml3 v0.0.14 // indirect
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk=
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
|
||||
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
|
||||
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/getkin/kin-openapi v0.152.0 h1:XRVo77lMRyOGMHf1paMu9lxX3wzuQDZeprssZJnz/x8=
|
||||
github.com/getkin/kin-openapi v0.152.0/go.mod h1:1+BHDzstro+P5CKtPy1X4PfofnFgmRe6uvMy9+r9fKY=
|
||||
github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
|
||||
github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0=
|
||||
github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo=
|
||||
github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
|
||||
github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
|
||||
github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/3KntMs=
|
||||
github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY=
|
||||
github.com/oapi-codegen/runtime v1.8.0 h1:RJzEgQSJQADEPaG1cYuSCKYai/cCVRE2xnkrqhJs/3c=
|
||||
github.com/oapi-codegen/runtime v1.8.0/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU=
|
||||
github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY=
|
||||
github.com/oasdiff/yaml v0.1.1/go.mod h1:EYJNoyktvWMJ0Hmhx+6qTaqMOsalUaRGT8Sj1hNcegU=
|
||||
github.com/oasdiff/yaml3 v0.0.14 h1:aLJee3hxBK2H5wdXd9iPcIXb93Nty1Ge0pT171eHtkw=
|
||||
github.com/oasdiff/yaml3 v0.0.14/go.mod h1:csto2xfDjYccdUn/yw/bPjj/cYTdp6HtFA0J4TWG+gg=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
|
||||
github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,45 @@
|
||||
// Package nvsmi samples GPU memory with nvidia-smi (no cgo/NVML needed).
|
||||
package nvsmi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched"
|
||||
)
|
||||
|
||||
// Query is the nvidia-smi invocation whose output Parse reads.
|
||||
var Query = []string{"--query-gpu=index,memory.total,memory.used", "--format=csv,noheader,nounits"}
|
||||
|
||||
// Parse reads "index, total MiB, used MiB" lines.
|
||||
func Parse(out string) ([]sched.GPU, error) {
|
||||
var gpus []sched.GPU
|
||||
for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
|
||||
fields := strings.Split(line, ",")
|
||||
if len(fields) != 3 {
|
||||
return nil, fmt.Errorf("unexpected nvidia-smi line %q", line)
|
||||
}
|
||||
var n [3]int
|
||||
for i, f := range fields {
|
||||
v, err := strconv.Atoi(strings.TrimSpace(f))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unexpected nvidia-smi line %q", line)
|
||||
}
|
||||
n[i] = v
|
||||
}
|
||||
gpus = append(gpus, sched.GPU{Index: n[0], TotalMB: n[1], UsedMB: n[2]})
|
||||
}
|
||||
return gpus, nil
|
||||
}
|
||||
|
||||
// Sample runs nvidia-smi once.
|
||||
func Sample(ctx context.Context) ([]sched.GPU, error) {
|
||||
out, err := exec.CommandContext(ctx, "nvidia-smi", Query...).Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nvidia-smi: %w", err)
|
||||
}
|
||||
return Parse(string(out))
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package nvsmi
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched"
|
||||
)
|
||||
|
||||
func TestParseYveltalOutput(t *testing.T) {
|
||||
// nvidia-smi --query-gpu=index,memory.total,memory.used --format=csv,noheader,nounits on yveltal
|
||||
out := "0, 6144, 3959\n1, 8192, 4467\n"
|
||||
got, err := Parse(out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []sched.GPU{{Index: 0, TotalMB: 6144, UsedMB: 3959}, {Index: 1, TotalMB: 8192, UsedMB: 4467}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsGarbage(t *testing.T) {
|
||||
for _, out := range []string{"", "NVIDIA-SMI has failed\n", "0, 6144\n", "0, x, 1\n"} {
|
||||
if _, err := Parse(out); err == nil {
|
||||
t.Errorf("Parse(%q) accepted", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Package server exposes the scheduler over HTTP (see api/openapi.yaml) and as Prometheus metrics.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/api"
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched"
|
||||
)
|
||||
|
||||
type handlers struct {
|
||||
s *sched.Scheduler
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
var priorities = map[api.Priority]sched.Priority{
|
||||
api.Batch: sched.Batch, api.Interactive: sched.Interactive, api.Realtime: sched.Realtime,
|
||||
}
|
||||
|
||||
var priorityNames = map[sched.Priority]api.Priority{
|
||||
sched.Batch: api.Batch, sched.Interactive: api.Interactive, sched.Realtime: api.Realtime,
|
||||
}
|
||||
|
||||
func (h handlers) Health(_ context.Context, _ api.HealthRequestObject) (api.HealthResponseObject, error) {
|
||||
if len(h.s.Status().GPUs) == 0 {
|
||||
return api.Health200JSONResponse{Status: api.NoSample}, nil
|
||||
}
|
||||
return api.Health200JSONResponse{Status: api.Ok}, nil
|
||||
}
|
||||
|
||||
func (h handlers) AcquireLease(ctx context.Context, r api.AcquireLeaseRequestObject) (api.AcquireLeaseResponseObject, error) {
|
||||
body := r.Body
|
||||
priority, ok := priorities[body.Priority]
|
||||
if !ok || body.VramMb < 1 || body.Client == "" {
|
||||
return api.AcquireLease400JSONResponse{ProblemJSONResponse: api.ProblemJSONResponse{Error: "need client, priority and vram_mb >= 1"}}, nil
|
||||
}
|
||||
req := sched.Request{Client: body.Client, Priority: priority, VRAMMB: body.VramMb}
|
||||
if body.MaxWaitS != nil {
|
||||
req.MaxWait = time.Duration(*body.MaxWaitS) * time.Second
|
||||
}
|
||||
if body.CpuFallback != nil {
|
||||
req.CPUFallback = *body.CpuFallback
|
||||
}
|
||||
if body.Prefer != nil {
|
||||
req.Prefer = *body.Prefer
|
||||
}
|
||||
g, err := h.s.Acquire(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, sched.ErrTooBig):
|
||||
return api.AcquireLease413JSONResponse{Error: err.Error()}, nil
|
||||
case errors.Is(err, sched.ErrTimeout):
|
||||
return api.AcquireLease503JSONResponse{Error: err.Error()}, nil
|
||||
case err != nil:
|
||||
return nil, err
|
||||
}
|
||||
if g.GPU == sched.CPU {
|
||||
return api.AcquireLease200JSONResponse{Device: api.Cpu, Gpu: sched.CPU}, nil
|
||||
}
|
||||
return api.AcquireLease200JSONResponse{Device: api.Gpu, Gpu: g.GPU, LeaseId: &g.LeaseID, ExpiresAt: &g.ExpiresAt}, nil
|
||||
}
|
||||
|
||||
func (h handlers) RenewLease(_ context.Context, r api.RenewLeaseRequestObject) (api.RenewLeaseResponseObject, error) {
|
||||
if err := h.s.Renew(r.Id); err != nil {
|
||||
return api.RenewLease404JSONResponse{ProblemJSONResponse: api.ProblemJSONResponse{Error: err.Error()}}, nil
|
||||
}
|
||||
return api.RenewLease204Response{}, nil
|
||||
}
|
||||
|
||||
func (h handlers) ReleaseLease(_ context.Context, r api.ReleaseLeaseRequestObject) (api.ReleaseLeaseResponseObject, error) {
|
||||
h.s.Release(r.Id)
|
||||
return api.ReleaseLease204Response{}, nil
|
||||
}
|
||||
|
||||
func (h handlers) Status(_ context.Context, _ api.StatusRequestObject) (api.StatusResponseObject, error) {
|
||||
st := h.s.Status()
|
||||
out := api.Status200JSONResponse{TtlS: int(h.ttl / time.Second)}
|
||||
for _, g := range st.GPUs {
|
||||
out.Gpus = append(out.Gpus, api.GpuStatus{Index: g.Index, TotalMb: g.TotalMB, UsedMb: g.UsedMB, ReserveMb: g.ReserveMB, FreeMb: g.FreeMB})
|
||||
}
|
||||
for _, l := range st.Leases {
|
||||
out.Leases = append(out.Leases, api.LeaseInfo{Id: l.ID, Client: l.Client, Gpu: l.GPU, VramMb: l.VRAMMB, GrantedAt: l.Granted, ExpiresAt: l.Expires})
|
||||
}
|
||||
for _, w := range st.Waiting {
|
||||
out.Waiting = append(out.Waiting, api.WaitInfo{Client: w.Client, Priority: priorityNames[w.Priority], VramMb: w.VRAMMB, Since: w.Since})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Handler serves the API plus /metrics.
|
||||
func Handler(s *sched.Scheduler, ttl time.Duration) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
api.HandlerFromMux(api.NewStrictHandler(handlers{s: s, ttl: ttl}, nil), mux)
|
||||
mux.HandleFunc("GET /metrics", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
|
||||
fmt.Fprint(w, Metrics(s))
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
// Tick drives lease expiry and queue timeouts until ctx ends.
|
||||
func Tick(ctx context.Context, s *sched.Scheduler, every time.Duration) {
|
||||
t := time.NewTicker(every)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
s.Tick()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Metrics renders the scheduler state in the Prometheus text format.
|
||||
func Metrics(s *sched.Scheduler) string {
|
||||
st := s.Status()
|
||||
var b strings.Builder
|
||||
b.WriteString("# HELP gpu_broker_vram_free_mb VRAM the broker can still lease (after reserve and fresh leases).\n# TYPE gpu_broker_vram_free_mb gauge\n")
|
||||
gpus := st.GPUs
|
||||
sort.Slice(gpus, func(i, j int) bool { return gpus[i].Index < gpus[j].Index })
|
||||
for _, g := range gpus {
|
||||
fmt.Fprintf(&b, "gpu_broker_vram_free_mb{gpu=\"%d\"} %d\n", g.Index, g.FreeMB)
|
||||
}
|
||||
b.WriteString("# HELP gpu_broker_vram_used_mb VRAM in use per nvidia-smi.\n# TYPE gpu_broker_vram_used_mb gauge\n")
|
||||
for _, g := range gpus {
|
||||
fmt.Fprintf(&b, "gpu_broker_vram_used_mb{gpu=\"%d\"} %d\n", g.Index, g.UsedMB)
|
||||
}
|
||||
fmt.Fprintf(&b, "# HELP gpu_broker_leases Active leases.\n# TYPE gpu_broker_leases gauge\ngpu_broker_leases %d\n", len(st.Leases))
|
||||
fmt.Fprintf(&b, "# HELP gpu_broker_waiting Queued requests.\n# TYPE gpu_broker_waiting gauge\ngpu_broker_waiting %d\n", len(st.Waiting))
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/api"
|
||||
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched"
|
||||
)
|
||||
|
||||
func ptr[T any](v T) *T { return &v }
|
||||
|
||||
// start runs the broker's HTTP API over a real scheduler (real clock, fast ticks).
|
||||
func start(t *testing.T, used0, used1 int) (*api.ClientWithResponses, *sched.Scheduler) {
|
||||
t.Helper()
|
||||
s := sched.New(sched.Config{ReserveMB: map[int]int{0: 1500}, LoadWindow: time.Minute, LeaseTTL: time.Minute}, time.Now)
|
||||
s.Observe([]sched.GPU{{Index: 0, TotalMB: 6144, UsedMB: used0}, {Index: 1, TotalMB: 8192, UsedMB: used1}})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go Tick(ctx, s, 20*time.Millisecond)
|
||||
srv := httptest.NewServer(Handler(s, time.Minute))
|
||||
t.Cleanup(srv.Close)
|
||||
c, err := api.NewClientWithResponses(srv.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c, s
|
||||
}
|
||||
|
||||
func TestLeaseIsGrantedRenewedAndReleased(t *testing.T) {
|
||||
c, s := start(t, 0, 0)
|
||||
ctx := context.Background()
|
||||
r, err := c.AcquireLeaseWithResponse(ctx, api.AcquireLeaseJSONRequestBody{
|
||||
Client: "genres", Priority: api.Interactive, VramMb: 7000, Prefer: ptr([]int{1}),
|
||||
})
|
||||
if err != nil || r.JSON200 == nil {
|
||||
t.Fatalf("%v %s", err, r.Body)
|
||||
}
|
||||
g := r.JSON200
|
||||
if g.Device != api.Gpu || g.Gpu != 1 || g.LeaseId == nil {
|
||||
t.Fatalf("grant %+v", g)
|
||||
}
|
||||
if rr, _ := c.RenewLeaseWithResponse(ctx, *g.LeaseId); rr.StatusCode() != 204 {
|
||||
t.Fatalf("renew %d", rr.StatusCode())
|
||||
}
|
||||
st, _ := c.StatusWithResponse(ctx)
|
||||
if len(st.JSON200.Leases) != 1 || st.JSON200.Leases[0].Client != "genres" {
|
||||
t.Fatalf("status %+v", st.JSON200)
|
||||
}
|
||||
if rel, _ := c.ReleaseLeaseWithResponse(ctx, *g.LeaseId); rel.StatusCode() != 204 {
|
||||
t.Fatalf("release %d", rel.StatusCode())
|
||||
}
|
||||
if len(s.Status().Leases) != 0 {
|
||||
t.Fatal("lease still there")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusyGPUsWithFallbackAnswerCPU(t *testing.T) {
|
||||
c, _ := start(t, 6144, 8192)
|
||||
r, err := c.AcquireLeaseWithResponse(context.Background(), api.AcquireLeaseJSONRequestBody{
|
||||
Client: "genres", Priority: api.Batch, VramMb: 3000, MaxWaitS: ptr(1), CpuFallback: ptr(true),
|
||||
})
|
||||
if err != nil || r.JSON200 == nil || r.JSON200.Device != api.Cpu || r.JSON200.Gpu != -1 {
|
||||
t.Fatalf("%v %s", err, r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusyGPUsWithoutFallbackAre503(t *testing.T) {
|
||||
c, _ := start(t, 6144, 8192)
|
||||
r, _ := c.AcquireLeaseWithResponse(context.Background(), api.AcquireLeaseJSONRequestBody{
|
||||
Client: "llama", Priority: api.Interactive, VramMb: 3000, MaxWaitS: ptr(1),
|
||||
})
|
||||
if r.StatusCode() != 503 || !strings.Contains(string(r.Body), "no GPU became free") {
|
||||
t.Fatalf("%d %s", r.StatusCode(), r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTooBigWithoutFallbackIs413(t *testing.T) {
|
||||
c, _ := start(t, 0, 0)
|
||||
r, _ := c.AcquireLeaseWithResponse(context.Background(), api.AcquireLeaseJSONRequestBody{
|
||||
Client: "ollama", Priority: api.Interactive, VramMb: 17000,
|
||||
})
|
||||
if r.StatusCode() != 413 {
|
||||
t.Fatalf("%d %s", r.StatusCode(), r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewingAnUnknownLeaseIs404(t *testing.T) {
|
||||
c, _ := start(t, 0, 0)
|
||||
if r, _ := c.RenewLeaseWithResponse(context.Background(), "nope"); r.StatusCode() != 404 {
|
||||
t.Fatalf("%d", r.StatusCode())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthWantsASample(t *testing.T) {
|
||||
c, _ := start(t, 0, 0)
|
||||
r, _ := c.HealthWithResponse(context.Background())
|
||||
if r.JSON200 == nil || r.JSON200.Status != api.Ok {
|
||||
t.Fatalf("%s", r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsShowFreeVRAMPerGPU(t *testing.T) {
|
||||
_, s := start(t, 1000, 2000)
|
||||
body := Metrics(s)
|
||||
for _, want := range []string{
|
||||
`gpu_broker_vram_free_mb{gpu="0"} 3644`,
|
||||
`gpu_broker_vram_free_mb{gpu="1"} 6192`,
|
||||
"gpu_broker_leases 0",
|
||||
"gpu_broker_waiting 0",
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics missing %q:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user