scenario

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: 17 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 scenario defines the load harness's scenario file: the YAML schema, its defaults, its validation and the --set overrides applied on top of it.

Index

Constants

View Source
const (
	DistConstant  = "constant"
	DistUniform   = "uniform"
	DistLognormal = "lognormal"
)

Distribution kinds.

View Source
const (
	DatabaseStall = "stall"
	DatabaseDrop  = "drop"
	VolumeServer  = "server"
	VolumeWorkers = "workers"
)

The database fault modes and disk_full volumes.

View Source
const (
	PowerCutServerFirst  = "server-first"
	PowerCutWorkersFirst = "workers-first"
)

The power cut orders.

View Source
const (
	KnownMust = "must"
	KnownMay  = "may"
)

The kinds of known violation.

View Source
const (
	FaultKill      = "kill"
	FaultTerm      = "term"
	FaultStall     = "stall"
	FaultPartition = "partition"
	FaultBlackhole = "blackhole"
	FaultLatency   = "latency"
	FaultFlap      = "flap"
	FaultPowerCut  = "power_cut"
	FaultDatabase  = "database"
	FaultDiskFull  = "disk_full"
	FaultFDLimit   = "fd_limit"
	FaultRevoke    = "revoke"
)

The fault kinds.

View Source
const ClassArgPrefix = "--sqi-load-class="

ClassArgPrefix starts the onRun argument that names a job's class. The driver appends it to every template it builds, so a simulated worker can tell which class an assignment belongs to without a job lookup (the server sends a job's name only with EXPR assignments). A real worker's no-op command ignores it.

View Source
const KeyArgPrefix = "--sqi-load-key="

KeyArgPrefix starts the onRun argument that names a task: the driver puts it before the class argument, with the task's parameters as format strings, so a real task's no-op command can name what it writes.

View Source
const ReworkCheck = "rework"

ReworkCheck names the rework budget in a KnownViolation.

Variables

View Source
var CheckNames = []string{
	"terminal",
	"outcomes",
	"single-attempt",
	"logs",
	"workers-converge",
	"caps",
	"submission-atomic",
	"executions-recorded",
	"store-integrity",
	"no-orphans",
	"single-writer",
	"reclaims",
	"revoked",
	"skew-warning",
	"attempt-order",
	"disk-full",
}

CheckNames lists the invariant checks a known violation may name. The verify package cannot be imported here, so a test there keeps this list equal to verify.Names().

View Source
var KnownOSes = []string{"linux", "darwin", "windows"}

KnownOSes are the GOOS values a known violation may be limited to, and the ones a chaos matrix is listed for.

Functions

func BuiltinNames

func BuiltinNames() []string

BuiltinNames lists the built-in scenarios, sorted.

func ClassArg

func ClassArg(class string) string

ClassArg returns the onRun argument naming class.

func ClassFromArgs

func ClassFromArgs(args []string) (string, bool)

ClassFromArgs returns the class named by the last class argument in args.

func KeyArg

func KeyArg(key string) string

KeyArg returns the onRun argument naming the task key.

func KeyFromArgs

func KeyFromArgs(args []string) (string, bool)

KeyFromArgs returns the value of the last key argument.

func LastArg

func LastArg(args []string, prefix string) (string, bool)

LastArg returns the value of the last argument in args that starts with prefix.

func SplitTasks

func SplitTasks(tasksPerStep, chunk int) (frames, blocks int, ok bool)

SplitTasks divides tasksPerStep tasks over two task parameters so that no parameter exceeds sqi's 1024-value cap. The first (frames) is a frame range 1-frames*chunk; the second (blocks) multiplies it. It returns the factors with frames*blocks == tasksPerStep, frames*chunk <= 1024 and blocks <= 1024, preferring the largest frames, so blocks is 1 whenever the frame range fits. ok is false when no such factorization exists, or an argument is below 1.

func TaskKey

func TaskKey(jobName, stepName, frame, block string) string

TaskKey is the key of one task: "<job name>/<step name>/<Frame>", with "/<Block>" added when block is not empty.

Types

type Action

type Action struct {
	At             Duration  `yaml:"at"`
	CancelJobs     *Fraction `yaml:"cancel_jobs"`
	RetryFailed    bool      `yaml:"retry_failed"`
	PauseQueue     string    `yaml:"pause_queue"`
	ResumeQueue    string    `yaml:"resume_queue"`
	DisableWorkers *Fraction `yaml:"disable_workers"`
}

Action is a timed event during the run. It does at least one thing.

