diff --git a/api/oapi-codegen.yaml b/api/oapi-codegen.yaml new file mode 100644 index 0000000..8a6f89b --- /dev/null +++ b/api/oapi-codegen.yaml @@ -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 diff --git a/api/openapi.yaml b/api/openapi.yaml new file mode 100644 index 0000000..f582f7c --- /dev/null +++ b/api/openapi.yaml @@ -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} diff --git a/go.mod b/go.mod index f70a186..c726b2b 100644 --- a/go.mod +++ b/go.mod @@ -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 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5bb0b24 --- /dev/null +++ b/go.sum @@ -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= diff --git a/internal/api/api.gen.go b/internal/api/api.gen.go new file mode 100644 index 0000000..0da112c --- /dev/null +++ b/internal/api/api.gen.go @@ -0,0 +1,1740 @@ +//go:build go1.22 + +// Package api provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.8.2 DO NOT EDIT. +package api + +import ( + "bytes" + "compress/flate" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/getkin/kin-openapi/openapi3" + "github.com/oapi-codegen/runtime" +) + +// Defines values for GrantDevice. +const ( + Cpu GrantDevice = "cpu" + Gpu GrantDevice = "gpu" +) + +// Valid indicates whether the value is a known member of the GrantDevice enum. +func (e GrantDevice) Valid() bool { + switch e { + case Cpu: + return true + case Gpu: + return true + default: + return false + } +} + +// Defines values for HealthStatus. +const ( + NoSample HealthStatus = "no_sample" + Ok HealthStatus = "ok" +) + +// Valid indicates whether the value is a known member of the HealthStatus enum. +func (e HealthStatus) Valid() bool { + switch e { + case NoSample: + return true + case Ok: + return true + default: + return false + } +} + +// Defines values for Priority. +const ( + Batch Priority = "batch" + Interactive Priority = "interactive" + Realtime Priority = "realtime" +) + +// Valid indicates whether the value is a known member of the Priority enum. +func (e Priority) Valid() bool { + switch e { + case Batch: + return true + case Interactive: + return true + case Realtime: + return true + default: + return false + } +} + +// GpuStatus defines model for GpuStatus. +type GpuStatus struct { + FreeMb int `json:"free_mb"` + Index int `json:"index"` + ReserveMb int `json:"reserve_mb"` + TotalMb int `json:"total_mb"` + UsedMb int `json:"used_mb"` +} + +// Grant defines model for Grant. +type Grant struct { + Device GrantDevice `json:"device"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + + // Gpu GPU index, -1 for the CPU. + Gpu int `json:"gpu"` + + // LeaseId Absent for CPU grants. + LeaseId *string `json:"lease_id,omitempty"` +} + +// GrantDevice defines model for Grant.Device. +type GrantDevice string + +// Health defines model for Health. +type Health struct { + Status HealthStatus `json:"status"` +} + +// HealthStatus defines model for Health.Status. +type HealthStatus string + +// LeaseInfo defines model for LeaseInfo. +type LeaseInfo struct { + Client string `json:"client"` + ExpiresAt time.Time `json:"expires_at"` + Gpu int `json:"gpu"` + GrantedAt time.Time `json:"granted_at"` + Id string `json:"id"` + VramMb int `json:"vram_mb"` +} + +// LeaseRequest defines model for LeaseRequest. +type LeaseRequest struct { + // Client Who is asking, e.g. ollama-proxy, genres-guess. + Client string `json:"client"` + CpuFallback *bool `json:"cpu_fallback,omitempty"` + + // MaxWaitS 0 or absent: wait as long as it takes. + MaxWaitS *int `json:"max_wait_s,omitempty"` + + // Prefer GPU indexes to try first. + Prefer *[]int `json:"prefer,omitempty"` + Priority Priority `json:"priority"` + VramMb int `json:"vram_mb"` +} + +// Priority defines model for Priority. +type Priority string + +// Problem defines model for Problem. +type Problem struct { + Error string `json:"error"` +} + +// Status defines model for Status. +type Status struct { + Gpus []GpuStatus `json:"gpus"` + Leases []LeaseInfo `json:"leases"` + TtlS int `json:"ttl_s"` + Waiting []WaitInfo `json:"waiting"` +} + +// WaitInfo defines model for WaitInfo. +type WaitInfo struct { + Client string `json:"client"` + Priority Priority `json:"priority"` + Since time.Time `json:"since"` + VramMb int `json:"vram_mb"` +} + +// LeaseId defines model for LeaseId. +type LeaseId = string + +// AcquireLeaseJSONRequestBody defines body for AcquireLease for application/json ContentType. +type AcquireLeaseJSONRequestBody = LeaseRequest + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + + // Health performs a GET /v1/health (the `Health` operationId) request. + Health(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AcquireLeaseWithBody performs a POST /v1/leases (the `AcquireLease` operationId) request, + // with any type of body and a specified content type. + // + // Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. + AcquireLeaseWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AcquireLease performs a POST /v1/leases (the `AcquireLease` operationId) request. + // Takes a body of the `application/json` content type. + // + // Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. + AcquireLease(ctx context.Context, body AcquireLeaseJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ReleaseLease performs a DELETE /v1/leases/{id} (the `ReleaseLease` operationId) request. + ReleaseLease(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RenewLease performs a POST /v1/leases/{id}/renew (the `RenewLease` operationId) request. + RenewLease(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*http.Response, error) + + // Status performs a GET /v1/status (the `Status` operationId) request. + Status(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +// Health performs a GET /v1/health (the `Health` operationId) request. +func (c *Client) Health(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewHealthRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// AcquireLeaseWithBody performs a POST /v1/leases (the `AcquireLease` operationId) request, +// with any type of body and a specified content type. +// +// Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. +func (c *Client) AcquireLeaseWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAcquireLeaseRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// AcquireLease performs a POST /v1/leases (the `AcquireLease` operationId) request. +// Takes a body of the `application/json` content type. +// +// Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. +func (c *Client) AcquireLease(ctx context.Context, body AcquireLeaseJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAcquireLeaseRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ReleaseLease performs a DELETE /v1/leases/{id} (the `ReleaseLease` operationId) request. +func (c *Client) ReleaseLease(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewReleaseLeaseRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// RenewLease performs a POST /v1/leases/{id}/renew (the `RenewLease` operationId) request. +func (c *Client) RenewLease(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRenewLeaseRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// Status performs a GET /v1/status (the `Status` operationId) request. +func (c *Client) Status(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewStatusRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewHealthRequest constructs an http.Request for the Health method +func NewHealthRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/health") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewAcquireLeaseRequest calls the generic AcquireLease builder with application/json body +func NewAcquireLeaseRequest(server string, body AcquireLeaseJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewAcquireLeaseRequestWithBody(server, "application/json", bodyReader) +} + +// NewAcquireLeaseRequestWithBody constructs an http.Request for the AcquireLease method, with any body, and a specified content type +func NewAcquireLeaseRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/leases") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewReleaseLeaseRequest constructs an http.Request for the ReleaseLease method +func NewReleaseLeaseRequest(server string, id LeaseId) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/leases/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRenewLeaseRequest constructs an http.Request for the RenewLease method +func NewRenewLeaseRequest(server string, id LeaseId) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/leases/%s/renew", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewStatusRequest constructs an http.Request for the Status method +func NewStatusRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/status") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + + // HealthWithResponse performs a GET /v1/health (the `Health` operationId) request. + // + // Returns a wrapper object for the known response body format(s). + HealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*HealthResponse, error) + + // AcquireLeaseWithBodyWithResponse performs a POST /v1/leases (the `AcquireLease` operationId) request, + // with any type of body and a specified content type. + // + // Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. + // + // Returns a wrapper object for the known response body format(s). + AcquireLeaseWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AcquireLeaseResponse, error) + + // AcquireLeaseWithResponse performs a POST /v1/leases (the `AcquireLease` operationId) request. + // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). + // + // Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. + AcquireLeaseWithResponse(ctx context.Context, body AcquireLeaseJSONRequestBody, reqEditors ...RequestEditorFn) (*AcquireLeaseResponse, error) + + // ReleaseLeaseWithResponse performs a DELETE /v1/leases/{id} (the `ReleaseLease` operationId) request. + // + // Returns a wrapper object for the known response body format(s). + ReleaseLeaseWithResponse(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*ReleaseLeaseResponse, error) + + // RenewLeaseWithResponse performs a POST /v1/leases/{id}/renew (the `RenewLease` operationId) request. + // + // Returns a wrapper object for the known response body format(s). + RenewLeaseWithResponse(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*RenewLeaseResponse, error) + + // StatusWithResponse performs a GET /v1/status (the `Status` operationId) request. + // + // Returns a wrapper object for the known response body format(s). + StatusWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*StatusResponse, error) +} + +type HealthResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *Health +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r HealthResponse) GetJSON200() *Health { + return r.JSON200 +} + +// GetBody returns the raw response body bytes +func (r HealthResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r HealthResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r HealthResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r HealthResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type AcquireLeaseResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *Grant + // JSON400 the response for an HTTP 400 `application/json` response + JSON400 *Problem + // JSON413 the response for an HTTP 413 `application/json` response + JSON413 *Problem + // JSON503 the response for an HTTP 503 `application/json` response + JSON503 *Problem +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r AcquireLeaseResponse) GetJSON200() *Grant { + return r.JSON200 +} + +// GetJSON400 returns the response for an HTTP 400 `application/json` response +func (r AcquireLeaseResponse) GetJSON400() *Problem { + return r.JSON400 +} + +// GetJSON413 returns the response for an HTTP 413 `application/json` response +func (r AcquireLeaseResponse) GetJSON413() *Problem { + return r.JSON413 +} + +// GetJSON503 returns the response for an HTTP 503 `application/json` response +func (r AcquireLeaseResponse) GetJSON503() *Problem { + return r.JSON503 +} + +// GetBody returns the raw response body bytes +func (r AcquireLeaseResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r AcquireLeaseResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AcquireLeaseResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r AcquireLeaseResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ReleaseLeaseResponse struct { + Body []byte + HTTPResponse *http.Response +} + +// GetBody returns the raw response body bytes +func (r ReleaseLeaseResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r ReleaseLeaseResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ReleaseLeaseResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ReleaseLeaseResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type RenewLeaseResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON404 the response for an HTTP 404 `application/json` response + JSON404 *Problem +} + +// GetJSON404 returns the response for an HTTP 404 `application/json` response +func (r RenewLeaseResponse) GetJSON404() *Problem { + return r.JSON404 +} + +// GetBody returns the raw response body bytes +func (r RenewLeaseResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r RenewLeaseResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RenewLeaseResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r RenewLeaseResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type StatusResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *Status +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r StatusResponse) GetJSON200() *Status { + return r.JSON200 +} + +// GetBody returns the raw response body bytes +func (r StatusResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r StatusResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r StatusResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r StatusResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +// HealthWithResponse performs a GET /v1/health (the `Health` operationId) request. +// +// Returns a wrapper object for the known response body format(s). +func (c *ClientWithResponses) HealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*HealthResponse, error) { + rsp, err := c.Health(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseHealthResponse(rsp) +} + +// AcquireLeaseWithBodyWithResponse performs a POST /v1/leases (the `AcquireLease` operationId) request, +// with any type of body and a specified content type. +// +// Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. +// +// Returns a wrapper object for the known response body format(s). +func (c *ClientWithResponses) AcquireLeaseWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AcquireLeaseResponse, error) { + rsp, err := c.AcquireLeaseWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAcquireLeaseResponse(rsp) +} + +// AcquireLeaseWithResponse performs a POST /v1/leases (the `AcquireLease` operationId) request. +// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). +// +// Blocks until a GPU is free, the CPU fallback applies, or max_wait_s passes. +func (c *ClientWithResponses) AcquireLeaseWithResponse(ctx context.Context, body AcquireLeaseJSONRequestBody, reqEditors ...RequestEditorFn) (*AcquireLeaseResponse, error) { + rsp, err := c.AcquireLease(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAcquireLeaseResponse(rsp) +} + +// ReleaseLeaseWithResponse performs a DELETE /v1/leases/{id} (the `ReleaseLease` operationId) request. +// +// Returns a wrapper object for the known response body format(s). +func (c *ClientWithResponses) ReleaseLeaseWithResponse(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*ReleaseLeaseResponse, error) { + rsp, err := c.ReleaseLease(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseReleaseLeaseResponse(rsp) +} + +// RenewLeaseWithResponse performs a POST /v1/leases/{id}/renew (the `RenewLease` operationId) request. +// +// Returns a wrapper object for the known response body format(s). +func (c *ClientWithResponses) RenewLeaseWithResponse(ctx context.Context, id LeaseId, reqEditors ...RequestEditorFn) (*RenewLeaseResponse, error) { + rsp, err := c.RenewLease(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseRenewLeaseResponse(rsp) +} + +// StatusWithResponse performs a GET /v1/status (the `Status` operationId) request. +// +// Returns a wrapper object for the known response body format(s). +func (c *ClientWithResponses) StatusWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*StatusResponse, error) { + rsp, err := c.Status(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseStatusResponse(rsp) +} + +// ParseHealthResponse parses an HTTP response from a HealthWithResponse call +func ParseHealthResponse(rsp *http.Response) (*HealthResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &HealthResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Health + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseAcquireLeaseResponse parses an HTTP response from a AcquireLeaseWithResponse call +func ParseAcquireLeaseResponse(rsp *http.Response) (*AcquireLeaseResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AcquireLeaseResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Grant + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 413: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON413 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON503 = &dest + + } + + return response, nil +} + +// ParseReleaseLeaseResponse parses an HTTP response from a ReleaseLeaseWithResponse call +func ParseReleaseLeaseResponse(rsp *http.Response) (*ReleaseLeaseResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ReleaseLeaseResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + return response, nil +} + +// ParseRenewLeaseResponse parses an HTTP response from a RenewLeaseWithResponse call +func ParseRenewLeaseResponse(rsp *http.Response) (*RenewLeaseResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RenewLeaseResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseStatusResponse parses an HTTP response from a StatusWithResponse call +func ParseStatusResponse(rsp *http.Response) (*StatusResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &StatusResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Status + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + + // (GET /v1/health) + Health(w http.ResponseWriter, r *http.Request) + + // (POST /v1/leases) + AcquireLease(w http.ResponseWriter, r *http.Request) + + // (DELETE /v1/leases/{id}) + ReleaseLease(w http.ResponseWriter, r *http.Request, id LeaseId) + + // (POST /v1/leases/{id}/renew) + RenewLease(w http.ResponseWriter, r *http.Request, id LeaseId) + + // (GET /v1/status) + Status(w http.ResponseWriter, r *http.Request) +} + +// ServerInterfaceWrapper converts contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface + HandlerMiddlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +type MiddlewareFunc func(http.Handler) http.Handler + +// Health operation middleware +func (siw *ServerInterfaceWrapper) Health(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.Health(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// AcquireLease operation middleware +func (siw *ServerInterfaceWrapper) AcquireLease(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AcquireLease(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// ReleaseLease operation middleware +func (siw *ServerInterfaceWrapper) ReleaseLease(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // ------------- Path parameter "id" ------------- + var id LeaseId + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: "", ValueIsUnescaped: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ReleaseLease(w, r, id) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// RenewLease operation middleware +func (siw *ServerInterfaceWrapper) RenewLease(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // ------------- Path parameter "id" ------------- + var id LeaseId + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: "", ValueIsUnescaped: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.RenewLease(w, r, id) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// Status operation middleware +func (siw *ServerInterfaceWrapper) Status(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.Status(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +type UnescapedCookieParamError struct { + ParamName string + Err error +} + +func (e *UnescapedCookieParamError) Error() string { + return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) +} + +func (e *UnescapedCookieParamError) Unwrap() error { + return e.Err +} + +type UnmarshalingParamError struct { + ParamName string + Err error +} + +func (e *UnmarshalingParamError) Error() string { + return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) +} + +func (e *UnmarshalingParamError) Unwrap() error { + return e.Err +} + +type RequiredParamError struct { + ParamName string +} + +func (e *RequiredParamError) Error() string { + return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) +} + +type RequiredHeaderError struct { + ParamName string + Err error +} + +func (e *RequiredHeaderError) Error() string { + return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) +} + +func (e *RequiredHeaderError) Unwrap() error { + return e.Err +} + +type InvalidParamFormatError struct { + ParamName string + Err error +} + +func (e *InvalidParamFormatError) Error() string { + return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) +} + +func (e *InvalidParamFormatError) Unwrap() error { + return e.Err +} + +type TooManyValuesForParamError struct { + ParamName string + Count int +} + +func (e *TooManyValuesForParamError) Error() string { + return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) +} + +// Handler creates http.Handler with routing matching OpenAPI spec. +func Handler(si ServerInterface) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{}) +} + +// ServeMux is an abstraction of [http.ServeMux]. +type ServeMux interface { + HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) + http.Handler +} + +type StdHTTPServerOptions struct { + BaseURL string + BaseRouter ServeMux + Middlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. +func HandlerFromMux(si ServerInterface, m ServeMux) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{ + BaseRouter: m, + }) +} + +func HandlerFromMuxWithBaseURL(si ServerInterface, m ServeMux, baseURL string) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{ + BaseURL: baseURL, + BaseRouter: m, + }) +} + +// HandlerWithOptions creates http.Handler with additional options +func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler { + m := options.BaseRouter + + if m == nil { + m = http.NewServeMux() + } + if options.ErrorHandlerFunc == nil { + options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } + + wrapper := ServerInterfaceWrapper{ + Handler: si, + HandlerMiddlewares: options.Middlewares, + ErrorHandlerFunc: options.ErrorHandlerFunc, + } + + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/v1/health", wrapper.Health) + m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/v1/leases", wrapper.AcquireLease) + m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/v1/leases/{id}/renew", wrapper.RenewLease) + m.HandleFunc(http.MethodDelete+" "+options.BaseURL+"/v1/leases/{id}", wrapper.ReleaseLease) + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/v1/status", wrapper.Status) + + return m +} + +type ProblemJSONResponse Problem + +type HealthRequestObject struct { +} + +type HealthResponseObject interface { + VisitHealthResponse(w http.ResponseWriter) error +} + +type Health200JSONResponse Health + +func (response Health200JSONResponse) VisitHealthResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type AcquireLeaseRequestObject struct { + Body *AcquireLeaseJSONRequestBody +} + +type AcquireLeaseResponseObject interface { + VisitAcquireLeaseResponse(w http.ResponseWriter) error +} + +type AcquireLease200JSONResponse Grant + +func (response AcquireLease200JSONResponse) VisitAcquireLeaseResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type AcquireLease400JSONResponse struct{ ProblemJSONResponse } + +func (response AcquireLease400JSONResponse) VisitAcquireLeaseResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + _, err := buf.WriteTo(w) + return err +} + +type AcquireLease413JSONResponse Problem + +func (response AcquireLease413JSONResponse) VisitAcquireLeaseResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(413) + _, err := buf.WriteTo(w) + return err +} + +type AcquireLease503JSONResponse Problem + +func (response AcquireLease503JSONResponse) VisitAcquireLeaseResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(503) + _, err := buf.WriteTo(w) + return err +} + +type ReleaseLeaseRequestObject struct { + Id LeaseId `json:"id"` +} + +type ReleaseLeaseResponseObject interface { + VisitReleaseLeaseResponse(w http.ResponseWriter) error +} + +type ReleaseLease204Response struct { +} + +func (response ReleaseLease204Response) VisitReleaseLeaseResponse(w http.ResponseWriter) error { + w.WriteHeader(204) + return nil +} + +type RenewLeaseRequestObject struct { + Id LeaseId `json:"id"` +} + +type RenewLeaseResponseObject interface { + VisitRenewLeaseResponse(w http.ResponseWriter) error +} + +type RenewLease204Response struct { +} + +func (response RenewLease204Response) VisitRenewLeaseResponse(w http.ResponseWriter) error { + w.WriteHeader(204) + return nil +} + +type RenewLease404JSONResponse struct{ ProblemJSONResponse } + +func (response RenewLease404JSONResponse) VisitRenewLeaseResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + _, err := buf.WriteTo(w) + return err +} + +type StatusRequestObject struct { +} + +type StatusResponseObject interface { + VisitStatusResponse(w http.ResponseWriter) error +} + +type Status200JSONResponse Status + +func (response Status200JSONResponse) VisitStatusResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +// StrictServerInterface represents all server handlers. +type StrictServerInterface interface { + + // (GET /v1/health) + Health(ctx context.Context, request HealthRequestObject) (HealthResponseObject, error) + + // (POST /v1/leases) + AcquireLease(ctx context.Context, request AcquireLeaseRequestObject) (AcquireLeaseResponseObject, error) + + // (DELETE /v1/leases/{id}) + ReleaseLease(ctx context.Context, request ReleaseLeaseRequestObject) (ReleaseLeaseResponseObject, error) + + // (POST /v1/leases/{id}/renew) + RenewLease(ctx context.Context, request RenewLeaseRequestObject) (RenewLeaseResponseObject, error) + + // (GET /v1/status) + Status(ctx context.Context, request StatusRequestObject) (StatusResponseObject, error) +} + +type StrictHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error) +type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFunc + +type StrictHTTPServerOptions struct { + RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) + ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { + return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ + RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + }, + ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusInternalServerError) + }, + }} +} + +func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { + if options.RequestErrorHandlerFunc == nil { + options.RequestErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } + if options.ResponseErrorHandlerFunc == nil { + options.ResponseErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + } + return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} +} + +type strictHandler struct { + ssi StrictServerInterface + middlewares []StrictMiddlewareFunc + options StrictHTTPServerOptions +} + +// Health operation middleware +func (sh *strictHandler) Health(w http.ResponseWriter, r *http.Request) { + var request HealthRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.Health(ctx, request.(HealthRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "Health") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(HealthResponseObject); ok { + if err := validResponse.VisitHealthResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// AcquireLease operation middleware +func (sh *strictHandler) AcquireLease(w http.ResponseWriter, r *http.Request) { + var request AcquireLeaseRequestObject + + var body AcquireLeaseJSONRequestBody + if err := runtime.BindJSONBody(r, &body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.AcquireLease(ctx, request.(AcquireLeaseRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "AcquireLease") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(AcquireLeaseResponseObject); ok { + if err := validResponse.VisitAcquireLeaseResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// ReleaseLease operation middleware +func (sh *strictHandler) ReleaseLease(w http.ResponseWriter, r *http.Request, id LeaseId) { + var request ReleaseLeaseRequestObject + + request.Id = id + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.ReleaseLease(ctx, request.(ReleaseLeaseRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "ReleaseLease") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(ReleaseLeaseResponseObject); ok { + if err := validResponse.VisitReleaseLeaseResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// RenewLease operation middleware +func (sh *strictHandler) RenewLease(w http.ResponseWriter, r *http.Request, id LeaseId) { + var request RenewLeaseRequestObject + + request.Id = id + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.RenewLease(ctx, request.(RenewLeaseRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "RenewLease") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(RenewLeaseResponseObject); ok { + if err := validResponse.VisitRenewLeaseResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// Status operation middleware +func (sh *strictHandler) Status(w http.ResponseWriter, r *http.Request) { + var request StatusRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.Status(ctx, request.(StatusRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "Status") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(StatusResponseObject); ok { + if err := validResponse.VisitStatusResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// Base64 encoded, compressed with deflate, json marshaled OpenAPI spec. +// Stored as a slice of fixed-width chunks rather than one concatenated +// const string: with thousands of chunks the chained `+` fold is several +// times slower for the Go compiler than parsing a slice literal. +var swaggerSpec = []string{ + "vFdtb9u2E/8qB/7/wBJAkeUm2woVe5EWQzqgA4KuWQc0gUNLZ4sNRarkKYkR6LsPJCX5QXKaFO1emabI", + "e/zd744PLNNlpRUqsix9YBU3vERC4/+9Q27xj9wthWIpqzgVLGKKl8hSJnIWMYNfamEwZymZGiNmswJL", + "7m7QqnKnLBmhlqxpGnfYVlpZ9MLPjZ5LLN0y04pQkVvyqpIi4yS0mny2Wrm9tcz/G1ywlP1vsrZ6Er7a", + "SSfPa8rRZkZUTgxL2e/GaBMz96E97YSdVfVfxKkOjhtdoSERbFsYxFk533BDKMIlGtZETKgc78c/GbRo", + "bvdfJU1c7v1aW8z3fGw2I/2pNWFD3vrylhFR78lV1MnU88+YkdN3ZriiofM53ooM3QpVXTp1y6pmEcuq", + "ekNMl9eI4X0lDNoZ97IW2pRuxXJOeESiRDZyx0lMH3bSdHZ+Ad6zCI6msNAGqEB4c34Rs2gQkYhJ5BZn", + "Ih8KOp1bVOQlvDm/gKXz08ZDO3ai2joerBsL2FvkkophxGwPoy5i+sbViZ5ZXlYS2dXXVLcSxpSGIlQL", + "PdSbSdGWzfdMyjDSPoCYP0tYyMtg+9bw8okYd/TSehi1EOxub5m05ezeCL7HLzVaeiyI2yD6WGgQFri9", + "EWoZAcbLGLSUvORHldH3qwiWqAzao2WNdgxdvmJmCy7lnGc3QcGC15JYuuDSYn9hrrVErtyNkt/P7rig", + "mR0alIA2wD20U3CHgFuQWi3dryAgfoPejlIoUTocJmNlUxlcoHmk+tACaSCzgoUwlpxEQVjaPZQWdrgx", + "fBXEC20Erb5O1+25bVD0tk+jrwGkx0avci1pDAbnG5Z1dTrnlLmW5nQYnpG4Rc+gXHpcj9HdRt/aBhK6", + "LjPW+bbNDsfGDNzXjZZV2O2z8Fhc111tJDmeMp8ua009I7KI5GwPJhw4netP1fORCxpXsxM7H4nejbWi", + "zpqxqPbCn0Of34JiK1SGTyfIpzPhY0Dv1A49b/yostDDSn/LVW5B1wSu5ksstVmBVrC6RUlcwsHZh39g", + "mvySwG/+RBJB2HnZ7UwPwWr4rOcWcq1+IliIZUGgb9GAoPhSXapTCGY7ArW+FXPweYM7QYXv7H+/P/3T", + "EZdCzG0MHwqEudE3aNqODdwr8+eN1mXkCPBLjTXaS+UEmMDpcNAVLFzWSXKMsFHO3Zav9ChQGmS6xHbp", + "Z6XcKxEKOHQxPozhY4HqUl2vOfkaKm4t2gh4r9tbd73J9NeubZCWuaPR2mI3xYBQlpDnMfi6shDa1qWq", + "lURrwaDCO8zh4NqD+RqE8lfDbHD4CgyGAFKBJdwVqFzw0Uf7nbCEyrosTl/8GidxEk9BK7l6BUoDr6lA", + "Re1cHV8qFjESJJGlrqSOQtQdqtDYgJGpk+FgqitUvBIsZcdxEh87FHIqfP1MbqeToh+JluhLyRWYV+Pe", + "Dd3EtDP6v0iS7zb2txpGpv4NPAkLdQVc5VBw65OXOWh6AIYRzb0OnAjn05olK21HJoPXUmc3FmpFQrYY", + "FRYWBjHqc92BAbxnDjLawBpJLZBcb90O2Gnm694jpH1eoaXXOl99t4htjUNN0+w+4pofmK3w5BhJ1lmY", + "5+DAx9NHqw3lYexgeJIk+2T3xq6fgBE7mR4/6/zPyXPO70Bl8iDyJuBEIuGwDN6Hyu2yuvnK/jSudH1k", + "0r3Cm6tBYk6G4GxVuUhKqwNNCIKC58ClQZ6vWt7JD+NxRyaeiDbhv+uMwrv/xhVPiG3+T74lP+uX2Sg9", + "tZPSDwR8q2EM8ecXNgot0Xpqcnj33S3kpYmY701tZGsjWcoKoiqdTHqOT19OjxPWXDX/DgA=", +} + +// decodeSpec returns the embedded OpenAPI spec as raw JSON bytes, +// after base64-decoding and flate-decompressing the embedded blob. +func decodeSpec() ([]byte, error) { + encoded := strings.Join(swaggerSpec, "") + compressed, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, fmt.Errorf("error base64 decoding spec: %w", err) + } + zr := flate.NewReader(bytes.NewReader(compressed)) + var buf bytes.Buffer + if _, err := buf.ReadFrom(zr); err != nil { + return nil, fmt.Errorf("read flate: %w", err) + } + if err := zr.Close(); err != nil { + return nil, fmt.Errorf("close flate reader: %w", err) + } + + return buf.Bytes(), nil +} + +var rawSpec = decodeSpecCached() + +// a naive cache of the decoded OpenAPI spec +func decodeSpecCached() func() ([]byte, error) { + data, err := decodeSpec() + return func() ([]byte, error) { + return data, err + } +} + +// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. +func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { + res := make(map[string]func() ([]byte, error)) + if len(pathToFile) > 0 { + res[pathToFile] = rawSpec + } + + return res +} + +// GetSpec returns the OpenAPI specification corresponding to the generated +// code in this file. External references in the spec are resolved through +// PathToRawSpec; externally-referenced files must be embedded in their +// corresponding Go packages (via the import-mapping feature). URL-based +// external refs are not supported. +func GetSpec() (swagger *openapi3.T, err error) { + resolvePath := PathToRawSpec("") + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { + pathToFile := url.String() + pathToFile = path.Clean(pathToFile) + getSpec, ok := resolvePath[pathToFile] + if !ok { + err1 := fmt.Errorf("path not found: %s", pathToFile) + return nil, err1 + } + return getSpec() + } + var specData []byte + specData, err = rawSpec() + if err != nil { + return + } + swagger, err = loader.LoadFromData(specData) + if err != nil { + return + } + return +} + +// GetSpecJSON returns the raw JSON bytes of the embedded OpenAPI +// specification: decompressed but not unmarshaled. External references +// are not resolved here; the bytes are the spec exactly as embedded by +// codegen. The result is cached at package init time, so repeated calls +// are cheap. +func GetSpecJSON() ([]byte, error) { + return rawSpec() +} + +// GetSwagger returns the OpenAPI specification corresponding to the +// generated code in this file. +// +// Deprecated: GetSwagger predates kin-openapi renaming openapi3.Swagger +// to openapi3.T. Use [GetSpec] instead. This wrapper is retained for +// backwards compatibility. +func GetSwagger() (*openapi3.T, error) { + return GetSpec() +} diff --git a/internal/nvsmi/nvsmi.go b/internal/nvsmi/nvsmi.go new file mode 100644 index 0000000..b7f6e0c --- /dev/null +++ b/internal/nvsmi/nvsmi.go @@ -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)) +} diff --git a/internal/nvsmi/nvsmi_test.go b/internal/nvsmi/nvsmi_test.go new file mode 100644 index 0000000..2d6f9e6 --- /dev/null +++ b/internal/nvsmi/nvsmi_test.go @@ -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) + } + } +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..a9eff4a --- /dev/null +++ b/internal/server/server.go @@ -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() +} diff --git a/internal/server/server_test.go b/internal/server/server_test.go new file mode 100644 index 0000000..968563f --- /dev/null +++ b/internal/server/server_test.go @@ -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) + } + } +}