nodeagent

package
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 42 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ExposeNone        = "none"        // the operator supplies --endpoint
	ExposeCloudflared = "cloudflared" // gateway on localhost behind a quick tunnel
)

How the node becomes reachable by the proxy.

View Source
const (
	SampleStateServing  = "serving"
	SampleStatePaused   = "paused"
	SampleStateDraining = "draining"
	SampleStateOffline  = "offline"
)
View Source
const DefaultEngineURL = "http://127.0.0.1:11434"

DefaultEngineURL is Ollama's default listen address.

Variables

This section is empty.

Functions

func DefaultStatsDir added in v1.3.0

func DefaultStatsDir() string

DefaultStatsDir is where the installer's node keeps its log.

func FilterModels

func FilterModels(models []*pb.NodeModelSpec, allow []string) []*pb.NodeModelSpec

FilterModels keeps only the allowed models; an empty allow list keeps all. An engine shared with other tools would otherwise advertise models this node must not serve.

func ParseRetention added in v1.3.0

func ParseRetention(s string) (time.Duration, error)

ParseRetention reads "90d", "12h" or "0" (keep everything).

func ParseWhen added in v1.3.0

func ParseWhen(s string, now time.Time) (time.Time, error)

ParseWhen reads "24h", "7d", "2026-10-01" or "2026-10-01T15:04" (local time) as a moment before now.

func Render

func Render(w io.Writer, findings []Finding) (problems int)

Render prints the findings and returns how many are problems.

func ResolveURLs

func ResolveURLs(engineURL, endpoint string) (poll, report string)

ResolveURLs returns the engine URL to poll and the endpoint to report. With only endpoint set, polling uses it too, as before --engine-url existed.

func TagJudgeModels

func TagJudgeModels(models []*pb.NodeModelSpec, judgeModels []string) []*pb.NodeModelSpec

TagJudgeModels ensures models in judge list declare the "judge" capability.

func TailRequests added in v1.3.0

func TailRequests(ctx context.Context, st *StatsStore, since time.Time, w io.Writer, every time.Duration) error

TailRequests prints requests as they reach the log, from since on, until ctx ends.

func WriteReport added in v1.3.0

func WriteReport(w io.Writer, rep *Report, format string) error

WriteReport renders the report as "table", "json" or "csv".

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

func NewAgent

func NewAgent(cfg AgentConfig) *Agent

func (*Agent) Run

func (a *Agent) Run(ctx context.Context) error

type AgentConfig

type AgentConfig struct {
	ProxyAddr      string
	TLS            bool // dial ProxyAddr over TLS with system roots, e.g. a load balancer on :443
	NodeKey        string
	NodeID         string
	NodeName       string
	EngineURL      string // where the agent itself polls the engine; local, never reported
	Endpoint       string // address the proxy dials, as reported at registration
	Engine         string
	NodeAuthToken  string   // bearer the proxy presents to Endpoint; replaced by a generated key when exposing
	EngineToken    string   // bearer the engine itself requires, if any
	OnlyModels     []string // when set, report only these engine models
	JudgeModels    []string // models to tag with capability "judge"
	Expose         string   // ExposeNone or ExposeCloudflared
	CloudflaredBin string
	BaseWeight     float64
	MaxConcurrent  uint32
	ScheduleFile   string        // capacity levels by local time; missing = 100%
	Warmup         time.Duration // load the model this long before a paused window ends
	StatsDir       string        // where the usage log is kept for the owner; "" = none
	StatsRetention time.Duration // days of usage log kept; 0 = all
}

type DecisionsInspector

type DecisionsInspector struct{}

DecisionsInspector inspects engines serving decision models (/v1/decisions).

func (*DecisionsInspector) Inspect

func (di *DecisionsInspector) Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)

type Doctor

type Doctor struct {
	Cfg   AgentConfig
	Model string // the model this node should serve; empty = any

	// Seams for tests; zero values use the real thing.
	HTTP       *http.Client
	DialTCP    func(ctx context.Context, addr string) error
	UsesProxy  func(addr string) bool // true when HTTPS_PROXY or similar routes addr; gRPC honors it, a raw dial does not
	LookPath   func(name string) (string, error)
	RunCmd     func(ctx context.Context, name string, args ...string) error
	MachOArchs func(path string) ([]string, error)
	Now        func() time.Time
	GOOS       string
	GOARCH     string
}

