system

package
v14.1.7 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package system provides methods for working with system data (metrics/users)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyPath is returned when a required path argument is empty
	ErrEmptyPath = errors.New("path is empty")

	// ErrEmptyUserName is returned when a required user name or UID is empty
	ErrEmptyUserName = errors.New("user name/ID can't be blank")

	// ErrEmptyGroupName is returned when a required group name or GID is empty
	ErrEmptyGroupName = errors.New("group name/ID can't be blank")

	// ErrCantParseIdOutput is returned when the output of the id command has an unexpected format
	ErrCantParseIdOutput = errors.New("can't parse id command output")

	// ErrCantParseGetentOutput is returned when the output of getent has an unexpected format
	ErrCantParseGetentOutput = errors.New("can't parse getent command output")
)
View Source
var CurrentUserCachePeriod = 5 * time.Minute

CurrentUserCachePeriod is the duration for which the current user info is cached

Functions

func CalculateIOUtil

func CalculateIOUtil(io1, io2 map[string]*IOStats, duration time.Duration) map[string]float64

CalculateIOUtil calculates I/O utilization percentages from two IOStats snapshots

func CalculateNetworkSpeed

func CalculateNetworkSpeed(ii1, ii2 map[string]*InterfaceStats, duration time.Duration) (uint64, uint64)

CalculateNetworkSpeed calculates inbound and outbound bytes per second from two interface snapshots

func CurrentTTY

func CurrentTTY() string

CurrentTTY returns the path of the TTY attached to the current process, or an empty string if none

func GetFSUsage

func GetFSUsage() (map[string]*FSUsage, error)

GetFSUsage returns usage statistics for all currently mounted filesystems

Example
fsInfo, err := GetFSUsage()

if err != nil {
	return
}

// info is slice path -> info
for path, info := range fsInfo {
	fmt.Printf(
		"Path: %s Type: %s Device: %s Used: %d Free: %d Total: %d\n",
		path, info.Type, info.Device, info.Used, info.Free, info.Total,
	)
}

func GetIOStats

func GetIOStats() (map[string]*IOStats, error)

GetIOStats returns current I/O counters keyed by block device name

Example
ioStats, err := GetIOStats()

if err != nil {
	return
}

// print info for each device
for device, info := range ioStats {
	fmt.Printf("Device: %s", device)
	fmt.Printf(
		"  ReadComplete: %d ReadMerged: %d ReadSectors: %d ReadMs: %d\n",
		info.ReadComplete, info.ReadMerged, info.ReadSectors, info.ReadMs,
	)

	fmt.Printf(
		"  WriteComplete: %d WriteMerged: %d WriteSectors: %d WriteMs: %d\n",
		info.WriteComplete, info.WriteMerged, info.WriteSectors, info.WriteMs,
	)

	fmt.Printf(
		"  IOPending: %d IOMs: %d IOQueueMs: %d\n\n",
		info.IOPending, info.IOMs, info.IOQueueMs,
	)
}

func GetIOUtil

func GetIOUtil(duration time.Duration) (map[string]float64, error)

GetIOUtil measures I/O utilization per device over the given duration and returns values as percentages

Example
// get 5 sec IO utilization
ioUtil, err := GetIOUtil(5 * time.Second)

if err != nil {
	return
}

// print utilization for each device
for device, utilization := range ioUtil {
	fmt.Printf("Device: %s Utilization: %g\n", device, utilization)
}

func GetInterfacesStats

func GetInterfacesStats() (map[string]*InterfaceStats, error)

// GetInterfacesStats returns current traffic counters keyed by interface name

func GetNetworkSpeed

func GetNetworkSpeed(duration time.Duration) (uint64, uint64, error)

GetNetworkSpeed measures inbound and outbound throughput in bytes per second over the given duration

Example
input, output, err := GetNetworkSpeed(5 * time.Second)

if err != nil {
	return
}

// print input and output speed for all interfaces
fmt.Printf("Input: %d kb/s\n Output: %d kb/s\n", input/1024, output/1024)

