utils

package
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HTTPTimeout = 30 * time.Second
	MaxRetries  = 3
	BaseBackoff = 100 * time.Millisecond
)
View Source
const StaleTempAge = time.Hour

StaleTempAge is the age threshold for removing stale temp files during GC.

Variables

This section is empty.

Functions

func AtomicWriteFile

func AtomicWriteFile(path string, data []byte, perm os.FileMode) error

AtomicWriteFile writes data to a file atomically using temp + fsync + rename. This prevents partial writes from being visible to readers.

func AtomicWriteJSON

func AtomicWriteJSON(path string, v any) error

AtomicWriteJSON marshals v to JSON and writes it atomically.

func CheckSocket

func CheckSocket(socketPath string) error

CheckSocket verifies that a Unix socket is connectable.

func CleanStaleRecords

func CleanStaleRecords[T any](
	items map[string]*T,
	nameMap map[string]string,
	targetIDs []string,
	nameOf func(*T) string,
	isStale func(*T) bool,
)

CleanStaleRecords removes records matching targetIDs from items, with a staleness re-check via isStale to guard against TOCTOU. nameOf extracts the name for nameMap cleanup ("" means no name entry).

func DetectHugePages

func DetectHugePages() bool

DetectHugePages reads /proc/sys/vm/nr_hugepages and returns true if the host has hugepages configured (value > 0). Returns false on any error (non-Linux, file missing, etc.).

func DoAPI

func DoAPI(ctx context.Context, hc *http.Client, method, url string, body []byte, expectedStatus int) ([]byte, error)

DoAPI sends an HTTP request and validates the response status code. url must be a fully-formed URL (e.g., "http://localhost/api/v1/vm.shutdown"). Returns the response body on success. For 204 No Content the body is nil.

func DoWithRetry

func DoWithRetry[T any](ctx context.Context, fn func() (T, error)) (T, error)

DoWithRetry retries fn with exponential backoff for transient errors.

func EnsureDirs

func EnsureDirs(dirs ...string) error

EnsureDirs creates all directories with 0o750 permissions.

func ExtractTar

func ExtractTar(dir string, r io.Reader) error

ExtractTar extracts tar entries as flat files into dir. Only regular files are extracted; the base name is used to prevent path traversal.

Entries with COCOON.sparse PAX records are extracted using the embedded sparse map, writing data segments to their original offsets and leaving holes untouched. This preserves sparsity without scanning for zero blocks.

func FilterUnreferenced

func FilterUnreferenced(candidates []string, refs map[string]struct{}, exclude ...map[string]struct{}) []string

FilterUnreferenced returns the elements of candidates not present in refs or any of the optional exclude sets. Used by GC Resolve to compute deletions.

func GenerateID

func GenerateID() (string, error)

GenerateID returns a random 16-character hex string (8 bytes of entropy).

func InitNamedIndex

func InitNamedIndex[T any](items *map[string]*T, names *map[string]string)

InitNamedIndex initializes nil maps in a named index (Items + Names pattern).

func IsProcessAlive

func IsProcessAlive(pid int) bool

IsProcessAlive returns true if a process with the given PID currently exists. Uses kill(pid, 0) — no signal is sent, only existence is checked. EPERM means the process exists but we lack permission to signal it.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable returns true for transient errors (connection failures, 5xx, 429).

func LookupCopy

func LookupCopy[T any](m map[string]*T, key string) (T, error)

LookupCopy returns a shallow copy of the value at key in m. Returns an error if the key is absent or the stored pointer is nil. NOTE: this is a shallow copy — pointer, slice, and map fields inside T still reference the original data. Callers must not mutate such fields on the returned value without additional deep-copy logic.

func Map added in v0.2.5

func Map[T, R any](ctx context.Context, items []T, fn func(ctx context.Context, idx int, item T) (R, error), concurrency ...int) ([]R, error)

Map runs fn for each item concurrently, returning results in input order. Fail-fast: the errgroup context is canceled on the first error, so in-flight callbacks see a canceled ctx and new ones are not started. An optional concurrency limit caps in-flight goroutines; zero or omitted means no limit.

func MergeSets

func MergeSets[K comparable](sets ...map[K]struct{}) map[K]struct{}

MergeSets unions any number of set maps into a new set.

func NewSocketHTTPClient

func NewSocketHTTPClient(socketPath string) *http.Client

NewSocketHTTPClient creates an HTTP client that dials a Unix socket.

func ReadPIDFile

func ReadPIDFile(path string) (int, error)

ReadPIDFile reads a PID integer from path.

func ReflinkCopy

func ReflinkCopy(dst, src string) error

ReflinkCopy copies a single file, preferring FICLONE (O(1) CoW on btrfs/xfs/bcachefs) and falling back to SparseCopy on any error.