Doctor explains why a node is not (or is badly) serving. It sends one Heartbeat for a made-up node id, which the proxy answers without storing.

func (*Doctor) Run

func (d *Doctor) Run(ctx context.Context) []Finding

Run executes every check. A failed check never stops the later ones.

type EngineController added in v1.1.0

type EngineController interface {
	Warm(ctx context.Context, endpoint, authToken, model string) error
	Unload(ctx context.Context, endpoint, authToken, model string) error
}

EngineController is implemented by inspectors whose engine can load and free a model on demand; a paused node frees the machine's memory with it.

type EngineInspector

type EngineInspector interface {
	Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)
}

func GetInspector

func GetInspector(engine string) EngineInspector

type EngineLoad added in v0.13.1

type EngineLoad struct {
	Running uint32
	Waiting uint32
}

EngineLoad is the engine's own view of its work: requests it is generating and requests it has accepted but not started. The proxy adds Waiting to its queue estimate, so a node busy with other clients is not overbooked.

type Finding

type Finding struct {
	Check   string
	Level   Level
	Message string
	Fix     string
}

Finding is one line of the report, in plain language, with what to do next.

type GPUStats

type GPUStats struct {
	TotalVRAMMB uint64
	FreeVRAMMB  uint64
	UtilPercent float64
	TempC       uint32
	ModelName   string
}

func ReadNvidiaSMI

func ReadNvidiaSMI(ctx context.Context) (*GPUStats, error)

ReadNvidiaSMI parses `nvidia-smi --query-gpu=memory.total,memory.free,utilization.gpu,temperature.gpu,name --format=csv,noheader,nounits`

type Gap added in v1.3.0

type Gap struct {
	From  time.Time `json:"from"`
	Until time.Time `json:"until"`
}

Gap is a stretch the proxy no longer had when the agent pulled: requests in it may be missing from the log.

type Gateway

type Gateway struct {
	// contains filtered or unexported fields
}

Gateway is the only door to the engine that the proxy gets: a bearer check plus an allowlist of the routes it needs (/v1/chat/completions, /v1/decisions, /v1/models). Everything else (pull, delete, engine admin APIs) is unreachable.

func NewGateway

func NewGateway(engineURL, accessKey, engineToken string) *Gateway

NewGateway forwards to the engine at engineURL. accessKey is what callers must present; engineToken, if any, is what the engine itself expects.

func (*Gateway) ServeHTTP

func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Gateway) SetAccepting added in v1.1.0

func (g *Gateway) SetAccepting(ok bool)

SetAccepting opens or closes the door to engine routes. Closed, the node answers 503: a proxy that ignores the schedule still cannot reach the engine.

type GenericOpenAIInspector

type GenericOpenAIInspector struct{}

Generic OpenAI Inspector

func (*GenericOpenAIInspector) Inspect

func (goi *GenericOpenAIInspector) Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)

type Level

type Level int

Level ranks a finding. Only a problem makes the doctor exit non-zero.

const (
	LevelOK Level = iota
	LevelWarn
	LevelProblem
)

type LlamaCppInspector

type LlamaCppInspector struct{}

LlamaCpp Inspector

func (*LlamaCppInspector) Inspect

func (li *LlamaCppInspector) Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)

func (*LlamaCppInspector) Load added in v0.13.1

func (li *LlamaCppInspector) Load(ctx context.Context, endpoint, authToken string) (EngineLoad, error)

type LoadProber added in v0.13.1

type LoadProber interface {
	Load(ctx context.Context, endpoint, authToken string) (EngineLoad, error)
}

LoadProber is implemented by inspectors whose engine publishes its queue. Ollama has no such API.

type OllamaInspector

type OllamaInspector struct{}

Ollama Inspector

func (*OllamaInspector) Inspect

func (oi *OllamaInspector) Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)

func (*OllamaInspector) Unload added in v1.1.0

func (oi *OllamaInspector) Unload(ctx context.Context, endpoint, authToken, model string) error

Unload frees the model once its running requests end.

func (*OllamaInspector) Warm added in v1.1.0

