guardian

package
v0.0.0-...-0b698e0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0, MIT Imports: 23 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.

Documentation

Overview

Package guardian observes host-wide process consumption and, when an operator enables it, acts on unmanaged processes under host pressure. It is separate from lease policy: observation never grants process authority, and every action revalidates the target's identity first.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultLadder

func DefaultLadder(role string) []model.GuardianStepRule

DefaultLadder prefers notification and reversible steps on a manned host. An unmanned host freezes and terminates, because nobody will intervene.

func Signal

func Signal(id model.ProcessIdentity, sig syscall.Signal) error

Signal delivers sig to the exact identity.

func Steps

func Steps() []string

Steps returns every ladder step in its required order.

func Thaw

func Thaw(id model.ProcessIdentity) error

Thaw resumes the exact process, matched by PID, start time and namespace.

func ValidateSettings

func ValidateSettings(s *model.GuardianSettings) error

ValidateSettings checks a configured table, even when disabled, so a later enable cannot reveal a broken policy.

Types

type Candidate

type Candidate struct {
	*Group
	Protected     string
	Managed       bool
	Agent         string
	AgentEvidence string
	Profile       string
}

Candidate is a group with the attributes that decide eligibility.

type Config

type Config struct {
	Mode           string
	Role           string
	Interval       time.Duration
	Ladder         []model.GuardianStepRule
	Recover        time.Duration // pressure at or below elevated this long closes an incident
	Cooldown       time.Duration // minimum spacing between applied steps of one incident
	FreezeMax      time.Duration // frozen groups resume after this long
	TerminateGrace time.Duration // forced termination follows graceful termination
	Budget         int           // applied process actions per hour
	Desktop        bool          // desktop notifications
	Protect        []string
}

Config is the resolved guardian policy. The zero value is disabled.

func FromSettings

func FromSettings(s *model.GuardianSettings) Config

FromSettings resolves configuration. Unconfigured or disabled settings resolve to mode off; enabling without a mode selects act.

func (Config) Defaults

func (c Config) Defaults() Config

Defaults fills unset fields for the role.

func (Config) Validate

func (c Config) Validate() error

type Contact

type Contact struct {
	ID, Adapter, CWD string
}

Contact is a registered agent the guardian may ask to reduce its work.

type Decision

type Decision struct {
	Step, Resource, Level, Incident string
	Group                           *Candidate
	Targets                         []Process
	Execute                         bool
	Reason                          string
	Usage                           string
	Outcome                         string // preset for skipped decisions
	Undoes                          string // revert of this action
	Extends                         string // adds new group members to this action
}

Decision is one planned step. The runtime executes it when Execute is set and records it either way.

type Engine

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

Engine is the pure, single-threaded guardian decision core. It performs no I/O; the runtime supplies observations and reports applied actions.

func NewEngine

func NewEngine(cfg Config) *Engine

func (*Engine) ActiveIDs

func (e *Engine) ActiveIDs() []string

ActiveIDs lists all active reversible action IDs.

func (*Engine) ActiveSteps

func (e *Engine) ActiveSteps(group string) []string

ActiveSteps lists active reversible steps for a group.

func (*Engine) Adopt

func (e *Engine) Adopt(id, step, group string, at time.Time, targets []model.ProcessIdentity)

Adopt registers a recovered action whose revert failed, so maintenance retries it.

func (*Engine) Applied

func (e *Engine) Applied(id string, d Decision, at time.Time, targets []model.ProcessIdentity)

Applied registers a reversible action so recovery can undo it.

func (*Engine) BudgetUsed

func (e *Engine) BudgetUsed(now time.Time) int

func (*Engine) Incidents

func (e *Engine) Incidents() []model.GuardianIncident

func (*Engine) Prune

func (e *Engine) Prune(id string, keep []model.ProcessIdentity)

Prune replaces the identities an extension already considered.

func (*Engine) Release

func (e *Engine) Release(id string)

Release forgets a reversible action after it was reverted or abandoned.

func (*Engine) Spare

func (e *Engine) Spare(group string)

Spare excludes a group from further steps in every open incident after an operator undid an action on it.

func (*Engine) Step

func (e *Engine) Step(now time.Time, pressure model.MonitorPressure, stale, partial bool, cands []*Candidate, host Host) []Decision

Step advances incidents for one observation. Stale or unknown pressure holds every incident unchanged: unknown evidence neither escalates nor recovers.

A partial inventory may miss protected members, so it holds escalation and sticky extension but still permits recovery.

type Group

type Group struct {
	ID, Kind string
	Name     string
	UID      string
	Members  []Usage
	CPU      float64 // sum of known member rates
	Memory   uint64
	Disk     float64
	// Known reports whether any member has interval CPU evidence.
	Known bool
}

Group is a set of processes a person recognizes as one program.

func Groups

func Groups(rows []Usage) []*Group

Groups aggregates process rates. Within a process group the leader names the group; otherwise the busiest member does.

type Hooks

type Hooks struct {
	// Pressure returns the latest monitor pressure, its time, whether it
	// is stale, and host capacity.
	Pressure func() (model.MonitorPressure, time.Time, bool, Host)
	// Managed returns identities of live ARM-supervised process roots.
	Managed  func() []model.ProcessIdentity
	Contacts func() []Contact
	// Notify posts an operator inbox message.
	Notify func(body string) error
	// Ask sends a message to a registered agent contact; key identifies
	// the guardian action, so a retried delivery is not duplicated.
	Ask func(contact, key, body string) error
}

Hooks connect the runtime to the manager without an import cycle.

type Host

type Host struct {
	CPUs        int
	MemoryTotal uint64
}

Host carries capacity facts for significance thresholds.

type Inventory

type Inventory struct {
	At        time.Time
	Processes []Process
	Complete  bool
	Detail    string
}

func Collect

func Collect(ctx context.Context) Inventory

Collect enumerates host processes through bounded native interfaces. It reads names, executable paths and cgroups, not environments; command lines are read only to classify members of a known profile.

type Journal

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

Journal keeps recent actions in memory and appends each change to a bounded JSON-lines file, so reversible actions survive a restart.

func OpenJournal

func OpenJournal(path string) (*Journal, error)

func (*Journal) Get

func (j *Journal) Get(id string) (model.GuardianAction, map[string]Priority, bool)

func (*Journal) Recent

func (j *Journal) Recent(limit int) []model.GuardianAction

Recent returns actions newest first.

func (*Journal) Save

func (j *Journal) Save(a model.GuardianAction, priorities map[string]Priority) error

Save stores a new or changed action.

func (*Journal) Unreverted

func (j *Journal) Unreverted() []model.GuardianAction

Unreverted returns applied reversible actions that were never undone.

type Priority

type Priority struct {
	Background bool `json:"background,omitempty"` // Darwin PRIO_DARWIN_BG applied
	Nice       *int `json:"nice,omitempty"`       // previous nice, when changed
	IOPrio     *int `json:"ioprio,omitempty"`     // previous Linux I/O priority, when changed
}

Priority records what deprioritizing changed, so restore can undo only that. Nice values can be raised back only with privilege.

type Process

type Process struct {
	Identity   model.ProcessIdentity
	PPID       int
	Name       string
	Executable string
	Cgroup     string // Linux unified cgroup path
	CPUSeconds *float64
	Memory     *uint64 // footprint (Darwin) or resident (Linux) bytes
	DiskBytes  *uint64 // cumulative read+write bytes
	Kind       string  // profile role, such as "renderer"
	Stopped    bool    // already stopped by its owner or a debugger
}

Process is one inventory row. Counters are cumulative so two inventories give interval rates; a missing counter is unknown, not zero.

type Protection

type Protection struct {
	UID   string       // only this user's processes are eligible
	Self  map[int]bool // ARM's own PID
	Extra []string     // operator entries: names or path prefixes
}

Protection decides which processes and groups are never targets.

func (Protection) Group

func (pr Protection) Group(g *Group) string

Group returns a reason when any member is protected. A group is acted on as a whole, so one protected member protects it.

func (Protection) Process

func (pr Protection) Process(p Process) string

Process returns a reason when p must not be targeted.

type Runtime

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

func New

func New(cfg Config, home string, hooks Hooks) (*Runtime, error)

func (*Runtime) Run

func (r *Runtime) Run(ctx context.Context)

Run samples and acts until ctx ends, then reverts active reversible actions. Actions left by an earlier run are reverted first.

Recovery runs even when the guardian is off: disabling it after a crash must not leave processes frozen or deprioritized.

func (*Runtime) Status

func (r *Runtime) Status() model.GuardianStatus

Status returns the latest guardian state.

func (*Runtime) Undo

func (r *Runtime) Undo(id string) (model.GuardianAction, error)

Undo reverts one action on operator request.

type Usage

type Usage struct {
	Process
	CPUCores  *float64
	DiskRate  *float64
	Available bool
}

Usage is the interval estimate for one process between two inventories.

func Rates

func Rates(current, previous Inventory) []Usage

Rates matches processes by full identity between inventories. New processes have unknown rates; PID reuse never inherits counters.

Jump to

Keyboard shortcuts

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