overlay

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: 19 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

overlay

Overlay image file operations providing creation, resizing, ownership changes, integrity checking, and locking for ext3/SquashFS images.

Architecture

create.go   Image creation with filesystem profiles
resize.go   ext3 image resizing (grow/shrink)
chown.go    Ownership changes (requires fakeroot)
check.go    Integrity checking and repair
lock.go     File locking (shared/exclusive)
info.go     Image information queries
squashfs.go SquashFS packing operations
error.go    Structured error types

Key Types

Predefined Profiles:

  • ProfileSmall - 4KB per inode (Conda, Python packages)
  • ProfileDefault - 16KB per inode (general purpose)
  • ProfileLarge - 1MB per inode (genomes, databases)

Stats - Usage() (usedBytes, percent), InodeUsage() percent

Lock - Close() error

Creation API

There are three creation paths depending on the caller's needs:

Function When to use
CreateWithOptions(ctx, opts) Simple create + move in one call (e.g. internal/build)
CreateInTmp(ctx, opts) → MoveOverlayCopied Caller needs to run work on the tmp image first (e.g. conda init in cmd/overlay)
CreateDirectly(ctx, opts) Target is already on fast local storage (--no-tmp)

Default tmp-staging flow (used by condatainer o / overlay create):

  1. CreateInTmp — builds the overlay sparse at utils.GetTmpDir() (local SSD, fast random I/O for dd/mke2fs/debugfs/conda)
  2. Caller runs additional work (e.g. conda environment init) on the tmp path
  3. MoveOverlayCopied(tmpPath, finalPath, sparse) — moves to destination:
    • Same filesystem → os.Rename (instant); may need AllocateOverlay afterward
    • Cross-filesystem (e.g. local /tmp → LustreFS) → copy then remove src:
      • sparse=false: io.Copy writes all zeros, destination is fully allocated
      • sparse=true: sparseAwareCopy via SEEK_DATA/SEEK_HOLE, holes preserved

Override the tmp location with CNT_TMPDIR (takes priority over SLURM_TMPDIR, TMPDIR, /tmp).

Usage

// --- Simple create (internal/build) ---
overlay.CreateWithOptions(ctx, &overlay.CreateOptions{
    Path: "env.img", SizeMB: 3000,
    UID: os.Getuid(), GID: os.Getgid(),
    Profile: overlay.ProfileDefault, Sparse: true, FilesystemType: "ext3", Quiet: true,
})

// --- Create at tmp, do work, then move (cmd/overlay) ---
opts := &overlay.CreateOptions{Path: "env.img", SizeMB: 10240, ...}
tmpPath, err := overlay.CreateInTmp(ctx, opts)
// ... run conda init on tmpPath ...
copied, err := overlay.MoveOverlayCopied(tmpPath, opts.Path, opts.Sparse)
if !opts.Sparse && !copied {
    overlay.AllocateOverlay(ctx, opts.Path, opts.SizeMB)
}

// Resize (grow or shrink)
overlay.Resize(ctx, "env.img", 5000)

// Ownership (requires fakeroot; internalPath = path inside overlay)
overlay.ChownRecursively(ctx, "env.img", 0, 0, "/ext3")       // → root
overlay.ChownRecursively(ctx, "env.img", 1000, 1000, "/ext3")  // → user

// Integrity
overlay.CheckIntegrity(ctx, "env.img", false) // check
overlay.CheckIntegrity(ctx, "env.img", true)  // check and repair
overlay.CheckAvailable("env.img", false)      // shared lock check
overlay.CheckAvailable("env.img", true)       // exclusive lock check

// Stats
stats, err := overlay.GetStats("env.img")

// Locking
lock, err := overlay.AcquireLock("env.img", false) // shared
lock, err := overlay.AcquireLock("env.img", true)  // exclusive
defer lock.Close()

Error Types

All overlay errors use overlay.Error with an Op field (e.g. "lock", "check", "resize", "chown"):

var overlayErr *overlay.Error
if errors.As(err, &overlayErr) {
    fmt.Println(overlayErr.Op)
}

Locking Strategy

Locks use syscall.Flock on the image file itself (no separate .lock file), non-blocking (LOCK_NB):

  • Shared (LOCK_SH): multiple readers can hold concurrently; acquired read-only (O_RDONLY)
  • Exclusive (LOCK_EX): single writer; blocks all other locks; requires write permission (O_RDWR)
  • Released automatically when the file descriptor is closed

