resource

package
v1.2.12 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

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 pbruntime.Runtime, containerSvc *container.Service, logger *slog.Logger) *Collector

NewCollector creates a resource stats collector.

func (*Collector) GetAllLatest

func (c *Collector) GetAllLatest() map[int64]*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 int64) *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       pbruntime.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 HostStatReader added in v1.0.1

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

HostStatReader samples host CPU and memory at 1s intervals via /proc. It runs its own goroutine, independent of the container collector.

func NewHostStatReader added in v1.0.1

func NewHostStatReader() *HostStatReader

NewHostStatReader creates a reader and takes an initial CPU sample.

func (*HostStatReader) CPUPercent added in v1.0.1

func (r *HostStatReader) CPUPercent() float64

CPUPercent returns the latest host CPU usage percentage (0-100).

func (*HostStatReader) MemTotal added in v1.0.1

func (r *HostStatReader) MemTotal() int64

MemTotal returns host total memory in bytes.

func (*HostStatReader) MemUsed added in v1.0.1

func (r *HostStatReader) MemUsed() int64

MemUsed returns host memory used in bytes.

func (*HostStatReader) Start added in v1.0.1

func (r *HostStatReader) Start(ctx context.Context)

Start runs the sampling goroutine. Blocks until ctx is cancelled.

type ResourceAlertConfig

type ResourceAlertConfig struct {
	ID                     int64      `json:"id"`
	ContainerID            int64      `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              int64     `json:"id"`
	ContainerID     int64     `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"`
}

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

type ResourceStore

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

	GetAlertConfig(ctx context.Context, containerID int64) (*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) ([]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   int64
	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 int64) (*ResourceAlertConfig, error)

GetAlertConfig returns the alert configuration for a container.

func (*Service) GetAllLatestSnapshots

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

GetAllLatestSnapshots returns the latest snapshots for all containers.

func (*Service) GetContainerName

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

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

func (*Service) GetCurrentSnapshot

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

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

func (*Service) GetHistory

func (s *Service) GetHistory(ctx context.Context, containerID int64, 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) ([]TopConsumerRow, error)

GetTopConsumersByPeriod returns the top resource consumers averaged over a period.

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   int64
	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