helper

package
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 4, 2026 License: BSD-3-Clause Imports: 24 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.

README

internal/helper

Orchestrates the full lifecycle of a helper service job: resolve params, check/create overlays, submit to scheduler (or run headless), monitor NFS state files, and clean up.

Files

File Purpose
run.go RunHelper() — top-level entry point; also server auto-start, scheduler detection, wrapper generation
state.go NFS state files (ready, done, messages), JSONL history, HelperRun struct
monitor.go PollOnce() — shared non-blocking read of all three NFS state files
params.go ApplyParamFlags(), PromptMissingParams() — resolve #PARAM: headers
config.go Per-helper saved config (~/.local/share/condatainer/helper-config/<name>.conf)

Helper Script Headers

Helper scripts are plain bash files with metadata in comment headers. All headers are parsed before the job is submitted.

Resource headers

Parsed by scheduler.ReadScriptSpecs(). Standard scheduler directives also work (#SBATCH, #PBS, #BSUB).

#NCPUS: 4          # default CPU count
#MEM:   16G        # default memory       — bare number defaults to GB (16 = 16G)
#TIME:  12:00:00   # default walltime     — bare number defaults to hours (12 = 12h)
                   # also accepts: 12h, 2h30m, 4d, 1-12:00:00
#GPU:   a100:1     # optional GPU spec (type:count)
#WHATIS: — short description

Shown in condatainer helper --list and the server dashboard.

#WHATIS: Jupyter Lab
#PARAM: — helper-specific parameters

Defines a configurable variable. The Go runner resolves each param from (in order): CLI flag → saved config → script default.

#PARAM: KEY=default --long-flag,-s "Description shown in --help and prompts"

Three forms for the default value:

Default Behavior
KEY= Required — user must supply a value via CLI flag, saved config, or interactive prompt.
KEY=? Auto — filled from the first entry of the matching #VALUE: list; empty (optional) if no list.
KEY=literal Literal — always uses literal unless overridden by flag or saved config.
  • --long-flag,-s — optional CLI flags. All combinations are valid: both (--flag,-s), long-only (--flag), short-only (-s), or omitted entirely (prompt-only param).
  • "Description" — shown in condatainer helper <name> --help and the settings table.

The resolved value is exported as $KEY inside the job wrapper.

Auto default (KEY=?) example — picks the latest R version from #VALUE: automatically; user can override with -r:

#PARAM: POSIT_R=? --rversion,-r "R version"
#VALUE: POSIT_R=4.5.3,4.5.2,4.5.1,...
#REQUIRED_OVERLAYS: r{POSIT_R} rstudio-server

First-run save pattern — for params computed at runtime (e.g. tunnel names), leave the default empty (KEY=) and compute+save inside the script on first run:

if [ -z "${MACHINE_NAME:-}" ]; then
    MACHINE_NAME="$(whoami)-$(hostname -s)"
    condatainer helper "$CNT_HELPER_NAME" config set MACHINE_NAME "$MACHINE_NAME"
fi

Subsequent runs: Go reads the saved config and injects $MACHINE_NAME before the script runs.

#VALUE: — allowed values / version list

Provides the ordered list of valid values for a #PARAM: key, used for the interactive prompt selector and the web UI dropdown. Updated by auto.py.

#VALUE: CONDA_PYTHON=3.13.0,3.12.7,3.11.9,...

Two formats:

  • Comma-separated KEY=val1,val2,... — version list, sorted descending automatically (newest first). Order in the script doesn't matter.
  • Pipe-separated KEY=opt1 | opt2 | opt3 — ordered option labels, not sorted. Order in the script is preserved.
#IMG_PACKAGES: — conda packages for guided overlay creation

Presence signals that a writable conda-env overlay is required. Value is the default package list for guided creation; {KEY} tokens are substituted from resolved #PARAM: values.

#IMG_PACKAGES: python={CONDA_PYTHON} jupyterlab   # overlay required + package check
#IMG_PACKAGES:                                     # overlay required, no package check
  • With overlay (-e given): if packages are listed, Go runs a pre-submission install check (fatal if packages not found). If the value is empty, the overlay is still required but no check is performed.
  • Without overlay: Go prompts to create one (guided overlay creation flow).
#POST_INSTALL_CMD: — post-install hook

A single shell command run inside the container after guided overlay creation installs the packages. Used to pin package versions or run setup steps.

#POST_INSTALL_CMD: mm-pin r-base
#CHECK_PATH: — pre-submission binary check

One path per line. Checked inside the overlay (fatal) when #IMG_PACKAGES: is set, or in the base image (non-fatal warning) otherwise. Optional quoted message shown when the path is missing.

#CHECK_PATH: /ext3/env/bin/jupyter-lab "Jupyter Lab not found — install with: mm-install jupyterlab"
#CHECK_PATH: /ext3/env/bin/R "Conda R not found — install with: mm-install r-base=<version>"

Multiple lines accumulate independently (one path checked per line).

#REQUIRED_OVERLAYS: — named SquashFS overlays

Space-separated overlay names. {KEY} tokens are substituted from resolved params. Go checks each overlay exists on disk and installs any that are missing before submitting the job. Declaration order is preserved in the Apptainer overlay stack — the last name is the topmost layer (wins on file conflicts such as /var/lib/dpkg/status).

#REQUIRED_OVERLAYS: r{POSIT_R} rstudio-server build-essential
# resolves to: r4.4.3 rstudio-server build-essential
# → build-essential is topmost; its dpkg database is visible to tools like pak
#BIND: — extra bind mounts

One bind spec per line, in src:dest or src:dest:opts form (same as Apptainer --bind). {KEY} tokens are substituted from resolved #PARAM: values. $VAR references are left verbatim and expanded by the shell when the wrapper runs on the compute node — any of the injected env vars can be used directly.

#BIND: $CNT_HELPER_STATE_DIR/vnc:$HOME/.vnc
#BIND: /shared/data:/data:ro
#BIND: /path/to/{KEY_DIR}:/mnt/custom
#SINGLETON: — at most one running instance

When true, the "start new instance" option is suppressed if an instance is already running. --new/--force prints an error instead.

#SINGLETON: true

Environment Variables Injected by the Wrapper

The Go runner injects these into every job before the helper script body runs:

Variable Value
CNT_HELPER_NAME Helper script name (e.g. jupyterlab)
CNT_HELPER_ID Unique run ID: {name}-{job_id} or {name}-{pid}
CNT_HELPER_PORT Free TCP port on the compute node (helper must bind here)
CNT_HELPER_BIND_ADDR 127.0.0.1 normally; 0.0.0.0 when helper_bind_all is set
CNT_HELPER_BIND_ALL Set to 1 when helper_bind_all is enabled; absent otherwise
CNT_HELPER_CWD Working directory
CNT_HELPER_STATE_DIR NFS state directory for this run — write runtime files here
CNT_HELPER_WALLTIME_SECS Walltime in seconds
CNT_HELPER_JOB_ID Scheduler job ID (empty for headless)
CNT_HELPER_SCRIPT_DIR Directory containing the helper script
CNT_JOB_TMPDIR Node-local scratch dir (Unix sockets, etc.); cleaned up on exit
SCRATCH $SCRATCH or $HOME if unset
$KEY One var per resolved #PARAM: key

When writing helper scripts, use ${CNT_HELPER_BIND_ADDR:-127.0.0.1} as the bind address so the script works correctly in both normal and helper_bind_all modes.


NFS State Files

Written by the script on the compute node; read by the CLI monitor and server watcher on the login node.

~/.local/state/condatainer/helper/{id}/
    ready       — JSON written by _server_ready when service is accessible
    done        — JSON written by the wrapper on exit (always fires, even on crash)
    messages    — append-only JSONL written by _server_message
    job.log     — scheduler stdout/stderr (streamed by server dashboard)
ready JSON
{"port": 8888, "node": "cn01", "label": "Jupyter Lab", "timestamp": "...",
 "walltime_secs": 43200, "job_id": "12345",
 "url_path": "?token=abc123", "external_url": ""}

port: 0 + non-empty external_url = no proxy tunnel needed (e.g. vscode-tunnel).

done JSON
{"exit_code": 0, "ts": "2024-01-01T12:00:00Z"}
messages JSONL

One JSON object per line:

{"level": "info", "text": "Open project: rstudioapi::openProject(...)", "ts": "..."}
{"level": "warn", "text": "Low memory warning", "ts": "..."}
{"level": "error", "text": "Port already in use", "ts": "..."}

Hidden Commands Used by Scripts

Scripts call these condatainer subcommands from inside the container:

condatainer _server_ready

Writes the ready file and appends to JSONL history.

condatainer _server_ready \
    --port "$CNT_HELPER_PORT" \
    --label "Jupyter Lab" \
    --url-path "?token=$TOKEN"

# For external-URL services (no port forwarding):
condatainer _server_ready \
    --port 0 \
    --label "VS Code Tunnel: $MACHINE_NAME" \
    --external-url "https://vscode.dev/tunnel/$MACHINE_NAME$CNT_HELPER_CWD"
condatainer _server_message

Appends one line to the messages file. Shown in the terminal and the server dashboard.

condatainer _server_message "Open project: rstudioapi::openProject(\"$CNT_HELPER_CWD\")"
condatainer _server_message --level warn "Low disk space"
condatainer _server_message --level error "Failed to start"
condatainer helper <name> config

Reads and writes the per-helper saved config. Callable from inside the container (NFS-accessible).

condatainer helper "$CNT_HELPER_NAME" config set MACHINE_NAME "$MACHINE_NAME"
condatainer helper "$CNT_HELPER_NAME" config get MACHINE_NAME
condatainer helper "$CNT_HELPER_NAME" config show   # all keys
condatainer helper "$CNT_HELPER_NAME" config path   # config file path

Minimal Example Script

#!/bin/bash
#WHATIS: My Custom Service
#NCPUS: 2
#MEM: 8G
#TIME: 4:00:00
#PARAM: MODE=light --mode,-m "Interface mode: light or full"

my-service \
    --mode "$MODE" \
    --bind 127.0.0.1:"$CNT_HELPER_PORT" &
PID=$!

condatainer _server_ready \
    --port "$CNT_HELPER_PORT" \
    --label "My Custom Service ($MODE)"

wait $PID

Example: conda-env service (with overlay)

#!/bin/bash
#WHATIS: My App (conda)
#IMG_PACKAGES: my-app={VERSION}
#CHECK_PATH: /ext3/env/bin/my-app "my-app not found — install with: mm-install my-app"
#NCPUS: 4
#MEM: 16G
#TIME: 12:00:00
#VALUE: VERSION=2.0,1.9,1.8

my-app --port "$CNT_HELPER_PORT" &
PID=$!

condatainer _server_ready --port "$CNT_HELPER_PORT" --label "My App $VERSION"
wait $PID

Example: external-URL service (no port forwarding)

#!/bin/bash
#WHATIS: My Tunnel Service
#SINGLETON: true
#NCPUS: 2
#MEM: 4G
#TIME: 24:00:00
#PARAM: NAME= --name,-n "Tunnel name (auto-set on first run)"

if [ -z "${NAME:-}" ]; then
    NAME="$(whoami)-$(hostname -s | tr '.' '-')"
    condatainer helper "$CNT_HELPER_NAME" config set NAME "$NAME"
fi

my-tunnel --name "$NAME" 2>&1 | while IFS= read -r line; do
    echo "$line"
    case "$line" in
        *"device code"*) condatainer _server_message "$line" ;;
        *"tunnel ready"*)
            condatainer _server_ready \
                --port 0 \
                --label "My Tunnel: $NAME" \
                --external-url "https://my-service.example.com/tunnel/$NAME" ;;
    esac