Who holds locks:

  • exec/run: acquire and hold shared read locks on all .sqf overlays and the base .sif for the entire duration of apptainer exec. .img overlays are skipped — Apptainer flocks them itself; acquiring our own lock conflicts with Apptainer's locking.
  • overlay chown: acquires and holds an exclusive lock for the duration of the operation.
  • overlay resize/check: probe-and-release exclusive lock (via CheckIntegrity → CheckAvailable) — no lock is held across the resize2fs/e2fsck run, so the caller must not pre-acquire one (a held lock collides with the probe).
  • remove: probe-and-release exclusive lock before os.Remove() — fails if shared lock is held.
  • build --update: probe-and-release exclusive lock before starting any build work — fails if shared lock is held.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ProfileSmall is tuned for environments with many small files (Conda packages, Python/site-packages).
	ProfileSmall = Profile{InodeRatio: 4096, ReservedPerc: 3}

	// ProfileDefault is a general-purpose profile (Linux default 16K).
	ProfileDefault = Profile{InodeRatio: 16384, ReservedPerc: 3}

	// ProfileLarge is optimized for large files (genomes, FASTA, databases).
	ProfileLarge = Profile{InodeRatio: 1048576, ReservedPerc: 3}
)

Functions

func AllocateOverlay added in v1.3.0

func AllocateOverlay(ctx context.Context, path string, sizeMB int)

AllocateOverlay pre-allocates disk blocks for a sparse overlay file using fallocate.

func BuildTime added in v1.5.1

func BuildTime(path string) (time.Time, bool)

BuildTime returns the SquashFS creation time, which mksquashfs sets at build time, so for CondaTainer overlays it is the build timestamp. Returns false when the archive has no readable creation time (e.g. unsquashfs unavailable).

func Cat added in v1.2.0

func Cat(sqfPath, filePath string) []byte

Cat reads a file from a SquashFS archive using unsquashfs -cat. unsquashfs older than 4.5 (e.g. 4.4 on Ubuntu 20.04) has no -cat, so on failure fall back to extracting the file into a temp dir. Returns nil if the file cannot be read.

func CheckAvailable

func CheckAvailable(path string, write bool) error

CheckAvailable checks if the overlay image is available for reading or writing.

func CheckIntegrity

func CheckIntegrity(ctx context.Context, path string, force bool) error

CheckIntegrity runs a filesystem check (e2fsck) on the overlay image. force: If true, adds '-f' to force the check even if the filesystem appears clean. Returns an error immediately if the image is currently in use (mounted writable).

func ChownRecursively

func ChownRecursively(ctx context.Context, imagePath string, uid, gid int, internalPath string) error

ChownRecursively changes the UID/GID of files inside an unmounted overlay image. It maps the provided internalPath (e.g., "/") to the overlay's "/upper" structure.

func CondarcChannels added in v1.5.1

func CondarcChannels(overlayPath, envPrefix string) []string

CondarcChannels reads the channels list (in priority order) from the .condarc at envPrefix inside the overlay. This is what conda reads as context.channels and orders `env export` by; micromamba ignores it and sorts alphabetically. Returns nil if the file is absent or lists no channels.

func CreateDirectly added in v1.3.0

func CreateDirectly(ctx context.Context, opts *CreateOptions) error

CreateDirectly builds the overlay at opts.Path without using a local tmp directory.

func CreateInTmp added in v1.3.0

func CreateInTmp(ctx context.Context, opts *CreateOptions) (tmpPath string, err error)

CreateInTmp builds the overlay at a local temp path and returns that path. The overlay is always created sparse to minimize local disk usage. The caller is responsible for running additional init, moving to final destination, and calling AllocateOverlay if needed. The caller must remove the temp file on error.

func CreateWithOptions

func CreateWithOptions(ctx context.Context, opts *CreateOptions) error

CreateWithOptions builds the overlay at a local tmp path and moves it to opts.Path. If opts.Sparse is false, AllocateOverlay is called after the move to fill sparse holes. For cases where additional work must happen before the final move (e.g. conda init), use CreateInTmp + MoveOverlayCopied + AllocateOverlay instead.

func ForgetOSType added in v1.5.1

func ForgetOSType(path string)

ForgetOSType drops the cached IsOSType verdict for an overlay path. Call after deleting an overlay file so the cache does not keep stale entries.

func GetOverlayType added in v1.2.0

func GetOverlayType(sqfPath string) string

GetOverlayType classifies a SquashFS overlay based on its contents and filename:

  • "OS Overlay" : contains .singularity.d (Apptainer-built)
  • "Module Overlay" : contains cnt/ and filename uses -- name/version separator
  • "Bundle Overlay" : contains cnt/ but filename has no --
  • "" : unrecognized