func GetUptime

func GetUptime() (uint64, error)

GetUptime returns system uptime in seconds since boot

Example
uptime, err := GetUptime()

if err != nil {
	return
}

// print uptime
fmt.Printf("Uptime: %d seconds\n", uptime)

func IsGroupExist

func IsGroupExist(name string) bool

IsGroupExist returns true if a group with the given name or GID exists on the system

func IsUserExist

func IsUserExist(name string) bool

IsUserExist returns true if a user with the given name or UID exists on the system

Types

type CPUCount

type CPUCount struct {
	Possible uint32 `json:"possible"` // CPUs that can ever be online on this system
	Present  uint32 `json:"present"`  // CPUs currently present (plugged in)
	Online   uint32 `json:"online"`   // CPUs currently online and schedulable
	Offline  uint32 `json:"offline"`  // CPUs present but currently offline
}

CPUCount contains the number of CPUs in each availability state

func GetCPUCount

func GetCPUCount() (CPUCount, error)

GetCPUCount returns the number of CPUs in each availability state

type CPUInfo

type CPUInfo struct {
	Vendor    string    `json:"vendor"`          // Processor vendor identifier (e.g. GenuineIntel)
	Model     string    `json:"model"`           // Full model name of the processor
	Cores     int       `json:"cores"`           // Number of physical cores
	Siblings  int       `json:"siblings"`        // Total logical CPUs on the same physical package
	CacheSize uint64    `json:"cache_size"`      // L2 cache size in bytes
	Speed     []float64 `json:"speed,omitempty"` // Per-core speed in MHz
}

CPUInfo contains static information about a physical CPU package

func GetCPUInfo

func GetCPUInfo() ([]*CPUInfo, error)

GetCPUInfo returns static information about each physical CPU package

type CPUStats

type CPUStats struct {
	User   uint64 `json:"user"`   // Time in user mode
	Nice   uint64 `json:"nice"`   // Time in user mode with low priority
	System uint64 `json:"system"` // Time in system (kernel) mode
	Idle   uint64 `json:"idle"`   // Time spent idle
	Wait   uint64 `json:"wait"`   // Time waiting for I/O
	IRQ    uint64 `json:"irq"`    // Time servicing hardware interrupts
	SRQ    uint64 `json:"srq"`    // Time servicing software interrupts
	Steal  uint64 `json:"steal"`  // Time stolen by a hypervisor for other guests
	Total  uint64 `json:"total"`  // Sum of all CPU time fields
	Count  int    `json:"count"`  // Number of logical CPU cores seen in /proc/stat
}

CPUStats contains raw cumulative CPU time counters read from /proc/stat

func GetCPUStats

func GetCPUStats() (*CPUStats, error)

GetCPUStats returns a snapshot of raw cumulative CPU time counters

type CPUUsage

type CPUUsage struct {
	User    float64 `json:"user"`    // Time spent running user-space processes
	System  float64 `json:"system"`  // Time spent running kernel-space processes
	Nice    float64 `json:"nice"`    // Time spent running niced user-space processes
	Idle    float64 `json:"idle"`    // Time spent idle
	Wait    float64 `json:"wait"`    // Time spent waiting for I/O to complete
	Average float64 `json:"average"` // Overall average CPU usage across all states
	Count   int     `json:"count"`   // Number of logical CPU cores
}

CPUUsage contains percentage-based CPU usage breakdown for a measured interval

func CalculateCPUUsage

func CalculateCPUUsage(c1, c2 *CPUStats) *CPUUsage

CalculateCPUUsage calculates CPU usage percentages from two consecutive CPUStats snapshots

func GetCPUUsage

func GetCPUUsage(duration time.Duration) (*CPUUsage, error)

GetCPUUsage measures CPU usage over the given duration and returns a usage breakdown

Example
usage, err := GetCPUUsage(time.Minute)

if err != nil {
	return
}

