resource

package
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const HostSampleTTL = 35 * time.Second

HostSampleTTL bounds how long a remote agent's host sample is considered fresh. Beyond it the host is reported with no current metrics (the agent has likely disconnected). Three sample intervals of slack.

Variables

This section is empty.

Functions

func IsHostSampleFresh added in v1.3.0

func IsHostSampleFresh(sample *HostSample, now time.Time) bool

IsHostSampleFresh reports whether a host sample is recent enough to trust.

Types

type AlertState

type AlertState string

AlertState represents the current alerting state for a container's resources.

const (
	AlertStateNormal AlertState = "normal"
	AlertStateCPU    AlertState = "cpu_alert"
	AlertStateMemory AlertState = "mem_alert"
	AlertStateBoth   AlertState = "both_alert"
)

type Collector

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

Collector periodically collects resource stats from the active runtime.

func NewCollector

func NewCollector(rt runtime.Runtime, containerSvc *container.Service, logger *slog.Logger) *Collector

NewCollector creates a resource stats collector.

func (*Collector) GetAllLatest

func (c *Collector) GetAllLatest() map[string]*ResourceSnapshot

GetAllLatest returns the latest snapshots for all containers.

func (*Collector) GetHostStat added in v1.0.1

func (c *Collector) GetHostStat() *HostStatReader

GetHostStat returns the host stat reader for CPU and memory.

func (*Collector) GetLatestSnapshot

func (c *Collector) GetLatestSnapshot(containerID string) *ResourceSnapshot

GetLatestSnapshot returns the most recent in-memory snapshot for a container.

func (*Collector) SetInterval

func (c *Collector) SetInterval(d time.Duration)

SetInterval overrides the default collection interval.

func (*Collector) SetOnSnapshot

func (c *Collector) SetOnSnapshot(fn func(snap *ResourceSnapshot))

SetOnSnapshot sets the callback invoked for each computed snapshot.

func (*Collector) Start

func (c *Collector) Start(ctx context.Context)

Start begins the collection ticker. Blocks until ctx is cancelled.

type Deps added in v1.1.0

type Deps struct {
	Store         ResourceStore      // required
	Runtime       runtime.Runtime    // required
	ContainerSvc  *container.Service // required
	Logger        *slog.Logger       // required
	EventCallback EventCallback      // optional — nil-safe
}

Deps holds all dependencies for the resource Service.

type EventCallback

type EventCallback func(eventType string, data interface{})

EventCallback is the function signature for SSE event broadcasting.

type Granularity

type Granularity string

Granularity defines the time-bucket size for aggregated queries.

const (
	GranularityRaw Granularity = "raw"
	Granularity1m  Granularity = "1m"
	Granularity5m  Granularity = "5m"
	Granularity1h  Granularity = "1h"
)

type HostSample added in v1.3.0

type HostSample struct {
	AgentID    string    `json:"agent_id"`
	CPUPercent float64   `json:"cpu_percent"`
	MemUsed    int64     `json:"mem_used"`
	MemTotal   int64     `json:"mem_total"`
	DiskTotal  uint64    `json:"disk_total"`
	DiskUsed   uint64    `json:"disk_used"`
	Timestamp  time.Time `json:"timestamp"`
}

HostSample is the latest host-level resource measurement for a single host: the local server (AgentID == "") or a remote agent's machine. CPU is a percentage 0-100; memory and disk are bytes for the root filesystem.

type HostStatReader added in v1.0.1

type HostStatReader = hoststat.Reader

HostStatReader samples host CPU and memory via /proc. The implementation lives in the dependency-free internal/hoststat package so the remote agent collector can reuse it without importing this package.

func NewHostStatReader added in v1.0.1

func NewHostStatReader() *HostStatReader

NewHostStatReader creates a host stat reader and takes an initial sample.

type ResourceAlertConfig

type ResourceAlertConfig struct {
	ID                     string     `json:"id"`
	ContainerID            string     `json:"container_id"`
	CPUThreshold           float64    `json:"cpu_threshold"`
	MemThreshold           float64    `json:"mem_threshold"`
	Enabled                bool       `json:"enabled"`
	AlertState             AlertState `json:"alert_state"`
	CPUConsecutiveBreaches int        `json:"cpu_consecutive_breaches"`
	MemConsecutiveBreaches int        `json:"mem_consecutive_breaches"`
	LastAlertedAt          *time.Time `json:"last_alerted_at"`
	CreatedAt              time.Time  `json:"created_at"`
	UpdatedAt              time.Time  `json:"updated_at"`
}

ResourceAlertConfig holds per-container resource alert thresholds.

type ResourceSnapshot

type ResourceSnapshot struct {
	ID              string    `json:"id"`
	ContainerID     string    `json:"container_id"`
	CPUPercent      float64   `json:"cpu_percent"`
	MemUsed         int64     `json:"mem_used"`
	MemLimit        int64     `json:"mem_limit"`
	NetRxBytes      int64     `json:"net_rx_bytes"`
	NetTxBytes      int64     `json:"net_tx_bytes"`
	BlockReadBytes  int64     `json:"block_read_bytes"`
	BlockWriteBytes int64     `json:"block_write_bytes"`
	Timestamp       time.Time `json:"timestamp"`
	AgentID         string    `json:"agent_id"`
}

ResourceSnapshot is a point-in-time measurement of a container's resource usage.

type ResourceStore