func HasCntBin added in v1.2.0

func HasCntBin(sqfPath, nameVersion string) bool

HasCntBin returns true if the SquashFS archive contains a bin directory at cnt/<name>/<version>/bin. nameVersion accepts both slash form ("samtools/1.22") and the normalized double-dash form ("samtools--1.22").

func IsOSType added in v1.2.0

func IsOSType(sqfPath string) bool

IsOSType returns true if the SquashFS archive is an Apptainer OS image, identified by the presence of .singularity.d at the archive root. Verdicts are cached across processes keyed by path, size, and mtime, so repeated checks (e.g. shell completion) skip the unsquashfs probe.

func ListCondaPackages added in v1.5.0

func ListCondaPackages(imgPath string) (map[string]string, error)

ListCondaPackages reads the conda-meta directory from a writable ext3 overlay image and returns a map of package name → installed version for every conda package found. The conda environment is expected at /ext3/env inside the container, which maps to upper/ext3/env/conda-meta inside the .img file.

Returns (nil, nil) for non-.img files or when no conda-meta directory exists.

func MoveOverlayCopied added in v1.3.0

func MoveOverlayCopied(ctx context.Context, src, dst string, sparse bool) (copied bool, err error)

MoveOverlayCopied moves src to dst and reports whether a copy was performed.

func ParseStatTime added in v1.5.1

func ParseStatTime(s string) (time.Time, bool)

ParseStatTime parses a timestamp string from `unsquashfs -stat` / `tune2fs` output (run with LC_ALL=C). It accepts both ISO ("2006-01-02 15:04:05") and C-locale ctime() ("Mon Jan _2 15:04:05 2006") forms. Returns false if neither parses.

func PathExists added in v1.2.0

func PathExists(overlayPath, entry string) bool

PathExists dispatches to the appropriate backend check depending on the overlay type.

func ReadFile added in v1.4.1

func ReadFile(overlayPath, innerPath string) []byte

ReadFile reads a file at innerPath from inside an overlay image. For .sqf overlays it uses unsquashfs -cat; for .img overlays it uses debugfs. Returns nil if the file cannot be read.

func Resize

func Resize(ctx context.Context, imagePath string, newSizeMB int) error

Resize adjusts the size of an existing ext3 overlay image to newSizeMB.

Flow: fsck → grow the file (if growing) → resize2fs to the exact target → shrink the file (if shrinking) → fsck. Sizes are compared against the ext3 filesystem, not the container file's byte size, since the two can diverge.

Types

type CondaInfo added in v1.4.1

type CondaInfo struct {
	Channels []string
	Specs    []string
}

CondaInfo holds the channels and explicitly-requested packages parsed from a conda-meta/history file inside an overlay.

func ReadCondaInfo added in v1.4.1

func ReadCondaInfo(overlayPath, envPrefix string) *CondaInfo

ReadCondaInfo reads conda-meta/history from envPrefix inside the overlay and returns the channels and explicitly-installed package specs. Returns nil if the history file is absent or contains no specs.

type CreateOptions

type CreateOptions struct {
	Path           string  // Path to the overlay image file
	SizeMB         int     // Size in megabytes
	UID            int     // Owner user ID
	GID            int     // Owner group ID
	Profile        Profile // Filesystem tuning profile
	Sparse         bool    // Create sparse file (vs allocated)
	FilesystemType string  // Filesystem type: "ext3" or "ext4" (default: "ext3")
	Quiet          bool    // Suppress detailed specs output
}

CreateOptions holds all configuration options for creating an overlay image.

type Error

type Error struct {
	Op      string // high level intent: "create", "resize"
	Tool    string // low level tool: "mke2fs", "dd", "debugfs"
	Path    string // the file being manipulated
	Output  string // Captured Stderr/Stdout
	BaseErr error  // The underlying execution error
}

Error represents a failure in filesystem tools (dd, mkfs, debugfs, etc.). Usage: if err, ok := err.(*overlay.Error); ok { ... }

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap allows errors.Is/As to see the underlying BaseErr

type Lock

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

Lock represents a file lock on an overlay image. It must be closed to release the lock.

func AcquireLock

func AcquireLock(path string, write bool) (*Lock, error)

AcquireLock attempts to acquire a lock on the overlay file. If write is true, it attempts an exclusive lock (LOCK_EX). If write is false, it attempts a shared lock (LOCK_SH). Both are non-blocking (LOCK_NB).

func (*Lock) Close

