agentfake

package
v2.36.9 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: AGPL-3.0 Imports: 26 Imported by: 1 module, 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

This section is empty.

Variables

This section is empty.

Functions

func IsFatalEnumerationError

func IsFatalEnumerationError(err error) bool

IsFatalEnumerationError reports whether err from a coderd API call indicates an unrecoverable misconfiguration that retrying will not fix: missing/invalid session token, insufficient permissions, missing license feature, or a template that does not exist. All other errors (network blips, 429, 5xx) are treated as transient and can be retried.

Types

type Agent

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

Agent is a single fake agent. It owns one workspace-agent auth token and one dRPC connection to coderd.

func NewAgent

func NewAgent(logger slog.Logger, coderURL *url.URL, token string, opts ...Option) *Agent

func (*Agent) Close

func (a *Agent) Close()

Close stops the agent. Safe to call multiple times.

func (*Agent) Run

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

Run opens a dRPC websocket to coderd as the "agent" role and keeps it open until ctx is canceled or Close is called. On transient failures (e.g., coderd restart, brief auth churn while the workspace build is finalizing) Run reconnects with a small backoff. Returns nil when ctx is canceled or Close is called, and a non-nil error only if ctx returns a non-context error.

type ExternalAgentClient added in v2.35.0

type ExternalAgentClient interface {
	User(ctx context.Context, userIdent string) (codersdk.User, error)
	Template(ctx context.Context, id uuid.UUID) (codersdk.Template, error)
	TemplatesByOrganization(ctx context.Context, orgID uuid.UUID) ([]codersdk.Template, error)
	Workspaces(ctx context.Context, filter codersdk.WorkspaceFilter) (codersdk.WorkspacesResponse, error)
}

ExternalAgentClient is the subset of *codersdk.Client the Manager uses to resolve the template/owner the operator named on the command line and to poll the workspace count gate. The actual external-agent auth tokens are fetched in-process via a direct database query (see GetExternalAgentTokensByTemplateID), not via this client. *codersdk.Client satisfies this interface, so production callers pass their client directly; tests substitute a fake without standing up a real coderd.

type Manager

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

Manager supervises a set of fake Agents in one process. It enumerates the agents it owns from coderd at Run time (via coder_external_agent tokens on workspaces matching opts.Template), then opens a dRPC stream per agent and keeps them connected until ctx is canceled.

func NewManager

func NewManager(logger slog.Logger, coderURL *url.URL, client ExternalAgentClient, db database.Store, opts ManagerOptions) *Manager

NewManager returns an Agent Manager. The provided client must already be authenticated with sufficient privilege to list workspaces, look up the configured template, and (when --owner is set) look up the named user (template-admin or higher). db must be a database.Store connected to the same Postgres database as the target coderd; it is used to bulk-fetch external-agent tokens for the enumerated workspaces. coderURL is the URL the spawned fake agents will dial.

func (*Manager) Close

func (m *Manager) Close()

Close stops every Agent constructed during Run. Safe to call any number of times.

func (*Manager) EnumerateExternalAgents

func (m *Manager) EnumerateExternalAgents(ctx context.Context) ([]TokenInfo, error)

EnumerateExternalAgents bulk-fetches the auth tokens for every external agent on a running workspace of the configured template (optionally filtered by owner) via a single direct Postgres query. resolveTemplateAndOwner must have been called once before any invocation; Run handles that, but tests that call this method directly must do the same.

func (*Manager) ResolveTemplateAndOwner added in v2.35.0

func (m *Manager) ResolveTemplateAndOwner(ctx context.Context) error

ResolveTemplateAndOwner looks up the configured template name (and, when set, owner username) once and caches the resulting UUIDs on the Manager so that EnumerateExternalAgents can issue a single by-ID DB query per cycle. Run calls this automatically; tests that exercise EnumerateExternalAgents directly must call it themselves first.

