Documentation
¶
Overview ¶
Package state owns Rotari's filesystem-backed project state.
It reads and writes model values as durable JSON files, validates path elements, lists run and attempt directories, and manages locks and other persistence details. It should not decide run orchestration, retry policy, dependency scheduling, or executor behavior.
Index ¶
- Constants
- Variables
- func AcquireRunLock(lockPath string, info model.LockInfo) error
- func AcquireStateLock(lockPath string) (func(), error)
- func AcquireStateReadLock(lockPath string) (func(), error)
- func AppendLoadSample(path string, sample model.LoadSample) error
- func AppendRunNote(runDir string, note model.RunNote) error
- func AttemptJobDir(runDir string, job model.JobSpec) (string, error)
- func AttemptSource(runDir, attemptDir string) (model.SourceRevision, bool)
- func CheckRunVersions(runDir string) error
- func ContextPath(runDir string) string
- func DefaultMeta() model.Meta
- func DirectoryMode() os.FileMode
- func Elsewhere(identity ProcessIdentity, observation ProcessObservation) error
- func FileMode() os.FileMode
- func FinalizeRun(meta model.Meta, runID string, exitCode int, now time.Time) (model.Meta, error)
- func IsValidPathElement(value string) bool
- func LatestAttempt(runDir, jobID string) (attemptID, jobDir string, err error)
- func LatestAttemptDirs(runDir string) ([]string, error)
- func LatestAttemptID(runDir, jobID string) (string, error)
- func LatestAttemptJobDir(runDir, jobID string) (string, error)
- func ListAttemptIDs(runDir, jobID string) []string
- func LoadContext(store Store, runDir string) (model.RunContext, error)
- func LoadLocalJobResult(jobDir string, job model.JobSpec) (model.JobResult, bool)
- func LoadLock(path string) (model.LockInfo, error)
- func LoadMeta(path string) (model.Meta, error)
- func LoadQueue(path string) (model.Queue, error)
- func LoadRunClientStatus(store Store, runDir string) (model.RunClientStatus, error)
- func LoadRunNotes(runDir string) ([]model.RunNote, error)
- func LoadRunOrigin(runDir, jobID string) (*model.JobOrigin, error)
- func LoadRunSources(runDir string) (model.RunSources, bool, error)
- func LoadRunStartedBy(store Store, runDir string) (*model.StartedBy, error)
- func LoadRunSummary(path string) (model.RunSummary, error)
- func LoadRunSummaryHead(path string) (model.RunSummary, error)
- func MakeAttemptID(runID, jobID string, number int) string
- func NewRunID(now time.Time) string
- func NewestRunID(paths ProjectPaths) (string, error)
- func OtherPIDNamespace(lock model.LockInfo) bool
- func PIDNamespace() string
- func ProcessAlive(pid int) bool
- func ProcessStart(pid int) string
- func ProjectNameGiven(cliProjectName string) bool
- func ProjectNames(baseDir string) ([]string, error)
- func ProjectNamesOrNone(baseDir string) ([]string, error)
- func ReadAttemptExecutor(attemptDir string) string
- func ReadAttemptTimestamp(jobDir, name string) string
- func ReadEach(count int, read func(index int))
- func ReadJobName(jobDir string) string
- func ReadJobTimestamp(runDir, jobID, name string) string
- func ReadLoadSamples(path string) []model.LoadSample
- func ReadQueueFile(path string) (model.Queue, error)
- func RequireBaseDir(baseDir string) error
- func RequireRunStateFile(runDir, name, runID string) error
- func ResolveAttemptTimestamp(jobDir, name string) string
- func ResolveBaseDir(cliBaseDir string) (string, bool, error)
- func ResolveBaseDirDefault() (string, error)
- func ResolveMasterDir(cliMasterDir string) (string, error)
- func ResolveProjectName(baseDir, cliProjectName string) (string, error)
- func RunIDStart(runID string) (time.Time, bool)
- func RunsNewestFirst(paths ProjectPaths) ([]string, error)
- func SafeJoin(basePath, element string) (string, error)
- func SaveContext(store Store, runDir string, context model.RunContext) error
- func SaveRunSources(runDir string, sources model.RunSources) error
- func ScriptMode() os.FileMode
- func SpecificAttemptJobDir(runDir, jobID, attemptID string) (string, error)
- func TryAcquireStateReadLock(lockPath string) (release func(), ok bool, err error)
- func ValidateRunDirectory(runsDir, runID string, requireCommands bool) (string, error)
- func ValidateStatePath(path string) error
- func ValidatedStateFile(basePath, fileName string) (string, error)
- func WriteJSON(path string, value any) error
- func WriteRunClientStatus(store Store, runDir string, status model.RunClientStatus) error
- type AttemptIDPayload
- type BaseDirMissingError
- type ElsewhereError
- type LockState
- type ProcessIdentity
- type ProcessObservation
- type ProcessVerdict
- type ProgressCursor
- type ProgressJournal
- type ProjectPaths
- type RunSnapshot
- type Store
Constants ¶
const ( StdoutFileName = "stdout" StderrFileName = "stderr" // SchedulerEventsFileName is a scheduler job's log of query outcomes. SchedulerEventsFileName = "scheduler_events.jsonl" )
const ArtifactsFileName = "artifacts.json"
ArtifactsFileName holds the artifact candidates discovered for an attempt when it started. It is best-effort metadata: an attempt without one has no discovery information, not no associated files.
const (
BaseDirEnv = "ROTARI_BASEDIR"
)
const CarriedResultsFileName = "carried.json"
CarriedResultsFileName is the run file in which a run records, before it dispatches any job, the results it carries forward from earlier runs instead of executing. It holds a model.RunSummary with only RunID and Results, and is read through LoadRunSummary until the run writes summary.json; see jobstatus.RecordedResults.
const DefaultProjectName = "default"
DefaultProjectName is the project used when none is given and the base directory does not have exactly one.
const FinalResultFileName = "final_result.json"
FinalResultFileName marks an attempt whose job will not be retried.
const LoadSamplesFileName = "load_samples.jsonl"
LoadSamplesFileName is the run-directory file that holds a run's load samples.
const NoPIDNamespaces = "none"
NoPIDNamespaces is the PID namespace recorded on a platform that has none, such as macOS and the BSDs, where every process on a host shares one PID space. Two records naming it on the same host are in the same PID space, so Locate verifies them as it verifies two equal Linux namespaces. A record written there by an older rotari has an empty namespace and stays unverified.
const ProgressFileName = "progress.jsonl"
const ProjectNameEnv = "ROTARI_PROJECT_NAME"
const ReadConcurrency = 16
ReadConcurrency bounds how many independent reads ReadEach runs at once. On a shared file system each open, stat, and directory listing is a round trip, so reading independent files concurrently overlaps their latency.
const RunClientStatusFileName = "client_status.json"
const RunNotesFileName = "notes.jsonl"
RunNotesFileName is the run file holding a run's notes, one JSON model.RunNote per line, in the order they were added. It is the one run file that changes after a run finishes, and only by appending.
const RunSourcesFileName = "sources.json"
RunSourcesFileName is the run file in which a run records, before it dispatches any job, the version-control revisions its executed jobs run from. A run started before rotari recorded sources has none.
const StaleLockRemovalFileName = "stale_lock_removed.json"
StaleLockRemovalFileName is the record, in a run's directory, of the reader that removed the run's stale lock.
Variables ¶
var ErrBaseDirMissing = errors.New("basedir does not exist")
ErrBaseDirMissing matches a BaseDirMissingError.
var ErrInvalidJSON = errors.New("invalid JSON")
var ErrNewerStateVersion = errors.New("state file is from a newer rotari")
ErrNewerStateVersion reports a state file written by a newer rotari whose format this binary cannot read safely.
Functions ¶
func AcquireRunLock ¶
AcquireRunLock publishes info as the run lock at lockPath. It fails while another run holds an active or remote lock, and never replaces an existing lock file. The caller holds the state lock exclusively and has checked the project, so a stale lock left at lockPath is removed first.
func AcquireStateLock ¶
AcquireStateLock takes the exclusive project state lock at lockPath and returns its release function.
func AcquireStateReadLock ¶
AcquireStateReadLock takes the shared project state lock at lockPath. A missing lock file needs no lock.
func AppendLoadSample ¶
func AppendLoadSample(path string, sample model.LoadSample) error
func AppendRunNote ¶
AppendRunNote adds a note to the run in runDir. Each note is written with one append, so notes added at the same time do not interleave.
func AttemptSource ¶
func AttemptSource(runDir, attemptDir string) (model.SourceRevision, bool)
AttemptSource returns the recorded revision of the repository the attempt in attemptDir ran from: its working directory, from its command.json, matched against its run's sources. It returns false when either is not recorded.
func CheckRunVersions ¶
CheckRunVersions returns ErrNewerStateVersion when the run's commands.json or summary.json was written by a newer rotari, and nil otherwise, leaving a missing or unreadable file to the caller. Readers that treat those files as optional call it first, so a newer file is refused instead of being read as absent.
func ContextPath ¶
func DefaultMeta ¶
func DirectoryMode ¶
func Elsewhere ¶ added in v0.1.30
func Elsewhere(identity ProcessIdentity, observation ProcessObservation) error
Elsewhere returns an *ElsewhereError when observation places the process on another host or in another namespace, and nil otherwise.
func FinalizeRun ¶
FinalizeRun returns meta marked finished with runID's exit code.
func IsValidPathElement ¶
func LatestAttempt ¶
LatestAttempt lists jobID's attempts once and returns the latest attempt's ID, "" when there is none, and the directory holding the job's state: that attempt's directory, or the job directory without one.
func LatestAttemptDirs ¶
LatestAttemptDirs returns, sorted, the latest attempt directory of each job of runDir that has a command snapshot: JOB/attempts/ATTEMPT, or JOB itself in a run written before attempts had directories of their own.
func LatestAttemptID ¶
func LatestAttemptJobDir ¶
func ListAttemptIDs ¶
ListAttemptIDs lists a job's attempt IDs in the run, oldest first.
func LoadContext ¶
func LoadContext(store Store, runDir string) (model.RunContext, error)
func LoadLocalJobResult ¶
func LoadQueue ¶
LoadQueue reads a queue.json or commands.json file, treating a missing file as an empty queue.
func LoadRunClientStatus ¶
func LoadRunClientStatus(store Store, runDir string) (model.RunClientStatus, error)
LoadRunClientStatus reads the initiating client's persisted status for a run.
func LoadRunNotes ¶
LoadRunNotes reads a run's notes in the order they were added; a run without notes has none.
func LoadRunOrigin ¶
LoadRunOrigin returns jobID's origin from the run's commands.json snapshot, nil when the job has none (model.Queue.OriginOf), or the error when the snapshot cannot be read.
func LoadRunSources ¶
func LoadRunSources(runDir string) (model.RunSources, bool, error)
LoadRunSources reads a run's sources, and false when the run recorded none.
func LoadRunStartedBy ¶
LoadRunStartedBy reads how the run in runDir was started, nil when its context is missing or predates the record.
func LoadRunSummary ¶
func LoadRunSummary(path string) (model.RunSummary, error)
func LoadRunSummaryHead ¶
func LoadRunSummaryHead(path string) (model.RunSummary, error)
LoadRunSummaryHead is LoadRunSummary without the per-job results, which it leaves nil: a listing of many runs needs only their times, names, status, and exit code, and a run of many jobs has a large summary.
func MakeAttemptID ¶
func NewestRunID ¶ added in v0.1.30
func NewestRunID(paths ProjectPaths) (string, error)
NewestRunID is the first run of RunsNewestFirst, empty when the project has none.
func OtherPIDNamespace ¶
OtherPIDNamespace reports whether lock records a PID namespace other than this process's, where its PID names another process or none.
func PIDNamespace ¶
func PIDNamespace() string
PIDNamespace names this process's PID namespace, within which alone a PID identifies a process: Linux's namespace link, NoPIDNamespaces on a platform without namespaces, and empty where neither can be told.
func ProcessAlive ¶
func ProcessStart ¶
ProcessStart is pid's start time, which tells a process from a later one reusing its PID. It is compared only with values recorded on the same host, so its form is the platform's own. An empty value means the platform cannot verify PID reuse, or that pid is not running.
func ProjectNameGiven ¶
ProjectNameGiven reports whether a project was chosen explicitly, by cliProjectName or ROTARI_PROJECT_NAME, rather than inferred from the base directory.
func ProjectNames ¶ added in v0.1.30
ProjectNames lists the projects in baseDir, sorted: the directories under its projects directory whose names are valid path elements. A basedir without a projects directory has none and gives nil; one whose projects directory is empty, for example after its last project was deleted, gives an empty list. A basedir that does not exist is a BaseDirMissingError; each caller decides what that means for it, which is why this is the one place that reads the projects directory.
func ProjectNamesOrNone ¶ added in v0.1.30
ProjectNamesOrNone is ProjectNames for a basedir that may be the implicit default before its first run, or a basedir already checked by RequireBaseDir: a missing basedir has no projects.
func ReadAttemptExecutor ¶
ReadAttemptExecutor returns the executor an attempt ran on, as its command.json records it once submitted, or "" for an attempt that has none. It reflects a run-level --executor and the queue's default, which the job's definition alone does not.
func ReadAttemptTimestamp ¶
func ReadEach ¶
ReadEach calls read for every index in [0, count) from up to ReadConcurrency goroutines, and returns once all calls have returned. read must be safe to call concurrently; callers keep results in a slice indexed like their input, so output order does not depend on scheduling.
func ReadJobName ¶
ReadJobName returns the job name recorded in jobDir, or "" when there is none.
func ReadJobTimestamp ¶
func ReadLoadSamples ¶
func ReadLoadSamples(path string) []model.LoadSample
func ReadQueueFile ¶
ReadQueueFile reads a queue.json or commands.json file and returns an os.ErrNotExist error when it is missing.
func RequireBaseDir ¶ added in v0.1.30
RequireBaseDir returns a BaseDirMissingError if baseDir does not exist. A command that only reads state calls it for a basedir that was given to it, which is most likely mistyped if missing. The implicit default may not exist yet: that is a basedir in which nothing has run.
func RequireRunStateFile ¶
func ResolveAttemptTimestamp ¶
ResolveAttemptTimestamp reads an attempt's submitted_at or finished_at, falling back to the times job.json and status.json record.
func ResolveBaseDirDefault ¶
ResolveBaseDirDefault resolves the local/XDG/home state directory without consulting ROTARI_BASEDIR. Aggregate views use it when only CLI scope selectors may narrow their target.
func ResolveMasterDir ¶
ResolveMasterDir resolves the master directory that holds the run and server registries: cliMasterDir, then ROTARI_MASTERDIR, then $XDG_STATE_HOME/rotari/master, then ~/.local/state/rotari/master.
func ResolveProjectName ¶
func RunIDStart ¶ added in v0.1.30
RunIDStart is the start second a run ID records. ok is false for an ID in another form.
func RunsNewestFirst ¶ added in v0.1.30
func RunsNewestFirst(paths ProjectPaths) ([]string, error)
RunsNewestFirst lists the runs of a project, newest first. This is the one run order:
- The newest run is meta.json's last run when it names a run directory.
- The others are ordered by the start second in the run ID. Runs that share a second are ordered by the coordinator's recorded_at in their context.json, read only for those runs; a run without it sorts by its ID among them, after the runs that have it.
- Runs whose ID records no start are the oldest, ordered by ID.
A project without a runs directory has no runs.
func SaveContext ¶
func SaveContext(store Store, runDir string, context model.RunContext) error
func SaveRunSources ¶
func SaveRunSources(runDir string, sources model.RunSources) error
SaveRunSources writes a run's sources.
func ScriptMode ¶
func SpecificAttemptJobDir ¶
func TryAcquireStateReadLock ¶
TryAcquireStateReadLock takes the shared project state lock at lockPath without waiting, creating the lock file as AcquireStateLock does. ok is false while another holder, possibly in this process, has it exclusively.
func ValidateRunDirectory ¶
func ValidateStatePath ¶
func ValidatedStateFile ¶
func WriteRunClientStatus ¶
func WriteRunClientStatus(store Store, runDir string, status model.RunClientStatus) error
WriteRunClientStatus persists the initiating client's last known status.
Types ¶
type AttemptIDPayload ¶
func DecodeAttemptID ¶
func DecodeAttemptID(attemptID string) (AttemptIDPayload, error)
func DecodeAttemptIDForRun ¶
func DecodeAttemptIDForRun(attemptID, runID string) (AttemptIDPayload, error)
DecodeAttemptIDForRun decodes an attempt belonging to runID, including imported runs whose IDs do not have the usual timestamp format.
type BaseDirMissingError ¶ added in v0.1.30
type BaseDirMissingError struct {
Path string
}
BaseDirMissingError reports that a basedir's directory does not exist, as opposed to a basedir that exists and has no projects yet.
func (*BaseDirMissingError) Error ¶ added in v0.1.30
func (err *BaseDirMissingError) Error() string
func (*BaseDirMissingError) Is ¶ added in v0.1.30
func (err *BaseDirMissingError) Is(target error) bool
type ElsewhereError ¶ added in v0.1.30
type ElsewhereError struct {
Identity ProcessIdentity
Observation ProcessObservation
}
ElsewhereError is a refusal to control a process that runs on another host or in another PID namespace, where its PID names another process or none (COORD-1).
func (*ElsewhereError) Error ¶ added in v0.1.30
func (err *ElsewhereError) Error() string
type LockState ¶
type LockState string
func InspectLock ¶
InspectLock classifies the run lock at path without changing it. A lock whose coordinator PID cannot be checked here, because it was written on another host or in another PID namespace such as a sandbox or container, is remote. A stale lock is removed by internal/project, which checks the project first.
type ProcessIdentity ¶ added in v0.1.30
ProcessIdentity is a recorded process: the host and PID namespace it ran in, its PID there, and its start time (ProcessStart). A PID names a process only within its host and namespace, and the start time tells it from a later process that reuses the PID. Records from an earlier rotari may lack the namespace, the start, or even the host.
func (ProcessIdentity) Locate ¶ added in v0.1.30
func (identity ProcessIdentity) Locate(host, namespace string) (ProcessVerdict, bool)
Locate places identity relative to host and namespace without probing: ProcessOtherHost, ProcessOtherNamespace, or ProcessHere, and whether the record names both so that ProcessHere is verified.
type ProcessObservation ¶ added in v0.1.30
type ProcessObservation struct {
Verdict ProcessVerdict
// LocationVerified is true when the record names this host and PID
// namespace and this platform exposes its own namespace. A record without
// them, from an earlier rotari, is probed as if it were here, as before;
// callers that require a verified location check this.
LocationVerified bool
// ProbeErr is the signal-zero probe's error when it was neither nil nor
// ESRCH, such as EPERM, for a process that exists but is not ours.
ProbeErr error
// Host and PIDNamespace are this process's, for messages.
Host string
PIDNamespace string
}
ProcessObservation is the one answer to whether a recorded process can be observed from here, used by local job control and liveness, client attachments, the coordinator check, and the execution probe.
func LocateProcess ¶ added in v0.1.30
func LocateProcess(identity ProcessIdentity) ProcessObservation
LocateProcess is Locate from this process's host and PID namespace.
func ObserveProcess ¶ added in v0.1.30
func ObserveProcess(identity ProcessIdentity) ProcessObservation
ObserveProcess says whether the recorded process is the one running here under its PID.
func ObserveProcessGroup ¶ added in v0.1.30
func ObserveProcessGroup(identity ProcessIdentity) ProcessObservation
ObserveProcessGroup says the same of the process group the recorded process leads, which outlives its leader while its other members run.
func ProbeOutcome ¶ added in v0.1.30
func ProbeOutcome(recordedStart, currentStart string, probeErr error) ProcessObservation
ProbeOutcome is the verdict and probe error of a process probed here; see ClassifyProcess.
type ProcessVerdict ¶ added in v0.1.30
type ProcessVerdict string
ProcessVerdict is what can be said, from here, about a recorded process.
const ( // ProcessHere is a location verdict: the record does not place the // process on another host or in another namespace. ProcessHere ProcessVerdict = "here" // ProcessSame is the recorded process, still running. ProcessSame ProcessVerdict = "same" // ProcessGone is no process with the PID. ProcessGone ProcessVerdict = "gone" // ProcessReused is another process that now has the PID. ProcessReused ProcessVerdict = "reused" // ProcessOtherHost and ProcessOtherNamespace are processes whose PID // means nothing here; they must not be probed or signalled. ProcessOtherHost ProcessVerdict = "other host" ProcessOtherNamespace ProcessVerdict = "other namespace" // ProcessUnverifiable is a process with the PID whose identity cannot be // checked, or a PID that cannot be probed. ProcessUnverifiable ProcessVerdict = "unverifiable" )
func ClassifyProcess ¶ added in v0.1.30
func ClassifyProcess(recordedStart, currentStart string, probeErr error) ProcessVerdict
ClassifyProcess decides a probed process from the signal-zero probe's error and the recorded and current start times of its PID. EPERM means the process exists; a start time unknown on either side cannot be checked.
type ProgressCursor ¶
type ProgressCursor struct {
// contains filtered or unexported fields
}
ProgressCursor is an incremental reader for one run's append-only journal. Its zero value starts at the beginning. Use a separate cursor per run and consumer; it is not safe for concurrent reads.
func (*ProgressCursor) Read ¶
func (cursor *ProgressCursor) Read(runDir string) ([]model.ProgressEvent, error)
Read returns newly completed lines. An absent journal (including old runs) is an empty successful read. A trailing line without a newline is left at the cursor for the next read, even if it already contains valid JSON. A malformed complete line is consumed and returns ErrInvalidJSON along with any preceding events; a later Read can continue after it.
func (*ProgressCursor) SkipExisting ¶
func (cursor *ProgressCursor) SkipExisting(runDir string) (model.ProgressEvent, bool, error)
SkipExisting advances the cursor past complete events already in the journal and returns their latest progress-count snapshot, if one exists. If the final line is still being appended, the cursor stays at its start so Read can consume it once the line is complete.
type ProgressJournal ¶
type ProgressJournal struct {
// contains filtered or unexported fields
}
ProgressJournal appends progress events to one existing run directory. Share one instance between the run's writers; Append serializes whole lines. It holds no open file and does not create directories or rewrite history.
func NewProgressJournal ¶
func NewProgressJournal(runDir string) (*ProgressJournal, error)
func (*ProgressJournal) Append ¶
func (journal *ProgressJournal) Append(event model.ProgressEvent) error
Append writes one newline-terminated JSON event using the state file mode. Non-progress events are rejected. Errors are returned to the caller, which decides whether journaling is best-effort; Append does not fsync each event.
type ProjectPaths ¶
type ProjectPaths struct {
BaseDir string
BaseDirExplicit bool
ProjectName string
ProjectDir string
QueueFile string
MetaFile string
StateLockFile string
LockFile string
RunsDir string
}
func ResolveProjectPaths ¶
func ResolveProjectPaths(cliBaseDir, projectName string) (ProjectPaths, error)
type RunSnapshot ¶
type RunSnapshot struct {
Commands model.Queue
CommandsErr error
Summary model.RunSummary
SummaryErr error
Carried model.RunSummary
CarriedErr error
}
RunSnapshot is what a run directory records about the whole run: commands.json, summary.json, and carried.json, each read once. An error field is os.ErrNotExist for a missing file.
func LoadRunSnapshot ¶
func LoadRunSnapshot(runDir string) (RunSnapshot, error)
LoadRunSnapshot reads runDir's run files. It fails, with ErrNewerStateVersion, only when one was written by a newer rotari; any other error is kept in the snapshot for the caller.
func (RunSnapshot) Queue ¶
func (snapshot RunSnapshot) Queue() (model.Queue, error)
Queue is the run's command snapshot as LoadQueue reads it: empty when the file is missing.
func (RunSnapshot) RecordedSummary ¶
func (snapshot RunSnapshot) RecordedSummary() *model.RunSummary
RecordedSummary is the run's summary, or nil when it has no readable one.