simworker

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 35 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

Overview

Package simworker is the load harness's simulated worker: a process-light stand-in for sqi-worker that speaks the real worker protocol through the real worker packages (lease, heartbeat, status, logstreamer, cancel), so a protocol change breaks its build rather than skewing its numbers. Only the executor is replaced: a Dispatcher plays each assignment out from a sampled TaskPlan instead of starting a process.

Index

Constants

View Source
const (
	// OutcomeSucceeded ends the task with a succeeded status and exit code 0.
	OutcomeSucceeded = "succeeded"
	// OutcomeFailed ends the task with a failed status and exit code 1.
	OutcomeFailed = "failed"
	// OutcomeHang emits the plan's lines over its duration, then runs until
	// the task is canceled or the worker stops.
	OutcomeHang = "hang"
)

Task plan outcomes.

View Source
const (
	// KindLeased is recorded when an assignment reaches the dispatcher.
	KindLeased = "leased"
	// KindRunning is recorded after the running status is published.
	KindRunning = "running"
	// KindTerminal is recorded after a succeeded or failed status is
	// published. Outcome names which, or "worker_shutdown" for an attempt a
	// graceful Stop gave up on.
	KindTerminal = "terminal"
	// KindCanceled is recorded after a canceled status is published.
	KindCanceled = "canceled"
	// KindCrashed is recorded for an attempt the worker abandoned without
	// publishing a terminal status: a Crash, or a Restart.
	KindCrashed = "crashed"
)

Ledger event kinds.

Variables

This section is empty.

Functions

func LogLine

func LogLine(taskID string, n, lineBytes int) string

LogLine is line n (from 1) of a simulated task's output: "sim <taskID> line <n> " padded with 'x' to lineBytes. A lineBytes shorter than the prefix leaves the prefix whole, so every line stays identifiable.

Types

type Behavior

type Behavior interface {
	Plan(m *protocol.AssignMsg, r *rand.Rand) TaskPlan
}

Behavior decides the plan for each assignment. The dispatcher calls Plan with its own seeded generator under a lock, so Plan may use r freely but must not keep it.

func ScenarioBehavior

func ScenarioBehavior(classes map[string]scenario.TaskSpec) Behavior

ScenarioBehavior plans each task from the TaskSpec of its job's class.

The class is the one named by the assignment's last onRun argument starting with scenario.ClassArgPrefix, which the driver adds to every template. A task with no such argument, or one naming an unknown class, runs for one second, succeeds and writes no lines.

Sampling, in a fixed number of draws per plan: Duration is the class's duration sample in seconds and LogLines its line-count sample rounded down; then one draw decides hang (probability hang_rate) and a second decides failed (fail_rate) when it is not a hang. The assignment carries no attempt number, so fail_rate applies to every attempt, not only the first.

type BehaviorFunc

type BehaviorFunc func(m *protocol.AssignMsg, r *rand.Rand) TaskPlan

BehaviorFunc adapts a function to Behavior.

func (BehaviorFunc) Plan

Plan calls f.

type ChurnCounts

type ChurnCounts struct {
	// Crashes and Disconnects are events carried out; Crashes include those of
	// [Fleet.CrashAll].
	Crashes, Disconnects int64
	// Restarts are workers brought back after a crash, by churn or by
	// [Fleet.RestartAll].
	Restarts int64
	// Skipped are events due for a worker that was not running.
	Skipped int64
	// Failures are events whose restart, or reconnect and re-registration,
	// failed.
	Failures int64
}

ChurnCounts is what RunChurn has done so far.

type Credentials

type Credentials interface {
	// For returns the credential worker workerID connects with. A nil seed and
	// an empty public key mean the broker needs none.
	For(ctx context.Context, workerID string) (seed []byte, publicKey string, err error)
}

Credentials supplies a simulated worker's broker credential: its nkey seed and public key, as WorkerSpec carries them. An implementation must be safe for concurrent use, since the fleet asks for many workers' credentials at once.

func JoinTokenCredentials

func JoinTokenCredentials(c *client.Client, joinToken string) Credentials

JoinTokenCredentials enrolls each worker with the server by exchanging joinToken, the way sqi-worker's enrollment does. The token must be reusable (the server's join_token_single_use off), since every worker presents it. Each call to For generates a fresh key pair and enrolls it, with no lock shared between workers.

type Dispatcher

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

Dispatcher plays assignments out according to a Behavior. It implements lease.Dispatcher and the lease loop's Hold, heartbeat.StateSource and heartbeat.AttemptSource, and cancel.TaskCanceler.

