Help us shape the future of Go! Take the 2026 Go Developer Survey

metrics

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: BSD-3-Clause Imports: 17 Imported by: 0

README

sysc-metrics

sysc-metrics is a small Go library for read-only Linux system telemetry. It supplies the built-in monitoring widgets in sysc-shell without importing a CLI, TUI, HTTP server, or unrelated application framework.

The M0 contract, M1 core collectors, sysfs battery, CPU temperature, GPU usage/temperature, and opt-in process sampling are implemented.

Usage

package main

import (
	"fmt"
	"github.com/Nomadcxx/sysc-metrics"
)

func main() {
	sampler := metrics.NewGPUSampler()
	snapshot, err := sampler.Sample()
	if err != nil {
		panic(err)
	}
	if snapshot.Usage.Valid {
		fmt.Println(snapshot.Usage.Fraction)
	}
	sampler.Close()
}

M1 is Linux-only and uses only the Go standard library. Samplers belong to one sequential polling owner; they do not start goroutines. First and discontinuous rate samples have Valid == false, while valid zero values remain valid. A snapshot may contain partial data and Issue values for failed individual sources or entities.

GPUSampler reports the same GPU snapshot as ReadGPU and additionally fills Intel i915 usage from the second sample on, derived from PMU engine-busy counters opened with perf_event_open. On measured kernels, opening those system-wide counters requires CAP_PERFMON (or CAP_SYS_ADMIN) on the process; lowering kernel.perf_event_paranoid did not lift the gate. Without privilege the sampler records an Issue and leaves Intel usage invalid while identity and temperature stay filled. ReadGPU never reports Intel usage. Close a GPUSampler when its polling stops; it owns open counter descriptors.

Polling cadence, caching, presentation, units shown to users, alerts, and filtering remain consumer responsibilities.

Scope

The first releases will collect:

  • aggregate and per-core CPU usage, load, and frequency;
  • memory and swap;
  • mounted-filesystem capacity and block-device I/O rates;
  • per-interface network counters and rates;
  • thermal sensors and available GPU metrics;
  • battery and UPS state, energy, rate, and estimated time;
  • uptime and basic totals;
  • process CPU and memory only when a consumer requests it.

Battery is the sysfs power-supply aggregate. CPU temperature is one scored hwmon / thermal_zone reading. GPU usage and temperature come from drm sysfs, with AMD usage from gpu_busy_percent, NVIDIA falling back to nvidia-smi when a 10de: device is present, and Intel i915 usage from PMU engine-busy counters through the stateful GPUSampler. Collectors use Linux interfaces such as /proc, /sys, statfs, and os/exec for that optional NVIDIA binary.

The library will not provide power controls, recursive directory sizes, filesystem indexing, SMART, quotas, vendor administration, a daemon, or cross-platform abstractions.

Development gates

  1. Define snapshot and sampling semantics, including first-sample behavior and counter reset handling.
  2. Implement CPU, memory, filesystem, block-device, and network collectors with fixture tests.
  3. Add thermal and battery collection, including UPower loss and sysfs fallback tests.
  4. Add GPU and process collectors only for a confirmed shell consumer.
  5. Qualify suspend/resume, device removal, permission errors, and real hardware before v0.1.0.

See the design and roadmap. Package directories will be added with their first tested behavior; the repository will not track empty scaffolding.

Licence

sysc-metrics uses the BSD 3-Clause License.

Documentation

Overview

Package metrics provides read-only Linux system telemetry snapshots.

Index

Constants

This section is empty.

Variables

View Source
var ErrProcessIdentityChanged = errors.New("process identity changed")

ErrProcessIdentityChanged means a PID now identifies a different process.

Functions

func ValidateProcessIdentity added in v0.4.0

func ValidateProcessIdentity(identity ProcessIdentity) error

ValidateProcessIdentity confirms that identity still names the same process.

Types

type BatterySnapshot added in v0.2.0

type BatterySnapshot struct {
	CollectedAt   time.Time
	Present       bool
	Charge        float64 // 0..1
	ChargeValid   bool
	State         BatteryState
	EnergyJoules  float64
	RateWatts     float64
	RateValid     bool
	TimeRemaining time.Duration
	TimeValid     bool
	Issues        []Issue
}

BatterySnapshot is the aggregate battery observation. Present is false on a machine with no battery; that is not an error.

func ReadBattery added in v0.2.0

func ReadBattery() (BatterySnapshot, error)

ReadBattery collects the current aggregate battery. It prefers sysfs power-supply devices of type Battery or UPS. A machine with none reports Present false.

type BatteryState added in v0.2.0

type BatteryState uint8

BatteryState is the charging state of the aggregate battery.

const (
	BatteryUnknown BatteryState = iota
	BatteryCharging
	BatteryDischarging
	BatteryFull
)

