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
- Variables
- func DefaultDBPath() string
- func DefaultLeaseDir() string
- type AcquireRequest
- type AgentDescription
- type ConflictError
- type Identity
- type Lease
- type LeaseState
- type ListFilter
- type SQLiteStore
- func (s *SQLiteStore) Acquire(ctx context.Context, req AcquireRequest) (*Lease, error)
- func (s *SQLiteStore) AuditDetail(ctx context.Context, leaseID, op string) (string, string, error)
- func (s *SQLiteStore) AuditRowCount(ctx context.Context, leaseID, op string) (int, error)
- func (s *SQLiteStore) Close() error
- func (s *SQLiteStore) Extend(ctx context.Context, leaseID, agentID string, add time.Duration) (*Lease, error)
- func (s *SQLiteStore) ForceRelease(ctx context.Context, leaseID, forcedBy, reason string) error
- func (s *SQLiteStore) JournalMode(ctx context.Context) (string, error)
- func (s *SQLiteStore) List(ctx context.Context, filter ListFilter) ([]*Lease, error)
- func (s *SQLiteStore) Path() string
- func (s *SQLiteStore) Release(ctx context.Context, leaseID, agentID string) error
- func (s *SQLiteStore) Sweep(ctx context.Context, hostname string, ...) (SweepResult, error)
- type Store
- type SweepResult
Constants ¶
const DefaultDuration = 60 * time.Minute
DefaultDuration is the default TTL applied when AcquireRequest.Duration is zero. Mirrors design memo OQ2.
Variables ¶
var ErrLeaseExpired = &leaseError{code: "LeaseExpired", msg: "lease has expired"}
ErrLeaseExpired is returned by Extend when the lease is no longer active.
var ErrLeaseNotFound = &leaseError{code: "LeaseNotFound", msg: "lease not found"}
ErrLeaseNotFound is returned when the lease_id does not exist.
var ErrNoNodes = &leaseError{code: "NoNodes", msg: "no nodes specified for lease"}
ErrNoNodes is returned when AcquireRequest.Nodes is empty.
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.
var ErrReasonRequired = &leaseError{code: "ReasonRequired", msg: "force_release requires a non-empty reason"}
ErrReasonRequired is returned when ForceRelease is called with no reason.
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 AgentDescription ¶ added in v0.4.5
type AgentDescription struct {
Raw string // always the input, never empty
Decoded bool // true if the default cookie-host-pid-suffix shape was matched
Cookie string
Hostname string
PID int
Suffix string
SameHost bool // Hostname == self.Hostname
SameUser bool // Cookie == self.Cookie && SameHost
}
AgentDescription holds the decoded components of a stored agent_id string relative to the calling process's own identity.
When Decoded is false (e.g., LABLINK_AGENT_ID override was in effect when the lease was acquired), only Raw is meaningful. Callers must fall back to the raw form in that case.
func DescribeAgentID ¶ added in v0.4.5
func DescribeAgentID(agentID string, self Identity) AgentDescription
DescribeAgentID returns a human-readable breakdown of a stored agent_id string relative to the calling process's own identity. The returned struct carries decoded fields plus boolean SameHost / SameUser markers that the conflict-error renderer uses to phrase ownership.
If the agent_id does not match the default <cookie>-<hostname>-<pid>-<suffix> shape (e.g., when LABLINK_AGENT_ID was set), all decoded fields are zero/empty and Raw is the input. Callers MUST fall back to the raw form in that case.
Parsing strategy: cookie is the first dash-delimited segment (must be 8 hex chars), suffix is the last segment (must be 4 hex chars), pid is the segment immediately before suffix (must be decimal digits), and hostname is everything between cookie and pid. This handles hostnames that themselves contain dashes.
type ConflictError ¶
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.
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.
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 ¶
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 ¶
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 ¶
AuditRowCount returns the number of audit rows for a lease. Test helper.
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.
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.