Documentation
¶
Overview ¶
Package executor implements the bare-metal task executor for sqi-worker.
An Executor starts OS processes via os/exec for each assigned task, captures their stdout and stderr line-by-line, manages per-task execution timeouts and cancellation per the OpenJD Action.cancelation method (TERMINATE = immediate SIGKILL, the spec default; NOTIFY_THEN_TERMINATE = SIGTERM then SIGKILL after the notify period), and publishes task-status messages back to sqi-server via NATS.
Interfaces ¶
Executor implements [lease.Dispatcher], so it can be wired directly into the lease loop. It also satisfies [heartbeat.StateSource] by exposing Executor.ActiveTaskCount, Executor.ActiveTaskIDs, and Executor.LastAssignmentAt, and [heartbeat.AttemptSource] by exposing Executor.ActiveAttemptIDs.
Concurrency ¶
The server gates how many tasks a worker receives via CPU-core accounting; the worker runs whatever it is leased without an additional local cap. Multiple leases are dispatched in separate goroutines and run concurrently.
Output handling ¶
The OutputHandler interface abstracts what happens with each line of process output. The log-chunk publisher and the OpenJD progress line parser implement this interface; LogOutput forwards lines to the structured logger.
Root-user check ¶
Call CheckRootUser before creating an Executor. It returns an error if the worker process is running as root on Linux/macOS and Config.AllowRoot is false (see docs/worker-configuration.md, "worker.allow_root").
Index ¶
- func CheckRootUser(allowRoot bool, logger *slog.Logger) error
- func FirstS3Path(action *protocol.Action, env map[string]string) (string, bool)
- func IsRunningAsRoot() bool
- func ResolveAssignment(msg *protocol.AssignMsg, sess *session.Session) (*protocol.Action, map[string]string, []protocol.EmbeddedFile, error)
- type Config
- type DiscardOutput
- type Executor
- func (e *Executor) ActiveAttemptIDs() []string
- func (e *Executor) ActiveTaskCount() int
- func (e *Executor) ActiveTaskIDs() []string
- func (e *Executor) Cancel(taskID, attemptID string) bool
- func (e *Executor) Dispatch(ctx context.Context, msg *protocol.AssignMsg) error
- func (e *Executor) DrainAndShutdown(gracePeriod time.Duration) (completed, killed int)
- func (e *Executor) Hold(attemptID string)
- func (e *Executor) LastAssignmentAt() *time.Time
- type LogFlusher
- type LogOutput
- type OutputHandler
- type ProgressPatternHook
- type TaskLifecycleHook
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckRootUser ¶
CheckRootUser warns and returns an error if the worker is running as the root user on Linux/macOS and allowRoot is false (see docs/worker-configuration.md, "worker.allow_root").
Call this at worker startup, before constructing an Executor. If the function returns a non-nil error the caller should treat it as fatal and exit with a non-zero code.
func FirstS3Path ¶ added in v0.2.0
FirstS3Path returns the first s3:// URI found among the resolved action's command, args, and env-var values, or ("", false) if none. It underpins the pre-exec guard that rejects an object-store path which was not staged to local scratch. Env iteration order is unspecified, so tests should place the token in the command or args when they assert a specific value.
func IsRunningAsRoot ¶ added in v0.3.0
func IsRunningAsRoot() bool
IsRunningAsRoot returns true when the effective user ID of the worker process is 0 (root) on Linux or macOS.
Exported because cmd/sqi-worker also uses it to decide the default run-as-user session root: /var/lib/sqi-worker-sessions when root (its ancestors are traversable), otherwise a location under worker.data_dir. See cmd/sqi-worker's effectiveSessionRoot.
func ResolveAssignment ¶ added in v0.4.0
func ResolveAssignment( msg *protocol.AssignMsg, sess *session.Session, ) (*protocol.Action, map[string]string, []protocol.EmbeddedFile, error)
ResolveAssignment is [resolveAssignment] for callers outside this package: it returns the resolved OnRun action, the session's static environment, and the resolved embedded files for msg, exactly as the worker computes them before launching a process.
It delegates verbatim and adds nothing. internal/presettest renders the result into a reviewed golden file per shipped preset, so anything this wrapper did on its own would be a difference between what the goldens show and what a worker runs.
Types ¶
type Config ¶
type Config struct {
// KillGracePeriod is the time the executor waits after sending SIGTERM
// before escalating to SIGKILL when forcibly terminating a process during
// worker force-shutdown (DrainAndShutdown). Defaults to 10 s when zero or
// negative.
//
// Per-task timeout and per-task cancellation do not use this value; they
// follow the assignment's OpenJD Action.cancelation method (TERMINATE =
// immediate SIGKILL; NOTIFY_THEN_TERMINATE = SIGTERM then the action's notify
// period). KillGracePeriod governs only the worker-shutdown grace window.
KillGracePeriod time.Duration
// AllowRoot, when true, allows the worker to run as the root user on
// Linux/macOS. [CheckRootUser] returns an error if this is false and the
// process UID is 0.
AllowRoot bool
// StagingScratchDir is the base directory for per-attempt staged copies.
// Passed to staging.New; staging is disabled when empty.
StagingScratchDir string
// StagingSyncCommand is the operator-configured sync command template.
// Passed to staging.New; staging is disabled when empty.
StagingSyncCommand string
// StagingDefaults enables the built-in copy + TEMP scratch when staging is
// otherwise unconfigured (no StagingScratchDir/StagingSyncCommand). Passed
// to staging.New; when false an unconfigured stage_locally job fails hard.
StagingDefaults bool
// StagingIsolationCapable records, once per worker, whether this worker can
// run-as-user isolate at all. cmd/sqi-worker sets it from
// executor.IsRunningAsRoot. Passed to staging.New via
// staging.WithIsolationCapable so the shared scratch base and job directory
// are created traversable (0711) on a capable worker whichever job type's
// assignment arrives first, and stay at the narrower 0750 on a worker that
// can never isolate. See staging.WithIsolationCapable's doc for why this is
// a per-worker, not per-assignment, decision.
StagingIsolationCapable bool
}
Config holds the tunable parameters for an Executor.
type DiscardOutput ¶
type DiscardOutput struct{}
DiscardOutput is an OutputHandler that silently drops every line. Use it in tests or when output logging is disabled.
func (DiscardOutput) HandleLine ¶
func (DiscardOutput) HandleLine(_ context.Context, _, _, _, _, _ string)
HandleLine discards the output line.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor starts and manages bare-metal OS processes for assigned tasks.
Create an instance with New and wire it into the pull loop and heartbeat publisher. Call CheckRootUser before creating an Executor to verify the process is not running as root. The worker's cancel subscription (package cancel) delivers the server's cancels to Executor.Cancel.
func New ¶
func New( statusPub *status.Publisher, sessionMgr *session.Manager, m *metrics.Metrics, outputHandler OutputHandler, cfg Config, logger *slog.Logger, ) *Executor
New creates a ready-to-use Executor.
statusPub is the typed status publisher used for all task-status messages; it must not be nil.
outputHandler may be nil; if so LogOutput is used to forward process output to the structured logger.
cfg.KillGracePeriod defaults to 10 s if zero or negative.
func (*Executor) ActiveAttemptIDs ¶ added in v0.4.0
ActiveAttemptIDs returns a sorted snapshot of the held attempts together with those whose status report the stream has not yet acknowledged (status.Publisher.WithPending). Implements [heartbeat.AttemptSource].
func (*Executor) ActiveTaskCount ¶
ActiveTaskCount returns the number of runs in progress, from Dispatch registering a run until its goroutine exits. Implements [heartbeat.StateSource].
func (*Executor) ActiveTaskIDs ¶
ActiveTaskIDs returns a snapshot of the IDs of all currently running tasks, each once, however many attempts of it run. Implements [heartbeat.StateSource].
func (*Executor) Cancel ¶
Cancel requests cancellation of the task identified by taskID.
A run is known from the moment Dispatch registers it, before its session is created, so a cancel reaches session setup as well as the task. Its per-run context is canceled: an environment being entered is stopped by that action's cancelation method, the task never starts, and the attempt is reported canceled; a running task process is terminated per the assignment's OpenJD Action.cancelation method (TERMINATE by default → immediate SIGKILL; NOTIFY_THEN_TERMINATE → SIGTERM then SIGKILL after the notify period). If the run is known but its context does not exist yet, the cancel is noted and takes effect as soon as Dispatch makes it.
A non-empty attemptID limits the cancel to that attempt (protocol.TaskCancelMsg.AttemptID); a run of another attempt is left alone. An empty one stops every run of the task. An empty taskID with a non-empty attemptID stops that attempt whatever its task; both empty stop nothing.
Returns true if a matching run was found in the active-tasks map (regardless of whether cancellation completed), false if none was (already finished, never dispatched, or another attempt).
func (*Executor) Dispatch ¶
Dispatch implements [lease.Dispatcher].
It creates a session synchronously, which enters the assignment's environments, then runs the task process on its own goroutine. The run is registered, with its context derived from e.execCtx, before the session is created, so a Executor.Cancel and the shutdown drain reach an environment being entered. ctx, the worker's root context, is used for logging and to tell whether the worker is stopping.
Once ctx is done (SIGINT/SIGTERM, a service stop, a preemption notice), an assignment is not started: it is reported "failed" with protocol.MessageWorkerShutdown so the server reclaims it. Otherwise the rest of a leased batch would enter its environments during the drain.
A failed session setup is published as a terminal status (see [Executor.publishSetupFailure]), so the server sees the actual reason rather than a lease timeout. Both cases also return an error for the lease loop to log.
func (*Executor) DrainAndShutdown ¶
DrainAndShutdown implements the worker graceful-shutdown sequence.
It first waits up to gracePeriod for all in-flight tasks to complete naturally. If tasks are still running when the grace period expires, it sets the shuttingDown flag (so goroutines publish "failed"/"worker_shutdown" rather than "canceled") and cancels the shared execCtx, triggering SIGTERM → SIGKILL escalation in each runTask goroutine and stopping each environment still being entered by its action's cancelation method. It then blocks until every run has published its terminal status and ended.
A run counts from the moment Dispatch registers it, before its session is created, so a run still entering its environments is waited for and counted.
Returns (completed, killed): the number of tasks that finished naturally during the grace period vs the number that were force-terminated.
A gracePeriod of zero skips the wait phase and force-kills immediately.
func (*Executor) Hold ¶ added in v0.4.0
Hold records attemptID as held by this worker from now until its task ends (or Dispatch fails before running it). The lease loop holds a whole batch before dispatching any of it, so an attempt waiting behind another's session setup is still reported. Idempotent.
func (*Executor) LastAssignmentAt ¶
LastAssignmentAt returns the time of the most recent task assignment dispatched to this executor, or nil if none has been dispatched. Implements [heartbeat.StateSource].
type LogFlusher ¶
type LogFlusher interface {
// FlushLogs drains all remaining buffered lines for the given
// (taskID, attemptID) pair and blocks until the drain is complete.
// It is idempotent: calling it multiple times is safe.
FlushLogs(ctx context.Context, taskID, attemptID string) error
}
LogFlusher is an optional interface that an OutputHandler may implement to flush remaining buffered log output for a specific task attempt before the terminal status message is published.
If the configured OutputHandler also implements LogFlusher, the executor calls FlushLogs immediately after the task process exits and before publishing the terminal "succeeded", "failed", or "canceled" status. The server therefore has the complete log before the task reaches a terminal state.
type LogOutput ¶
LogOutput is an OutputHandler that forwards each output line to the structured logger at debug level. This is the default handler used when nil is passed to New.
type OutputHandler ¶
type OutputHandler interface {
// HandleLine is called for each line read from the task process stdout or
// stderr. stream is "stdout" or "stderr". The line does not include a
// trailing newline.
HandleLine(ctx context.Context, taskID, attemptID, sessionID, stream, line string)
}
OutputHandler processes lines of output emitted by a running task process. Implementations include the log-chunk publisher and the OpenJD progress-line parser. An OutputHandler must be safe for concurrent use from multiple goroutines (multiple tasks may emit output simultaneously).
type ProgressPatternHook ¶ added in v0.4.0
type ProgressPatternHook interface {
// SetLogProgress installs m as attemptID's matcher.
SetLogProgress(attemptID string, m *logprogress.Matcher)
}
ProgressPatternHook is an optional interface that an OutputHandler may implement to turn a step's SQI_LOG_PROGRESS patterns into progress and status updates.
When an assignment carries LogProgress, the executor compiles it after TaskLifecycleHook.RegisterTask and before the process starts, and hands the matcher over with SetLogProgress. The OpenJD interceptor (internal/worker/openjd) implements it.
type TaskLifecycleHook ¶
type TaskLifecycleHook interface {
// RegisterTask associates task metadata and a cancel function with
// attemptID. The cancel function is called when an openjd_fail directive
// is seen; termination then honors the action's OpenJD cancelation method
// (TERMINATE by default → immediate SIGKILL; NOTIFY_THEN_TERMINATE →
// SIGTERM then SIGKILL after the notify period).
RegisterTask(attemptID, taskID, jobID, sessionID string, taskCancel context.CancelFunc)
// Deregister removes the per-task state for attemptID. Safe to call
// multiple times.
Deregister(attemptID string)
// TakeFailReason returns the failure reason stored by an openjd_fail
// directive for attemptID and true if one is present. Returns ("", false)
// if no openjd_fail was seen.
TakeFailReason(attemptID string) (string, bool)
}
TaskLifecycleHook is an optional interface that an OutputHandler may implement to participate in the per-task execution lifecycle.
The executor calls [RegisterTask] before starting each task process and [Deregister] after the task completes, giving the handler a per-task cancel function it can call when an OpenJD fail directive is seen. After the process exits, the executor calls [TakeFailReason] to retrieve any stored failure reason before publishing the terminal status message.
The OpenJD interceptor (internal/worker/openjd) implements this interface so that openjd_fail directives can terminate a specific task without canceling the worker-wide context.