done

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HistoryRetentionLimit = 100

HistoryRetentionLimit is the maximum number of completed (non-active) entries kept in history. Active entries are always preserved. 0 disables pruning.

View Source
var ReservedShortFlags = map[string]string{
	"-c": "--cpus", "-m": "--mem", "-t": "--time", "-g": "--gpu",
	"-b": "--base", "-e": "--env", "-o": "--overlay", "-w": "--cwd",
}

ReservedShortFlags is the set of short flags consumed by parsePostScriptHelperFlags. -l/-u are cobra-level only and never reach script arg parsing, so they are excluded.

Functions

func AppendEvent

func AppendEvent(id string, ev StateEvent) error

AppendEvent appends a StateEvent to the events file for the given helper ID. Sets Ts to now if zero. The state directory must already exist (created by newHelperID).

func AppendHistory

func AppendHistory(run *HelperRun) error

AppendHistory appends a HelperRun record to the JSONL history file.

func ApplyParamFlags

func ApplyParamFlags(params []HelperParam, args []string) (map[string]string, []string, error)

ApplyParamFlags scans raw CLI args for flags defined by params. Standard resource flags (-c/-m/-t/-g/-b/-e/-o/-w) are already parsed by cobra and must NOT be in args — this handles only helper-specific #PARAM: flags. Returns (values map, unrecognised args, error).