type ResourceStore interface {
	InsertSnapshot(ctx context.Context, s *ResourceSnapshot) (string, error)
	GetLatestSnapshot(ctx context.Context, containerID string) (*ResourceSnapshot, error)
	ListSnapshots(ctx context.Context, containerID string, from, to time.Time) ([]*ResourceSnapshot, error)
	ListSnapshotsAggregated(ctx context.Context, containerID string, from, to time.Time, granularity Granularity) ([]*ResourceSnapshot, error)

	GetAlertConfig(ctx context.Context, containerID string) (*ResourceAlertConfig, error)
	UpsertAlertConfig(ctx context.Context, cfg *ResourceAlertConfig) error

	DeleteSnapshotsBefore(ctx context.Context, before time.Time, batchSize int) (int64, error)

	InsertHourlyRollup(ctx context.Context, r *RollupRow) error
	InsertDailyRollup(ctx context.Context, r *RollupRow) error
	AggregateHourlyRollup(ctx context.Context, bucketStart, bucketEnd time.Time) error
	AggregateDailyRollup(ctx context.Context, bucketStart, bucketEnd time.Time) error
	GetTopConsumersByPeriod(ctx context.Context, metric string, period string, limit int, agentID *string) ([]TopConsumerRow, error)
	DeleteHourlyBefore(ctx context.Context, before time.Time, batchSize int) (int64, error)
	DeleteDailyBefore(ctx context.Context, before time.Time, batchSize int) (int64, error)
}

ResourceStore defines the persistence interface for resource monitoring data.

type RollupRow

type RollupRow struct {
	ContainerID   string
	Bucket        time.Time
	AvgCPUPercent float64
	AvgMemUsed    int64
	AvgMemLimit   int64
	AvgNetRx      int64
	AvgNetTx      int64
	SampleCount   int
}

RollupRow represents an aggregated resource measurement for a time bucket.

type Service

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

Service orchestrates resource collection, persistence, and alerting.

func NewService

func NewService(d Deps) *Service

NewService creates a resource monitoring service.

func (*Service) GetAlertConfig

func (s *Service) GetAlertConfig(ctx context.Context, containerID string) (*ResourceAlertConfig, error)

GetAlertConfig returns the alert configuration for a container.

func (*Service) GetAllLatestSnapshots

func (s *Service) GetAllLatestSnapshots() map[string]*ResourceSnapshot

GetAllLatestSnapshots returns the latest snapshots for all containers.

func (*Service) GetContainerName

func (s *Service) GetContainerName(containerID string) string

GetContainerName resolves a container ID to its name via the container service.

func (*Service) GetCurrentSnapshot

func (s *Service) GetCurrentSnapshot(containerID string) *ResourceSnapshot

GetCurrentSnapshot returns the latest in-memory snapshot for a container.

func (*Service) GetHistory

func (s *Service) GetHistory(ctx context.Context, containerID string, timeRange string) ([]*ResourceSnapshot, Granularity, error)

GetHistory returns historical resource snapshots for charting.

func (*Service) GetHostStat added in v1.0.1

func (s *Service) GetHostStat() *HostStatReader

GetHostStat returns the host stat reader for CPU and memory.

func (*Service) GetTopConsumersByPeriod

func (s *Service) GetTopConsumersByPeriod(ctx context.Context, metric, period string, limit int, agentID *string) ([]TopConsumerRow, error)

GetTopConsumersByPeriod returns the top resource consumers averaged over a period. agentID filters by host: nil = all hosts, *agentID == "" = the local server, *agentID == id = that agent.

func (*Service) HandleAgentEvent added in v1.3.0

func (s *Service) HandleAgentEvent(ctx context.Context, agentID string, ev *agentpb.ResourceSample) error

HandleAgentEvent records a resource sample pushed by a remote agent. The container must already exist (verified via external_id lookup, so an orphan FK is never written); its id is the deterministic uid.Container of the reporting agent and the Docker external_id, identical to what the agent mints.

func (*Service) HostStatForAgent added in v1.3.0

func (s *Service) HostStatForAgent(agentID string) *HostSample

HostStatForAgent returns the latest host sample for the given host. The local server uses the empty-string key and is always available. A remote agent's sample is returned only when fresher than HostSampleTTL; nil otherwise.

func (*Service) ListHostStats added in v1.3.0

func (s *Service) ListHostStats() []*HostSample

ListHostStats returns the latest sample for every known host: the local server first, then every remote agent that has reported (including stale ones — callers decide how to present staleness via the Timestamp).

func (*Service) RecordHostSample added in v1.3.0

func (s *Service) RecordHostSample(sample *HostSample)

RecordHostSample stores the latest host-level sample for a remote agent. A non-empty AgentID is required; samples with an empty AgentID are ignored (the local server host is read live, never stored).

func (*Service) SetEventCallback

func (s *Service) SetEventCallback(fn EventCallback)

SetEventCallback sets the SSE broadcasting callback.

func (*Service) Start

func (s *Service) Start(ctx context.Context)

Start begins the resource collection loop. Blocks until ctx is cancelled.

func (*Service) UpsertAlertConfig

func (s *Service) UpsertAlertConfig(ctx context.Context, cfg *ResourceAlertConfig) error

UpsertAlertConfig creates or updates alert configuration.

type TopConsumerRow

type TopConsumerRow struct {
	ContainerID   string
	ContainerName string
	AvgValue      float64
	AvgPercent    float64
}

TopConsumerRow represents a container's average resource usage over a period.

Jump to

Keyboard shortcuts

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