Template resolution walks every organization the calling user belongs to, matching scaletest convention (see cli.parseTemplate). Owner resolution is skipped when opts.Owner is empty; the cached uuid.Nil is interpreted by the underlying query as "match workspaces of any owner".

func (*Manager) Run

func (m *Manager) Run(ctx context.Context) error

Run enumerates the Manager's external agents from coderd, constructs one Agent per token, and runs the "fake agent" routines all until ctx is canceled or any Agent returns a non-context error. Enumeration is retried with exponential backoff for transient errors (network failures, 5xx, 429). Auth/permission/license/template-not-found errors (401, 403, 404) are treated as fatal. Run blocks until ctx is canceled, an Agent fails irrecoverably, or enumeration permanently fails.

type ManagerOptions

type ManagerOptions struct {
	// Template restricts enumeration to workspaces of the given template name. Required.
	Template string
	// Owner restricts enumeration to workspaces owned by the given user. Optional; if empty, all owners are included.
	Owner string
	// Metrics collectors. Optional; nil disables metric reporting.
	Metrics *Metrics
	// ExpectedAgents, when non-zero, causes Run to poll until the workspace
	// count is within [ExpectedAgents-Tolerance, ExpectedAgents+Tolerance]
	// before enumerating.
	ExpectedAgents          int64
	ExpectedAgentsTolerance int64
	// A zero ConnectionReportInterval or ConnectionReportDuration disables
	// synthetic SSH connection reporting.
	ConnectionReportInterval time.Duration
	ConnectionReportDuration time.Duration
	// Clock is used for the workspace-count polling interval.
	// Defaults to the real clock; override in tests with quartz.NewMock.
	Clock quartz.Clock
}

ManagerOptions configures a Manager. Authentication is supplied via the *codersdk.Client passed to NewManager rather than here, so the CLI / caller can construct the client with whatever session token (operator-issued, admin, template-admin) suits its deployment.

type Metrics added in v2.35.0

type Metrics struct {
	// ConnectedAgents is the number of fake agents with an established dRPC connection.
	ConnectedAgents  prometheus.Gauge
	DERPMapsReceived prometheus.Counter
}

Metrics holds the Prometheus collectors for the agentfake manager. A nil *Metrics is a valid no-op.

func NewMetrics added in v2.35.0

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics registers agentfake collectors on reg and returns the handle.

type Option added in v2.35.0

type Option func(*Agent)

Option configures an Agent.

func WithClock added in v2.35.0

func WithClock(c quartz.Clock) Option

WithClock injects a clock for time-based operations. Defaults to quartz.NewReal(). Tests pass a *quartz.Mock to drive the metadata loop deterministically. The clock is per-agent so a future caller can give different agents slightly different cadences.

func WithConnectionReports added in v2.35.0

func WithConnectionReports(interval, duration time.Duration) Option

WithConnectionReports enables periodic synthetic SSH connection reporting. A zero interval or duration disables reporting.

func WithDialer added in v2.35.0

func WithDialer(d rpcDialer) Option

WithDialer injects a custom RPC dialer. Defaults to a real agentsdk.Client built from coderURL + token. Tests use this to substitute *agent/agenttest.Client and avoid standing up a real coderd.

func WithFirstConnect added in v2.35.0

func WithFirstConnect(ch chan<- time.Duration) Option

WithFirstConnect sets a shared channel used by the Manager to aggregate time-to-first-connect across all agents without one stalled agent blocking the others.

func WithMetrics added in v2.35.0

func WithMetrics(m *Metrics) Option

WithMetrics injects Prometheus collectors. A nil *Metrics (the default when this option is not used) is a valid no-op; every collector helper method nil-guards on the receiver.

type TokenInfo

type TokenInfo struct {
	WorkspaceID   uuid.UUID
	WorkspaceName string
	AgentID       uuid.UUID
	AgentName     string
	Token         string
}

TokenInfo is a single workspace-agent auth token retrieved for a coder external agent, along with the identifying metadata needed to report the agent in metrics and logs.

Jump to

Keyboard shortcuts

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