func CheckHelperPackages

func CheckHelperPackages(meta HelperScriptMeta, envImg string, params map[string]string) error

CheckHelperPackages verifies that every package in meta.ImgPackages is installed in the conda environment inside envImg. {KEY} tokens in ImgPackages are substituted from params before checking. Public wrapper around checkPackages so the server can run pre-submission validation without going through PlanRun.

func CheckRequiredOverlays

func CheckRequiredOverlays(ctx context.Context, requiredTemplate string, params map[string]string) ([]string, error)

CheckRequiredOverlays expands {tokens} in meta.RequiredOverlays using params, ensures each overlay exists on disk (building any missing ones via `condatainer create`), and returns the resolved absolute paths.

Returns (nil, nil) when the template is empty. Public wrapper around the previously unexported checkAndInstallNamedOverlays.

func DeleteHistoryEntry

func DeleteHistoryEntry(id string) error

DeleteHistoryEntry removes the entry with the given ID from the JSONL history file and deletes the associated state directory (events, job.log, etc.). It is a no-op if the ID is not found. Active (in-flight) entries are rejected so callers must stop/cancel the job before deleting its history record.

func EnsureServer

func EnsureServer()

EnsureServer auto-starts the condatainer server if not running. Delegates to "condatainer server start" so the fork logic stays in one place. Prints the dashboard URL on first start.

