overlay

package
v1.1.2-alpha Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: BSD-3-Clause Imports: 12 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
utils.go    Helpers (is.sqf check, etc.)
error.go    Structured error types

Key Types

CreateOptions:

  • Path, SizeMB, UID, GID, Profile, Sparse, FilesystemType, Quiet

Profile - Filesystem tuning:

  • InodeRatio - Bytes per inode
  • ReservedPerc - Reserved space percentage

Predefined Profiles:

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

Usage

Create Overlay
import "github.com/Justype/condatainer/internal/overlay"

ctx := context.Background()

// For current user
err := overlay.CreateForCurrentUser(
    ctx, "env.img", 3000, "small", sparse=true, "ext3", quiet=false)

// For root (requires fakeroot)
err := overlay.CreateForRoot(
    ctx, "env.img", 3000, "default", sparse=false, "ext3", quiet=false)

// Custom options
opts := &overlay.CreateOptions{
    Path:           "custom.img",
    SizeMB:         5000,
    UID:            1000,
    GID:            1000,
    Profile:        overlay.ProfileLarge,
    Sparse:         true,
    FilesystemType: "ext3",
    Quiet:          false,
}
err = overlay.CreateWithOptions(ctx, opts)
Resize
// Grow to 5000 MB
err := overlay.Resize(ctx, "env.img", 5000)

// Shrink also supported (checks free space first)
err = overlay.Resize(ctx, "env.img", 2000)
Change Ownership
// Change to root (requires fakeroot)
err := overlay.ChownToRoot(ctx, "env.img")

// Change to specific user
err = overlay.ChownToUser(ctx, "env.img", 1000, 1000)
Integrity Check
// Check integrity
err := overlay.Check(ctx, "env.img", repair=false)

// Check and repair
err = overlay.Check(ctx, "env.img", repair=true)

// Verify availability (lock check)
err = overlay.CheckAvailable("env.img", writeLock=false)
err = overlay.CheckAvailable("env.img", writeLock=true)
Information
// Get overlay stats
stats, err := overlay.GetStats("env.img")
// stats.Usage() returns (usedBytes, percent)
// stats.InodeUsage() returns percent

// Check if SquashFS (from utils package)
isSqf := utils.IsSqf("file.sqf")
Locking
// Acquire shared lock (multiple readers)
lock, err := overlay.AcquireLock("env.img", exclusive=false)
defer lock.Release()

// Acquire exclusive lock (single writer)
lock, err := overlay.AcquireLock("env.img", exclusive=true)
defer lock.Release()

Filesystem Profiles

Choose profile based on use case:

Profile Inode Ratio Use Case
Small 4KB Conda environments, Python site-packages
Default 16KB General applications
Large 1MB Reference genomes, large databases

Resize Algorithm

  1. Check current size via stat
  2. If growing: truncate + e2fsck + resize2fs
  3. If shrinking: Check free space first, then e2fsck + resize2fs + truncate
  4. Verify final size

Ownership Changes

Uses fakeroot + Apptainer to:

  1. Mount overlay as writable
  2. Run chown -R UID:GID /ext3 inside container
  3. Unmount

Locking Strategy

  • .img files are locked during use to prevent concurrent writes
  • Shared locks (read-only): Multiple instances can mount same overlay
  • Exclusive locks (writable): Only one process can write
  • Lock files: .img.lock in same directory

Error Types

  • LockError - Cannot acquire lock (overlay in use)
  • IntegrityError - Filesystem corruption detected
  • ResizeError - Resize operation failed
  • OwnershipError - Chown operation failed

Integration

  • internal/container - Checks overlay availability before mounting
  • internal/build - Creates temporary overlays for builds
  • cmd/overlay.go - CLI operations (create, resize, chown, check)

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).
	// 1 inode per 4KB keeps metadata lean so you don't hit inode exhaustion inside Conda envs.
	ProfileSmall = Profile{InodeRatio: 4096, ReservedPerc: 3}

	// ProfileDefault is a general-purpose profile (Linux default 16K).
	// 1 inode per 16KB balances metadata and data for typical workloads.
	ProfileDefault = Profile{InodeRatio: 16384, ReservedPerc: 3}
	// ProfileLarge is optimized for large files (genomes, FASTA, databases).
	// 1 inode per 1MB drastically lowers metadata pressure for huge single files.
	ProfileLarge = Profile{InodeRatio: 1048576, ReservedPerc: 3}
)

Functions

func CheckAvailable

func CheckAvailable(path string, write bool) error

CheckAvailable checks if the overlay image is available for reading or writing. It matches the probe-and-release behavior of the original bash scripts.

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.

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 CreateForCurrentUser

func CreateForCurrentUser(ctx context.Context, path string, sizeMB int, profileType string, sparse bool, fsType string, quiet bool) error

CreateForCurrentUser generates an overlay owned by the current host user.

func CreateForRoot

func CreateForRoot(ctx context.Context, path string, sizeMB int, profileType string, sparse bool, fsType string, quiet bool) error

CreateForRoot generates an overlay owned by root (UID=0, GID=0).

func CreateWithOptions

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

CreateWithOptions generates an overlay image using the provided options. Supports ext3 and ext4 filesystem types.

func Resize

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

Resize adjusts the size of an existing ext3 overlay image.

Types

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 Profile

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

Profile defines the tuning parameters for the filesystem.

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.

func (UIDStatus) String

func (s UIDStatus) String() string

Jump to

Keyboard shortcuts

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