type BlockDevice

type BlockDevice struct {
	Name            string
	Major           uint32
	Minor           uint32
	ReadBytes       uint64
	WriteBytes      uint64
	ReadOperations  uint64
	WriteOperations uint64
	Busy            time.Duration
	Rates           BlockRates
}

BlockDevice contains cumulative counters and derived rates for one block device.

type BlockRates

type BlockRates struct {
	ReadBytesPerSecond       float64
	WriteBytesPerSecond      float64
	ReadOperationsPerSecond  float64
	WriteOperationsPerSecond float64
	BusyFraction             float64
	Valid                    bool
}

BlockRates contains rates derived from two block-device observations. Valid distinguishes observed zero rates from unavailable derived values.

type BlockSampler

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

BlockSampler retains previous block counters for sequential rate sampling.

func NewBlockSampler

func NewBlockSampler() *BlockSampler

NewBlockSampler returns a block sampler owned by one sequential polling caller.

func (*BlockSampler) Sample

func (s *BlockSampler) Sample() (BlockSnapshot, error)

Sample returns one block-device snapshot. The sampler is not safe for concurrent use.

type BlockSnapshot

type BlockSnapshot struct {
	CollectedAt time.Time
	Devices     []BlockDevice
	Issues      []Issue
}

BlockSnapshot contains block-device data collected at one time. Devices and Issues are caller-owned snapshot slices.

type CPUCore

type CPUCore struct {
	ID             int
	Usage          CPUUsage
	FrequencyHz    uint64
	FrequencyValid bool
}

CPUCore contains one core's usage and best-effort frequency.

type CPUSampler

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

CPUSampler retains the previous CPU counters for sequential rate sampling.

func NewCPUSampler

func NewCPUSampler() *CPUSampler

NewCPUSampler returns a CPU sampler owned by one sequential polling caller.

func (*CPUSampler) Sample

func (s *CPUSampler) Sample() (CPUSnapshot, error)

Sample returns one CPU snapshot. The sampler is not safe for concurrent use.

type CPUSnapshot

type CPUSnapshot struct {
	CollectedAt time.Time
	Usage       CPUUsage
	Cores       []CPUCore
	Load1       float64
	Load5       float64
	Load15      float64
	LoadValid   bool
	Issues      []Issue
}

CPUSnapshot contains aggregate and per-core CPU data collected at one time. Cores and Issues are caller-owned snapshot slices.

type CPUUsage

type CPUUsage struct {
	Fraction float64
	Valid    bool
}

CPUUsage contains a utilization fraction. Valid distinguishes an observed zero from no sample.

type Capacity

type Capacity struct {
	TotalBytes     uint64
	UsedBytes      uint64
	AvailableBytes uint64
}

Capacity contains byte totals. Byte fields are uint64 values.

type Filesystem

type Filesystem struct {
	MountID    uint64
	MountPoint string
	Source     string
	Type       string
	ReadOnly   bool
	Capacity   Capacity
}

Filesystem contains one mounted filesystem and its byte capacity.

type FilesystemSnapshot

type FilesystemSnapshot struct {
	CollectedAt time.Time
	Filesystems []Filesystem
	Issues      []Issue
}

FilesystemSnapshot contains mounted filesystem data collected at one time. Filesystems and Issues are caller-owned snapshot slices.

func ReadFilesystems

func ReadFilesystems() (FilesystemSnapshot, error)

ReadFilesystems returns one mounted-filesystem snapshot from Linux.

type GPU added in v0.3.0

type GPU struct {
	PCIID     string
	Driver    string
	Name      string
	Usage     GPUUsage
	Celsius   float64
	TempValid bool
}

GPU is one display device.

type GPUSampler added in v0.5.0

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

GPUSampler retains Intel i915 PMU engine counters for sequential rate sampling. It is owned by one sequential polling caller, starts no goroutines, and owns open PMU counters until Close. ReadGPU cannot report Intel usage; a consumer that needs it must sample here and close the sampler when its polling stops.

func NewGPUSampler added in v0.5.0

func NewGPUSampler() *GPUSampler

NewGPUSampler returns a GPU sampler owned by one sequential polling caller. It reports the same snapshot as ReadGPU and additionally fills Intel i915 usage from the second sample on.

func (*GPUSampler) Close added in v0.5.0

func (s *GPUSampler) Close() error

Close closes every open PMU counter and drops sampling state. It is idempotent; sampling after Close starts from a fresh baseline.

func (*GPUSampler) Sample added in v0.5.0

func (s *GPUSampler) Sample() (GPUSnapshot, error)

Sample returns one GPU snapshot. The sampler is not safe for concurrent use.

type GPUSnapshot added in v0.3.0

type GPUSnapshot struct {
	CollectedAt time.Time
	GPUs        []GPU
	Issues      []Issue
}

