build

package
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: BSD-3-Clause Imports: 29 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

build

Build system for creating overlay images from Conda packages, shell scripts, or Apptainer definition files with dependency resolution and scheduler integration.

Build Types

Type Source Description
Conda Package spec, YAML, or channel::pkg/version Micromamba environment
Shell Build script (#DEP, #SBATCH, #ENV, #INTERACTIVE) Custom installation
Def Apptainer .def file Apptainer build
Ref Shell script (large datasets) Reference data (genomes, indices)

Architecture

object.go       BuildObject interface, base implementation
conda.go        Conda package builds via micromamba
script.go       Shell script builds (apps and ref data)
def.go          Apptainer definition file builds
base_image.go   Base image provisioning (download/build)
graph.go        Dependency graph, topological sort, parallel execution
fetch.go        Remote build script downloading
env.go          Environment variable extraction from overlays

Key Types

BuildObject - Interface for all build types:

  • NameVersion(), BuildSource(), Dependencies(), Type()
  • IsInstalled(), RequiresScheduler(), Update()
  • ScriptSpecs() - Parsed scheduler directives
  • LockPath() - Path to the build lock file
  • Build(ctx, buildDeps bool), GetMissingDependencies()
  • CreateTmpOverlay(ctx, force bool), Cleanup(failed bool)

BuildLockInfo - JSON metadata stored in .lock files:

  • Type - "local", "slurm", "pbs", "lsf", or "htcondor"
  • JobID - Scheduler job ID (empty until submit returns; set by submitJob)
  • Node - Short hostname (domain suffix stripped) where lock was created
  • PID - OS process ID for local builds; 0 for scheduler builds
  • CreatedAt - RFC3339 timestamp

BuildType - IsConda, IsDef, IsShell, IsRef

BuildGraph - Dependency graph with topological sort, cycle detection, and parallel execution (local worker pool + scheduler job submission).

ScriptSpecs - Build resource requirements (alias to scheduler.ScriptSpecs)

Usage

// Auto-resolve from name/version
obj, err := build.NewBuildObject(ctx, "cellranger/9.0.1", false, imagesDir, tmpDir, false)

// Channel-annotated package: skips build script lookup, version required
obj, err := build.NewBuildObject(ctx, "bioconda::star/2.7.11b", false, imagesDir, tmpDir, false)
// → sqf: star--2.7.11b.sqf, micromamba spec: bioconda::star=2.7.11b

// Conda with custom source (YAML or package list)
obj, err := build.NewCondaObjectWithSource("myenv/1.0", "/path/env.yml", imagesDir, tmpDir, false)

// From external file (script or def)
obj, err := build.FromExternalSource(ctx, "myapp/1.0", "/path/script.sh", false, imagesDir, tmpDir)

// Single build
obj.Build(ctx, true)

// Build with dependency graph
graph, err := build.NewBuildGraph(ctx, objects, imagesDir, tmpDir, true, false)
graph.Run(ctx)

// Base image
build.EnsureBaseImage(ctx, false) // download prebuilt or build from def

// Script lookup
info, found := build.FindBuildScript("cellranger/9.0.1")

Build Scripts

Shell scripts support metadata headers:

  • #DEP:name/version - Exact dependency
  • #DEP:name/version>=min - Dependency with version constraint (range [min, version])
  • #SBATCH / #PBS / #BSUB - Scheduler directives (HTCondor uses native .sub files)
  • #ENV:VAR=$app_root - Environment variables to export
  • #INTERACTIVE:prompt - User input prompts (collected locally before scheduler submission; embedded as a heredoc in the job script)

Available variables: $NCPUS, $target_dir, $tmp_dir, $app_name, $version Required function: install()

Dependency Resolution

#DEP:samtools/1.22.1>=1.10 — accepts any installed version in [1.10, 1.22.1]:

  • If a satisfying version is installed → skip build, mount the latest satisfying version
  • If none installed → build the preferred version (1.22.1)
  • Versions above preferred (2.0) are rejected (implicit upper bound)
  • Operators: >= (inclusive lower bound) and > (exclusive lower bound)
// Check missing dependencies
missing, err := obj.GetMissingDependencies()

// Find and download remote build script
info, found := build.FindBuildScript("cellranger/9.0.1")
if found && info.IsRemote {
    localPath, err := build.DownloadRemoteScript(info, tmpDir)
}

Build Lock

Each build target has a lock file at <targetOverlayPath>.lock containing BuildLockInfo JSON.

Lifecycle:

  • Scheduler submit (submitJob in graph.go): lock created with type=scheduler, job_id="", no node before calling the scheduler. Updated with the real job ID after Submit() returns. Removed if submit fails.
  • Local / scheduler job start (Build()): createBuildLock() writes type=local with current node and PID. If a scheduler lock already exists with a matching job ID ($SLURM_JOB_ID / $PBS_JOBID / $LSB_JOBID), it adopts and updates that lock with the runtime node and PID.
  • Build end: defer removeBuildLock() removes the lock on success or failure.

Stale detection (in NewBuildObject):

Lock state Action
Empty or corrupt file (old format) Treat as stale — remove and continue
type=slurm/pbs/lsf/htcondor, job_id="" Stale (failed before submit returned) — remove
type=slurm/pbs/lsf/htcondor, job_id set Call scheduler.IsJobAlive(job_id) — remove if not alive
type=local, same node, PID dead Stale — remove and continue
type=local, same node, PID alive Active — error with details
type=local, different node Cannot verify remotely — error, ask user to check
Scheduler unavailable for job check Conservative — error, ask user to check

Build Workflow

Conda:

  1. Check if overlay exists (skip if not updating)
  2. If updating existing overlay: probe exclusive lock — fail immediately if in use
  3. Create build lock (local); create temporary ext3 overlay
  4. micromamba create inside container
  5. Set permissions, pack to SquashFS
  6. Atomic rename .new → target; remove lock

Shell:

  1. Check if overlay exists (skip if not updating)
  2. If updating existing overlay: probe exclusive lock — fail immediately if in use
  3. Create build lock (local, or adopt scheduler lock); create temporary overlay
  4. Build missing dependencies (if enabled)
  5. Run script inside container with overlays
  6. For ref: verify files, create SquashFS from $cnt_dir
  7. For apps: create SquashFS from /cnt
  8. Atomic rename .new → target; remove lock

The build script (with its #ENV: directives) is embedded inside the overlay at /cnt/<name>/<version>/.cnt-build-script, so the overlay is self-contained; env is resolved from it at load time rather than written to a sidecar .env at build time.

Def:

  1. Check if overlay exists (skip if not updating)
  2. If updating existing overlay: probe exclusive lock — fail immediately if in use
  3. Create build lock; try prebuilt download (if remote source)
  4. Build SIF with Apptainer; extract SquashFS partition
  5. Atomic rename .new → target; remove lock

Base image (.sif):

  1. Check if already installed (skip if not updating)
  2. If updating existing image: probe exclusive lock — fail immediately if in use
  3. Create build lock; try prebuilt .sif download (if remote source)
  4. Build SIF with Apptainer
  5. Atomic rename .new → target; remove lock

BuildGraph Execution

  1. Expand dependencies - Resolve all transitive deps
  2. Detect cycles - Fail on circular dependencies
  3. Topological sort - Order by dependencies
  4. Separate local/scheduler - Based on resource requirements
  5. Parallel execution:
    • Local builds: Run concurrently with worker pool
    • Scheduler builds: Submit with dependency chains

Environment Variables

Overlays can export environment variables via #ENV: directives:

#ENV:CELLRANGER_ROOT=$app_root
#ENV:PATH=$app_root/bin:$PATH

These live in the build script embedded inside the overlay. $app_root is resolved to the overlay's mount root at load time (see internal/container env handling).

Tmp Directory Strategy

Each build type uses a different base directory for build artifacts ($TMPDIR, build dir, tmp overlay):

Build path tmpDir source Rationale
Conda (name/version) utils.GetTmpDir() Fast local node storage (scheduler TMPDIR → TMPDIR → /tmp/cnt-$USER)
App script (name/version) utils.GetTmpDir() Fast local node storage
Ref script (a/b/c, 2+ slashes) config.GetWritableTmpDir() Stable condatainer data path (large datasets)
Def (internal) config.GetWritableTmpDir() Stable path; set in createConcreteType after type is resolved
External sh filepath.Dir(targetPrefix) Next to output target (user controls location)
External def filepath.Dir(targetPrefix) Next to output target (user controls location)
Base image config.GetWritableTmpDir() Stable condatainer data path

utils.GetTmpDir() priority: scheduler-assigned scratch (SLURM_TMPDIR, PBS_TMPDIR, LSF_TMPDIR, _CONDOR_SCRATCH_DIR) → TMPDIR/TEMP/TMP → /tmp/cnt-$USER.

Resource Allocation for Builds

CPU and memory derived from scriptSpecs:

State HasDirectives Spec CPU source Memory source
No directives false non-nil Build.Defaults.CpusPerTask Build.Defaults.MemPerNodeMB
Has directives true non-nil CpusPerTask × TasksPerNode MemPerNodeMB
Passthrough true nil build fails with error —

Build defaults are configured via build.* keys in config.yaml. See Config README.

Error Handling

  • ErrTmpOverlayExists - Temporary overlay already exists (stale from previous run)
  • ErrBuildCancelled - User interrupted build (Ctrl+C)
  • "build lock found for <name> ..." - Lock exists and is active (job pending/running or local build in progress)
  • "build already queued or running for <name>" - Duplicate scheduler submission blocked by submit-time lock
  • "cannot update <name>: ..." - Target overlay is locked (currently used by a running exec/run)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBuildCancelled = errors.New("build cancelled by user")
View Source
var ErrTmpOverlayExists = errors.New("temporary overlay already exists")
View Source
var ForceRefresh bool

ForceRefresh skips the on-disk metadata cache and fetches fresh data from remote. Set by CLI commands (e.g. `update` command).

View Source
var PreferRemote bool

PreferRemote controls the precedence of build script resolution. When true, remote scripts take precedence over local scripts. When false (default), local scripts take precedence over remote scripts. Set by CLI commands (--remote flag) or config (prefer_remote: true).

View Source
var SkipPrebuilt bool

SkipPrebuilt disables downloading prebuilt artifacts (.sif/.sqf) for remote def builds, forcing a local apptainer build from the .def file. Set by CLI commands (--no-prebuilt flag).

Functions

func DownloadRemoteScript

func DownloadRemoteScript(info ScriptInfo, tmpDir string) (string, error)

DownloadRemoteScript downloads a remote build script to the local tmp directory. Uses info.SourceURL (set during metadata fetch) as the base for the download URL.

func EnsureBaseImage added in v1.2.0

func EnsureBaseImage(ctx context.Context, update bool) error

EnsureBaseImage is the fast-path entry point for ensuring the base image exists. If the base image is already installed and update=false, returns immediately without constructing any build object or fetching remote metadata.

func ExpandDefaultDistroName added in v1.5.0

func ExpandDefaultDistroName(nameVersion string) (string, bool)

ExpandDefaultDistroName normalizes a build-script overlay name and expands a bare name to <default_distro>/<name> only when that build script exists.

func ExpandTemplate added in v1.5.1

func ExpandTemplate(info ScriptInfo) map[string]ScriptInfo

ExpandTemplate returns a single PL template's variants, keyed by interpolated name. Returns nil if info is not a template, or if its #PL: and #TARGET: disagree — those are reported and skipped rather than expanded into wrong entries.

func GetEnvDictFromBuildScript

func GetEnvDictFromBuildScript(scriptPath string) (map[string]EnvEntry, error)

GetEnvDictFromBuildScript parses #ENV:KEY=VALUE and #ENVNOTE:KEY description lines from build script. Returns a map of environment variables with their values and notes.

Example lines in script:

#ENV:STAR_INDEX_DIR=$app_root/star
#ENVNOTE:STAR_INDEX_DIR STAR index dir

func GetLocalBuildScripts

func GetLocalBuildScripts() (map[string]ScriptInfo, error)

GetLocalBuildScripts scans all build-scripts directories and returns a map of name -> ScriptInfo. Searches user → scratch → legacy → system directories. First match wins (user scripts shadow system ones).

PL templates are returned unexpanded — the map holds the template entry, not its variants. Use ExpandTemplate for one template's variants; FindBuildScript resolves concrete names without expanding.

func GetOverlayArgsFromDependencies

func GetOverlayArgsFromDependencies(dependencies []string) ([]string, error)

GetOverlayArgsFromDependencies generates overlay mount arguments for Apptainer from dependencies. Each dependency is mounted as read-only.

func GetRemoteBuildScripts

func GetRemoteBuildScripts() (map[string]ScriptInfo, error)

GetRemoteBuildScripts fetches and merges build script metadata from all configured remote URLs. Earlier URLs in ScriptsLinks take precedence (first match wins).

As with GetLocalBuildScripts, PL templates are returned unexpanded.

func PruneOrphanedCaches added in v1.3.0

func PruneOrphanedCaches()

PruneOrphanedCaches removes cache files (build and helper) for URLs no longer in ScriptsLinks. Errors are non-fatal.

func SaveEnvFile

func SaveEnvFile(overlayPath string, envDict map[string]EnvEntry, relativePath string, whatis string) error

SaveEnvFile saves environment variables to a .env file next to the overlay. The $app_root placeholder is replaced with the actual overlay path. whatis is written as a #WHATIS: comment at the top if non-empty.

func SetBuildDefaults added in v1.2.0

func SetBuildDefaults(d scheduler.ResourceSpec)

SetBuildDefaults sets the resource defaults used for build job submissions.

Types

type BaseImageBuildObject added in v1.2.0

type BaseImageBuildObject struct {
	*BuildObject
}

BaseImageBuildObject wraps BuildObject but overrides IsInstalled() and Build() to search all configured image paths and skip SquashFS extraction.

func NewBaseImageBuildObject added in v1.2.0

func NewBaseImageBuildObject(update bool) (*BaseImageBuildObject, error)

NewBaseImageBuildObject creates a BuildObject for the base image using the same path resolution as regular build objects. base_image.def is searched in the build-scripts directories (same structure as any other build script) and downloaded from GitHub if not found locally. When the def comes from GitHub, BaseImageBuildObject also tries to download a prebuilt .sif before falling back to a local build.

When update=false the build is skipped if the image already exists anywhere in the configured search paths. When update=true the image is always rebuilt (written to .new then atomically renamed).

func (*BaseImageBuildObject) Build added in v1.2.0

func (b *BaseImageBuildObject) Build(ctx context.Context, buildDeps bool) error

Build overrides DefBuildObject.Build for base images. Unlike regular def builds, the SIF produced by apptainer is kept directly as the final image — no SquashFS extraction step is performed.

func (*BaseImageBuildObject) IsInstalled added in v1.2.0

func (b *BaseImageBuildObject) IsInstalled() bool

IsInstalled checks all image search paths for the base image.

type BuildGraph

type BuildGraph struct {
	// contains filtered or unexported fields
}

BuildGraph manages dependency resolution and build ordering It expands BuildObject items to include all transitive dependencies, detects cycles, produces a topologically-sorted order (dependencies before dependents), and separates items into two ordered lists:

  • localBuilds: BuildObjects without scheduler requirements (build locally)
  • schedulerBuilds: BuildObjects that require scheduler submission

func NewBuildGraph

func NewBuildGraph(ctx context.Context, buildObjects []*BuildObject, imagesDir, tmpDir string, submitJobs bool, update bool) (*BuildGraph, error)

NewBuildGraph creates a BuildGraph from a list of BuildObjects All overlays are stored in imagesDir regardless of type

func (*BuildGraph) GetJobIDs

func (bg *BuildGraph) GetJobIDs() map[string]string

GetJobIDs returns the map of job IDs for scheduler builds

func (*BuildGraph) Run

func (bg *BuildGraph) Run(ctx context.Context) error

Run executes the build graph First runs local builds, then submits scheduler jobs

type BuildLockInfo added in v1.3.0

type BuildLockInfo struct {
	Type      string `json:"type"`       // "local", "slurm", "pbs", "lsf", or "htcondor"
	JobID     string `json:"job_id"`     // scheduler job ID (empty until submit returns)
	Node      string `json:"node"`       // short hostname where lock was created
	PID       int    `json:"pid"`        // OS PID for local builds; 0 for scheduler
	CreatedAt string `json:"created_at"` // RFC3339 timestamp
}

BuildLockInfo holds metadata stored inside a build lock file.

type BuildObject

type BuildObject struct {
	// contains filtered or unexported fields
}

BuildObject holds all state and implements all build operations.

func FromExternalSource

func FromExternalSource(ctx context.Context, targetPrefix, source string, isApptainer bool, imagesDir string) (*BuildObject, error)

FromExternalSource creates a BuildObject from an external build script or def file All overlays are stored in imagesDir regardless of type

func NewBuildObject

func NewBuildObject(ctx context.Context, nameVersion string, external bool, imagesDir, tmpDir string, update bool) (*BuildObject, error)

NewBuildObject creates a BuildObject from a name/version string Format: "name/version" for conda/shell, "name" for def, "prefix/name/version" for ref All overlays are stored in imagesDir regardless of type

func NewCondaObjectWithSource

func NewCondaObjectWithSource(nameVersion, buildSource string, imagesDir, tmpDir string, update bool) (*BuildObject, error)

NewCondaObjectWithSource creates a CondaBuildObject with custom buildSource This is used for the -n flag to create a single sqf with multiple packages or YAML buildSource can be:

  • Path to YAML file (e.g., "/path/to/environment.yml")
  • Comma-separated package list (e.g., "nvim,nodejs,samtools/1.16")

func (*BuildObject) Build

func (b *BuildObject) Build(ctx context.Context, buildDeps bool) error

Build dispatches to the appropriate build implementation based on buildType.

func (*BuildObject) BuildSource

func (b *BuildObject) BuildSource() string

func (*BuildObject) Cleanup

func (b *BuildObject) Cleanup(failed bool) error

Cleanup removes the build workspace (remote source, tmp overlay, build dir), plus the partial target overlay on failure. Announces the work when there is something to remove; a no-op cleanup stays silent.

func (*BuildObject) CntDirPath

func (b *BuildObject) CntDirPath() string

func (*BuildObject) CreateBuildDirs added in v1.4.0

func (b *BuildObject) CreateBuildDirs(ctx context.Context, force bool) error

CreateBuildDirs creates host directories for dir-mode builds (use_tmp_overlay=false). Layout: <buildDir>/cnt/ (bound as /cnt) and <buildDir>/tmp/ (bound as /ext3/tmp). Checks both dir-mode (buildDir) and ext3-mode (.img) artifacts for cross-mode stale detection.

func (*BuildObject) CreateTmpOverlay

func (b *BuildObject) CreateTmpOverlay(ctx context.Context, force bool) error

func (*BuildObject) Dependencies

func (b *BuildObject) Dependencies() []string

func (*BuildObject) GetMissingDependencies

func (b *BuildObject) GetMissingDependencies() ([]string, error)

func (*BuildObject) InteractiveInputs added in v1.4.0

func (b *BuildObject) InteractiveInputs() []string

func (*BuildObject) IsInstalled

func (b *BuildObject) IsInstalled() bool

func (*BuildObject) LockPath added in v1.3.0

func (b *BuildObject) LockPath() string

LockPath returns the lock file path.

func (*BuildObject) NameVersion

func (b *BuildObject) NameVersion() string

func (*BuildObject) RequiresScheduler

func (b *BuildObject) RequiresScheduler() bool

func (*BuildObject) ScriptSpecs

func (b *BuildObject) ScriptSpecs() *ScriptSpecs

func (*BuildObject) String

func (b *BuildObject) String() string

func (*BuildObject) TargetOverlayPath

func (b *BuildObject) TargetOverlayPath() string

func (*BuildObject) TmpDir added in v1.4.0

func (b *BuildObject) TmpDir() string

func (*BuildObject) TmpOverlayPath

func (b *BuildObject) TmpOverlayPath() string

func (*BuildObject) Type

func (b *BuildObject) Type() BuildType

func (*BuildObject) Update added in v1.2.0

func (b *BuildObject) Update() bool

type BuildType

type BuildType int

BuildType represents the type of build target.

const (
	BuildTypeConda BuildType = iota + 1
	BuildTypeDef
	BuildTypeShell
	BuildTypeRef
)

Predefined build types.

func (BuildType) String

func (bt BuildType) String() string

String implements fmt.Stringer for BuildType.

type EnvEntry

type EnvEntry struct {
	Value string
	Note  string
}

EnvEntry holds an environment variable value and its note

type LocalScriptsCache added in v1.3.0

type LocalScriptsCache struct {
	FetchedAt    time.Time                             `json:"fetched_at"`
	SearchPaths  []string                              `json:"search_paths"`
	Fingerprints map[string]localScriptsDirFingerprint `json:"fingerprints"`
	Scripts      map[string]ScriptInfo                 `json:"scripts"`
}

type RemoteMetadataCache added in v1.3.0

type RemoteMetadataCache struct {
	FetchedAt    time.Time             `json:"fetched_at"`
	SourceURL    string                `json:"source_url"`
	PrebuiltLink string                `json:"prebuilt_link,omitempty"`
	Metadata     map[string]ScriptInfo `json:"metadata"`
}

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

type ScriptInfo

type ScriptInfo struct {
	// ---- runtime fields (NOT serialized) ----
	Name         string `json:"-"` // populated from map key after loading
	IsRemote     bool   `json:"-"` // set after loading based on source
	SourceURL    string `json:"-"` // base URL of the remote (empty for local)
	PrebuiltLink string `json:"-"` // base URL for prebuilt downloads; empty = no prebuilt

	// ---- serialized fields ----
	Path           string              `json:"path"`                      // full path (local) or relative path (remote)
	IsContainer    bool                `json:"is_container,omitempty"`    // true if .def file
	Deps           []string            `json:"deps,omitempty"`            // build dependencies
	IsTemplate     bool                `json:"is_template,omitempty"`     // true if the script has #PL: placeholders
	TargetTemplate string              `json:"target_template,omitempty"` // raw #TARGET: value before interpolation
	PL             map[string][]string `json:"pl,omitempty"`              // template: all values (sorted desc, "*" last if open); expanded: single-element [current_value]
	PLOrder        []string            `json:"pl_order,omitempty"`        // placeholder key declaration order (PL map iteration is non-deterministic)
	Whatis         string              `json:"whatis,omitempty"`          // description (interpolated for expanded entries)
}

ScriptInfo holds information about a build script. Runtime-only fields are tagged json:"-" so they are not serialized to the on-disk cache. Serialized fields use lowercase JSON keys shared by both the local scripts cache and the PL remote metadata JSON.

func FindBuildScript

func FindBuildScript(nameVersion string) (ScriptInfo, bool)

FindBuildScript looks for a build script by name/version. By default, local scripts take precedence over remote. When PreferRemote is true, remote scripts take precedence over local. Falls back to template pattern matching for open-ended (*) placeholders. Returns the ScriptInfo and a boolean indicating if it was found.

func (ScriptInfo) CurrentVars added in v1.4.0

func (s ScriptInfo) CurrentVars() map[string]string

CurrentVars returns a map of placeholder name → current value for an expanded (non-template) entry. The current value is PL[key][0]. Returns nil if PL is empty or if this is a template entry.

type ScriptSpecs

type ScriptSpecs = scheduler.ScriptSpecs

ScriptSpecs mirrors the scheduler module's job spec metadata.

Jump to

Keyboard shortcuts

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