func (oi *OllamaInspector) Warm(ctx context.Context, endpoint, authToken, model string) error

Warm loads the model and keeps it resident.

type Report added in v1.3.0

type Report struct {
	From  time.Time   `json:"from"`
	To    time.Time   `json:"to"`
	By    string      `json:"by"`
	Rows  []ReportRow `json:"rows"`
	Total ReportRow   `json:"total"`
	Gaps  []Gap       `json:"gaps,omitempty"`
}

Report is the usage log over [From, To) split by hour, day or model.

func BuildReport added in v1.3.0

func BuildReport(st *StatsStore, from, to, now time.Time, by string) (*Report, error)

BuildReport reads the log in [from, to) and sums it by "hour", "day" or "model".

type ReportRow added in v1.3.0

type ReportRow struct {
	Key          string  `json:"key"`
	Requests     int     `json:"requests"`
	Errors       int     `json:"errors"` // outcome error or timeout
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	BusyMs       int64   `json:"busy_ms"` // time with at least one request running
	SpanMs       int64   `json:"span_ms"` // the period, up to now
	BusyShare    float64 `json:"busy"`    // BusyMs / SpanMs
	CooldownMs   int64   `json:"cooldown_ms"`
	PausedShare  float64 `json:"paused"`      // share of the agent's samples at 0%; -1 = no samples
	NoDataMin    int     `json:"no_data_min"` // minutes without a sample: the agent was not running
	Samples      int     `json:"samples"`
	TTFTp50Ms    int64   `json:"ttft_p50_ms,omitempty"`
	TTFTp95Ms    int64   `json:"ttft_p95_ms,omitempty"`
	TPS          float64 `json:"tps,omitempty"`
}

ReportRow sums one period (or model) of the usage log.

type RequestRecord added in v1.3.0

type RequestRecord struct {
	ID              string    `json:"id"`
	RequestID       string    `json:"request_id"`
	StartedAt       time.Time `json:"started_at"`
	DurationMs      int64     `json:"duration_ms"`
	TTFTMs          int64     `json:"ttft_ms,omitempty"`
	Model           string    `json:"model"`
	Kind            string    `json:"kind"`
	InputTokens     int64     `json:"input_tokens"`
	OutputTokens    int64     `json:"output_tokens"`
	CacheReadTokens int64     `json:"cache_read_tokens,omitempty"`
	Outcome         string    `json:"outcome"`
	ErrorCode       string    `json:"error_code,omitempty"`
	Level           uint32    `json:"level"`
	CooldownMs      int64     `json:"cooldown_ms,omitempty"`
}

RequestRecord is one request the proxy sent to this node, one line of requests-YYYY-MM-DD.jsonl (the day it started, local time).

type Sample added in v1.3.0

type Sample struct {
	At            time.Time `json:"at"`
	State         string    `json:"state"` // serving | paused | draining | offline
	Level         uint32    `json:"level"`
	ProxyActive   int32     `json:"proxy_active"`
	EngineRunning uint32    `json:"engine_running,omitempty"`
	EngineWaiting uint32    `json:"engine_waiting,omitempty"`
	GPUUtil       float64   `json:"gpu_util,omitempty"`
	GPUTempC      uint32    `json:"gpu_temp_c,omitempty"`
	VRAMFreeMB    uint64    `json:"vram_free_mb,omitempty"`
	VRAMTotalMB   uint64    `json:"vram_total_mb,omitempty"`
	Warm          []string  `json:"warm,omitempty"`
}

Sample is the agent's own view of the node once a minute, one line of samples-YYYY-MM-DD.jsonl.

type Schedule added in v1.1.0

type Schedule struct {
	// contains filtered or unexported fields
}

Schedule is the node's capacity level for every minute of the week, in the machine's local time. Minutes no rule covers run at 100%.

func LoadSchedule added in v1.1.0

func LoadSchedule(path string) (*Schedule, error)

LoadSchedule parses the file at path. A missing file is no schedule: nil, nil.

func ParseSchedule added in v1.1.0

func ParseSchedule(r io.Reader) (*Schedule, error)

ParseSchedule reads rules of the form "[days] HH:MM-HH:MM level", one per line; "#" starts a comment. A window past midnight belongs to the day it starts on. Overlapping rules are an error.