func EventsFilePath

func EventsFilePath(id string) string

EventsFilePath returns the path to the events JSONL file for a helper run.

func ExecutePlan

func ExecutePlan(ctx context.Context, plan *RunPlan, io IO) (string, error)

ExecutePlan submits the helper job (or runs it headless) using the supplied IO for any subprocess output. Writes a "pending"/"starting" history record and returns the helperID. Subprocess stdout/stderr go through io.Stdout/ io.Stderr; status messages go through logging.FromContext(ctx).

Does not poll — call helper.Monitor (CLI) or rely on the server watcher to observe ready/done events.

func FormatGpuSpec

func FormatGpuSpec(spec *scheduler.ResourceSpec) string

FormatGpuSpec formats a ResourceSpec's GPU field back to a display string. Returns "" when no GPU is set.

func GetHelperConfigKey

func GetHelperConfigKey(name, key string) (string, bool)

GetHelperConfigKey reads a single key from the per-helper config. Keys are case-insensitive. Returns ("", false) if the file or key is absent.

func HelperConfigPath

func HelperConfigPath(name string) string

HelperConfigPath returns the path to the per-helper saved config file. Path: ~/.config/condatainer/helper-config/{name}.conf

func HistoryPath

func HistoryPath() string

HistoryPath returns the JSONL history file path.

func IsHeadlessProcessAlive

func IsHeadlessProcessAlive(id string) bool

IsHeadlessProcessAlive reports whether the process in {stateDir}/pid is still running. Returns false if the pid file is absent, unreadable, or the process no longer exists.

func JobLogFilePath

func JobLogFilePath(id string) string

JobLogFilePath returns the path to the job output log.

func KillHeadlessProcess

func KillHeadlessProcess(id string) error

KillHeadlessProcess sends SIGTERM to the process group of the headless helper. PGID == bash wrapper PID because ExecutePlan sets Setpgid: true. The wrapper's SIGTERM trap calls condatainer _server_done and exits cleanly.

func LoadHelperConfig

func LoadHelperConfig(name string) (map[string]string, error)

LoadHelperConfig reads the saved KEY=value config for a helper. Returns an empty map if the file doesn't exist.

func ParseGPUSpec

func ParseGPUSpec(s string) *scheduler.GpuSpec

ParseGPUSpec parses a GPU spec string into a GpuSpec. Formats:

"a100:2"  → {Type:"a100", Count:2}
"a100"    → {Type:"a100", Count:1}
"2"       → {Type:"gpu",  Count:2}
""        → nil

func ParseValueSpec

func ParseValueSpec(spec string) []string

ParseValueSpec parses a #VALUE: value specification into a string slice. Formats:

"opt1 | opt2 | opt3"     → pipe-separated option list (spaces allowed in labels)
"1.0,2.0,3.0"            → comma-separated version list
"EXPR:range:1-41"        → expression (stored as single-element slice for future use)

func PidFilePath

func PidFilePath(id string) string

PidFilePath returns the path to the ephemeral PID file for a headless helper run.

func PrintHelperUsage

func PrintHelperUsage(scriptName string, params []HelperParam, spec *scheduler.ResourceSpec, versions map[string][]string)

PrintHelperUsage prints the combined --help text for a helper. versions is the map from ParseHelperScriptMeta().ParamValues; pass nil if unavailable.

func ReadHelperPid

func ReadHelperPid(id string) (int, error)

ReadHelperPid reads the PID from {stateDir}/pid. Returns an error if the file does not exist or contains an invalid PID.

func RefreshRemoteMetadata

func RefreshRemoteMetadata(ctx context.Context, force bool, w io.Writer) (map[string]RemoteScriptEntry, error)

RefreshRemoteMetadata refreshes or loads remote helper script metadata. Earlier URLs in ScriptsLinks take precedence.

func ResolveEnv

func ResolveEnv(cwd string) string

ResolveEnv returns the env overlay path that the folder-based convention would auto-pick for the given cwd, or "" if none exists. Thin wrapper around ResolveEnvOverlayInDir for symmetry with CheckEnv.

