leasing

package
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package leasing implements a SQLite-backed lease store that coordinates access to lab nodes across multiple lablink-server.exe processes running on the same dev box.

The design memo is manager-log/lablink-leasing-design.md (frozen). This package implements Milestone 1 — the store layer only. MCP tool wiring, existing-tool gating, and the server-boot sweeper land in M2/M3/M4.

Index

Constants

View Source
const DefaultDuration = 60 * time.Minute

DefaultDuration is the default TTL applied when AcquireRequest.Duration is zero. Mirrors design memo OQ2.

Variables

View Source
var ErrLeaseExpired = &leaseError{code: "LeaseExpired", msg: "lease has expired"}

ErrLeaseExpired is returned by Extend when the lease is no longer active.

View Source
var ErrLeaseNotFound = &leaseError{code: "LeaseNotFound", msg: "lease not found"}

ErrLeaseNotFound is returned when the lease_id does not exist.

View Source
var ErrNoNodes = &leaseError{code: "NoNodes", msg: "no nodes specified for lease"}

ErrNoNodes is returned when AcquireRequest.Nodes is empty.

View Source
var ErrNotOwner = &leaseError{code: "NotOwner", msg: "lease is not owned by this agent"}

ErrNotOwner is returned by Release/Extend when the caller's agent_id does not match the lease's owner.

View Source
var ErrReasonRequired = &leaseError{code: "ReasonRequired", msg: "force_release requires a non-empty reason"}

ErrReasonRequired is returned when ForceRelease is called with no reason.

View Source
var ErrWaitTimeout = &leaseError{code: "WaitTimeout", msg: "wait_seconds elapsed before nodes became free"}

ErrWaitTimeout is returned by Acquire when wait_seconds elapses without the contested nodes becoming free.

Functions

func DefaultDBPath

func DefaultDBPath() string

DefaultDBPath returns the conventional location for leases.db.

func DefaultLeaseDir

func DefaultLeaseDir() string

DefaultLeaseDir returns the directory holding the SQLite leases db plus the agent-cookie file. Mirrors the design memo (~/.lablink).

Types

type AcquireRequest

type AcquireRequest struct {
	Nodes    []string
	Duration time.Duration
	Wait     time.Duration
	AgentID  string
	Reason   string
	// Identity carries the layered identity components (cookie, hostname,
	// pid, process start time) for this agent. Set by the server at boot.
	// If empty, Acquire falls back to Default() at call time.
	Identity Identity
}

AcquireRequest is the input to Store.Acquire.

type ConflictError

type ConflictError struct {
	Holders map[string]*Lease
}

ConflictError is returned by Store.Acquire when one or more requested nodes are held by another active lease. Holders maps node name to the active holder lease.

func (*ConflictError) Error

func (e *ConflictError) Error() string

func (*ConflictError) HeldNodes

func (e *ConflictError) HeldNodes() []string

HeldNodes returns the held node names in no particular order.

type Identity

type Identity struct {
	Cookie      string    // ~/.lablink/agent-cookie, 8 hex chars, per-user
	Hostname    string    // os.Hostname()
	PID         int       // os.Getpid()
	StartTime   time.Time // process start time, for sweeper
	RandSuffix  string    // 4 hex chars, per-process (PID-reuse disambiguation)
	EffectiveID string    // user override (LABLINK_AGENT_ID) or layered default
}

Identity is the layered agent identity defined in memo Section 5.

EffectiveID is what gets recorded as agent_id on the lease row. The other components are recorded separately so a post-mortem can disambiguate two agents that share an effective id.

func Default

func Default() Identity

Default returns the layered identity for THIS process, computing it once per program run.

Cookie source: ~/.lablink/agent-cookie (created on first call if missing). Override priority: LABLINK_AGENT_ID env var > layered default.

func (Identity) Empty

func (i Identity) Empty() bool

Empty reports whether the identity is zero-valued.

type Lease

type Lease struct {
	ID         string
	AgentID    string
	Cookie     string
	Hostname   string
	PID        int
	StartTime  time.Time
	Nodes      []string
	Reason     string
	AcquiredAt time.Time
	ExpiresAt  time.Time
	ReleasedAt time.Time
	State      LeaseState
}

Lease is one row in the leases table joined with its leased nodes.

func (*Lease) IsActive

func (l *Lease) IsActive(now time.Time) bool

IsActive reports whether the lease is currently holding its nodes.

type LeaseState

type LeaseState string

LeaseState is the lifecycle state of a Lease row.

const (
	// LeaseAcquired means the lease currently holds its nodes.
	LeaseAcquired LeaseState = "acquired"
	// LeaseReleased means the owning agent voluntarily dropped the lease.
	LeaseReleased LeaseState = "released"
	// LeaseExpired means the TTL deadline passed (or the owning process
	// went away and the sweeper noticed).
	LeaseExpired LeaseState = "expired"
	// LeaseForced means an admin called ForceRelease.
	LeaseForced LeaseState = "forced"
)

type ListFilter

type ListFilter struct {
	AgentID        string
	Role           string
	Topology       string
	IncludeExpired bool
	Limit          int
}

ListFilter narrows a Store.List query.

type SQLiteStore

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

SQLiteStore is the SQLite-backed Store. One DB handle per lablink-server.exe process; cross-process serialization is delegated to SQLite's WAL + BEGIN IMMEDIATE.

func OpenSQLiteStore

func OpenSQLiteStore(path string) (*SQLiteStore, error)

OpenSQLiteStore opens (and migrates) the leases db at the given path. If path is empty, DefaultDBPath() is used. The parent directory is created with 0700 permissions if missing.