// print all available CPU info
fmt.Printf("User: %f\n", usage.User)
fmt.Printf("System: %f\n", usage.System)
fmt.Printf("Nice: %f\n", usage.Nice)
fmt.Printf("Idle: %f\n", usage.Idle)
fmt.Printf("Wait: %f\n", usage.Wait)
fmt.Printf("Average: %f\n", usage.Average)
fmt.Printf("CPU Count: %d\n", usage.Count)

type FSUsage

type FSUsage struct {
	Type    string   `json:"type"`    // Filesystem type (ext4, xfs, tmpfs, etc.)
	Device  string   `json:"device"`  // Block device or remote spec
	Used    uint64   `json:"used"`    // Used space in bytes
	Free    uint64   `json:"free"`    // Available space in bytes
	Total   uint64   `json:"total"`   // Total capacity in bytes
	IOStats *IOStats `json:"iostats"` // I/O statistics for the backing device
}

FSUsage contains info about FS usage

type Group

type Group struct {
	Name string `json:"name"`
	GID  int    `json:"gid"`
}

Group contains information about a system group

func LookupGroup

func LookupGroup(nameOrID string) (*Group, error)

LookupGroup returns group information for the given group name or GID string

type IOStats

type IOStats struct {
	ReadComplete  uint64 `json:"read_complete"`  // Total reads completed successfully
	ReadMerged    uint64 `json:"read_merged"`    // Adjacent reads merged by the I/O scheduler
	ReadSectors   uint64 `json:"read_sectors"`   // Total sectors read
	ReadMs        uint64 `json:"read_ms"`        // Total time spent reading in milliseconds
	WriteComplete uint64 `json:"write_complete"` // Total writes completed successfully
	WriteMerged   uint64 `json:"write_merged"`   // Adjacent writes merged by the I/O scheduler
	WriteSectors  uint64 `json:"write_sectors"`  // Total sectors written
	WriteMs       uint64 `json:"write_ms"`       // Total time spent writing in milliseconds
	IOPending     uint64 `json:"io_pending"`     // Number of I/Os currently in flight
	IOMs          uint64 `json:"io_ms"`          // Total time spent on I/Os in milliseconds
	IOQueueMs     uint64 `json:"io_queue_ms"`    // Weighted time spent on I/Os (reflects queue depth)
}

IOStats contains raw I/O counters for a block device from /proc/diskstats

type InterfaceStats

type InterfaceStats struct {
	ReceivedBytes      uint64 `json:"received_bytes"`
	ReceivedPackets    uint64 `json:"received_packets"`
	TransmittedBytes   uint64 `json:"transmitted_bytes"`
	TransmittedPackets uint64 `json:"transmitted_packets"`
}

InterfaceStats contains cumulative traffic counters for a network interface

type LoadAvg

type LoadAvg struct {
	Min1  float64 `json:"min1"`  // LA in last 1 minute
	Min5  float64 `json:"min5"`  // LA in last 5 minutes
	Min15 float64 `json:"min15"` // LA in last 15 minutes
	RProc int     `json:"rproc"` // Number of currently runnable kernel scheduling entities
	TProc int     `json:"tproc"` // Number of kernel scheduling entities that currently exist on the system
}

LoadAvg contains average system load over 1, 5, and 15 minute intervals

func GetLA

func GetLA() (*LoadAvg, error)

GetLA returns current system load averages

Example
la, err := GetLA()

if err != nil {
	return
}

// print 1, 5 and 15 min load average
fmt.Printf("Min1: %g Min5: %g Min15: %g\n", la.Min1, la.Min5, la.Min15)

type MemUsage