type ChaosEnv

type ChaosEnv struct {
	GOOS      string // runtime.GOOS of the test process
	Store     string // "sqlite" or "postgres"
	Container bool   // size-limited volumes are mounted (make chaos-container)
}

ChaosEnv is where a chaos scenario would run.

type Churn

type Churn struct {
	CrashPerHour      float64  `yaml:"crash_per_hour"`
	DisconnectPerHour float64  `yaml:"disconnect_per_hour"`
	RestartAfter      Duration `yaml:"restart_after"`
}

Churn is how often a worker in the group crashes or loses its connection.

type ClientsSpec

type ClientsSpec struct {
	WebSocket   WSSpec   `yaml:"websocket"`
	RESTPollers PollSpec `yaml:"rest_pollers"`
}

ClientsSpec is the read-side load: browsers and scripts watching the farm.

type Command

type Command struct {
	Path string
	Args []string
}

Command is the onRun command the driver writes into every template: the no-op binary real workers run, or a placeholder no worker executes.

type DatabaseFault

type DatabaseFault struct {
	Mode string `yaml:"mode"` // "stall" or "drop"
}

DatabaseFault stalls the store (SQLite: an outside write lock; PostgreSQL: the server's connections stop forwarding) or, on PostgreSQL only, drops the server's connections and refuses new ones.

type DiskFull

type DiskFull struct {
	Volume        string `yaml:"volume"`         // "server" (data directory) or "workers" (real workers' session directories)
	HeadroomBytes int64  `yaml:"headroom_bytes"` // free space left; 0 fills it
	Inodes        bool   `yaml:"inodes"`         // also use up the free inodes
	// Reason, on a workers volume, is an RE2 pattern every attempt that fails
	// on a real worker inside the window must match; "" checks none.
	Reason string `yaml:"reason"`
	// MinFailed, on a workers volume, is the fewest attempts that must fail
	// on real workers inside the window, so a run in which the fault made no
	// task fail does not pass; nil has no minimum.
	MinFailed *int `yaml:"min_failed,omitempty"`
	// MaxFailed, on a workers volume, bounds the attempts that fail on real
	// workers inside the window; nil is unbounded.
	MaxFailed *int `yaml:"max_failed,omitempty"`
}

DiskFull fills a size-limited volume with ballast for Duration.

type Dist

type Dist struct {
	Kind                         string
	Value, Min, Max, Median, P95 float64
	Unit                         string
}

Dist is a value a task draws from a distribution: how long it runs, how many log lines it writes. It is written as a bare duration (20s) or number (200), meaning a constant, or as a map:

{dist: uniform, min: 5s, max: 1m}
{dist: lognormal, median: 20s, p95: 90s}

A map without dist is lognormal when it has median and p95, and uniform when it has min and max. Durations are stored as seconds with Unit "s"; plain numbers have an empty Unit. The zero Dist means unset.

func (Dist) MarshalYAML

func (d Dist) MarshalYAML() (any, error)

MarshalYAML writes a Dist in the form it is read in: a bare duration or number for a constant, a {dist: ...} map otherwise. The zero Dist is null.

func (Dist) Mean

func (d Dist) Mean() float64

Mean is the distribution's mean: what Sample returns on average. The zero Dist's mean is 0.

func (Dist) Sample

func (d Dist) Sample(r *rand.Rand) float64

Sample draws one value: seconds for a duration, a count otherwise. It never returns a negative number. A lognormal whose p95 is not above its median has no spread and always returns the median. The zero Dist samples 0. Sample assumes a Dist that parsing or validation accepted: a lognormal with a median at or below zero yields NaN.

func (*Dist) UnmarshalYAML

func (d *Dist) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML parses every form Dist is written in.

type Duration

type Duration struct{ time.Duration }

Duration is a time.Duration written as a Go duration string ("90s", "1h30m").

func (Duration) MarshalYAML

func (d Duration) MarshalYAML() (any, error)

MarshalYAML writes a duration the way it is read, like 1m30s.

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML parses a Go duration string.

type Expect

type Expect struct {
	MaxReworkAttempts *int `yaml:"max_rework_attempts,omitempty"` // nil: report only
	// MaxReclaims bounds the attempts the server took back from a worker (the
	// reclaims check); nil: report only.
	MaxReclaims     *int             `yaml:"max_reclaims,omitempty"`
	KnownViolations []KnownViolation `yaml:"known_violations,omitempty"`
}

Expect declares what a chaos run is allowed to find.

type FDLimit

type FDLimit struct {
	Headroom int `yaml:"headroom"`
}

FDLimit lowers sqi-server's soft RLIMIT_NOFILE for Duration so that it can open Headroom more files, then restores it. Linux only.

type FarmSpec

type FarmSpec struct {
	Queues     []QueueSpec `yaml:"queues"`
	UsagePools []PoolSpec  `yaml:"usage_pools"`
}

FarmSpec declares the queues and usage pools the run creates.

type Fault

type Fault struct {
	At Duration `yaml:"at"`
	// Duration is how long a stall, partition, blackhole, latency, flap,
	// database, disk_full, fd_limit or revoke fault lasts before it heals.
	Duration Duration `yaml:"duration"`
	// RestartAfter is how long after a kill or term the process is started
	// again; 0 leaves a worker down. A server must be restarted.
	RestartAfter Duration       `yaml:"restart_after"`
	Kill         *ProcTarget    `yaml:"kill,omitempty"`
	Term         *ProcTarget    `yaml:"term,omitempty"`
	Stall        *ProcTarget    `yaml:"stall,omitempty"`
	Partition    *NetTarget     `yaml:"partition,omitempty"`
	Blackhole    *NetTarget     `yaml:"blackhole,omitempty"`
	Latency      *LatencySpec   `yaml:"latency,omitempty"`
	Flap         *FlapSpec      `yaml:"flap,omitempty"`
	PowerCut     *PowerCut      `yaml:"power_cut,omitempty"`
	Database     *DatabaseFault `yaml:"database,omitempty"`
	DiskFull     *DiskFull      `yaml:"disk_full,omitempty"`
	FDLimit      *FDLimit       `yaml:"fd_limit,omitempty"`
	Revoke       *ProcTarget    `yaml:"revoke,omitempty"` // a group's real workers; server is an error
}

Fault is one disruption injected during the run. Exactly one of Kill, Term, Stall, Partition, Blackhole, Latency, Flap, PowerCut, Database, DiskFull, FDLimit and Revoke is set.

func (Fault) End

func (f Fault) End() time.Duration

End is At plus everything the fault does before it has healed: Duration, RestartAfter, and for a power cut Down plus Gap.

func (Fault) Kind

func (f Fault) Kind() string

Kind returns the name of the one kind the fault sets (see faultKinds), and "" when none or more than one is set.

func (Fault) NetGroups

func (f Fault) NetGroups() (groups []string, ok bool)

NetGroups returns the worker groups a network fault (partition, blackhole, latency or flap) acts on, empty for every group. ok is false for any other kind.

type FlapSpec

type FlapSpec struct {
	Groups []string `yaml:"groups"`
	Period Duration `yaml:"period"` // cut for Period/2, open for Period/2
}

FlapSpec cuts and restores the connections of the named groups in turn.

type Fraction

type Fraction struct {
	Fraction float64 `yaml:"fraction"`
}

Fraction is a share of some population, in [0, 1].

type JobClass

type JobClass struct {
	Name         string   `yaml:"name"`
	Rate         Rate     `yaml:"rate"`
	Total        int      `yaml:"total"`
	Queue        string   `yaml:"queue"`
	Steps        int      `yaml:"steps"` // step i+1 depends on step i
	TasksPerStep int      `yaml:"tasks_per_step"`
	Chunk        int      `yaml:"chunk"` // frames per task
	Cores        int      `yaml:"cores"` // 0 means the whole worker
	UsagePool    string   `yaml:"usage_pool"`
	EXPR         bool     `yaml:"expr"`
	Task         TaskSpec `yaml:"task"`
	// RealTask changes what the no-op command does on a real worker; nil keeps
	// the default.
	RealTask *RealTask `yaml:"real_task,omitempty"`
}

JobClass is a family of jobs submitted at a rate, or in a burst of Total.

type KnownViolation

type KnownViolation struct {
	Check string   `yaml:"check"` // an invariant name, or "rework"
	Kind  string   `yaml:"kind"`  // "must" (default) or "may"
	OS    []string `yaml:"os"`    // GOOS values it applies on; empty = every OS
	// MaxAttempts is a rework entry's ceiling: rework above the scenario's
	// max_rework_attempts and at or under this is the known violation, and
	// more than this fails. Required on a rework entry, an error on any other.
	MaxAttempts *int `yaml:"max_attempts,omitempty"`
	// Match, when set, is an RE2 pattern that scopes the entry to the
	// violations it matches: a failure is excused only when each of its
	// violations matches an entry for its check (an entry with no pattern
	// excuses every violation). Not on a rework entry, whose finding is a
	// count.
	Match   string `yaml:"match,omitempty"`
	Reason  string `yaml:"reason"`
	Tracker string `yaml:"tracker"` // the issue that records the violation
}

KnownViolation is a finding the scenario expects. Tracker names the issue that records it.

type LatencySpec

type LatencySpec struct {
	Groups      []string `yaml:"groups"`
	Delay       Duration `yaml:"delay"`
	Jitter      Duration `yaml:"jitter"`
	BytesPerSec int      `yaml:"bytes_per_sec"` // 0 = unlimited
}

LatencySpec slows the connections of the named groups.

type NetTarget

type NetTarget struct {
	Groups []string `yaml:"groups"` // empty = every group
}

NetTarget names the worker groups whose connection to the server is hit.

type PollSpec

type PollSpec struct {
	Count     int      `yaml:"count"`
	Interval  Duration `yaml:"interval"`
	Endpoints []string `yaml:"endpoints"`
}

PollSpec is the REST pollers.

type PoolSpec

type PoolSpec struct {
	Name  string `yaml:"name"`
	Limit int    `yaml:"limit"`
}

PoolSpec is one usage pool.

type PowerCut

type PowerCut struct {
	Order string   `yaml:"order"` // "server-first" or "workers-first"
	Down  Duration `yaml:"down"`  // everything down this long
	Gap   Duration `yaml:"gap"`   // between the first and second side coming back
}

PowerCut takes the server and the real workers down together.

type ProcTarget

type ProcTarget struct {
	Server bool   `yaml:"server"`
	Group  string `yaml:"group"`
	Real   int    `yaml:"real"` // how many of the group's real workers; 0 = all of them
}

ProcTarget names the server or some of a group's real workers.

type QueueSpec

type QueueSpec struct {
	Name               string `yaml:"name"`
	MaxConcurrentTasks int    `yaml:"max_concurrent_tasks"`
}

QueueSpec is one queue.

type Rate

type Rate struct{ PerSecond float64 }

Rate is an events-per-second figure written as "2/s", "120/m" or "7200/h". The zero value means no rate is set.

func ParseRate

func ParseRate(s string) (Rate, error)

ParseRate parses "<positive number>/<s|m|h>".

func (Rate) MarshalYAML

func (r Rate) MarshalYAML() (any, error)

MarshalYAML writes a rate per second, like 2/s; the zero rate (none set) is null.

func (*Rate) UnmarshalYAML

func (r *Rate) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML parses a rate string.

type RealTask

type RealTask struct {
	Duration    Duration `yaml:"duration"`     // how long the main process runs
	LogEvery    Duration `yaml:"log_every"`    // main process prints a line this often; 0 = once
	ChattyChild bool     `yaml:"chatty_child"` // a child that prints to stdout every 200ms for Duration
	SilentChild bool     `yaml:"silent_child"` // a child with no stdio that writes the output file for Duration
	// ScratchBytes is how many bytes the task writes into its working
	// directory, spread over Duration.
	ScratchBytes int64 `yaml:"scratch_bytes"`
}

RealTask is how the no-op command behaves for this class on a real worker. Nil keeps the default no-op (print one line, exit 0).

type Scenario

type Scenario struct {
	Name         string              `yaml:"name"`
	Description  string              `yaml:"description"`
	Duration     Duration            `yaml:"duration"`
	Warmup       Duration            `yaml:"warmup"`
	DrainTimeout Duration            `yaml:"drain_timeout"`
	Server       ServerSpec          `yaml:"server"`
	Farm         FarmSpec            `yaml:"farm"`
	Workers      []WorkerGroup       `yaml:"workers"`
	Jobs         []JobClass          `yaml:"jobs"`
	JobDeps      float64             `yaml:"job_deps"`
	Clients      ClientsSpec         `yaml:"clients"`
	Actions      []Action            `yaml:"actions"`
	Assert       map[string]Duration `yaml:"assert"`
	Faults       []Fault             `yaml:"faults,omitempty"`
	Expect       Expect              `yaml:"expect,omitempty"`
}

Scenario is one load or soak run.

func Builtin

func Builtin(name string) (*Scenario, error)

Builtin parses the named built-in scenario, with defaults applied. Each call returns a fresh copy the caller may modify.

func Parse

func Parse(data []byte) (*Scenario, error)

Parse decodes a scenario and applies its defaults. A key the schema does not know is an error, so a misspelled field cannot silently do nothing.

func (*Scenario) ApplyDefaults

func (s *Scenario) ApplyDefaults()

ApplyDefaults fills the fields a scenario may leave out. It is idempotent.

func (*Scenario) ChaosSkipReason

func (s *Scenario) ChaosSkipReason(env ChaosEnv) string

ChaosSkipReason says why s cannot run in env, "" when it can. The rules apply in this order, each over every fault, and the first to match gives the reason: a stall fault on windows; an fd_limit fault off linux; a disk_full fault off linux; a disk_full fault without env.Container; a database drop without env.Store == "postgres".

func (*Scenario) Clone

func (s *Scenario) Clone() *Scenario

Clone returns a deep copy of s: changing the copy, its slices, maps and server configuration never changes s. Clone of nil is nil.

func (*Scenario) HasNetworkFault

func (s *Scenario) HasNetworkFault() bool

HasNetworkFault reports whether any fault needs lanes.

func (*Scenario) HasRealTask

func (s *Scenario) HasRealTask() bool

HasRealTask reports whether any job class runs a real task.

func (*Scenario) Set

func (s *Scenario) Set(path, value string) error

Set overrides one field, for example Set("workers[0].count", "500") or Set("jobs[1].task.fail_rate", "0.05"). The path names fields by their YAML keys, indexes lists with [n], and for a map names the key after it ("workers[0].tags.gpu", "assert.p95_submit_to_first_lease"). The value is parsed as YAML into the field's type, so anything a scenario file can say about a field, Set can too. A failed Set leaves the scenario unchanged.

func (*Scenario) Validate

func (s *Scenario) Validate(target TargetKind) error

Validate reports everything wrong with the scenario for the given target. The error joins one message per problem, each starting with the offending field's path, for example `jobs[0].queue: "comp2" is not in farm.queues`.

func (*Scenario) WorkerCounts

func (s *Scenario) WorkerCounts() (simulated, processes int)

WorkerCounts is the size of the simulated fleet and the number of real sqi-worker processes, each summed over the worker groups.

type ServerSpec

type ServerSpec struct {
	Store      string         `yaml:"store"` // "sqlite" or "postgres"
	BrokerAuth bool           `yaml:"broker_auth"`
	HTTPAuth   bool           `yaml:"http_auth"`
	TLS        bool           `yaml:"tls"`
	Config     map[string]any `yaml:"config"` // merged over the harness's settings; harness-owned and unknown keys are rejected
}

ServerSpec configures the server a managed target starts.

type TargetKind

type TargetKind int

TargetKind says what the harness drives. Some fields only make sense for one.

const (
	// TargetManaged starts and owns an sqi-server for the run.
	TargetManaged TargetKind = iota
	// TargetAttach drives an sqi-server somebody else is running.
	TargetAttach
)

type TaskSpec

type TaskSpec struct {
	Duration     Dist    `yaml:"duration"`
	FailRate     float64 `yaml:"fail_rate"` // each attempt fails with this probability
	HangRate     float64 `yaml:"hang_rate"` // runs until canceled or timed out
	LogLines     Dist    `yaml:"log_lines"`
	LogLineBytes int     `yaml:"log_line_bytes"`
	// ProgressEvery is how often a running task writes an openjd_progress
	// line; the worker's own throttle decides how many become snapshots.
	// 0 writes none.
	ProgressEvery Duration `yaml:"progress_every"`
}

TaskSpec describes how a simulated worker runs the tasks of a job class.

type WSSpec

type WSSpec struct {
	Count     int      `yaml:"count"`
	Subscribe []string `yaml:"subscribe"`
}

WSSpec is the WebSocket clients.

type WorkerGroup

type WorkerGroup struct {
	Name      string            `yaml:"name"`
	Count     int               `yaml:"count"` // simulated workers
	Real      int               `yaml:"real"`  // real sqi-worker processes (managed target only)
	Ramp      Rate              `yaml:"ramp"`  // connect and register rate
	CPU       int               `yaml:"cpu"`
	RAMMb     int               `yaml:"ram_mb"`
	OS        string            `yaml:"os"`
	Tags      map[string]string `yaml:"tags"`
	Queues    []string          `yaml:"queues"` // empty means every queue
	Heartbeat Duration          `yaml:"heartbeat"`
	Churn     Churn             `yaml:"churn"`
	// ClockSkew offsets the simulated workers' wire clock; it may be negative.
	ClockSkew Duration `yaml:"clock_skew"`
}

WorkerGroup is a set of identically configured workers.

Jump to

Keyboard shortcuts

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