func (*SQLiteStore) Acquire

func (s *SQLiteStore) Acquire(ctx context.Context, req AcquireRequest) (*Lease, error)

Acquire implements Store.Acquire. Multi-node acquire is all-or-nothing.

Concurrency: every attempt runs inside BEGIN IMMEDIATE so two processes (or two goroutines on one process) racing for the same node see exactly one winner. Wait>0 polls every 500ms (capped to remaining time).

func (*SQLiteStore) AuditDetail

func (s *SQLiteStore) AuditDetail(ctx context.Context, leaseID, op string) (string, string, error)

AuditDetail returns the JSON detail blob of the most recent audit row for (leaseID, op). Empty string when no row matches. Test helper.

func (*SQLiteStore) AuditRowCount

func (s *SQLiteStore) AuditRowCount(ctx context.Context, leaseID, op string) (int, error)

AuditRowCount returns the number of audit rows for a lease. Test helper.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close releases the database handle.

func (*SQLiteStore) Extend

func (s *SQLiteStore) Extend(ctx context.Context, leaseID, agentID string, add time.Duration) (*Lease, error)

Extend bumps the TTL. Owner-only. Idempotent; deadline becomes max(old, now+add).

func (*SQLiteStore) ForceRelease

func (s *SQLiteStore) ForceRelease(ctx context.Context, leaseID, forcedBy, reason string) error

ForceRelease marks state=forced. No ownership check. reason required.

func (*SQLiteStore) JournalMode

func (s *SQLiteStore) JournalMode(ctx context.Context) (string, error)

JournalMode returns the current PRAGMA journal_mode. Used by tests.

func (*SQLiteStore) List

func (s *SQLiteStore) List(ctx context.Context, filter ListFilter) ([]*Lease, error)

List returns leases matching the filter. M1: role and topology are recognized parameters but no nodes carry role/topology metadata yet, so those filters silently match everything. Will be wired in M3 when touched-node extraction lands.

func (*SQLiteStore) Path

func (s *SQLiteStore) Path() string

Path returns the on-disk db path. Useful for diagnostics.

func (*SQLiteStore) Release

func (s *SQLiteStore) Release(ctx context.Context, leaseID, agentID string) error

Release marks the lease state=released. Owner-only.

func (*SQLiteStore) Sweep

func (s *SQLiteStore) Sweep(ctx context.Context, hostname string, liveProcess func(pid int, startUnix int64) bool) (SweepResult, error)

Sweep is the startup crash-recovery pass. Returns a per-category breakdown of leases transitioned (see SweepResult).

type Store

type Store interface {
	// Acquire grants a lease over the requested node set atomically.
	// On conflict, returns *ConflictError unless req.Wait > 0 in which
	// case the call polls and may eventually return ErrWaitTimeout.
	// Multi-node acquire is all-or-nothing per memo OQ7.
	Acquire(ctx context.Context, req AcquireRequest) (*Lease, error)

	// Release marks the lease state=released, owner-only. Returns
	// ErrNotOwner if agentID does not match, ErrLeaseNotFound if the
	// id does not exist.
	Release(ctx context.Context, leaseID, agentID string) error

	// Extend bumps the TTL on an active lease, owner-only. Returns the
	// updated Lease. Returns ErrLeaseExpired if the lease is no longer
	// active.
	Extend(ctx context.Context, leaseID, agentID string, add time.Duration) (*Lease, error)

	// List returns currently-tracked leases filtered by ListFilter. By
	// default only active leases are returned; set IncludeExpired to
	// surface tombstoned rows too.
	List(ctx context.Context, filter ListFilter) ([]*Lease, error)

	// ForceRelease marks a lease state=forced regardless of ownership.
	// Audit row records forcedBy + reason. Reason MUST be non-empty.
	// M1 does NOT gate this behind an env var (per the manager — that
	// guardrail lives at the MCP tool surface in M4 via destructiveHint).
	ForceRelease(ctx context.Context, leaseID, forcedBy, reason string) error

	// Sweep performs startup crash recovery on leases owned by this host.
	// For every active lease whose (pid, process_start_time) no longer
	// corresponds to a live process per the supplied probe, mark expired
	// with audit reason process_gone. Also lazily expires leases past
	// their TTL deadline. Returns a per-category breakdown of leases
	// transitioned (see SweepResult).
	//
	// liveProcess(pid, startUnix) -> true if a process with that identity
	// is still running on the local host. Pass nil to skip the dead-
	// process check (useful in tests).
	Sweep(ctx context.Context, hostname string, liveProcess func(pid int, startUnix int64) bool) (SweepResult, error)

	// Close releases resources (db handle, etc).
	Close() error
}

Store is the abstract lease backend. M1 ships SQLiteStore as the only implementation. The interface is shaped to allow a network-backed v2 (etcd / sql.DB) drop-in.

type SweepResult

type SweepResult struct {
	// TTL counts leases whose expires_at deadline had already passed at
	// sweep time, on any host.
	TTL int
	// DeadProcess counts leases owned by the sweeping host whose recorded
	// (pid, process_start_unix) no longer corresponds to a live process.
	DeadProcess int
}

SweepResult is the per-category count of leases transitioned by a single Store.Sweep invocation. M4 added the breakdown so the boot-time log can distinguish "your sibling crashed" (DeadProcess) from "someone left a lease running past its TTL" (TTL) without re-querying the audit log.

func (SweepResult) Total

func (r SweepResult) Total() int

Total is TTL + DeadProcess — the same value the v0.4.0-pre Sweep returned as a single int.

Jump to

Keyboard shortcuts

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