type MemUsage struct {
	MemTotal     uint64 `json:"total"`                  // Total usable ram (i.e. physical ram minus a few reserved bits and the kernel binary code)
	MemFree      uint64 `json:"free"`                   // The sum of MemFree - (Buffers + Cached)
	MemUsed      uint64 `json:"used"`                   // MemTotal - MemFree
	MemAvailable uint64 `json:"available"`              // Available memory
	SwapTotal    uint64 `json:"swap_total"`             // Total amount of swap space available
	SwapFree     uint64 `json:"swap_free"`              // Memory which has been evicted from RAM, and is temporarily on the disk still also is in the swapfile
	SwapUsed     uint64 `json:"swap_used"`              // SwapTotal - SwapFree
	Active       uint64 `json:"active"`                 // Memory that has been used more recently and usually not reclaimed unless absolutely necessary
	Inactive     uint64 `json:"inactive"`               // Memory which has been less recently used.  It is more eligible to be reclaimed for other purposes
	Buffers      uint64 `json:"buffers,omitempty"`      // Relatively temporary storage for raw disk blocks shouldn't get tremendously large (20MB or so)
	Cached       uint64 `json:"cached,omitempty"`       // In-memory cache for files read from the disk (the pagecache).  Doesn't include SwapCached
	SwapCached   uint64 `json:"swap_cached,omitempty"`  // Memory that once was swapped out, is swapped back in but
	Dirty        uint64 `json:"dirty,omitempty"`        // Memory which is waiting to get written back to the disk
	Shmem        uint64 `json:"shmem,omitempty"`        // Total used shared memory
	Slab         uint64 `json:"slab,omitempty"`         // In-kernel data structures cache
	SReclaimable uint64 `json:"sreclaimable,omitempty"` // Reclaimable portion of Slab (e.g. caches)
}

MemUsage contains information about physical and swap memory usage

func GetMemUsage

func GetMemUsage() (*MemUsage, error)

GetMemUsage returns current physical and swap memory usage

Example
usage, err := GetMemUsage()

if err != nil {
	return
}

// print all available memory info
fmt.Printf("MemTotal: %d\n", usage.MemTotal)
fmt.Printf("MemFree: %d\n", usage.MemFree)
fmt.Printf("MemUsed: %d\n", usage.MemUsed)
fmt.Printf("MemUsedPerc: %g\n", usage.MemUsedPerc())
fmt.Printf("Buffers: %d\n", usage.Buffers)
fmt.Printf("Cached: %d\n", usage.Cached)
fmt.Printf("Active: %d\n", usage.Active)
fmt.Printf("Inactive: %d\n", usage.Inactive)
fmt.Printf("SwapTotal: %d\n", usage.SwapTotal)
fmt.Printf("SwapFree: %d\n", usage.SwapFree)
fmt.Printf("SwapUsed: %d\n", usage.SwapUsed)
fmt.Printf("SwapUsedPerc: %g\n", usage.SwapUsedPerc())
fmt.Printf("SwapCached: %d\n", usage.SwapCached)
fmt.Printf("Dirty: %d\n", usage.Dirty)
fmt.Printf("Slab: %d\n", usage.Slab)

func (*MemUsage) MemUsedPerc

func (m *MemUsage) MemUsedPerc() float64

MemUsedPerc returns used physical memory as a percentage of total RAM

func (*MemUsage) SwapUsedPerc

func (m *MemUsage) SwapUsedPerc() float64

SwapUsedPerc returns used swap space as a percentage of total swap

type OSInfo

type OSInfo struct {
	Name                  string `json:"name"`
	PrettyName            string `json:"pretty_name"`
	Version               string `json:"version"`
	Build                 string `json:"build"`
	VersionID             string `json:"version_id"`
	VersionCodename       string `json:"version_codename"`
	ID                    string `json:"id"`
	IDLike                string `json:"id_like"`
	PlatformID            string `json:"platform_id"`
	Variant               string `json:"variant"`
	VariantID             string `json:"variant_id"`
	CPEName               string `json:"cpe_name"`
	HomeURL               string `json:"home_url"`
	BugReportURL          string `json:"bugreport_url"`
	DocumentationURL      string `json:"documentation_url"`
	ANSIColor             string `json:"ansi_color"`
	SupportURL            string `json:"support_url"`
	SupportProduct        string `json:"support_product"`
	SupportProductVersion string `json:"support_product_version"`
}

OSInfo contains information parsed from /etc/os-release