func ResolveEnvOverlayInDir

func ResolveEnvOverlayInDir(envImg, cwd string) string

ResolveEnvOverlayInDir resolves the writable overlay path for a helper in a specific directory (delegates to utils.FindEnvOverlay).

func ResolveHelperSpec

func ResolveHelperSpec(scriptPath string) *scheduler.ResourceSpec

ResolveHelperSpec returns the effective ResourceSpec for a helper script, merging script headers with global build defaults. Used for display and prompts. Never errors — missing values are left as zero.

func ResolveResources

func ResolveResources(ctx context.Context, scriptPath string, overrides *scheduler.ResourceSpec) *scheduler.ResourceSpec

ResolveResources merges script headers with config defaults and explicit overrides. Pass a non-nil overrides to apply user-supplied resource values on top. Pure (no logger calls).

func SaveHelperConfig

func SaveHelperConfig(name string, cfg map[string]string) error

SaveHelperConfig writes KEY=value pairs to the per-helper config file.

func SetHelperConfigKey

func SetHelperConfigKey(name, key, value string) error

SetHelperConfigKey updates or inserts a single key in the per-helper config, preserving all other existing keys. Keys are normalized to lowercase.

func SingletonBlocked

func SingletonBlocked(meta HelperScriptMeta, running []*HelperRun) bool

SingletonBlocked reports whether the script's #SINGLETON: meta forbids a new launch given the running set.

func StateDir

func StateDir(id string) string

StateDir returns the NFS state directory for a helper run.

When called from inside a helper job (e.g. _server_message, _server_ready, _server_done), the wrapper has already set CNT_HELPER_STATE_DIR to the exact absolute path. Using it directly avoids any XDG/HOME resolution differences inside the Apptainer container — so messages are always written to the same directory the server watcher reads, even when the server is down.

func UpdateHistoryRun

func UpdateHistoryRun(id string, fn func(*HelperRun)) error

UpdateHistoryRun rewrites the JSONL history, applying fn to the record for id. If no record with that ID exists the call is a no-op. Uses an exclusive file lock to prevent concurrent writers from losing updates.

func UpdateHistoryStatus

func UpdateHistoryStatus(id, status string, endedAt time.Time) error

UpdateHistoryStatus rewrites the JSONL history, setting status and endedAt for the given ID. endedAt should reflect when the job actually ended (e.g. the done-event timestamp or StartedAt+Walltime for synthesised expiry), not merely when the server noticed. Prunes old completed entries if HistoryRetentionLimit is set.

func UpdateRemoteScripts

func UpdateRemoteScripts(ctx context.Context, name string, forceMetadata bool, w io.Writer) error

UpdateRemoteScripts syncs helper scripts from the configured remote script URLs. When name is non-empty, only that helper is updated.

func ValidateHelperParamConflicts

func ValidateHelperParamConflicts(params []HelperParam) error

ValidateHelperParamConflicts returns an error if any #PARAM: short flag clashes with a short flag reserved by condatainer's script-level flag parser.

func WriteHelperPid

func WriteHelperPid(id string, pid int) error

WriteHelperPid writes the bash wrapper's PID to {stateDir}/pid.

Types

type DoneState

type DoneState struct {
	ExitCode int       `json:"exit_code"`
	Ts       time.Time `json:"ts"`
}

DoneState is derived from a "done" StateEvent.

func ReadDoneEvent

func ReadDoneEvent(id string) (*DoneState, error)

ReadDoneEvent returns the first "done" event for the given helper, or nil if none yet.

type EnvStatus

type EnvStatus struct {
	Path     string `json:"path"`
	Exists   bool   `json:"exists"`
	InUse    bool   `json:"in_use"`
	Writable bool   `json:"writable"`
	SizeMB   int64  `json:"size_mb,omitempty"`
}

EnvStatus describes the state of an env overlay path for UI display. Returned by CheckEnv. Both CLI and server consume this directly.

func CheckEnv

func CheckEnv(ctx context.Context, path string) (EnvStatus, error)

CheckEnv inspects a single overlay path: existence, lock status, type, size. Returns (zero EnvStatus, nil) when path is empty so callers can probe an unresolved path without a special case. The lock probe uses the same kind (exclusive vs. shared) that an actual mount would request: exclusive for writable .img, shared for read-only .sqf.

type ErrEnvInUse

type ErrEnvInUse struct {
	Path string
}

ErrEnvInUse signals that the chosen writable overlay is locked by another process. The conflicting path is preserved so callers can render a useful message.

func (*ErrEnvInUse) Error

func (e *ErrEnvInUse) Error() string

type ErrMissingPackages