func (l *Lock) Close() error

Close releases the lock by closing the file.

type OSInfo added in v1.2.0

type OSInfo struct {
	ID        string   // e.g. "ubuntu", "debian", "rhel", "rocky"
	IDLike    []string // e.g. ["debian"] for ubuntu, ["rhel", "fedora"] for rocky/alma
	VersionID string   // e.g. "24.04", "12", "9.3"
	Codename  string   // e.g. "Noble", "Bookworm", "Blue Onyx" (title-cased)
	Name      string   // e.g. "Ubuntu", "Debian", "Rocky Linux"
}

OSInfo holds distribution identity parsed from /etc/os-release.

func GetOSInfo added in v1.2.0

func GetOSInfo(sqfPath string) *OSInfo

GetOSInfo reads /etc/os-release from a SquashFS archive and returns an OSInfo. Returns nil if the file cannot be read or parsed.

func (*OSInfo) String added in v1.2.0

func (o *OSInfo) String() string

String returns a human-readable distro string suitable for CLI display.

"Ubuntu 24.04 (Noble)"
"Debian 12 (Bookworm)"
"Rocky Linux 9.3 (Blue Onyx)"
"Red Hat Enterprise Linux 9.3 (Plow)"

type Profile

type Profile struct {
	InodeRatio   int // -i: bytes per inode
	ReservedPerc int // -m: percentage (0-100)
}

Profile defines the tuning parameters for the filesystem.

func ParseProfile added in v1.5.1

func ParseProfile(name string) (Profile, error)

ParseProfile resolves a profile name (small/balanced/large, or an alias) to its Profile. An empty name selects the default; an unrecognized name is an error.

type SquashFSStats added in v1.2.0

type SquashFSStats struct {
	CreatedTime         string
	FilesystemSizeBytes int64
	Compression         string
	CompressionLevel    int // 0 means not specified by the file
	BlockSize           int64
	NumFragments        int64
	NumInodes           int64
	NumIDs              int64
	DuplicatesRemoved   bool
	ExportableNFS       bool
}

SquashFSStats holds metadata parsed from `unsquashfs -stat`.

func GetSquashFSStats added in v1.2.0

func GetSquashFSStats(path string) (*SquashFSStats, error)

GetSquashFSStats runs `unsquashfs -stat` on the given path and parses its output.

type Stats

type Stats struct {
	// Filesystem metadata
	FilesystemType  string // "ext3", "ext4"
	BlockSize       int64
	TotalBlocks     int64
	FreeBlocks      int64
	ReservedBlocks  int64
	TotalInodes     int64
	FreeInodes      int64
	FilesystemState string // "clean", "dirty", etc.
	LastMounted     string
	CreatedTime     string
	FilesystemUUID  string
	JournalSize     int64 // in blocks
	InodeSize       int64

	// File metadata
	FileSizeBytes  int64 // Apparent size of the file
	FileBlocksUsed int64 // Actual blocks allocated on disk (for sparse detection)
	IsSparse       bool  // True if file is sparse

	// Overlay ownership
	UpperUID int
	UpperGID int
}

Stats holds metadata about the overlay filesystem.

func GetStats

func GetStats(path string) (*Stats, error)

GetStats reads the filesystem superblock to calculate usage without mounting.

func (*Stats) InodeUsage

func (s *Stats) InodeUsage() (percent float64)

InodeUsage returns the calculated inode usage percentage.

func (*Stats) Usage

func (s *Stats) Usage() (usedBytes int64, percent float64)

Usage returns the calculated used space in bytes and percentage.

type UIDStatus

type UIDStatus int

UIDStatus represents the result of InspectImageUIDStatus.

const (
	UIDStatusUnknown UIDStatus = iota
	// UIDStatusRoot indicates the 'upper' directory is owned by root (UID 0).
	UIDStatusRoot
	// UIDStatusCurrentUser indicates it's owned by the current user.
	UIDStatusCurrentUser
	// UIDStatusDifferentUser indicates it's owned by a different user.
	UIDStatusDifferentUser
)

func InspectImageUIDStatus

func InspectImageUIDStatus(imgPath string) UIDStatus

InspectImageUIDStatus checks the ownership of the 'upper' directory inside an ext3/4 image. Returns:

  • UIDStatusRoot: owned by root (UID 0)
  • UIDStatusCurrentUser: owned by current user
  • UIDStatusDifferentUser: owned by a different user
  • UIDStatusUnknown: failed to check or not an image file

This is used to determine if --fakeroot should be automatically enabled.

Jump to

Keyboard shortcuts

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