func RemoveMatching

func RemoveMatching(ctx context.Context, dir string, match func(os.DirEntry) bool) []error

RemoveMatching scans dir and removes entries where match returns true. Returns a slice of errors for entries that could not be removed.

func ResolveRef

func ResolveRef[T any](items map[string]*T, names map[string]string, ref string, notFound error) (string, error)

ResolveRef resolves a ref (exact ID, name, or ID prefix ≥3 chars) to a full ID. Works with any Index that has an Items map and a Names map.

func ResolveRefs

func ResolveRefs[T any](items map[string]*T, names map[string]string, refs []string, notFound error) ([]string, error)

ResolveRefs batch-resolves refs to exact IDs, deduplicating results.

func ScanFileStems

func ScanFileStems(dir, suffix string) ([]string, error)

ScanFileStems returns the name-without-suffix of every file in dir whose name ends with suffix. Used by GC to enumerate on-disk blobs.

func ScanSubdirs

func ScanSubdirs(dir string) ([]string, error)

ScanSubdirs returns the names of all immediate subdirectories of dir. Used by GC to enumerate per-VM runtime and log directories.

func SparseCopy

func SparseCopy(dst, src string) error

SparseCopy copies src to dst preserving sparsity via SEEK_HOLE/SEEK_DATA. dst is created as a new file (truncated to src size, then only data segments written).

func SyncParentDir

func SyncParentDir(dir string) error

SyncParentDir fsyncs the directory containing the file to ensure the directory entry is persisted.

func TarDir

func TarDir(tw *tar.Writer, dir string) error

TarDir writes all regular files in dir into tw as flat tar entries (no directory nesting). On Linux, sparse files are detected and only their data segments are stored.

func TarDirStream

func TarDirStream(dir string, cleanup func()) io.ReadCloser

func TarDirStreamWithRemove

func TarDirStreamWithRemove(dir string) io.ReadCloser

func TerminateProcess

func TerminateProcess(ctx context.Context, pid int, binaryName, expectArg string, gracePeriod time.Duration) error

TerminateProcess verifies the PID belongs to binaryName (with optional cmdline arg check), then sends SIGTERM, waits up to gracePeriod, and falls back to SIGKILL.

func UUIDv5

func UUIDv5(name string) string

UUIDv5 generates a deterministic UUID v5 from the given name using the URL namespace. Compatible with the uuid_v5() bash function in os-image/start.sh.

func ValidFile

func ValidFile(path string) bool

ValidFile returns true if path is a regular file with size > 0.

func VerifyProcess

func VerifyProcess(pid int, binaryName string) bool

VerifyProcess checks whether pid is running the expected binary. On Linux, reads /proc/{pid}/exe. On other platforms, falls back to IsProcessAlive (can confirm the process exists but not its binary name).

func VerifyProcessCmdline

func VerifyProcessCmdline(pid int, binaryName, expectArg string) bool

VerifyProcessCmdline checks binary name and that expectArg appears in /proc/{pid}/cmdline. This prevents cross-instance misidentification when multiple processes of the same binary are running (e.g. multiple VMs). On non-Linux platforms, falls back to IsProcessAlive.

func WaitFor

func WaitFor(ctx context.Context, timeout, interval time.Duration, check func() (done bool, err error)) error

WaitFor polls check at the given interval until it returns (true, nil), returns a non-nil error, or the timeout/context expires.

func WritePIDFile

func WritePIDFile(path string, pid int) error

WritePIDFile writes pid to path with 0600 permissions.

Types

type APIError

type APIError struct {
	Code    int
	Message string
}

APIError carries the HTTP status code from a REST API response.

func (*APIError) Error

func (e *APIError) Error() string

type BatchResult

type BatchResult[T any] struct {
	Succeeded []T
	Errors    []error
}

BatchResult holds the outcome of a best-effort batch operation.

func ForEach

func ForEach[T any](ctx context.Context, items []T, fn func(context.Context, T) error, concurrency ...int) BatchResult[T]

ForEach runs fn for each item concurrently, collecting successes and errors (best-effort). All items are attempted regardless of individual failures. An optional concurrency limit caps in-flight goroutines; zero or omitted means no limit.

func (BatchResult[T]) Err

func (r BatchResult[T]) Err() error

Err returns the combined error from all failed operations.

type PipeStreamReader

type PipeStreamReader struct {
	*io.PipeReader
	// contains filtered or unexported fields
}

func NewPipeStreamReader

func NewPipeStreamReader(pr *io.PipeReader, done <-chan error, cleanup func()) *PipeStreamReader

func (*PipeStreamReader) Close

func (r *PipeStreamReader) Close() error

Jump to

Keyboard shortcuts

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