type ErrMissingPackages struct {
	EnvImg         string
	Specs          []string            // raw specs for micromamba install, e.g. ["jupyterlab", "python>=3.12"]
	Messages       []string            // human-readable per-spec descriptions
	VersionChoices map[string][]string // package name → selectable versions (from #VALUE:)
}

ErrMissingPackages is returned by PlanRun when #IMG_PACKAGES: specs are not satisfied in the conda environment inside EnvImg. Specs holds the raw unsatisfied specs suitable for micromamba install; Messages holds matching human-readable descriptions for display. ErrMissingPackages is returned by PlanRun when #IMG_PACKAGES: specs are not satisfied in the conda environment inside EnvImg. Specs holds the raw unsatisfied specs suitable for micromamba install; Messages holds matching human-readable descriptions for display. VersionChoices is non-nil when one or more missing packages had an unresolved version token ({CONDA_PYTHON} etc.) with a known #VALUE: list — the UI should prompt the user to pick a concrete version before installing. Keys are package names (e.g. "python"); values are the selectable versions.

func (*ErrMissingPackages) Error

func (e *ErrMissingPackages) Error() string

type ErrMissingParam

type ErrMissingParam struct {
	Params []HelperParam
}

ErrMissingParam is returned by PlanRun when one or more required #PARAM: values are not supplied. The CLI prompts; the server returns HTTP 400.

func (*ErrMissingParam) Error

func (e *ErrMissingParam) Error() string

type ErrSingletonRunning

type ErrSingletonRunning struct {
	Existing []*HelperRun
}

ErrSingletonRunning indicates the script is marked #SINGLETON: true and at least one instance is already running. CLI prints "already running"; server returns HTTP 409.

func (*ErrSingletonRunning) Error

func (e *ErrSingletonRunning) Error() string

type HelperParam

type HelperParam struct {
	Key       string `json:"key"`
	Default   string `json:"default,omitempty"`
	Optional  bool   `json:"optional,omitempty"` // true when declared as KEY=?
	LongFlag  string `json:"long_flag,omitempty"`
	ShortFlag string `json:"short_flag,omitempty"`
	Desc      string `json:"desc,omitempty"`
}

HelperParam represents a single #PARAM: declaration from a helper script. Format: #PARAM: KEY=default --long-flag,-s "Description" Use KEY=? to mark the param as optional (passes through empty; script handles it).

func MissingParams

func MissingParams(scriptPath string, supplied map[string]string) ([]HelperParam, error)

MissingParams returns the #PARAM: entries from scriptPath that need user input — i.e. not present in `supplied`, not optional (KEY=?), and without a literal default.

Pure: no prompts, no I/O beyond reading the script file.

func ParseHelperParams

func ParseHelperParams(scriptPath string) ([]HelperParam, error)

ParseHelperParams extracts #PARAM: declarations from a helper script. Format per line: #PARAM: KEY=default --long-flag,-s "Description" - KEY=default: variable name and default value (empty after = means required) - --long-flag,-s: optional flag spec (comma-separated; either part may be omitted) - "Description": quoted description string

type HelperRun

type HelperRun struct {
	ID          string            `json:"id"`            // "{name}-YYYYMMDD-HHMMSS"
	Name        string            `json:"name"`          // helper script name
	JobID       string            `json:"job_id"`        // scheduler job ID or ""
	Node        string            `json:"node"`          // compute node hostname
	Port        int               `json:"port"`          // 0 = URL-only service (vscode-tunnel)
	CWD         string            `json:"cwd"`           // working directory
	Walltime    time.Duration     `json:"walltime_secs"` // from #TIME: / -t flag
	CPUs        int               `json:"cpus,omitempty"`
	Mem         string            `json:"mem,omitempty"`         // e.g. "32GB", "1536MB" — via utils.FormatMemoryMB
	GPU         string            `json:"gpu,omitempty"`         // e.g. "a100:1"
	BaseImage   string            `json:"base_image,omitempty"`  // overridden with -b
	EnvOverlay  string            `json:"env_overlay,omitempty"` // writable .img (-e)
	Overlays    []string          `json:"overlays,omitempty"`    // read-only .sqf (-o)
	Params      map[string]string `json:"params,omitempty"`      // resolved #PARAM: values
	URLPath     string            `json:"url_path"`              // appended to proxy URL (e.g. "?token=abc123")
	ExternalURL string            `json:"external_url"`          // shown as-is, no proxy (e.g. vscode-tunnel URL)
	BindAll     bool              `json:"bind_all,omitempty"`    // true = direct TCP proxy (no SSH tunnel)
	StartedAt   time.Time         `json:"started_at"`
	EndedAt     *time.Time        `json:"ended_at,omitempty"`
	Status      string            `json:"status"` // "running"|"done"|"failed"
}