Lock order: Dispatcher.mu is never held while publishing, while calling the ledger or the cancel handler, or while sampling; rngMu is never held with mu.

func NewDispatcher

func NewDispatcher(
	workerID string,
	st *status.Publisher,
	logs *logstreamer.Publisher,
	b Behavior,
	l *Ledger,
	r *rand.Rand,
) *Dispatcher

NewDispatcher returns a dispatcher publishing as workerID. r seeds every plan this dispatcher samples. Cancel signals reach it through cancel.Subscribe, which the worker opens before its lease loop starts.

func (*Dispatcher) AbandonStatuses

func (d *Dispatcher) AbandonStatuses() int

AbandonStatuses drops every report the dispatcher's status publisher still has pending, without waiting for any, and returns how many it dropped.

func (*Dispatcher) ActiveAttemptIDs

func (d *Dispatcher) ActiveAttemptIDs() []string

ActiveAttemptIDs returns the held attempts and those whose status report the stream has not yet acknowledged, sorted, as the real worker's executor does.

func (*Dispatcher) ActiveTaskCount

func (d *Dispatcher) ActiveTaskCount() int

ActiveTaskCount returns how many attempts are dispatched and not yet ended.

func (*Dispatcher) ActiveTaskIDs

func (d *Dispatcher) ActiveTaskIDs() []string

ActiveTaskIDs returns the task IDs of the dispatched attempts, each once.

func (*Dispatcher) Cancel

func (d *Dispatcher) Cancel(taskID, attemptID string) bool

Cancel stops taskID's attempts and reports whether one was running and is now being canceled (true again for a repeat cancel). A non-empty attemptID limits it to that attempt, and an empty taskID with one stops that attempt whatever its task (cancel.Applies). A task already finishing, abandoned by a shutdown, or running only another attempt reports false.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(_ context.Context, m *protocol.AssignMsg) error

Dispatch samples a plan for m and starts playing it out. It returns at once.

func (*Dispatcher) FlushStatuses

func (d *Dispatcher) FlushStatuses(ctx context.Context) int

FlushStatuses waits until the dispatcher's status publisher has no report pending or ctx ends, then drops what is left and returns how many it dropped.

func (*Dispatcher) Hold

func (d *Dispatcher) Hold(attemptID string)

Hold reports attemptID as held from now until its terminal status has been published. The lease loop calls it for a whole batch before dispatching any.

func (*Dispatcher) LastAssignmentAt

func (d *Dispatcher) LastAssignmentAt() *time.Time

LastAssignmentAt returns when the last assignment was dispatched, or nil.

func (*Dispatcher) SetProgress

func (d *Dispatcher) SetProgress(ic *openjd.Interceptor)

SetProgress routes the lines of tasks whose plan sets ProgressEvery through ic, which must wrap this dispatcher's log publisher. Call it before the first Dispatch.

type Event

type Event struct {
	At         time.Time
	WorkerID   string
	InstanceID string
	TaskID     string
	AttemptID  string
	JobID      string
	// AssignedAt is the server's time for the attempt's assignment, from its
	// assignment message; zero when the message carried none.
	AssignedAt time.Time
	Kind       string
	// Outcome is set on terminal events.
	Outcome string
	// LogLines is how many lines the attempt emitted, set on terminal,
	// canceled and crashed events.
	LogLines int
}

Event is one thing a simulated worker did with one attempt.

type Fleet

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

Fleet is a set of simulated workers: it ramps them up at each group's rate, shuts them down, and drives their crashes and disconnects.

func NewFleet

func NewFleet(cfg FleetConfig, b Behavior, l *Ledger, logger *slog.Logger) *Fleet

NewFleet returns a fleet that has started nothing. Worker IDs are "<IDPrefix>-<group>-<n>" and hostnames "sim-<RunID>-<group>-<n>", n from 1 within the group. A nil logger discards.

func (*Fleet) ChurnCounts

func (f *Fleet) ChurnCounts() ChurnCounts

ChurnCounts returns the churn events carried out so far.

func (*Fleet) CrashAll

func (f *Fleet) CrashAll()

CrashAll crashes every running worker at once, with no deregistration (see Worker.Crash); it returns when they are all down. Each worker's crash waits for that worker's churn event in progress, if any, so it never splits one. Nothing is restarted: Fleet.RestartAll brings them back. Workers crashed here count in ChurnCounts.Crashes.

func (*Fleet) GroupOf

func (f *Fleet) GroupOf(workerID string) string

GroupOf returns the group name of one of the fleet's workers, "" otherwise.

func (*Fleet) Live

func (f *Fleet) Live() int

Live returns how many workers currently have a running process. It does not wait for a worker that is mid-way through a lifecycle operation.

func (*Fleet) RestartAll

func (f *Fleet) RestartAll(ctx context.Context) error

RestartAll restarts every crashed worker as a new process on its worker ID (a new instance ID, see Worker.Restart), at most [startConcurrency] at a time, and returns the joined errors of those that failed. A worker that is running, or was never started, is left alone, and nothing restarts once Stop has begun. ctx bounds the whole call; each restart is also bounded by [restartTimeout]. Workers restarted here count in ChurnCounts.Restarts.

func (*Fleet) RunChurn

func (f *Fleet) RunChurn(ctx context.Context)

RunChurn carries out the groups' churn against wall time, from the moment it is called until ctx ends or Stop begins, then returns once the events in flight have finished. Events are generated an hour at a time (the first window is [churnSchedule] of the group's seed, so a ctx deadline shorter than an hour sees a prefix of it), each window from its own derived seed.

A crash is Worker.Crash, a wait of the group's RestartAfter, then Worker.Restart on the then-crashed worker: never a restart of a live, busy one. If ctx ends or Stop begins during the wait, a ctx end restarts the worker at once (a drain needs it up) and a Stop does not. A disconnect is Worker.Disconnect. Events for one worker never overlap: a later one waits for the earlier to finish. An event for a worker that is not running is skipped.

func (*Fleet) Simulates

func (f *Fleet) Simulates(workerID string) bool

Simulates reports whether workerID is one of the fleet's workers.

func (*Fleet) Specs

func (f *Fleet) Specs() []WorkerSpec

Specs returns the spec of every worker the fleet runs, without credentials (those are fetched by Start), in group then index order.

func (*Fleet) Start

func (f *Fleet) Start(ctx context.Context) error

Start ramps every group up at its Ramp.PerSecond (all at once when 0) and returns once every worker is registered. Groups ramp concurrently; within a group worker k is due k/rate seconds after Start was called, so a slow connect does not slow the schedule (at most [startConcurrency] workers are connecting at any moment, which does).

The first worker to fail aborts the fleet: Start stops launching, waits for the starts in flight, and returns that error naming the worker. A scenario with workers missing is not the scenario asked for. Workers that did start stay up; the caller still calls Stop. Start may be called once.

func (*Fleet) Stop

func (f *Fleet) Stop(ctx context.Context) error

Stop shuts the fleet down: every worker stops gracefully at once (see Worker.Stop), with in-flight tasks given [stopTimeout] (or ctx, if sooner) to finish; whatever then still runs is crashed. It also ends churn: events due after Stop begins do nothing. Stop is safe to call more than once. The returned error joins the first few worker errors.

type FleetConfig

type FleetConfig struct {
	RunID   string
	FarmID  string
	NATSURL string
	// NATSURLFor, when set, gives each group's broker URL (its lane); nil means
	// NATSURL for every group.
	NATSURLFor func(group string) string
	IDPrefix   string
	// Groups are the worker groups. Each group's Count simulated workers start;
	// its Real count belongs to the managed target and is ignored here.
	Groups []scenario.WorkerGroup
	// QueueIDs maps a queue name to its ID. A group's queue that is not a key
	// is taken to be an ID already. Nil means every group queue is an ID.
	QueueIDs map[string]string
	// Creds supplies each worker's broker credential. Nil means none
	// ([NoCredentials]).
	Creds Credentials
	// TLS is the broker TLS material, passed to every worker.
	TLS TLSFiles
	// Seed derives every random choice: each worker's behavior seed and the
	// churn schedule.
	Seed int64
}

FleetConfig describes a fleet of simulated workers.

type Ledger

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

Ledger is the record of what every simulated worker did, shared across the fleet and safe for concurrent use. The verifier compares it with what the server reports.

func NewLedger

func NewLedger() *Ledger

NewLedger returns an empty ledger.

func (*Ledger) Events

func (l *Ledger) Events() []Event

Events returns a copy of every event in record order.

func (*Ledger) EventsSince

func (l *Ledger) EventsSince(n int) []Event

EventsSince returns a copy of the events recorded after the first n, in record order. The ledger only grows, so a reader that has seen n events reads only the new ones.

func (*Ledger) LogLines

func (l *Ledger) LogLines() int64

LogLines returns how many log lines the simulated workers emitted in the attempts that have ended so far (by a terminal, canceled or crashed event): the sum of those events' LogLines.

func (*Ledger) Record

func (l *Ledger) Record(e Event)

Record appends e, stamping At with the current time when it is zero.

func (*Ledger) SetOutcome

func (l *Ledger) SetOutcome(taskID, outcome string) bool

SetOutcome rewrites the outcome of the last terminal event recorded for taskID and reports whether there was one. It is a test hook: it lets a test make the ledger disagree with the server on purpose.

type NoCredentials

type NoCredentials struct{}

NoCredentials is the credential of a server with broker authentication off: workers connect anonymously.

func (NoCredentials) For

func (NoCredentials) For(context.Context, string) (seed []byte, publicKey string, err error)

For returns no credential.

type TLSFiles

type TLSFiles struct {
	Enabled            string // "" or "auto", "true", "false"
	CAFile             string
	CertFile, KeyFile  string
	InsecureSkipVerify bool
}

TLSFiles is the broker TLS material as file paths, the form natsclient takes: sqi-worker's nats.tls_enabled, nats.tls_ca_file, nats.tls_cert_file, nats.tls_key_file and nats.insecure_skip_verify. The zero value is "auto" with no files, which dials without TLS.

func (TLSFiles) NATSConfig

func (f TLSFiles) NATSConfig() workerconfig.NATSConfig

NATSConfig returns f as the TLS fields of sqi-worker's NATS configuration.

type TaskPlan

type TaskPlan struct {
	Duration  time.Duration
	Outcome   string
	LogLines  int
	LineBytes int
	// ProgressEvery, when positive, makes the task write an openjd_progress
	// line this often, carrying elapsed/Duration as a percentage.
	ProgressEvery time.Duration
}

TaskPlan is what a simulated worker does with one assignment: run for Duration, emit LogLines lines of LineBytes bytes evenly over it, then end with Outcome.

type Worker

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

Worker is one simulated sqi-worker: one NATS connection, and the real registration, heartbeat, lease, status, log and cancel packages driving a Dispatcher. Its lifecycle methods are serialized.

func NewWorker

func NewWorker(spec WorkerSpec, b Behavior, l *Ledger, logger *slog.Logger) *Worker

NewWorker returns a stopped worker. A nil logger discards.

func (*Worker) Crash

func (w *Worker) Crash()

Crash drops the connection without deregistering. Heartbeats stop, and every in-flight attempt is abandoned with no terminal status published (ledger kind crashed). Nothing is kept running.

func (*Worker) Disconnect

func (w *Worker) Disconnect(ctx context.Context) error

Disconnect drops the connection's socket and waits until NATS has reconnected it and the worker has re-registered, with the same instance ID, so the server keeps its attempts. The reconnect handler re-registers, the same path a broker-side drop takes; if its registration has not landed handlerGrace after the connection is back (it failed, or the stream ack timed out), Disconnect registers itself, retrying. The wait is bounded by disconnectBound as well as ctx, so a lost registration cannot hold the worker's lifecycle lock indefinitely; after that error the worker keeps running and its heartbeat watchdog may still re-register it.

func (*Worker) InstanceID

func (w *Worker) InstanceID() string

InstanceID returns the instance ID of the current or most recent process, or "" before the first Start.

func (*Worker) Restart

func (w *Worker) Restart(ctx context.Context) error

Restart is a new worker process on the same worker ID: a running worker crashes first, then it reconnects and registers with a new instance ID, so the server reclaims the old process's attempts.

func (*Worker) Start

func (w *Worker) Start(ctx context.Context) error

Start connects, registers, and starts the heartbeat and lease loop. ctx bounds connecting and registering only: the worker then runs until Stop, Crash or Restart.

func (*Worker) Stop

func (w *Worker) Stop(ctx context.Context) error

Stop shuts the worker down the way sqi-worker does: no new leases, in-flight tasks run on until ctx is done, any still running then end failed with "worker_shutdown", and a deregistration goes out before the connection closes. Stopping a worker that is not running is a no-op.

type WorkerSpec

type WorkerSpec struct {
	ID, Hostname, FarmID string
	Group                scenario.WorkerGroup
	NATSURL              string
	Seed                 []byte
	PublicKey            string
	TLS                  TLSFiles
	RandSeed             uint64
}

WorkerSpec identifies one simulated worker. Group.Queues holds queue IDs (the fleet resolves the scenario's names). Seed and PublicKey are its nkey broker credential, nil when broker auth is off. RandSeed seeds its behavior sampling; the fleet derives it from the run seed.

Jump to

Keyboard shortcuts

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