func GetOSInfo

func GetOSInfo() (*OSInfo, error)

GetOSInfo returns information parsed from the default os-release file

func ParseOSInfo

func ParseOSInfo(file string) (*OSInfo, error)

ParseOSInfo parses OS release information from the given os-release file path

func (*OSInfo) ColoredName

func (i *OSInfo) ColoredName() string

ColoredName returns the OS name wrapped with its ANSI color code

func (*OSInfo) ColoredPrettyName

func (i *OSInfo) ColoredPrettyName() string

ColoredPrettyName returns the pretty OS name wrapped with its ANSI color code

type SessionInfo

type SessionInfo struct {
	Username         string    `json:"username"`
	Host             string    `json:"host"`
	LoginTime        time.Time `json:"login_time"`
	LastActivityTime time.Time `json:"last_activity_time"`
}

SessionInfo contains information about an active login session

func Who

func Who() ([]*SessionInfo, error)

Who returns information about all active login sessions

type SystemInfo

type SystemInfo struct {
	Hostname        string `json:"hostname"`         // System hostname
	ID              string `json:"id"`               // Unique machine ID
	OS              string `json:"os"`               // OS name
	Kernel          string `json:"kernel"`           // Kernel version string
	Arch            string `json:"arch"`             // Raw architecture identifier (x86_64, aarch64, etc.)
	ArchName        string `json:"arch_name"`        // Normalised architecture name (amd64, 386, etc.)
	ContainerEngine string `json:"container_engine"` // Detected container engine
	ArchBits        int    `json:"arch_bits"`        // Pointer width of the architecture (32 or 64)
}

SystemInfo contains general information about the host system

func GetSystemInfo

func GetSystemInfo() (*SystemInfo, error)

GetSystemInfo returns general information about the host system

Example
sysInfo, err := GetSystemInfo()

if err != nil {
	return
}

// print all available system info
fmt.Printf("Hostname: %s\n", sysInfo.Hostname)
fmt.Printf("OS: %s\n", sysInfo.OS)
fmt.Printf("Kernel: %s\n", sysInfo.Kernel)
fmt.Printf("Arch: %s\n", sysInfo.Arch)

type User

type User struct {
	UID      int      `json:"uid"`
	GID      int      `json:"gid"`
	Name     string   `json:"name"`
	Groups   []*Group `json:"groups"`
	Comment  string   `json:"comment"`
	Shell    string   `json:"shell"`
	HomeDir  string   `json:"home_dir"`
	RealUID  int      `json:"real_uid"`  // UID of the original user before sudo elevation
	RealGID  int      `json:"real_gid"`  // GID of the original user before sudo elevation
	RealName string   `json:"real_name"` // Name of the original user before sudo elevation
}

User contains information about a system user account

func CurrentUser

func CurrentUser(avoidCache ...bool) (*User, error)

CurrentUser returns information about the user running the current process. Results are cached for CurrentUserCachePeriod; pass true to bypass the cache.

func LookupUser

func LookupUser(nameOrID string) (*User, error)

LookupUser returns user information for the given username or UID string

func (*User) GroupList

func (u *User) GroupList() []string

GroupList returns the names of all groups the user belongs to

func (*User) IsRoot

func (u *User) IsRoot() bool

IsRoot returns true if the user is root (UID 0 and GID 0)

func (*User) IsSudo

func (u *User) IsSudo() bool

IsSudo returns true if the process is running under sudo elevation

Directories

Path Synopsis
Package container provides methods for checking container engine info
Package container provides methods for checking container engine info
Package process provides methods for gathering information about active processes
Package process provides methods for gathering information about active processes
Package procname provides methods for changing process name in the process tree
Package procname provides methods for changing process name in the process tree
Package sensors provides methods for collecting hardware sensor information
Package sensors provides methods for collecting hardware sensor information
Package sysctl provides methods for reading kernel parameters
Package sysctl provides methods for reading kernel parameters

Jump to

Keyboard shortcuts

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