GPUSnapshot lists GPUs collected at one time. GPUs and Issues are caller-owned.

func ReadGPU added in v0.3.0

func ReadGPU() (GPUSnapshot, error)

ReadGPU collects usage and temperature for each discrete or integrated GPU.

type GPUUsage added in v0.3.0

type GPUUsage struct {
	Fraction float64
	Valid    bool
}

GPUUsage is a 0..1 busy fraction. Valid distinguishes a real zero from no sample.

type Issue

type Issue struct {
	Source string
	Err    error
}

Issue describes a recoverable source or entity failure in a partial snapshot.

func (Issue) Error

func (i Issue) Error() string

Error returns the source and underlying error.

func (Issue) Unwrap

func (i Issue) Unwrap() error

Unwrap returns the underlying source error.

type MemorySnapshot

type MemorySnapshot struct {
	CollectedAt time.Time
	Memory      Capacity
	Swap        Capacity
}

MemorySnapshot contains memory and swap byte capacities collected at one time.

func ReadMemory

func ReadMemory() (MemorySnapshot, error)

ReadMemory returns one memory and swap snapshot from Linux.

type NetworkInterface

type NetworkInterface struct {
	Name            string
	Index           uint32
	ReceiveBytes    uint64
	ReceivePackets  uint64
	ReceiveErrors   uint64
	ReceiveDropped  uint64
	TransmitBytes   uint64
	TransmitPackets uint64
	TransmitErrors  uint64
	TransmitDropped uint64
	Rates           NetworkRates
}

NetworkInterface contains cumulative counters and derived rates for one interface.

type NetworkRates

type NetworkRates struct {
	ReceiveBytesPerSecond    float64
	TransmitBytesPerSecond   float64
	ReceivePacketsPerSecond  float64
	TransmitPacketsPerSecond float64
	Valid                    bool
}

NetworkRates contains rates derived from two network observations. Valid distinguishes observed zero rates from unavailable derived values.

type NetworkSampler

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

NetworkSampler retains previous interface counters for sequential rate sampling.

func NewNetworkSampler

func NewNetworkSampler() *NetworkSampler

NewNetworkSampler returns a network sampler owned by one sequential polling caller.

func (*NetworkSampler) Sample

func (s *NetworkSampler) Sample() (NetworkSnapshot, error)

Sample returns one network-interface snapshot. The sampler is not safe for concurrent use.

type NetworkSnapshot

type NetworkSnapshot struct {
	CollectedAt time.Time
	Interfaces  []NetworkInterface
	Issues      []Issue
}

NetworkSnapshot contains network-interface data collected at one time. Interfaces and Issues are caller-owned snapshot slices.

type Process added in v0.4.0

type Process struct {
	Identity      ProcessIdentity
	Name          string
	ParentPID     int
	UID           uint32
	UIDValid      bool
	ResidentBytes uint64
	ResidentValid bool
	Args          []string
	CPU           CPUUsage
}

Process contains one process observation and its best-effort derived CPU usage.

type ProcessIdentity added in v0.4.0

type ProcessIdentity struct {
	PID            int
	StartTimeTicks uint64
}

ProcessIdentity distinguishes a process from a later process that reuses its PID.

type ProcessSampler added in v0.4.0

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

ProcessSampler retains previous process and aggregate CPU counters for sequential rate sampling.

func NewProcessSampler added in v0.4.0

func NewProcessSampler() *ProcessSampler

NewProcessSampler returns a process sampler owned by one sequential polling caller.

func (*ProcessSampler) Sample added in v0.4.0

func (s *ProcessSampler) Sample() (ProcessSnapshot, error)

Sample returns one process snapshot. The sampler is not safe for concurrent use.

type ProcessSnapshot added in v0.4.0

type ProcessSnapshot struct {
	CollectedAt time.Time
	Processes   []Process
	Issues      []Issue
}

ProcessSnapshot contains processes collected at one time. Processes, Args, and Issues are caller-owned snapshot slices.

type ThermalSnapshot added in v0.3.0

type ThermalSnapshot struct {
	CollectedAt time.Time
	Celsius     float64
	Valid       bool
	Source      string
	Issues      []Issue
}

ThermalSnapshot is one scored CPU package temperature in Celsius. Valid is false when no known sensor exists; that is not an error.

func ReadThermal added in v0.3.0

func ReadThermal() (ThermalSnapshot, error)

ReadThermal collects the current CPU package temperature.

type UptimeSnapshot

type UptimeSnapshot struct {
	CollectedAt time.Time
	Uptime      time.Duration
}

UptimeSnapshot contains uptime as a duration collected at one time.

func ReadUptime

func ReadUptime() (UptimeSnapshot, error)

ReadUptime returns one uptime snapshot from Linux.

Jump to

Keyboard shortcuts

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