Documentation
¶
Overview ¶
Package session manages the lifecycle of OpenJD sessions on the worker.
A Session is the ephemeral execution context in which the task of one assignment runs. It provides:
- An isolated working directory under <session_root>/<session_id>/
- Ordered environment entry (OnEnter actions run in declaration order)
- Ordered environment exit (OnExit actions run in reverse order)
- Concurrency-safe tracking of running tasks via AddTask / RemoveTask
Session identity ¶
Session IDs are worker-generated UUIDs. The ID is included in every protocol.TaskStatusMsg and protocol.LogChunkMsg published from within the session so the server can group task attempts by session for debugging (consistent with the session_id column on task_attempts; see docs/architecture.md, "SQLite schema overview").
Scope ¶
Sessions are worker-side runtime state, not database rows. The server records the session ID only on task_attempts. There is no sessions table, and a session runs exactly one task, so sessions are never reused; see docs/architecture.md ("SQLite schema overview").
Usage ¶
mgr := session.NewManager(sessionRoot, cfg.Worker.KeepFailedSessions, provider, cfg.Isolation, limits, logger)
// sessionRoot is resolved by cmd/sqi-worker's effectiveSessionRoot; see
// its doc for why it is not cfg.Worker.DataDir.
s, err := mgr.Create(ctx, assignMsg)
if err != nil { ... }
defer mgr.Cleanup(ctx, s, true) // true = "failed" path; use false on success
// Execute tasks within s.WorkDir, using s.ID as the SessionID in status messages.
s.AddTask(taskID)
// ... run task process ...
s.RemoveTask(taskID)
// On session end:
if err := s.ExitEnvironments(ctx, logger); err != nil { ... }
mgr.Cleanup(ctx, s, failed)
Index ¶
- type Manager
- type ManagerOption
- type Session
- func (s *Session) ActiveTaskCount() int
- func (s *Session) ActiveTaskIDs() []string
- func (s *Session) AddTask(taskID string)
- func (s *Session) BaseEnv() map[string]string
- func (s *Session) Credential() *isolation.Credential
- func (s *Session) EnvOverrides() map[string]string
- func (s *Session) EnvUnset() map[string]bool
- func (s *Session) ExitEnvironments(ctx context.Context, logger *slog.Logger) error
- func (s *Session) ExprBudget() *fmtres.AssignmentBudget
- func (s *Session) HasPathMappingRules() bool
- func (s *Session) Ledger() *proctree.Ledger
- func (s *Session) PathMappingRulesFile() string
- func (s *Session) RemoveTask(taskID string)
- func (s *Session) ResolveAction(a *protocol.Action) *protocol.Action
- func (s *Session) ScrubRedacted(line string) string
- func (s *Session) StaticEnv() map[string]string
- func (s *Session) WriteEmbeddedFiles(files []protocol.EmbeddedFile) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager creates and cleans up sessions. A single Manager is constructed once at worker startup and shared by the executor for the process lifetime.
func NewManager ¶
func NewManager(sessionRoot string, keepFailedSessions bool, provider isolation.Provider, isolationCfg workerconfig.IsolationConfig, exprLimits fmtres.ExprLimits, logger *slog.Logger, opts ...ManagerOption) *Manager
NewManager returns a Manager that stores session working directories directly under sessionRoot (<sessionRoot>/<sessionID>/). The caller (cmd/sqi-worker's effectiveSessionRoot) resolves sessionRoot to a location separate from the worker's data_dir. keepFailedSessions controls whether working directories for failed sessions are retained for post-mortem inspection. provider resolves run-as-user credentials for isolated assignments (see Manager.Create); isolationCfg.EnvPassthrough is the additional daemon environment allowlist for isolated sessions. exprLimits is this host's operator-configured phase-3 expression budget (cmd/sqi-worker maps the worker config's expr: section to it; the zero value means "the built-in defaults"). opts may include WithSessionRootMode to override the default 0711 creation mode.
func (*Manager) Cleanup ¶
Cleanup exits any remaining environments (if ExitEnvironments has not been called already) and removes the session's working directory.
If failed is true and keepFailedSessions is set, the working directory is retained and a message is logged so the operator can inspect it.
Cleanup logs all errors but does not return them so it can be called safely in deferred cleanup chains. Do not use the session after Cleanup returns.
func (*Manager) Create ¶
Create allocates a new Session for the given assignment: generates a UUID as the session ID, creates the working directory under <session_root>/<session_id>/, and enters each environment in declaration order.
If any OnEnter action fails, already-entered environments are exited in reverse order and the working directory is removed before the error is returned. Create returns either a ready-to-use session and a nil error, or nil and a non-nil error.
On success the returned Session is ready for task execution.
type ManagerOption ¶ added in v0.3.0
type ManagerOption func(*Manager)
ManagerOption customizes a Manager constructed by NewManager, e.g. WithSessionRootMode or WithCommands.
func WithCommands ¶ added in v0.4.0
func WithCommands(r *commands.Resolver) ManagerOption
WithCommands gives every session this Manager creates the operator's worker.commands resolver; see Session.ResolveAction.
func WithLedger ¶ added in v0.4.0
func WithLedger(l *proctree.Ledger) ManagerOption
WithLedger gives every session this Manager creates the worker's process-tree ledger, so both launch sites (the executor's task action and an environment's onEnter/onExit) record the trees they start.
func WithSessionRootMode ¶ added in v0.3.0
func WithSessionRootMode(mode os.FileMode) ManagerOption
WithSessionRootMode overrides the mode sessionRoot is created at (see the Manager.sessionRootMode field doc). It has no effect on a session root that already exists, because os.MkdirAll never changes an existing directory's mode.
type Session ¶
type Session struct {
// ID is the worker-generated unique identifier for this session.
// Callers include this in every [protocol.TaskStatusMsg] (as
// SessionID) and every [protocol.LogChunkMsg] published from within
// the session so the server can group attempts by session.
ID string
// WorkDir is the absolute path to the session's isolated working directory,
// created by [Manager.Create] and removed by [Manager.Cleanup].
// Commands launched within the session run with this as their cwd so that
// relative file references resolve correctly.
WorkDir string
// JobID is the ID of the job that owns this session.
JobID string
// CreatedAt is the wall-clock time the session was created.
CreatedAt time.Time
// contains filtered or unexported fields
}
Session is the ephemeral execution context for the task of one assignment. Obtain one via Manager.Create; end it by calling Session.ExitEnvironments followed by Manager.Cleanup.
Session is safe for concurrent use.
func (*Session) ActiveTaskCount ¶
ActiveTaskCount returns the number of tasks currently executing within this session. Safe for concurrent use.
func (*Session) ActiveTaskIDs ¶
ActiveTaskIDs returns a snapshot of the task IDs currently executing within this session. Safe for concurrent use.
func (*Session) AddTask ¶
AddTask records taskID as executing within this session. Called by the executor when a task process is launched.
func (*Session) BaseEnv ¶ added in v0.3.0
BaseEnv returns the daemon environment already filtered for this session by the worker's isolation.env_passthrough policy (see the baseEnv field). It governs only what is inherited from the daemon; callers layer job-supplied variables on top via envutil.BuildFromBase, which never re-filters them. The returned map must not be mutated by callers.
func (*Session) Credential ¶ added in v0.3.0
func (s *Session) Credential() *isolation.Credential
Credential returns the OS identity every action in this session runs under, or nil when the assignment carried no run_as_user isolation, in which case every action runs as the worker daemon.
func (*Session) EnvOverrides ¶
EnvOverrides returns a snapshot of the environment variables accumulated from openjd_env / openjd_redacted_env directives, for callers (e.g. the executor's task-env construction) that must apply them on top of the task's static environment. Returns nil when no directives have set any variables.
func (*Session) EnvUnset ¶
EnvUnset returns a snapshot of the variables removed via openjd_unset_env, for callers that must strip them from a subsequent action's environment. Returns nil when no variables have been unset.
func (*Session) ExitEnvironments ¶
ExitEnvironments runs each entered environment's OnExit action in reverse entry order, whatever the session's outcome.
All teardown actions are attempted even if an earlier one fails. Errors from individual OnExit actions are logged as warnings and the first one is returned.
Each onExit runs even when ctx is canceled (by a cancel or the shutdown drain): teardown uses a context without ctx's cancellation, so only the action's own timeout bounds it.
ExitEnvironments is idempotent: the first call clears the entered-environments list, so later calls are no-ops. Manager.Cleanup always calls ExitEnvironments, so a caller that calls it beforehand (e.g. on the cancellation path) still calls Cleanup.
func (*Session) ExprBudget ¶ added in v0.3.0
func (s *Session) ExprBudget() *fmtres.AssignmentBudget
ExprBudget returns this assignment's shared fmtres.AssignmentBudget (see the exprBudget field). Callers resolving this session's task action (internal/worker/executor) or an environment's entry-side actions (enterOne, via resolveEnvEntry) pass this object to every fmtres phase-3 call, so the assignment's total live resolved-position and retained-byte spend is charged in one place. resolveEnvAction, the teardown path reached via ExitEnvironments, does not use it; see that method's doc comment.
func (*Session) HasPathMappingRules ¶
HasPathMappingRules reports whether the assignment carried any path-mapping rules. Exposed to format strings as Session.HasPathMappingRules.
func (*Session) Ledger ¶ added in v0.4.0
Ledger returns the worker's process-tree ledger, in which the executor records the task process it starts for this session, or nil.
func (*Session) PathMappingRulesFile ¶
PathMappingRulesFile returns the absolute path to the OpenJD path-mapping file written into the session working directory, or "" when the assignment carried no path-mapping rules. Exposed to format strings as Session.PathMappingRulesFile.
func (*Session) RemoveTask ¶
RemoveTask removes taskID from the active task list. Called by the executor when a task process exits. If taskID is not present the call is a no-op.
func (*Session) ResolveAction ¶ added in v0.4.0
ResolveAction returns the action to start for a: the same one when its command has no worker.commands entry, otherwise a copy that runs the entry's executable with the entry's arguments ahead of the action's own. a itself is never changed: it belongs to the assignment message, which a retry reuses.
Both places that start job-supplied commands call this: the executor for a task's onRun and runAction's callers for an environment's onEnter/onExit. A new launch site must call it too, or it ignores the operator's mapping.
func (*Session) ScrubRedacted ¶
ScrubRedacted replaces any value registered via openjd_redacted_env in line with the redaction placeholder. The executor applies it to every task stdout/stderr line: a step inherits redacted variables in its environment, so a command that echoes one (e.g. `echo $SECRET`) would otherwise publish the cleartext value to the log stream. Safe for concurrent use. Returns line unchanged when no redacted values are registered.
func (*Session) StaticEnv ¶
StaticEnv returns a snapshot of the merged, fully-resolved static environment from all environments' Variables (see the staticEnv field). The executor uses it as the base environment for the task, on top of which the session's dynamic env (openjd_env directives) is applied. Returns nil when no environment sets any variable. The returned map is a clone; callers may mutate it freely.
func (*Session) WriteEmbeddedFiles ¶
func (s *Session) WriteEmbeddedFiles(files []protocol.EmbeddedFile) error
WriteEmbeddedFiles materializes files into the session working directory. It is called by the executor before running the step OnRun action so that step-level embedded files are available to the task command.
Each file's Runnable flag is honored (execute permission set) and its EndOfLine value is applied before writing. Returns an error naming the first file that could not be written, which the caller uses to fail the task through its pre-execution failure path.