Documentation
¶
Overview ¶
Package config defines the sqi-worker runtime configuration and provides layered loading from built-in defaults, a YAML/JSON file, SQI_WORKER_* environment variables, and CLI flag overrides, in that override order.
The WorkerConfig struct is the canonical configuration type. Use Load to obtain a populated, validated instance. Use Default to obtain defaults alone.
This package is the authoritative definition of worker configuration. Fields added here must be mirrored in the example config file at config/sqi-worker.example.yaml.
Index ¶
- Constants
- func DataDirSetInFile(path string) (bool, error)
- func DefaultCredentialFile(dataDir string) string
- func LoadOrCreateWorkerID(dataDir string) (string, error)
- func LoadWithSources(configFile string, flags FlagOverrides) (WorkerConfig, Sources, error)
- func WorkerIDFilePath(dataDir string) string
- type CloudInstanceIDConfig
- type DiagnosticsConfig
- type DiscoveryConfig
- type ExprConfig
- type FlagOverrides
- type IsolationConfig
- type LogConfig
- type LogStreamerConfig
- type MetricsConfig
- type MetricsTLSConfig
- type NATSConfig
- type NamedPath
- type PowerConfig
- type PreemptionConfig
- type Sources
- type StagingConfig
- type ValidationError
- type WorkerConfig
- type WorkerSettings
Constants ¶
const ( DefaultWorkerExprOperationLimit int64 = 1_000_000 MinWorkerExprOperationLimit int64 = 10_000 MaxWorkerExprOperationLimit int64 = 10_000_000 DefaultWorkerExprMemoryLimit int64 = 20_000_000 MinWorkerExprMemoryLimit int64 = 1_000_000 MaxWorkerExprMemoryLimit int64 = 200_000_000 DefaultWorkerExprAssignmentPositions int64 = 10_000 MinWorkerExprAssignmentPositions int64 = 2_000 MaxWorkerExprAssignmentPositions int64 = 100_000 DefaultWorkerExprAssignmentRetainedBytes int64 = 20_000_000 MinWorkerExprAssignmentRetainedBytes int64 = 2_000_000 MaxWorkerExprAssignmentRetainedBytes int64 = 200_000_000 DefaultWorkerExprLetRetainedBytes int64 = 10_000_000 MinWorkerExprLetRetainedBytes int64 = 1_000_000 MaxWorkerExprLetRetainedBytes int64 = 100_000_000 )
The defaults and the range an operator may configure each expr: key to.
These are copies of internal/worker/fmtres's own constants: this package is the operator-facing configuration layer and fmtres is the enforcement leaf, and the worker's config package does not import it (the same direction internal/config and internal/openjd keep). cmd/sqi-worker is the one place that sees both, and its TestExprLimitsBounds_MatchFmtres fails if a number here drifts from the one it bounds.
Which of the five is a catastrophe bound (a tight ceiling) and which is a policy bound (wide but finite), and why, is recorded on fmtres.ExprLimits' own fields.
const ( MinPreemptionPollInterval = time.Second MaxPreemptionPollInterval = time.Minute )
Bounds of worker.preemption.poll_interval.
const ( TLSAuto = "auto" TLSOn = "true" TLSOff = "false" )
TLS modes for NATSConfig.TLSEnabled. The zero value ("") is treated as TLSAuto so a struct built in a test behaves like a defaulted config.
const CloudInstanceIDSourceNone = "none"
CloudInstanceIDSourceNone is the worker.cloud_instance_id.source value that reads nothing. The vendor values are preempt.VendorAWS, preempt.VendorGCP and preempt.VendorAzure.
const PreemptionWatchNone = "none"
PreemptionWatchNone is the worker.preemption.watch value that watches nothing. The vendor values are preempt.VendorAWS, preempt.VendorGCP and preempt.VendorAzure.
Variables ¶
This section is empty.
Functions ¶
func DataDirSetInFile ¶ added in v0.4.0
DataDirSetInFile reports whether the config file at path sets worker.data_dir. An SQI_WORKER_DATA_DIR does not count: `service install` asks, and the service it registers never sees the installing shell's environment. When the file leaves it unset the value is Default's, under the home directory of whoever loads the configuration, unless the environment changes it.
It asks yaml.v3 rather than comparing values, so a value equal to the default still counts as set, and one supplied through a merge key is found. A null counts as unset, as it leaves the default. A file that does not parse reports false; Load reports why.
func DefaultCredentialFile ¶ added in v0.4.0
DefaultCredentialFile returns the default nkey seed path under dataDir, used whenever NATS.CredentialFile is left unset in Load's resolution below. Exported so other worker-side entry points that write or look for the seed file, such as the "sqi-worker keygen" CLI, derive the same path from the data directory.
func LoadOrCreateWorkerID ¶
LoadOrCreateWorkerID returns the worker's persistent UUID.
On the first call for a given dataDir the function:
- Creates dataDir (and any missing parents) with mode 0700.
- Generates a new random UUID.
- Writes it to <dataDir>/worker.id (mode 0600).
On subsequent calls the existing file is read and the UUID returned unchanged, so the server can correlate the worker across restarts.
An error is returned if the directory cannot be created, the file cannot be read or written, or the stored value is not a valid UUID.
dataDir is never widened for run-as-user traversal. As the ancestor of isolated session working directories it would have to be traversable (0711) for isolated tasks to chdir into their own session, because Go's forkAndExecInChild sets the child's process credentials before chdir. But worker.id is the worker's persistent, server-correlated identity and must stay private (0700) and unchanged, while session scratch is ephemeral and must be world-traversable when isolation is in use. So a worker that can isolate (running as root, or on Windows) keeps its session working directories under a separate root, created traversable; only a non-root worker, which cannot isolate, keeps them under <dataDir>/sessions (see cmd/sqi-worker's effectiveSessionRoot and session.Manager). dataDir is created 0700 and its mode is never changed afterwards.
func LoadWithSources ¶ added in v0.4.0
func LoadWithSources(configFile string, flags FlagOverrides) (WorkerConfig, Sources, error)
LoadWithSources is Load, additionally reporting which of a subset of settings (see Sources) were explicitly decided by the config file or environment layer.
func WorkerIDFilePath ¶ added in v0.4.0
WorkerIDFilePath returns the path LoadOrCreateWorkerID reads and writes under dataDir. Exported so other worker-side entry points that need to check for an existing worker ID without creating one — the "sqi-worker keygen" CLI, notably — derive the same path from the data directory rather than each hardcoding the filename.
Types ¶
type CloudInstanceIDConfig ¶ added in v0.4.0
type CloudInstanceIDConfig struct {
// Source selects the provider whose metadata service is read: "none" (the
// default, in which case no network request is made), "aws", "gcp" or
// "azure".
// Env: SQI_WORKER_CLOUD_INSTANCE_ID_SOURCE
Source string `yaml:"source"`
// Endpoint, when set, replaces the provider's metadata base URL, for a
// proxy or a test. Empty uses the provider's well-known address.
// Env: SQI_WORKER_CLOUD_INSTANCE_ID_ENDPOINT
Endpoint string `yaml:"endpoint"`
}
CloudInstanceIDConfig controls reading the cloud provider's identifier for the instance the worker runs on, so the server can find that instance when it powers a worker off or scales a group down. The worker reads it once at startup and reports it when it registers.
type DiagnosticsConfig ¶
type DiagnosticsConfig struct {
// Enabled turns on diagnostic-log publishing. When true (the default) the
// worker's slog records are mirrored to sqi-server in addition to stderr.
// Env: SQI_DIAGNOSTICS_ENABLED
Enabled bool `yaml:"enabled"`
}
DiagnosticsConfig controls the diagnostic-log sink that ships the worker's own slog output to sqi-server over core NATS (worker.diag.<workerID>), where it is surfaced in the web UI.
type DiscoveryConfig ¶
type DiscoveryConfig struct {
// EnableMDNS enables mDNS browsing for "_sqi._tcp" services on the local
// network. When true and NATS.URL is empty, the worker uses the first
// discovered server address.
// Env: SQI_WORKER_DISCOVERY_ENABLE_MDNS
EnableMDNS bool `yaml:"enable_mdns"`
// MDNSTimeout is the maximum duration to wait for mDNS discovery results
// before falling back to an error.
// Env: SQI_WORKER_DISCOVERY_MDNS_TIMEOUT
MDNSTimeout time.Duration `yaml:"mdns_timeout"`
}
DiscoveryConfig controls mDNS-based sqi-server auto-discovery.
type ExprConfig ¶ added in v0.3.0
type ExprConfig struct {
// OperationLimit is the specification section 1.3.10 operation budget
// for one phase-3 expression evaluation.
// Default: 1000000 Range: 10000-10000000
// Env: SQI_WORKER_EXPR_OPERATION_LIMIT
OperationLimit int64 `yaml:"operation_limit"`
// MemoryLimit is the specification section 1.3.9 live-byte budget for
// one phase-3 expression evaluation. The per-let-block structural ceiling
// is 50x this number, which is the figure to size host RAM against.
// Default: 20000000 Range: 1000000-200000000
// Env: SQI_WORKER_EXPR_MEMORY_LIMIT
MemoryLimit int64 `yaml:"memory_limit"`
// AssignmentPositions is how many expression positions (a command, one
// args entry, one embedded file, one variable value) one assignment may
// resolve, summed across the task's own symbol table and every environment
// the session enters.
//
// Must not be lower than the server's openjd.expr_template_positions. An
// assignment's positions are a subset of its template's, so a lower value
// here rejects, on this host and once per task, a job the server already
// accepted, naming a budget the submitter never saw. The scheduler withholds
// EXPR work from a worker whose value is lower.
// Default: 10000 Range: 2000-100000
// Env: SQI_WORKER_EXPR_ASSIGNMENT_POSITIONS
AssignmentPositions int64 `yaml:"assignment_positions"`
// AssignmentRetainedBytes is the cumulative size of every let-bound
// value every phase-3 symbol table one assignment builds retains. See
// caveat 3 above: this is allocation across the session's entry phase, not
// simultaneously live memory.
// Default: 20000000 Range: 2000000-200000000
// Env: SQI_WORKER_EXPR_ASSIGNMENT_RETAINED_BYTES
AssignmentRetainedBytes int64 `yaml:"assignment_retained_bytes"`
// LetRetainedBytes is what one phase-3 symbol table may hold live. It
// measures the whole table, so a job whose own parameters are large spends
// budget its let: block never asked for.
// Default: 10000000 Range: 1000000-100000000
// Env: SQI_WORKER_EXPR_LET_RETAINED_BYTES
LetRetainedBytes int64 `yaml:"let_retained_bytes"`
}
ExprConfig is the operator-facing form of internal/worker/fmtres's ExprLimits: the five numbers that bound phase-3 (task-execution-time) OpenJD expression evaluation on this host.
Each worker reads its own file, so a heterogeneous farm can size these to each host's memory. The server has its own, separate set (internal/config's openjd.expr_* keys) covering submission-time evaluation. The scheduler compares the two and withholds EXPR work from a worker whose limits are lower than the server's; see AssignmentPositions.
Three things to know before raising any of them:
- None of these bounds wall-clock time. Specification section 1.3.10 prices 256 bytes at one operation, so an operation's real cost varies by orders of magnitude. Raising a limit lengthens the worst assignment this host can be asked to resolve, roughly in proportion; no setting makes a slow resolution impossible.
- expr.operation_limit and expr.assignment_positions multiply. The cumulative operation ceiling for one assignment is their product, so raising both raises it twice over.
- The byte dimensions count cumulative allocation, not peak live retention. A session that never holds more than a few MB at once is still charged the sum of every environment it enters, so sizing host RAM against expr.assignment_retained_bytes over-provisions, and sizing that number against an observed RSS under-bounds it.
An out-of-range value is a startup failure, not a clamp (see Validate).
type FlagOverrides ¶
type FlagOverrides struct {
// LogLevel overrides Log.Level when non-empty.
LogLevel string
// LogFormat overrides Log.Format when non-empty.
LogFormat string
// DryRun, when true, makes the start command print resolved config and exit.
DryRun bool
// NATSInsecureSkipVerify overrides NATS.InsecureSkipVerify when true.
// Corresponds to --nats-insecure-skip-verify on the start subcommand.
NATSInsecureSkipVerify bool
}
FlagOverrides carries values from CLI flags that take highest precedence during config loading. Only non-empty or non-zero values override the lower layers.
type IsolationConfig ¶ added in v0.3.0
type IsolationConfig struct {
// Required makes the worker exit at boot when it cannot assume another
// identity. Default false: a worker with no isolation capability keeps
// running ordinary queues.
// Env: SQI_WORKER_ISOLATION_REQUIRED
Required bool `yaml:"required"`
// Provider selects the Windows credential mechanism. "logon_user" (the
// default) is the only supported value.
//
// "s4u" is refused. An S4U logon needs no password, but the token it
// produces carries no network credentials: any UNC path, mapped drive, or
// authenticated license server fails as anonymous from inside the task.
// On a render farm, where scene files and outputs live on a share, that
// rules it out as a general-purpose provider.
// Env: SQI_WORKER_ISOLATION_PROVIDER
Provider string `yaml:"provider"`
// EnvPassthrough lists daemon environment variable name patterns inherited
// by isolated tasks, in addition to the minimal base. filepath.Match
// globs. Render farms depend on inherited licensing variables, so the
// allowlist is extensible.
// Env: SQI_WORKER_ISOLATION_ENV_PASSTHROUGH (comma-separated)
EnvPassthrough []string `yaml:"env_passthrough"`
}
IsolationConfig controls running tasks as a queue-configured OS user.
type LogConfig ¶
type LogConfig struct {
// Level is the minimum log level: debug, info, warn, error.
// Env: SQI_WORKER_LOG_LEVEL
Level string `yaml:"level"`
// Format is the log output format: json or text.
// Env: SQI_WORKER_LOG_FORMAT
Format string `yaml:"format"`
// File, when set, sends log output to this file instead of stderr,
// rotated by size. Empty keeps stderr. When sqi-worker runs as a Windows
// service with File empty, logs go to
// %ProgramData%\sqi\logs\<service-name>.log.
// Env: SQI_WORKER_LOG_FILE
File string `yaml:"file"`
// MaxSizeMB is the size in megabytes at which File is rotated. Must be > 0.
// Env: SQI_WORKER_LOG_MAX_SIZE_MB
MaxSizeMB int `yaml:"max_size_mb"`
// MaxBackups is how many rotated files are kept; 0 keeps none.
// Env: SQI_WORKER_LOG_MAX_BACKUPS
MaxBackups int `yaml:"max_backups"`
}
LogConfig controls structured logging output.
type LogStreamerConfig ¶
type LogStreamerConfig struct {
// MaxLinesPerChunk is the maximum number of output lines batched into a
// single NATS message. A flush is triggered immediately when the buffer
// reaches this count. Increase for verbose processes; decrease for more
// granular live log updates.
// Default: 50
// Env: SQI_WORKER_LOG_STREAMER_MAX_LINES_PER_CHUNK
MaxLinesPerChunk int `yaml:"max_lines_per_chunk"`
// MaxBytesPerChunk is the maximum total byte count of line content in a
// single NATS message. A flush is triggered when the accumulated bytes
// reach this limit after adding a line.
// Default: 16384 (16 KB)
// Env: SQI_WORKER_LOG_STREAMER_MAX_BYTES_PER_CHUNK
MaxBytesPerChunk int `yaml:"max_bytes_per_chunk"`
// FlushInterval is the maximum time a line may sit in the buffer before
// being flushed by the background goroutine regardless of chunk thresholds.
// Smaller values make the web UI log viewer feel more live at the cost of
// more frequent small NATS publishes.
// Default: 500ms
// Env: SQI_WORKER_LOG_STREAMER_FLUSH_INTERVAL
FlushInterval time.Duration `yaml:"flush_interval"`
}
LogStreamerConfig controls the log-chunk publisher that streams task process stdout/stderr to sqi-server.
type MetricsConfig ¶
type MetricsConfig struct {
// Addr is the TCP address the local HTTP server listens on.
// Env: SQI_WORKER_METRICS_ADDR
Addr string `yaml:"addr"`
// EnablePprof exposes Go runtime profiling endpoints at /debug/pprof/.
// Env: SQI_WORKER_METRICS_ENABLE_PPROF
EnablePprof bool `yaml:"enable_pprof"`
// TLS terminates TLS on this listener. Off by default, which is right for
// the loopback default address; turn it on together with any Addr that is
// reachable from elsewhere, since this endpoint carries metrics, health and,
// if EnablePprof is set, full runtime profiles.
TLS MetricsTLSConfig `yaml:"tls"`
}
MetricsConfig controls the local HTTP server for health probes and metrics.
type MetricsTLSConfig ¶ added in v0.4.0
type MetricsTLSConfig struct {
// Enabled serves HTTPS on metrics.addr. There is no plaintext port when it
// is on: the listener upgrades in place, as the server's does.
// Env: SQI_WORKER_METRICS_TLS_ENABLED
Enabled bool `yaml:"enabled"`
// CertFile is the PEM certificate served on this listener.
// Env: SQI_WORKER_METRICS_TLS_CERT_FILE
CertFile string `yaml:"cert_file"`
// KeyFile is the PEM private key matching CertFile.
// Env: SQI_WORKER_METRICS_TLS_KEY_FILE
KeyFile string `yaml:"key_file"`
}
MetricsTLSConfig terminates TLS on the worker's metrics/health listener.
type NATSConfig ¶
type NATSConfig struct {
// URL is the NATS server URL, e.g. "nats://localhost:4222".
// Env: SQI_WORKER_NATS_URL
URL string `yaml:"url"`
// TLSEnabled controls TLS on the broker connection. It is a three-valued
// string rather than a bool, mirroring auth.session.cookie_secure on the
// server:
//
// - "auto" (default): use TLS when there is a reason to. That means any
// of the TLS fields below being set, or the discovered server
// advertising a TLS-required broker over mDNS.
// - "true": always use TLS, even with no CA configured (system roots).
// For a broker presenting a publicly-trusted certificate, which
// nothing else would signal.
// - "false": never use TLS, even with a CA configured. For an operator
// who knows the broker is plaintext.
//
// A bool cannot express "infer" and "force off" apart: both collapse onto
// the same zero value.
// Env: SQI_WORKER_NATS_TLS_ENABLED
TLSEnabled string `yaml:"tls_enabled"`
// TLSCertFile is the path to the client TLS certificate (PEM).
// Env: SQI_WORKER_NATS_TLS_CERT_FILE
TLSCertFile string `yaml:"tls_cert_file"`
// TLSKeyFile is the path to the client TLS key (PEM).
// Env: SQI_WORKER_NATS_TLS_KEY_FILE
TLSKeyFile string `yaml:"tls_key_file"`
// TLSCAFile is the path to the CA certificate used to verify the NATS
// server certificate (PEM).
// Env: SQI_WORKER_NATS_TLS_CA_FILE
TLSCAFile string `yaml:"tls_ca_file"`
// InsecureSkipVerify disables TLS certificate verification. For
// development environments only.
// Env: SQI_WORKER_NATS_INSECURE_SKIP_VERIFY
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
// MaxReconnectAttempts is the maximum number of reconnection attempts
// before giving up. -1 means retry indefinitely.
// Env: SQI_WORKER_NATS_MAX_RECONNECT_ATTEMPTS
MaxReconnectAttempts int `yaml:"max_reconnect_attempts"`
// ReconnectWait is the base wait duration between reconnection attempts.
// Actual wait uses exponential backoff with jitter.
// Env: SQI_WORKER_NATS_RECONNECT_WAIT
ReconnectWait time.Duration `yaml:"reconnect_wait"`
// CredentialFile is the path to this worker's nkey seed file. When empty
// it defaults to <worker.data_dir>/worker.nk. The file is created by
// enrollment or by `sqi-worker keygen` and must be mode 0600.
// Env: SQI_WORKER_NATS_CREDENTIAL_FILE
CredentialFile string `yaml:"credential_file"`
// JoinToken is a worker enrollment token. Used exactly once, on first
// start, to obtain a credential; ignored once CredentialFile exists.
// Prefer JoinTokenFile: a token in a config file is a secret at rest.
// Env: SQI_WORKER_NATS_JOIN_TOKEN
JoinToken string `yaml:"join_token"`
// JoinTokenFile is a path to a file containing a join token. Takes
// precedence over JoinToken.
// Env: SQI_WORKER_NATS_JOIN_TOKEN_FILE
JoinTokenFile string `yaml:"join_token_file"`
// ServerURL is the sqi-server HTTP base URL used for enrollment, e.g.
// "http://sqi-server.example:8080". Enrollment runs over REST, not over
// NATS: the broker's job is to reject unauthenticated connections, so it
// cannot also be the channel a worker gets its first credential over.
// Required whenever a join token is configured. It is not derived from
// mDNS discovery: a worker relying on mDNS with no explicit server_url
// fails enrollment with an error naming this field rather than attempting
// a request with no host.
// Env: SQI_WORKER_NATS_SERVER_URL
ServerURL string `yaml:"server_url"`
// ServerTLSCAFile is the CA that verifies sqi-server's certificate at
// ServerURL, for enrollment over HTTPS. Empty means the system roots;
// set means that CA only.
//
// Separate from TLSCAFile above, which is the NATS broker CA: the two can
// differ (a publicly-issued certificate on the API, a private farm CA on
// the broker).
// Env: SQI_WORKER_NATS_SERVER_TLS_CA_FILE
ServerTLSCAFile string `yaml:"server_tls_ca_file"`
// ServerTLSInsecureSkipVerify disables verification of sqi-server's
// certificate during enrollment. Development only.
// Env: SQI_WORKER_NATS_SERVER_TLS_INSECURE_SKIP_VERIFY
ServerTLSInsecureSkipVerify bool `yaml:"server_tls_insecure_skip_verify"`
}
NATSConfig is the connection configuration for the remote NATS server.
func (NATSConfig) UseTLS ¶ added in v0.4.0
func (c NATSConfig) UseTLS(brokerAdvertisedTLS bool) bool
UseTLS reports whether the broker connection should use TLS.
brokerAdvertisedTLS is what mDNS discovery learned about the server (the tls:// scheme of the advertised nats_url); it is false when the URL was configured explicitly, since nothing was discovered. It only participates in "auto".
type NamedPath ¶ added in v0.4.0
type NamedPath struct{ Key, Path string }
NamedPath is one file or directory a configuration names, with the dotted YAML key that names it.
type PowerConfig ¶ added in v0.4.0
type PowerConfig struct {
// AllowRemoteSleep lets sqi-server order this machine to sleep or shut
// down when it retires the worker from a capacity group. Off (the default)
// refuses both. Waking a peer needs no opt-in: it only sends UDP
// broadcasts.
// Env: SQI_WORKER_POWER_ALLOW_REMOTE_SLEEP
AllowRemoteSleep bool `yaml:"allow_remote_sleep"`
// SleepCommand is the program and arguments that suspend the machine,
// run directly with no shell. Empty uses the platform's own: systemctl
// suspend on Linux, pmset sleepnow on macOS, and a PowerShell suspend call
// on Windows. There is no default on any other platform. File only.
SleepCommand []string `yaml:"sleep_command"`
// ShutdownCommand is the program and arguments that power the machine off,
// run directly with no shell. Empty uses the platform's own: systemctl
// poweroff on Linux, shutdown -h now on macOS and shutdown.exe /s /t 0 on
// Windows. File only.
ShutdownCommand []string `yaml:"shutdown_command"`
}
PowerConfig controls whether the server may suspend or power off this machine on a capacity group's behalf. Both are off unless the operator opts in, and a worker that is running a task refuses either way.
type PreemptionConfig ¶ added in v0.4.0
type PreemptionConfig struct {
// Watch selects the provider whose metadata service is polled: "none" (the
// default, in which case nothing is polled and no network request is made),
// "aws", "gcp" or "azure".
// Env: SQI_WORKER_PREEMPTION_WATCH
Watch string `yaml:"watch"`
// PollInterval is how often the metadata service is polled, 1s to 60s.
// Providers give from 30 seconds (Azure) to 2 minutes (AWS) of warning, so
// the default of 5s leaves almost all of it to hand work back.
// Env: SQI_WORKER_PREEMPTION_POLL_INTERVAL
PollInterval time.Duration `yaml:"poll_interval"`
// Endpoint, when set, replaces the provider's metadata base URL, for a
// proxy or a test. Empty uses the provider's well-known address.
// Env: SQI_WORKER_PREEMPTION_ENDPOINT
Endpoint string `yaml:"endpoint"`
}
PreemptionConfig controls the watcher that polls the provider's instance metadata service for a notice that this machine is about to be reclaimed. When one arrives the worker cancels its running tasks at once, hands them back to the server as a reclaim (not a failure) and deregisters as preempted.
type Sources ¶ added in v0.4.0
type Sources struct {
// CredentialFile is true when nats.credential_file was set by the
// config file or by SQI_WORKER_NATS_CREDENTIAL_FILE, before [Load]
// resolves an empty value to DefaultCredentialFile(Worker.DataDir).
CredentialFile bool
}
Sources reports, for a subset of settings, whether the config file or environment layer explicitly decided the value before Load's own default-fill step ran, as opposed to it being left empty for that step to fill in. Comparing the resolved value against the computed default (e.g. DefaultCredentialFile) is not sound: an operator can explicitly configure a value that equals what the default-fill would produce, in which case value comparison cannot tell "explicitly configured" apart from "left unset". Sources answers from the file/env layers themselves.
type StagingConfig ¶ added in v0.2.0
type StagingConfig struct {
// ScratchDir is the base directory for per-attempt staged copies.
ScratchDir string `yaml:"scratch_dir"`
// SyncCommand is the command template invoked per path, with {src}, {dest},
// and optional {object_type} placeholders, e.g. "rsync -a {src} {dest}".
SyncCommand string `yaml:"sync_command"`
// Defaults enables the built-in copy + TEMP scratch when staging is
// otherwise unconfigured. Default true; set false to make an unconfigured
// stage_locally job fail hard instead.
// Env: SQI_STAGING_DEFAULTS
Defaults bool `yaml:"defaults"`
}
StagingConfig is the operator-owned configuration for the stage_locally path delivery. sqi never copies bytes itself: it invokes SyncCommand per path.
type ValidationError ¶
ValidationError describes a single configuration problem.
func Validate ¶
func Validate(cfg WorkerConfig) []ValidationError
Validate returns a list of validation errors for cfg. An empty slice means the configuration is valid.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type WorkerConfig ¶
type WorkerConfig struct {
// NATS is the connection configuration for the broker sqi-server uses:
// the one it embeds, or an operator-run external NATS server.
NATS NATSConfig `yaml:"nats"`
// Worker contains identity and runtime behavior settings.
Worker WorkerSettings `yaml:"worker"`
// Log controls structured logging output.
Log LogConfig `yaml:"log"`
// Metrics controls the local HTTP server used for health probes and
// Prometheus metrics.
Metrics MetricsConfig `yaml:"metrics"`
// Discovery controls mDNS-based server auto-discovery.
Discovery DiscoveryConfig `yaml:"discovery"`
// LogStreamer controls the log-chunk publisher that batches task process
// output and streams it to sqi-server via NATS.
LogStreamer LogStreamerConfig `yaml:"log_streamer"`
// Diagnostics controls publishing the worker's own slog output to
// sqi-server for display in the web UI.
Diagnostics DiagnosticsConfig `yaml:"diagnostics"`
// Staging configures local input/output staging for the stage_locally path
// delivery. Both fields must be set for staging to function.
Staging StagingConfig `yaml:"staging"`
// Capabilities configures software capability auto-detection (built-in DCC
// detectors plus custom detectors and a disable list).
Capabilities capabilities.CapabilitiesConfig `yaml:"capabilities"`
// Isolation controls running tasks as a queue-configured OS user
// (protocol.AssignMsg.Isolation). Isolation is opt-in.
Isolation IsolationConfig `yaml:"isolation"`
// Expr bounds what one assignment may spend evaluating OpenJD EXPR
// expressions on this host.
Expr ExprConfig `yaml:"expr"`
}
WorkerConfig is the complete runtime configuration for sqi-worker. Zero values are not valid; use Default or Load to obtain a populated instance.
func Default ¶
func Default() WorkerConfig
Default returns a WorkerConfig populated with built-in defaults.
func Load ¶
func Load(configFile string, flags FlagOverrides) (WorkerConfig, error)
Load returns the effective WorkerConfig by merging layers in override order: built-in defaults, YAML/JSON file, SQI_WORKER_* env vars, CLI flags.
configFile may be empty, in which case Load searches the default paths.
func (WorkerConfig) NamedPaths ¶ added in v0.4.0
func (c WorkerConfig) NamedPaths() []NamedPath
NamedPaths returns every file and directory the configuration names, as written (a relative path is relative to the worker's working directory), skipping empty keys. A command the worker runs (staging's sync command, the power commands, and each worker.commands entry a job's command name is replaced with) counts by its program when that contains a path separator; a bare name is found on PATH. On Windows, `service install` refuses a service whose named paths an unprivileged user could change: each one decides whom the worker trusts or what it runs, and on a worker with no run_as_user queue a task runs as the service account.
The capability detectors' paths are not named: detected application install locations are the operator's, and on a worker with no run_as_user queue what they find runs as the service account (a documented gap).
type WorkerSettings ¶
type WorkerSettings struct {
// Name is a human-readable label for this worker shown in the web UI.
// Defaults to the hostname.
// Env: SQI_WORKER_NAME
Name string `yaml:"name"`
// FarmID is the farm this worker belongs to. When set, the worker only
// receives tasks belonging to that farm. When empty (the default), the
// worker is unaffiliated and accepts tasks from any farm, which suits
// single-farm or development setups.
// Env: SQI_WORKER_FARM_ID
FarmID string `yaml:"farm_id"`
// DataDir is the directory used to persist the worker ID file
// (worker.id), the worker's stable, server-correlated identity. Session
// working directories go under it only on a non-root POSIX worker, which
// cannot isolate (see SessionDir). It is never widened for run-as-user
// traversal: it stays private (0700).
// Env: SQI_WORKER_DATA_DIR
DataDir string `yaml:"data_dir"`
// SessionDir is the directory under which session working directories
// (<SessionDir>/<sessionID>/) are created. Separate from DataDir: session
// scratch is ephemeral and, when isolation is in use, must be traversable
// by whichever run-as-user identity a session resolves to, while DataDir
// holds the persistent worker-id and must stay private. Left empty (the
// default), the effective value is resolved at startup (see
// cmd/sqi-worker's effectiveSessionRoot):
// - running as root: /var/lib/sqi-worker-sessions, a sibling of, never
// a descendant of, this package's own data_dir default (see
// cmd/sqi-worker's defaultSessionRoot doc for why the two must not
// nest). Its ancestors, /var and /var/lib, are 0755 on every common
// distribution, so nothing needs to be created or widened for this.
// - on Windows: %ProgramData%\sqi\worker\sessions.
// - otherwise: <DataDir>/sessions. Run-as-user isolation cannot
// function without root regardless of directory permissions, so
// nothing needs to be traversable by another identity.
// Env: SQI_WORKER_SESSION_DIR
SessionDir string `yaml:"session_dir"`
// ComputeLocation is the named location (matching a storage location in
// sqi-server) where this worker's filesystem lives. Used for resolved-mode
// path mapping.
// Env: SQI_WORKER_COMPUTE_LOCATION
ComputeLocation string `yaml:"compute_location"`
// CapabilityTags is a list of arbitrary capability tags merged with
// auto-detected capabilities at registration time, e.g. ["maya_2025",
// "gpu", "highram"]. A bare tag means "true"; "key=value" sets a value.
// Env: SQI_WORKER_CAPABILITY_TAGS (comma-separated)
CapabilityTags []string `yaml:"capability_tags"`
// Commands maps a command name a job runs to the executable to run in
// its place, with optional leading arguments. The worker starts commands
// directly (no shell), so an alias never resolves, and some software
// installs under a versioned name; this is how an operator says where
// "nuke" really is, or that it needs "--nc". Config file only.
Commands commands.Table `yaml:"commands"`
// HeartbeatInterval is how often the worker publishes a heartbeat to the
// server. Should be shorter than the server's heartbeat sweep interval.
// Env: SQI_WORKER_HEARTBEAT_INTERVAL
HeartbeatInterval time.Duration `yaml:"heartbeat_interval"`
// ShutdownGracePeriod is the maximum time the worker waits for in-flight
// tasks to finish before force-killing them on shutdown.
// Env: SQI_WORKER_SHUTDOWN_GRACE_PERIOD
ShutdownGracePeriod time.Duration `yaml:"shutdown_grace_period"`
// AllowRoot permits the worker to run as the root user on Linux/macOS.
// Disabled by default because executing render processes as root is a
// security risk (see docs/worker-configuration.md, "worker.allow_root").
// Env: SQI_WORKER_ALLOW_ROOT
AllowRoot bool `yaml:"allow_root"`
// KeepFailedSessions retains a session's working directory after the
// session ends in failure (task cancellation, non-zero exit code, or
// environment setup error). Useful for post-mortem inspection of partial
// outputs and environment state. Disabled by default to avoid filling the
// data directory on busy workers.
// Env: SQI_WORKER_KEEP_FAILED_SESSIONS
KeepFailedSessions bool `yaml:"keep_failed_sessions"`
// CapacityGroup names the capacity group this worker asks to join when it
// registers. Empty (the default) joins none. The server honors it only with
// broker authentication off, and only for a sized group in the worker's
// farm; with authentication on, membership comes from the group token the
// worker enrolled with and this value is ignored.
// Env: SQI_WORKER_CAPACITY_GROUP
CapacityGroup string `yaml:"capacity_group"`
// Preemption configures watching the cloud provider's metadata service for
// a spot or preemptible reclaim notice. Off by default.
Preemption PreemptionConfig `yaml:"preemption"`
// CloudInstanceID configures reading this machine's cloud instance ID from
// the provider's metadata service. Off by default.
CloudInstanceID CloudInstanceIDConfig `yaml:"cloud_instance_id"`
// Power configures whether the server may put this machine to sleep or
// power it off. Off by default.
Power PowerConfig `yaml:"power"`
// QueueIDs restricts this worker to serving the listed queue IDs. An empty
// list means the worker accepts assignments from all queues (it requests
// leases on the wildcard queue token). Set this when running a
// heterogeneous farm where some workers specialise in a subset of queues.
//
// Each entry becomes a NATS subject token in the work-lease subject
// work.lease.<workerID>.<queueID>, so it must satisfy the same constraint
// as a worker ID (see brokerauth.ValidWorkerIDToken): non-empty, and free
// of '.', '*', '>' and whitespace. A queue ID that does not is rejected
// by [Validate] rather than producing a subject the broker never routes.
// With broker auth on, a queue ID containing a dot yields too many subject
// tokens for this worker's publish grant and every lease request for it is
// denied; with broker auth off it fails bus.ParseWorkerSubject on the
// server side and gets no reply. Either way the worker retries forever
// with nothing in its logs naming the cause.
// Env: SQI_WORKER_QUEUE_IDS (comma-separated)
QueueIDs []string `yaml:"queue_ids"`
// PullIdleBackoff is accepted but has no effect: the worker's lease request
// is held by the server and re-issued on return, so there is no polling
// loop to throttle. A negative value fails validation.
// Default: 2s
// Env: SQI_WORKER_PULL_IDLE_BACKOFF
PullIdleBackoff time.Duration `yaml:"pull_idle_backoff"`
// PullNackDelay is accepted but has no effect: the server checks
// eligibility before leasing, so the worker runs what it is given. A
// negative value fails validation.
// Default: 5s
// Env: SQI_WORKER_PULL_NACK_DELAY
PullNackDelay time.Duration `yaml:"pull_nack_delay"`
}
WorkerSettings controls the worker's identity and runtime behavior.