Documentation
¶
Overview ¶
Package agentcfg stores and serves agent remote-configuration revisions (append-only overlays per agent) and the agent instances that report against them.
Index ¶
- Constants
- Variables
- func DeleteInstancesForAgent(tx *gorm.DB, agentID uuid.UUID) error
- func DeleteRevisionsForAgent(tx *gorm.DB, agentID uuid.UUID) error
- func DeriveStatus(i relational.AgentInstance, desired int64) string
- func DeriveSyncStatus(i relational.AgentInstance, desired int64) string
- func IsStale(i relational.AgentInstance, now time.Time, s Settings) bool
- func PruneInstances(ctx context.Context, db *gorm.DB, s Settings, now time.Time) (int64, error)
- type CreateRevisionParams
- type InstanceBase
- type InstanceCounts
- type PreviewSet
- type RevisionConflictError
- type RevisionHead
- type RevisionMeta
- type Service
- func (s *Service) CountInstances(ctx context.Context, agentID uuid.UUID, desired int64, now time.Time) (InstanceCounts, error)
- func (s *Service) CreateRevision(ctx context.Context, p CreateRevisionParams) (*relational.AgentConfigRevision, error)
- func (s *Service) Current(ctx context.Context, agentID uuid.UUID) (*relational.AgentConfigRevision, error)
- func (s *Service) CurrentHead(ctx context.Context, agentID uuid.UUID) (*RevisionHead, error)
- func (s *Service) CurrentRevisionNumber(ctx context.Context, agentID uuid.UUID) (int64, error)
- func (s *Service) GetInstance(ctx context.Context, agentID, instanceID uuid.UUID) (*relational.AgentInstance, error)
- func (s *Service) GetRevision(ctx context.Context, agentID uuid.UUID, rev int64) (*relational.AgentConfigRevision, error)
- func (s *Service) ListInstances(ctx context.Context, agentID uuid.UUID, p service.PaginationParams) ([]relational.AgentInstance, int64, error)
- func (s *Service) ListRevisions(ctx context.Context, agentID uuid.UUID, p service.PaginationParams) ([]RevisionMeta, int64, error)
- func (s *Service) Now() time.Time
- func (s *Service) PreviewBases(ctx context.Context, agentID uuid.UUID) (PreviewSet, error)
- func (s *Service) SetClock(now func() time.Time)
- func (s *Service) Settings() Settings
- func (s *Service) TouchFromHeartbeat(ctx context.Context, agentID uuid.UUID, credentialID *uuid.UUID, ...) error
- func (s *Service) UpsertReport(ctx context.Context, agentID uuid.UUID, credentialID *uuid.UUID, ...) error
- func (s *Service) ValidationBases(ctx context.Context, agentID uuid.UUID) ([]InstanceBase, bool, error)
- type Settings
Constants ¶
const ( PreviewMaxInstances = 50 PreviewMaxConfigBytes = 16 << 20 )
Preview bounds (R14): a preview shows at most PreviewMaxInstances instances and decodes at most PreviewMaxConfigBytes of reported base+effective config, so one agent credential cannot make a single preview cost minutes of CPU by reporting many large instances.
const ( SyncInSync = "in-sync" SyncOutOfSync = "out-of-sync" SyncNotApplicable = "not-applicable" SyncUnknown = "unknown" )
Sync statuses.
const InstancesPageLimit = 25
InstancesPageLimit is the default and the maximum page size of ListInstances. A listed instance's summary columns are bounded only by the report handler (normalizeReport): every free-text field has a byte cap, and the summary fields as a whole are cut to 3 MiB once JSON-encoded with HTML escaping, as the instance list encodes them (maxReportSummaryEncodedBytes; a plain-text report at every cap is about 2.9 MB and is never cut). So a page encodes to about 75 MiB at most, whatever the agent's instance count (up to MaxInstancesPerAgent non-prunable instances plus the prune-eligible ones PruneInstances has not deleted yet) and whatever the reports contain.
Variables ¶
var ( // ErrNotFound is returned when the agent, revision or instance does not exist. ErrNotFound = errors.New("not found") // ErrRevisionConflict is returned (wrapped in *RevisionConflictError) when the expected // revision is not the current one. ErrRevisionConflict = errors.New("configuration revision conflict") // ErrInstanceLimit is returned when a new instance would exceed the per-agent cap. ErrInstanceLimit = errors.New("instance limit reached") )
Functions ¶
func DeleteInstancesForAgent ¶
DeleteInstancesForAgent removes every instance of an agent (agent deletion).
func DeleteRevisionsForAgent ¶
DeleteRevisionsForAgent removes every configuration revision of an agent (agent deletion). It is the purge path for an overlay that held a secret, so it bypasses the append-only BeforeDelete hook, which still blocks every other delete of a revision.
func DeriveStatus ¶
func DeriveStatus(i relational.AgentInstance, desired int64) string
DeriveStatus returns the displayed status of an instance (R10): unknown when it never reported; the reported status in report/off mode; pending when an apply-mode instance is behind the desired revision and has not attempted it yet; otherwise the reported status.
func DeriveSyncStatus ¶
func DeriveSyncStatus(i relational.AgentInstance, desired int64) string
DeriveSyncStatus: report/off => not-applicable; never reported => unknown; COALESCE(applied,0) == desired => in-sync; else out-of-sync.
func IsStale ¶
func IsStale(i relational.AgentInstance, now time.Time, s Settings) bool
IsStale reports whether an instance was last seen before now - InstanceStaleAfter.
Types ¶
type CreateRevisionParams ¶
type CreateRevisionParams struct {
AgentID uuid.UUID
ExpectedRevision int64
Overlay json.RawMessage
Comment *string
CreatedBy string
CreatedByID *uuid.UUID
RevertOf *int64
}
CreateRevisionParams are the inputs of CreateRevision.
type InstanceBase ¶
type InstanceBase struct {
Instance relational.AgentInstance
Base agentconfig.Config
Remote agentconfig.RemoteConfig // reported remote-config, or the base's block normalized with hasAuth=true
Stale bool
Validated bool // member of ValidationBases (R48)
// BaseKey identifies the content of the reported base (set by ValidationBases only):
// instances with the same BaseKey share one decoded Base, so a caller validates it once.
// Base is shared, not copied: treat it as read-only.
BaseKey string
}
InstanceBase is a reported base an overlay is validated or previewed against.
type InstanceCounts ¶
type InstanceCounts struct {
Total int
Fresh int
Stale int
InSync int
OutOfSync int
Pending int
Rejected int
Failed int
Unknown int
}
InstanceCounts are the counts of an agent's instances by derived state.
type PreviewSet ¶
type PreviewSet struct {
// Validated is the size of the ValidationBases set, the instances a save validates
// against (R48). Their configs are not loaded: preview only shows them.
Validated int
// Instances are the instances the preview shows, each marked Validated when it is in
// the validation set: the validated ones first, then the others, newest first, within
// PreviewMaxInstances and PreviewMaxConfigBytes.
Instances []InstanceBase
// Omitted counts the instances with a reported base the bounds left out.
Omitted int64
}
PreviewSet is what a preview works on.
type RevisionConflictError ¶
type RevisionConflictError struct {
Current int64
}
RevisionConflictError carries the current revision of a failed CreateRevision.
func (*RevisionConflictError) Error ¶
func (e *RevisionConflictError) Error() string
func (*RevisionConflictError) Is ¶
func (e *RevisionConflictError) Is(target error) bool
Is makes errors.Is(err, ErrRevisionConflict) true.
type RevisionHead ¶
RevisionHead identifies a revision without loading its overlay.
type RevisionMeta ¶
type RevisionMeta struct {
ID uuid.UUID
AgentID uuid.UUID
Revision int64
CreatedAt time.Time
Comment *string
CreatedBy string
CreatedByID *uuid.UUID
RevertOf *int64
OverlaySize int // bytes of the stored overlay's text form
}
RevisionMeta is a revision without its overlay (list views, R12).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the agent remote-configuration store.
func NewService ¶
NewService builds a Service. Zero settings take the defaults; a nil logger is a no-op.
func (*Service) CountInstances ¶
func (s *Service) CountInstances(ctx context.Context, agentID uuid.UUID, desired int64, now time.Time) (InstanceCounts, error)
CountInstances counts all of an agent's instances by freshness (IsStale at now), sync status (DeriveSyncStatus) and status (DeriveStatus) against the desired revision. It loads only the scalar columns those read (no JSON column), so its cost does not depend on what the instances reported, and the counts cover every instance, not one ListInstances page.
func (*Service) CreateRevision ¶
func (s *Service) CreateRevision(ctx context.Context, p CreateRevisionParams) (*relational.AgentConfigRevision, error)
CreateRevision appends revision ExpectedRevision+1 in one transaction: it locks the agent row, re-reads the current revision and fails with *RevisionConflictError when it is not ExpectedRevision. The agent row lock serializes writers, so the insert cannot hit the unique (agent_id, revision) index; any insert error is returned as is. The returned row is read back after the insert, so its Overlay bytes are the stored form GetRevision and ListRevisions (overlay size) see.
func (*Service) Current ¶
func (s *Service) Current(ctx context.Context, agentID uuid.UUID) (*relational.AgentConfigRevision, error)
Current returns the latest revision of an agent, or nil (revision 0) when none exists.
func (*Service) CurrentHead ¶
CurrentHead returns the id, revision and creation time of an agent's latest revision, or nil (revision 0) when none exists. It is Current's indexed query without the overlay, so an agent poll can compute its ETag (and answer 304) without reading the overlay.
func (*Service) CurrentRevisionNumber ¶
CurrentRevisionNumber returns the latest revision number, 0 when none exists.
func (*Service) GetInstance ¶
func (s *Service) GetInstance(ctx context.Context, agentID, instanceID uuid.UUID) (*relational.AgentInstance, error)
GetInstance returns one instance of an agent (all columns) or ErrNotFound.
func (*Service) GetRevision ¶
func (s *Service) GetRevision(ctx context.Context, agentID uuid.UUID, rev int64) (*relational.AgentConfigRevision, error)
GetRevision returns one revision or ErrNotFound.
func (*Service) ListInstances ¶
func (s *Service) ListInstances(ctx context.Context, agentID uuid.UUID, p service.PaginationParams) ([]relational.AgentInstance, int64, error)
ListInstances returns one page of an agent's instances, most recently seen first (last_seen_at DESC, instance_id), without the heavy base/effective columns, and the total number of the agent's instances. p.Limit is capped at InstancesPageLimit (a zero or negative limit means InstancesPageLimit), so a page's cost is bounded by the per-instance bound above. Fleet-wide counts come from CountInstances, which loads no JSON column.
func (*Service) ListRevisions ¶
func (s *Service) ListRevisions(ctx context.Context, agentID uuid.UUID, p service.PaginationParams) ([]RevisionMeta, int64, error)
ListRevisions returns one page of revisions, newest first, and the total count.
func (*Service) PreviewBases ¶
PreviewBases returns the size of the validation set and the bounded list of instances with a reported base (fresh and stale, flagged) a preview shows. Only the selected instances' configs are loaded; the validation set is read as instance ids only, so the cost stays within PreviewMaxInstances and PreviewMaxConfigBytes however many instances validate.
func (*Service) TouchFromHeartbeat ¶
func (s *Service) TouchFromHeartbeat(ctx context.Context, agentID uuid.UUID, credentialID *uuid.UUID, instanceID uuid.UUID, rev *int64, digest *string) error
TouchFromHeartbeat records an authenticated heartbeat (R11). With a digest it upserts only last_seen_at, credential_id and the heartbeat_* columns (a new row keeps an empty reported status; over the cap it is silently skipped, with a warning at most once per agent per capReachedTTL, and for capReachedTTL after the cap was found reached a new instance skips the cap check altogether). Without a digest (an old agent, or mode off) it only updates last_seen_at of an existing row and never inserts, so old agents' per-reload random instance ids never flood the table.
func (*Service) UpsertReport ¶
func (s *Service) UpsertReport(ctx context.Context, agentID uuid.UUID, credentialID *uuid.UUID, instanceID uuid.UUID, r agentconfig.Report) error
UpsertReport stores a (validated, re-redacted) config report. A new instance at the per-agent cap replaces the oldest stale instance, or fails with ErrInstanceLimit when every counted instance is fresh; prune-eligible rows do not count (R37).
func (*Service) ValidationBases ¶
func (s *Service) ValidationBases(ctx context.Context, agentID uuid.UUID) ([]InstanceBase, bool, error)
ValidationBases is exactly the set PUT and revert validate against (R14, R48):
- all fresh instances (seen within InstanceStaleAfter) with a reported base and an apply mode;
- else the single most recently reported instance with a base and an apply mode, whatever its age;
- else none, and standalone=true (overlay-level checks only).
Report-mode instances and instances without a base are never validated against. A base that no longer decodes is skipped with a warning.
The cost follows the distinct bases, not the instance count: the set is grouped by base content in SQL (BaseKey), and each distinct base is loaded and decoded once and shared by every instance of its group (instances of one fleet usually report the same base). Both reads run in one read-only repeatable-read transaction, so the groups and the loaded bases are one snapshot.
type Settings ¶
type Settings struct {
InstanceStaleAfter time.Duration // fresh <=> last_seen_at >= now - InstanceStaleAfter
InstanceRetention time.Duration // daemon (or unknown) instances
OneShotInstanceRetention time.Duration // daemon=false instances (R37)
MaxInstancesPerAgent int // non-prunable instances per agent; the oldest stale one is replaced when full
}
Settings tunes instance freshness, retention and the per-agent instance cap.
func SettingsFromConfig ¶
SettingsFromConfig maps the CCF_AGENT_* config onto Settings (nil config or nil Agents => defaults).
func (Settings) WithDefaults ¶
WithDefaults fills zero or negative values with config.DefaultAgentsConfig (R37, R14), the single source of the defaults.