Documentation
¶
Overview ¶
Package actions provides remote action execution and hook management for plexd mesh nodes.
Index ¶
- Constants
- Variables
- func DiscoverHooks(hooksDir string, logger *slog.Logger) ([]api.HookInfo, error)
- func ParseHookTimeout(timeout string) (time.Duration, error)
- type ActionReporter
- type BuiltinFunc
- func ConfigDump(provider ConfigProvider) BuiltinFunc
- func DiagnosticsCollect(reader metrics.SystemReader) BuiltinFunc
- func DiagnosticsTraceroutePeer(info NodeInfoProvider) BuiltinFunc
- func GatherInfo(info NodeInfoProvider) BuiltinFunc
- func HealthCheck(health HealthProvider) BuiltinFunc
- func LogsSnapshot(provider LogProvider) BuiltinFunc
- func MeshReconnect(reconnector MeshReconnector) BuiltinFunc
- func PingPeer(info NodeInfoProvider) BuiltinFunc
- func ServiceReloadConfig() BuiltinFunc
- func ServiceRestart(ctl ServiceController) BuiltinFunc
- func ServiceUpgrade(fetcher ReleaseFetcher, verifier BundleVerifier, ctl ServiceController) BuiltinFunc
- type BundleVerifier
- type Config
- type ConfigProvider
- type Dispatcher
- type Executor
- func (e *Executor) ActiveCount() int
- func (e *Executor) Cancel(executionID string) bool
- func (e *Executor) Capabilities() ([]api.ActionInfo, []api.HookInfo)
- func (e *Executor) Execute(ctx context.Context, nodeID string, entry api.NodeStateExecution) error
- func (e *Executor) FailOrphan(ctx context.Context, nodeID, executionID string) error
- func (e *Executor) IsActive(executionID string) bool
- func (e *Executor) RegisterBuiltin(name, description string, params []api.ActionParam, fn BuiltinFunc)
- func (e *Executor) RemoveRolloutHook(name string, remove func() error) error
- func (e *Executor) Resume(ctx context.Context, nodeID string, entry api.NodeStateExecution) error
- func (e *Executor) RunLocal(ctx context.Context, action string, params map[string]string) (string, string, int, error)
- func (e *Executor) SetHooks(hooks []api.HookInfo)
- func (e *Executor) SetPlexdHookRunner(r PlexdHookRunner)
- func (e *Executor) SetRolloutHooks(hooks []api.HookInfo)
- func (e *Executor) Shutdown(_ context.Context)
- func (e *Executor) SwapRolloutHook(name string, version int, checksum string, swap func() error) error
- type HealthProvider
- type HookChangeCallback
- type HookEvent
- type HookSignatureVerifier
- type HookVerifier
- type HookVersionFetcher
- type HookWatcher
- type IntegrityAlertCallback
- type LogProvider
- type MeshReconnector
- type NodeInfoProvider
- type PlexdHookResult
- type PlexdHookRun
- type PlexdHookRunner
- type ReleaseFetcher
- type RolloutInstaller
- type ServiceController
Constants ¶
const DefaultMaxActionTimeout = 10 * time.Minute
DefaultMaxActionTimeout is the default maximum duration for a single action.
const DefaultMaxConcurrent = 5
DefaultMaxConcurrent is the default maximum number of concurrent actions.
const DefaultMaxOutputBytes = 1 << 20
DefaultMaxOutputBytes is the default maximum output size per action (1 MiB).
const MaxHookTimeout = 24 * time.Hour
MaxHookTimeout is the largest timeout a sidecar can declare, the contract's 86400 seconds as a duration.
const MaxSnapshotLines = 10000
MaxSnapshotLines is the maximum number of lines that logs.snapshot will return.
Variables ¶
var DefaultHooksDir = paths.HooksDir()
DefaultHooksDir is the default directory for hook scripts. It is resolved per platform, which is why it is a var rather than a const.
var ErrActionsDisabled = errors.New("actions are disabled on this node")
ErrActionsDisabled is what RunLocal returns while actions.enabled is false.
var ErrDispatchDeferred = errors.New("actions: dispatch deferred")
ErrDispatchDeferred reports that a dispatch has not been settled: local backpressure prevented it — shutdown, a run already in flight under the same id, or a saturated concurrency slot — or a transient control-plane failure cut a callback sequence short before it resolved the execution. It is not a failure of the execution: the pull's executions block redelivers the entry, so the caller must retry it on a later cycle instead of suppressing it.
var ErrPlexdHookJobNotFound = errors.New("actions: plexd hook job not found")
ErrPlexdHookJobNotFound reports that the Job of a run is gone. On a resumed run that means the run did not survive the restart.
var ErrPlexdHookNotFound = errors.New("actions: plexd hook not found")
ErrPlexdHookNotFound reports that the PlexdHook a dispatch names does not exist. The executor reports it as unknown_action.
Functions ¶
func DiscoverHooks ¶
DiscoverHooks scans hooksDir for executable files and returns their metadata, each with Source api.HookSourceLocal. Returns an empty slice (not nil) and no error if the directory does not exist. Individual file errors (hash failures, unreadable sidecars) are logged at warn level but do not prevent discovery of other hooks.
func ParseHookTimeout ¶ added in v0.27.0
ParseHookTimeout parses a sidecar's timeout. The empty string means none declared and is checked first, because time.ParseDuration refuses it. The manifest and the run both call this, so they agree on what a usable timeout is.
Types ¶
type ActionReporter ¶
type ActionReporter interface {
ExecutionCallback(ctx context.Context, nodeID, executionID string, req api.ExecutionCallbackRequest) (*api.ExecutionCallbackResponse, error)
UploadExecutionOutput(ctx context.Context, uploadURL string, output []byte) error
}
ActionReporter abstracts control plane communication for testability.
type BuiltinFunc ¶
type BuiltinFunc func(ctx context.Context, params map[string]string) (stdout string, stderr string, exitCode int, err error)
BuiltinFunc is the signature for built-in action implementations. It receives a context (with timeout deadline) and parameters, and returns stdout, stderr, an exit code, and an optional error.
func ConfigDump ¶
func ConfigDump(provider ConfigProvider) BuiltinFunc
ConfigDump returns a BuiltinFunc that outputs the sanitized configuration.
func DiagnosticsCollect ¶
func DiagnosticsCollect(reader metrics.SystemReader) BuiltinFunc
DiagnosticsCollect returns a BuiltinFunc that collects system diagnostics and returns them as JSON. Optional parameters: "include_network" (default "true"), "include_processes" (default "true"). The reader fills "memory_total" and "load_avg" where the /proc files yield nothing, which is the case on macOS and Windows. A nil reader keeps the /proc-only behaviour. A reading or listing that the end of the context cut short makes it return the partial JSON with exit 1 and the context's error.
func DiagnosticsTraceroutePeer ¶
func DiagnosticsTraceroutePeer(info NodeInfoProvider) BuiltinFunc
DiagnosticsTraceroutePeer returns a BuiltinFunc that runs traceroute to a mesh peer. Requires a "peer_id" parameter (mesh IP). Optional "max_hops" parameter (default 15).
func GatherInfo ¶
func GatherInfo(info NodeInfoProvider) BuiltinFunc
GatherInfo returns a BuiltinFunc that collects system information and returns it as JSON. The output includes: hostname, os, arch, go_version, mesh_ip, peer_count, node_id.
func HealthCheck ¶
func HealthCheck(health HealthProvider) BuiltinFunc
HealthCheck returns a BuiltinFunc that reports the node's health status. Optional parameter: "include_peers" (default "true") — include per-peer status. Status is "healthy" if tunnel_count > 0, otherwise "degraded".
func LogsSnapshot ¶
func LogsSnapshot(provider LogProvider) BuiltinFunc
LogsSnapshot returns a BuiltinFunc that retrieves recent log lines. Accepts optional parameters:
- "lines": number of lines to return (default 100, max 10000)
- "since": duration string (e.g. "5m", "1h") to filter lines by age
func MeshReconnect ¶
func MeshReconnect(reconnector MeshReconnector) BuiltinFunc
MeshReconnect returns a BuiltinFunc that triggers mesh reconnection. On failure, returns exit code 1 with error details but no system error, unless the end of the context cut the reconnect short: that stop is returned as the error.
func PingPeer ¶
func PingPeer(info NodeInfoProvider) BuiltinFunc
PingPeer returns a BuiltinFunc that pings a mesh peer and reports latency. Requires a "peer_id" parameter (mesh IP). Optional "count" parameter (default 1).
func ServiceReloadConfig ¶
func ServiceReloadConfig() BuiltinFunc
ServiceReloadConfig returns a BuiltinFunc that sends SIGHUP to the current process to trigger a configuration reload.
func ServiceRestart ¶
func ServiceRestart(ctl ServiceController) BuiltinFunc
ServiceRestart returns a BuiltinFunc that restarts plexd through the host's service manager: systemd on Linux, launchd on macOS, the Service Control Manager on Windows.
func ServiceUpgrade ¶
func ServiceUpgrade(fetcher ReleaseFetcher, verifier BundleVerifier, ctl ServiceController) BuiltinFunc
ServiceUpgrade returns a BuiltinFunc that performs an in-place binary upgrade from the GitHub release channel.
It downloads the target release binary, verifies its SHA-256 checksum against the dispatched value, then downloads and verifies the release's Sigstore bundle against the fetched binary's digest. Only after both checks pass is the current binary made executable, replaced, and a restart triggered through the host's service manager. A release without a bundle asset (the fetch fails) or one whose bundle fails verification is refused, and the on-disk binary is left untouched.
Required parameters:
- version: target version string (e.g. "1.5.0")
- checksum: expected SHA-256 checksum of the new binary (hex-encoded, with or without "sha256:" prefix)
type BundleVerifier ¶ added in v0.2.0
BundleVerifier verifies a Sigstore bundle against an artifact digest.
type Config ¶
type Config struct {
// Enabled controls whether action execution is active.
// nil means use default (true); explicit false disables execution.
//
// The tri-state is what makes the switch usable: with a plain bool an
// operator's `enabled: false` is indistinguishable from an omitted key,
// and defaulting turns it back on. Enabled is the only switch that stops
// the control plane from running actions and hooks on the node, so it has
// to survive ApplyDefaults exactly as written.
Enabled *bool `yaml:"enabled"`
// RolloutsEnabled is the node owner's veto on hooks the control plane
// rolls out. nil means use default (true); explicit false makes plexd
// remove every rolled-out hook, fetch none, and report each version the
// pull lists as install_failed. Builtins and hand-placed hooks keep
// working either way.
//
// It is a tri-state for the reason Enabled is: an operator who writes
// `rollouts_enabled: false` refuses scripts delivered by the control
// plane, and defaulting must not turn that refusal back into consent.
RolloutsEnabled *bool `yaml:"rollouts_enabled"`
// HooksDir is the directory containing hook scripts.
// Default: paths.HooksDir()
HooksDir string `yaml:"hooks_dir"`
// RolloutHooksDir is the directory plexd installs rolled-out hooks into.
// AgentConfig.ApplyDefaults sets it to <data_dir>/hooks, which makes it
// the only source of the value. It is not a YAML key because plexd owns
// the directory and everything in it: the path derives from data_dir like
// every other file plexd persists, and pointing it at a directory an
// operator fills would hand plexd's cleanup the operator's files.
RolloutHooksDir string `yaml:"-"`
// MaxConcurrent is the maximum number of actions that can run concurrently.
// Must be at least 1 when enabled. Default: 5.
MaxConcurrent int `yaml:"max_concurrent"`
// MaxActionTimeout is the maximum duration for a single action.
// Must be at least 10s when enabled. Default: 10m.
MaxActionTimeout time.Duration `yaml:"max_action_timeout"`
// MaxOutputBytes is the maximum output size per action in bytes.
// Must be at least 1024 when enabled. Default: 1 MiB.
MaxOutputBytes int64 `yaml:"max_output_bytes"`
}
Config holds the configuration for remote action execution.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets default values for zero-valued fields.
func (*Config) IsEnabled ¶ added in v0.3.0
IsEnabled returns the effective Enabled setting: true unless explicitly set to false.
func (*Config) IsRolloutsEnabled ¶ added in v0.28.0
IsRolloutsEnabled returns the effective RolloutsEnabled setting: true unless explicitly set to false.
func (Config) MarshalYAML ¶ added in v0.3.0
MarshalYAML renders the effective Enabled and RolloutsEnabled values so a dump of the live config never reports a switch that gates remote execution as null. config.dump is what an operator reads to audit which nodes accept control-plane-driven execution and delivered scripts, and a null there reads as "unset" — which for these fields reads as off, while it means on.
type ConfigProvider ¶
type ConfigProvider interface {
DumpConfig() string
}
ConfigProvider supplies sanitized configuration for dumping.
type Dispatcher ¶ added in v0.3.0
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher consumes the executions block of the reconciliation pull and turns each entry into an execution on the Executor. The block is a delivery queue, not desired state: an entry keeps reappearing on every pull until its execution reaches a terminal status through the callback, so suppressing the re-observations is the node's job.
The one thing a re-observation can still carry is a cancel request, set on the entry of a run in flight. It is forwarded to the executor while the block's ids are collected, ahead of the settled check and of the budget: the run's id sits in handled, so the pass itself never reads that entry again, and a pass that spends its budget must not hold back a stop.
A Dispatcher is not safe for concurrent use. Handle is invoked only from the reconcile goroutine, one cycle at a time, so handled needs no mutex.
func NewDispatcher ¶ added in v0.3.0
func NewDispatcher(executor *Executor, nodeID string, logger *slog.Logger) *Dispatcher
NewDispatcher creates a Dispatcher that dispatches the pull's executions block through executor on behalf of nodeID.
func (*Dispatcher) Handle ¶ added in v0.3.0
func (d *Dispatcher) Handle(ctx context.Context, desired *api.NodeStateSnapshot)
Handle dispatches every entry of the snapshot's executions block, in block order. Its signature matches reconcile.DispatchHandler.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor orchestrates action execution, concurrency control, and result reporting.
func NewExecutor ¶
func NewExecutor(cfg Config, reporter ActionReporter, verifier HookVerifier, logger *slog.Logger) *Executor
NewExecutor creates an Executor with the given configuration, reporter, verifier, and logger.
func (*Executor) ActiveCount ¶
ActiveCount returns the number of currently running actions.
func (*Executor) Cancel ¶ added in v0.27.0
Cancel stops the run of one execution the way Shutdown stops all of them: it cancels the run's action context, which kills a hook's process group and ends a built-in that watches its context. It reports whether this executor held a run under executionID. An empty or unknown id does nothing and reports false. A second call for the same run does nothing more, because a cancel function is idempotent. Unlike Shutdown it leaves shuttingDown alone, so other dispatches go on.
The run still sends its own terminal report. A run whose result is already computed when Cancel lands reports its real outcome, because that report leg runs on a context detached from the action's.
Cancel records the id in cancelRequested before it ends the context, so a PlexdHook run that sees its context end knows it was cancelled, not shut down, and deletes its Job.
func (*Executor) Capabilities ¶
func (e *Executor) Capabilities() ([]api.ActionInfo, []api.HookInfo)
Capabilities returns builtin action metadata and hooks for capability reporting. The actions are sorted by name, so the inventory reads the same on every call whatever order the builtins map ranges in; each action's parameters keep the order they were registered in.
func (*Executor) Execute ¶
Execute is the main entry point for action execution. It returns ErrDispatchDeferred when the execution is left unresolved — local backpressure, or a transient control-plane failure during the claim handshake or a rejection walk — and nil once the run has been accepted or the execution settled with a callback.
func (*Executor) FailOrphan ¶ added in v0.3.0
FailOrphan reports an execution the control plane still holds at started but whose run this agent no longer owns — the process restarted mid-run. Actions are not idempotent, so the run is not repeated; started → failed is a legal edge, so the single terminal callback settles the execution. The report runs under its own deadline so an unreachable control plane cannot pin a reconciliation cycle open.
It returns ErrDispatchDeferred when the report was not delivered. That leaves the execution exactly where it was — at started, with no terminal recorded — so the caller must let the next pull redeliver the entry rather than treat it as settled.
func (*Executor) IsActive ¶ added in v0.3.0
IsActive reports whether this executor is running the given execution right now. It is the authoritative answer to "did this agent lose that run?", which a caller tracking dispatches by id cannot answer on its own.
func (*Executor) RegisterBuiltin ¶
func (e *Executor) RegisterBuiltin(name, description string, params []api.ActionParam, fn BuiltinFunc)
RegisterBuiltin stores a builtin action for execution.
func (*Executor) RemoveRolloutHook ¶ added in v0.28.0
RemoveRolloutHook runs remove, which deletes the files of the rolled-out hook name, and then drops its pin, which takes it out of the merged list. A nil remove drops the pin alone. It holds swapMu like SwapRolloutHook, so a run that already passed verification keeps its started process, and a later dispatch is rejected as unknown_action.
When remove fails, its error is returned and the pin and the merged list stay as they were.
func (*Executor) Resume ¶ added in v0.32.0
Resume follows the run of a plexd_hook entry the control plane holds at started, which an earlier agent process claimed. Its Job outlived that process, so the run is not lost: Resume takes an active slot for it and waits for the Job the way the original run would have. It sends no claim callback, because the entry is already at started. A Job that is gone is reported as an execution lost to an agent restart.
It returns errNotResumable when the entry is not a plexd_hook entry or no runner is set, ErrDispatchDeferred under the backpressure Execute defers on, and nil once the run is going.
func (*Executor) RunLocal ¶
func (e *Executor) RunLocal(ctx context.Context, action string, params map[string]string) (string, string, int, error)
RunLocal executes a built-in action synchronously and returns the output. This is used by the local node API for CLI-triggered action execution. Only built-in actions are supported: hooks are arbitrary operator scripts, and dispatch from the pull's executions block is the only path the control plane authorizes server-side. It refuses every run while actions.enabled is false, as the dispatcher refuses every dispatch.
func (*Executor) SetHooks ¶
SetHooks sets the snapshot of hooks_dir, the hand-placed hooks, and pins the integrity anchor of every hook this process has not seen before.
The snapshot itself is refreshed by HookWatcher, which re-hashes a hook on every write, so verifying an execution against the snapshot digest would compare a file with a hash of itself and pass for any bytes an attacker with write access to the hooks directory puts there. The pin is therefore recorded once, at first discovery, and never updated: a hook whose bytes change afterwards fails verification and stays unrunnable until the agent restarts and re-attests it. The pin matches the first report to the control plane only. Later reports carry the digest the watcher last computed, which is how the control plane sees the drift.
A hand-placed hook takes precedence over a rolled-out hook of the same name, so while both exist the merged list holds the hand-placed one.
func (*Executor) SetPlexdHookRunner ¶ added in v0.32.0
func (e *Executor) SetPlexdHookRunner(r PlexdHookRunner)
SetPlexdHookRunner sets the runner plexd_hook entries run through. plexd up calls it once, before the reconciler starts, when it runs in a pod that can create Jobs, and never again. Without it the executor rejects a plexd_hook entry as unsupported_action_type, and the dispatcher reports a started one lost.
func (*Executor) SetRolloutHooks ¶ added in v0.28.0
SetRolloutHooks sets the snapshot of the rollout directory, the hooks plexd installed from versions the control plane published. It pins nothing: the pin of a rolled-out hook is the checksum the control plane delivered, which only SwapRolloutHook records. A file in the rollout directory that has no pin, a leftover or one an account other than plexd put there, therefore stays out of the merged list and cannot be dispatched.
func (*Executor) Shutdown ¶
Shutdown cancels all running actions, prevents new ones from starting, and waits for all in-flight goroutines to drain.
func (*Executor) SwapRolloutHook ¶ added in v0.28.0
func (e *Executor) SwapRolloutHook(name string, version int, checksum string, swap func() error) error
SwapRolloutHook runs swap, which replaces the files of the rolled-out hook name, and then pins name to version and checksum, the lowercase hex digest the control plane signed for that version. A nil swap pins without writing, for a hook already on disk. The swap and the pin update share swapMu with runHook's verify and start, so no dispatch sees the new bytes under the old pin or the old bytes under the new one.
The caller passes swap rather than writing before the call, because the lock has to cover the write: a dispatch between a write and the pin update would refuse the new bytes as tampered.
When swap succeeds, the entry of name in the rollout snapshot, if there is one, takes checksum along with the pin, because the bytes swap just wrote have that digest. The merged entry then moves to the new version and its checksum together, instead of pairing the new version with the old file's digest until the rollout watcher rescans, which the control plane would read as drift. The watcher's next scan confirms the digest or shows real tampering, and the entry's sidecar fields catch up at that scan. A nil swap writes nothing and changes no snapshot.
When swap fails, its error is returned and the pin and the merged list stay as they were: the previous version stays runnable, as far as the files the failed swap left behind allow.
type HealthProvider ¶
type HealthProvider interface {
TunnelCount() int
ConnectedPeers() int
Uptime() time.Duration
LastHeartbeat() time.Time
LastReconcile() time.Time
}
HealthProvider supplies health status information to built-in actions.
type HookChangeCallback ¶
HookChangeCallback is called when hooks change. Receives the full current hooks list.
type HookSignatureVerifier ¶ added in v0.28.0
HookSignatureVerifier checks the Domain signature of an envelope without a freshness window, because a hook_version envelope carries the instant the version was signed, often days before the fetch. *api.Ed25519Verifier satisfies it.
type HookVerifier ¶
type HookVerifier interface {
VerifyHook(ctx context.Context, nodeID, hookPath, expectedChecksum string) (bool, error)
}
HookVerifier abstracts hook integrity verification for testability.
type HookVersionFetcher ¶ added in v0.28.0
type HookVersionFetcher interface {
FetchHookVersion(ctx context.Context, nodeID, name string, version int) (*api.NodeHookVersion, error)
}
HookVersionFetcher fetches one published hook version. *api.ControlPlane satisfies it.
type HookWatcher ¶
type HookWatcher struct {
// contains filtered or unexported fields
}
HookWatcher monitors a hooks directory for changes using fsnotify.
func NewHookWatcher ¶
func NewHookWatcher(hooksDir string, onChange HookChangeCallback, onIntegrity IntegrityAlertCallback, logger *slog.Logger) *HookWatcher
NewHookWatcher creates a HookWatcher for hooksDir, the directory of hand-placed hooks. Every hook it reports has Source api.HookSourceLocal.
func NewRolloutHookWatcher ¶ added in v0.28.0
func NewRolloutHookWatcher(dir string, onChange HookChangeCallback, onIntegrity IntegrityAlertCallback, logger *slog.Logger) *HookWatcher
NewRolloutHookWatcher creates a HookWatcher for dir, the directory plexd installs rolled-out hooks into. Every hook it reports has Source api.HookSourceRollout. It works like the watcher NewHookWatcher builds for hooks_dir, so a write in the rollout directory reaches the executor and the capability manifest the way a write in hooks_dir does.
func (*HookWatcher) Hooks ¶
func (w *HookWatcher) Hooks() []api.HookInfo
Hooks returns a sorted snapshot of the current hooks.
func (*HookWatcher) Reload ¶ added in v0.25.0
func (w *HookWatcher) Reload() ([]api.HookInfo, error)
Reload re-scans the hooks directory, replaces the list with the result and returns it. It reports through the same callbacks as a file event: onIntegrity once per hook whose digest changed, then onChange. It works with or without Watch running.
A missing directory is an empty list. Any other failure to read the directory is returned, with the list left as it was and no callback fired.
type IntegrityAlertCallback ¶
type IntegrityAlertCallback func(hookName, oldChecksum, newChecksum string)
IntegrityAlertCallback is called when a hook file's checksum changes unexpectedly.
type LogProvider ¶
LogProvider supplies recent log lines.
type MeshReconnector ¶
MeshReconnector triggers mesh reconnection.
type NodeInfoProvider ¶
NodeInfoProvider supplies mesh node information to built-in actions.
type PlexdHookResult ¶ added in v0.32.0
type PlexdHookResult struct {
Succeeded bool
// ExitCode is the hook container's exit code; nil when it never terminated.
ExitCode *int
TimedOut bool
// Reason says why a run without an exit code failed.
Reason string
// Output is the pod's log.
Output string
}
PlexdHookResult is the outcome of a run the runner followed to its end.
type PlexdHookRun ¶ added in v0.32.0
type PlexdHookRun struct {
ExecutionID string
// Hook is the PlexdHook's metadata.name: the entry's action.
Hook string
// Parameters are the dispatch's parameters, through flattenParams. It is
// never nil.
Parameters map[string]string
// Deadline is the run's bound, as runBound computed it.
Deadline time.Duration
}
PlexdHookRun is what the executor hands a PlexdHookRunner to start one run of a dispatched PlexdHook.
type PlexdHookRunner ¶ added in v0.32.0
type PlexdHookRunner interface {
// Start creates the run's Job. A Job that already exists is not an error.
Start(ctx context.Context, run PlexdHookRun) error
// Wait returns once the Job is over, or deletes it when bound runs out.
Wait(ctx context.Context, executionID string, bound time.Duration) (PlexdHookResult, error)
// Stop reads the log so far and deletes the Job.
Stop(ctx context.Context, executionID string) (output string, err error)
}
PlexdHookRunner runs a dispatched PlexdHook outside the agent's process. The executor runs a plexd_hook entry through it, and only when one is set: a plexd outside a cluster has none and rejects the entry as unsupported_action_type. Every method addresses the run by its execution id.
type ReleaseFetcher ¶ added in v0.2.0
type ReleaseFetcher interface {
FetchBinary(ctx context.Context, version string) (io.ReadCloser, error)
FetchBundle(ctx context.Context, version string) ([]byte, error)
}
ReleaseFetcher downloads plexd release assets for a version.
type RolloutInstaller ¶ added in v0.28.0
type RolloutInstaller struct {
// contains filtered or unexported fields
}
RolloutInstaller converges the rollout directory on the hooks block of the state pull. For each listed version it fetches the signed version, verifies it against the Domain key and the checksum the pull delivered, and installs it atomically, pinned to that checksum. It removes the rolled-out hooks the block no longer lists, and reports what it could not install as hook_rollout_errors for the capability manifest.
It owns the rollout directory and everything in it: Load removes files it did not write. It compares the pull with its own record of what it installed, never with the bytes on disk, so a rolled-out file edited after install stays refused at dispatch until a new version or a withdrawal replaces it, or until the edited file is deleted: a recorded hook whose script is gone counts as not installed, and the next pass fetches it again.
Handle runs on the reconcile goroutine and only hands the block over. Run does the work on its own goroutine, so a slow fetch never holds back the rest of the reconcile cycle.
func NewRolloutInstaller ¶ added in v0.28.0
func NewRolloutInstaller(cfg Config, dataDir, nodeID string, fetcher HookVersionFetcher, verifier HookSignatureVerifier, executor *Executor, logger *slog.Logger) (*RolloutInstaller, error)
NewRolloutInstaller returns an installer for cfg.RolloutHooksDir that keeps its record in dataDir, fetches versions for nodeID with fetcher, checks their signatures with verifier, and pins what it installs in executor.
It refuses a rollout directory that is hooks_dir under any spelling, a relative path or a symlink included, because the installer removes every file it did not write from its directory, which there would be the operator's hand-placed hooks.
func (*RolloutInstaller) Errors ¶ added in v0.28.0
func (r *RolloutInstaller) Errors() []api.HookRolloutError
Errors returns the rollout errors of the last pass, sorted by name and at most api.MaxHookRolloutErrors, or nil when there are none. The slice is a copy.
func (*RolloutInstaller) Handle ¶ added in v0.28.0
func (r *RolloutInstaller) Handle(_ context.Context, desired *api.NodeStateSnapshot)
Handle is a reconcile.DispatchHandler. It hands the hooks block of a successful pull to Run and returns at once, because the dispatch handlers run one after another inside the reconcile cycle and a fetch here would hold back the executions block. A nil block, from a control plane that could not compute the set this time, changes nothing: no pass runs and the rollout errors stay as they were.
func (*RolloutInstaller) Load ¶ added in v0.28.0
func (r *RolloutInstaller) Load() error
Load restores what the installer put into the rollout directory before this process started. It runs once, before the first scan of the rollout directory, so the scan finds only files the record vouches for, each already pinned.
A missing record is an empty one, and so is a corrupt one, which is logged. An entry whose script is gone is dropped. Every surviving entry is pinned to its recorded checksum, and every other file in the directory is removed, which covers the temporary files of a write a crash interrupted. With rollouts disabled it removes every file in the directory and saves an empty record instead. On Windows, where script hooks do not run, it does nothing.
It returns an error when the rollout directory cannot be created or read. Every later pass tries again.
func (*RolloutInstaller) Run ¶ added in v0.28.0
func (r *RolloutInstaller) Run(ctx context.Context) error
Run runs one pass per signal from Handle, always on the newest block handed over, so blocks that arrive while a pass runs collapse into the next one. It returns nil when ctx ends.
func (*RolloutInstaller) SetOnChange ¶ added in v0.28.0
func (r *RolloutInstaller) SetOnChange(fn func())
SetOnChange registers fn, called after every pass that changed the set of installed hooks or the rollout errors, so the caller can rescan the rollout directory and report the manifest again. fn runs on Run's goroutine.