func (*Schedule) Level added in v1.1.0

func (s *Schedule) Level(t time.Time) uint32

Level is the capacity at t; a nil schedule is always 100%.

func (*Schedule) Next added in v1.1.0

func (s *Schedule) Next(t time.Time) (at time.Time, level uint32, ok bool)

Next returns when the level next changes and to what; ok is false when it never does. It steps in real minutes, so DST gaps and repeats count right.

func (*Schedule) Status added in v1.1.0

func (s *Schedule) Status(now time.Time) string

Status is the one-line summary the CLI, the doctor and the installer print.

type StatsStore added in v1.3.0

type StatsStore struct {
	// contains filtered or unexported fields
}

StatsStore is the node's usage log on disk: JSON Lines per kind and local day, appended and fsynced, closed days gzipped. Plain files keep the binary cgo-free and readable with jq.

func OpenStats added in v1.3.0

func OpenStats(dir string, create bool) (*StatsStore, error)

OpenStats returns the store in dir, creating it for writing when create is set.

func (*StatsStore) AppendGap added in v1.3.0

func (s *StatsStore) AppendGap(g Gap) error

func (*StatsStore) AppendRequests added in v1.3.0

func (s *StatsStore) AppendRequests(recs []RequestRecord) error

AppendRequests writes records to the file of the day each started.

func (*StatsStore) AppendSample added in v1.3.0

func (s *StatsStore) AppendSample(sm Sample) error

func (*StatsStore) Cursor added in v1.3.0

func (s *StatsStore) Cursor() (string, error)

Cursor is the proxy log position already stored; "" before the first pull.

func (*StatsStore) CursorAge added in v1.3.0

func (s *StatsStore) CursorAge(now time.Time) (age time.Duration, ok bool)

CursorAge is how long ago the cursor last moved; ok is false before the first pull.

func (*StatsStore) Days added in v1.3.0

func (s *StatsStore) Days(kind, from, to string) ([]string, error)

Days lists the days in [from, to] (local dates) that have files of kind.

func (*StatsStore) Dir added in v1.3.0

func (s *StatsStore) Dir() string

func (*StatsStore) Gaps added in v1.3.0

func (s *StatsStore) Gaps(from, to time.Time) ([]Gap, error)

Gaps returns the recorded gaps that overlap [from, to).

func (*StatsStore) Maintain added in v1.3.0

func (s *StatsStore) Maintain(now time.Time, retention time.Duration) error

Maintain gzips the files of closed days and deletes days older than retention (0 keeps everything). A record pulled late for a closed day lands in a fresh .jsonl, which joins the .gz as one more gzip member.

func (*StatsStore) Requests added in v1.3.0

func (s *StatsStore) Requests(from, to time.Time) ([]RequestRecord, error)

Requests returns the requests that started in [from, to), without the repeats a crash between a write and its cursor leaves behind.

func (*StatsStore) Samples added in v1.3.0

func (s *StatsStore) Samples(from, to time.Time) ([]Sample, error)

Samples returns the samples taken in [from, to), each once.

func (*StatsStore) SetCursor added in v1.3.0

func (s *StatsStore) SetCursor(id string) error

SetCursor moves the position, after the records before it are on disk: a crash in between repeats records (readers drop them by request_id), never loses them.

func (*StatsStore) Touch added in v1.3.0

func (s *StatsStore) Touch(now time.Time) error

Touch marks a pull that found nothing new, so CursorAge tells a live agent from a stopped one.

type TGIInspector

type TGIInspector struct{}

TGI Inspector

func (*TGIInspector) Inspect

func (ti *TGIInspector) Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)

func (*TGIInspector) Load added in v0.13.1

func (ti *TGIInspector) Load(ctx context.Context, endpoint, authToken string) (EngineLoad, error)

type VLLMInspector

type VLLMInspector struct{}

vLLM Inspector

func (*VLLMInspector) Inspect

func (vi *VLLMInspector) Inspect(ctx context.Context, endpoint, authToken string) ([]*pb.NodeModelSpec, error)

func (*VLLMInspector) Load added in v0.13.1

func (vi *VLLMInspector) Load(ctx context.Context, endpoint, authToken string) (EngineLoad, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL