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
- func LogLine(taskID string, n, lineBytes int) string
- type Behavior
- type BehaviorFunc
- type ChurnCounts
- type Credentials
- type Dispatcher
- func (d *Dispatcher) AbandonStatuses() int
- func (d *Dispatcher) ActiveAttemptIDs() []string
- func (d *Dispatcher) ActiveTaskCount() int
- func (d *Dispatcher) ActiveTaskIDs() []string
- func (d *Dispatcher) Cancel(taskID, attemptID string) bool
- func (d *Dispatcher) Dispatch(_ context.Context, m *protocol.AssignMsg) error
- func (d *Dispatcher) FlushStatuses(ctx context.Context) int
- func (d *Dispatcher) Hold(attemptID string)
- func (d *Dispatcher) LastAssignmentAt() *time.Time
- func (d *Dispatcher) SetProgress(ic *openjd.Interceptor)
- type Event
- type Fleet
- func (f *Fleet) ChurnCounts() ChurnCounts
- func (f *Fleet) CrashAll()
- func (f *Fleet) GroupOf(workerID string) string
- func (f *Fleet) Live() int
- func (f *Fleet) RestartAll(ctx context.Context) error
- func (f *Fleet) RunChurn(ctx context.Context)
- func (f *Fleet) Simulates(workerID string) bool
- func (f *Fleet) Specs() []WorkerSpec
- func (f *Fleet) Start(ctx context.Context) error
- func (f *Fleet) Stop(ctx context.Context) error
- type FleetConfig
- type Ledger
- type NoCredentials
- type TLSFiles
- type TaskPlan
- type Worker
- type WorkerSpec
Constants ¶
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.
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 ¶
Types ¶
type Behavior ¶
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 ¶
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 ¶
BehaviorFunc adapts a function to Behavior.
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 ¶
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 ¶
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) Live ¶
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 ¶
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 ¶
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) 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 ¶
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 ¶
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 (*Ledger) EventsSince ¶
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 ¶
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) SetOutcome ¶
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.
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 (*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 ¶
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 ¶
InstanceID returns the instance ID of the current or most recent process, or "" before the first Start.
func (*Worker) Restart ¶
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 ¶
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.
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.