HelperRun records one execution of a helper (stored in JSONL history).

func HistoryEntryForID

func HistoryEntryForID(id string) *HelperRun

HistoryEntryForID returns the most recent JSONL record for the given helper ID.

func LoadHistory

func LoadHistory() ([]*HelperRun, error)

LoadHistory reads the JSONL history file and returns all records (oldest first).

func RecentHistoryByName

func RecentHistoryByName(name string, max int) []*HelperRun

RecentHistoryByName returns the last N distinct-CWD runs for a helper name.

func Running

func Running(name string) ([]*HelperRun, error)

Running returns the active HelperRun records for name (empty = any). Symmetric alias for RunningHelpers.

func RunningHelpers

func RunningHelpers(name string) ([]*HelperRun, error)

RunningHelpers returns all HelperRun records with an active status, verifying each is still alive via the events file (no done event yet).

func (*HelperRun) AccessURL

func (r *HelperRun) AccessURL(serverPort int) string

AccessURL returns the link the user should open. ExternalURL takes priority; otherwise returns the subdomain proxy URL (http://{id}.localhost:{port}/{urlPath}).

func (*HelperRun) EstimatedEnd

func (r *HelperRun) EstimatedEnd() time.Time

EstimatedEnd returns StartedAt + Walltime; zero value if walltime is unknown.

type HelperScriptMeta

type HelperScriptMeta struct {
	// ImgRequired is true when the #IMG_PACKAGES: header is present, meaning the
	// helper requires a writable overlay (.img) even if no packages are listed.
	ImgRequired bool
	// ImgPackages is a template of conda packages for guided overlay creation and
	// pre-submission package verification. {KEY} tokens are substituted from
	// resolved #PARAM: values before use. Empty when #IMG_PACKAGES: has no value.
	ImgPackages string
	// RequiredOverlays is a space-separated template of named condatainer overlays
	// (SquashFS images) to load before the helper runs. {KEY} tokens are substituted
	// from resolved #PARAM: values (e.g. "rstudio-server build-essential r{POSIT_R}").
	// Parsed from #REQUIRED_OVERLAYS: (alias: legacy #OVERLAY_PACKAGES:).
	RequiredOverlays string
	// PostInstallCmd is run inside the container after micromamba installs ImgPackages.
	PostInstallCmd string
	// Singleton is true when at most one running instance of this helper is allowed.
	Singleton bool
	// Binds is a list of extra bind-mount specs from #BIND: headers, in "src:dest" form.
	// {KEY} tokens are substituted from resolved #PARAM: values before use.
	// $VAR references (e.g. $CNT_HELPER_STATE_DIR, $HOME) are passed verbatim and
	// expanded by the shell when the wrapper runs on the compute node.
	Binds []string
	// ParamValues holds the valid-value lists parsed from #VALUE: headers.
	// Keys are param names (e.g. "POSIT_R", "CONDA_PYTHON"); values are the parsed list.
	ParamValues map[string][]string
	// NCPUs is the default CPU count from #NCPUS:. Zero means not set.
	NCPUs int
	// MemMB is the default memory in MB from #MEM:. Zero means not set.
	MemMB int64
	// Walltime is the default walltime from #TIME:. Zero means not set.
	Walltime time.Duration
	// GPU is the default GPU spec from #GPU:. Empty means not set.
	GPU string
}

HelperScriptMeta holds overlay and singleton metadata extracted from a helper script.

func ParseHelperScriptMeta

func ParseHelperScriptMeta(scriptPath string) (HelperScriptMeta, error)

ParseHelperScriptMeta extracts metadata from a helper script. Recognised headers: #NCPUS:, #MEM:, #TIME:, #GPU:, #IMG_PACKAGES:, #REQUIRED_OVERLAYS:, #OVERLAY_PACKAGES: (legacy), #POST_INSTALL_CMD:, #SINGLETON:, #BIND:, #VALUE:.

type IO

type IO struct {
	Stdout io.Writer
	Stderr io.Writer
}

IO carries explicit streams for ExecutePlan. The CLI passes os.Stdout/os.Stderr; the server passes an HTTP response writer so install/post-install subprocess output reaches the browser instead of the daemon log.

type MessageLine

type MessageLine struct {
	Level string    `json:"level"`
	Text  string    `json:"text"`
	Ts    time.Time `json:"ts"`
}

MessageLine is derived from a "msg" StateEvent.

func ReadMessages

func ReadMessages(id string, offset int64) ([]MessageLine, int64, error)

ReadMessages reads "msg" events from the events file starting at byte offset. Returns message lines, the new offset, and any error.

type PollResult

type PollResult struct {
	NewMessages []MessageLine
	NewOffset   int64
	Ready       *ReadyState // non-nil when a "ready" event appears in this window
	Done        *DoneState  // non-nil when a "done" event appears in this window
}

PollResult is the outcome of one non-blocking pass over a helper's events file.

func PollOnce

func PollOnce(id string, offset int64) PollResult

PollOnce reads new events from the helper's events file starting at offset. Returns new messages, a ready state (if the ready event fell within this window), a done state (likewise), and the advanced byte offset for the next call.

type ReadyState

type ReadyState struct {
	Port        int       `json:"port"`
	Node        string    `json:"node"`
	Timestamp   time.Time `json:"ts"`
	WalltimeSec int64     `json:"walltime_secs"`
	JobID       string    `json:"job_id"`
	URLPath     string    `json:"url_path"`
	ExternalURL string    `json:"external_url"`
}

ReadyState is derived from a "ready" StateEvent; used by callers that need the ready information as a typed struct.

func ReadReadyEvent

func ReadReadyEvent(id string) (*ReadyState, error)

ReadReadyEvent returns the first "ready" event for the given helper, or nil if none yet.

type RemoteMetadataCache

type RemoteMetadataCache struct {
	FetchedAt time.Time                    `json:"fetched_at"`
	SourceURL string                       `json:"source_url"`
	Metadata  map[string]remoteHelperEntry `json:"metadata"`
}

RemoteMetadataCache is the on-disk envelope for cached helper script metadata.

type RemoteScriptEntry

type RemoteScriptEntry struct {
	Path      string `json:"path"`
	SourceURL string `json:"-"`
}

RemoteScriptEntry represents a helper script entry from remote metadata.

type RunOptions

type RunOptions struct {
	ScriptPath string
	ScriptName string
	// Resources holds user-specified resource values (nil = use script/config defaults).
	Resources *scheduler.ResourceSpec
	// Container options
	BaseImage string
	EnvImg    string   // writable overlay (.img)
	Overlays  []string // additional read-only overlays
	CWD       string   // working directory inside job
	// Behaviour
	ForceNew bool
	// ExtraBinds is the resolved list of extra bind-mount specs ("src:dest") from
	// #BIND: headers, with {KEY} tokens already substituted from params.
	// $VAR references are left as-is for shell expansion when the wrapper runs.
	ExtraBinds []string
	// #PARAM: values resolved from flags + prompts (raw args passed through)
	FlagArgs []string
	Params   map[string]string
}

RunOptions holds all resolved options for running a helper.

type RunPlan

type RunPlan struct {
	Options       RunOptions
	Meta          HelperScriptMeta
	Spec          *scheduler.ResourceSpec
	Scheduler     scheduler.Scheduler
	UserOverlays  []string
	NamedOverlays []string
	Params        map[string]string
	ContainerCmd  string
}

RunPlan is the resolved, validated state of a helper invocation. PlanRun produces it; ExecutePlan consumes it.

func PlanRun

func PlanRun(ctx context.Context, opts RunOptions) (*RunPlan, error)

PlanRun validates and resolves opts into a RunPlan without any user I/O. All prompts (param menus, resource menus, history menu, guided overlay creation) are the caller's responsibility — fill opts first.

Returns typed errors (*ErrMissingParam, *ErrSingletonRunning, *ErrEnvInUse) so callers can react contextually. Other errors are plain.

type StateEvent

type StateEvent struct {
	Type string    `json:"type"`
	Ts   time.Time `json:"ts"`

	// "msg" fields
	Level string `json:"level,omitempty"` // "info"|"warn"|"error"
	Text  string `json:"text,omitempty"`

	// "ready" fields
	Port        int    `json:"port,omitempty"`
	Node        string `json:"node,omitempty"`
	WalltimeSec int64  `json:"walltime_secs,omitempty"`
	JobID       string `json:"job_id,omitempty"`
	URLPath     string `json:"url_path,omitempty"`
	ExternalURL string `json:"external_url,omitempty"`

	// "done" fields — pointer so exit_code:0 is preserved in JSON (not omitted by omitempty)
	ExitCode *int `json:"exit_code,omitempty"`
}

StateEvent is one entry in the unified events JSONL file per helper run. Type is one of "msg", "ready", or "done".

func ReadEventsFrom

func ReadEventsFrom(id string, offset int64) ([]StateEvent, int64, error)

ReadEventsFrom reads StateEvents from the events file starting at byte offset. Returns the events, the new byte offset, and any error. Returns offset unchanged and nil slice if the file does not exist yet.

Jump to

Keyboard shortcuts

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