system

package
v12.41.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2022 License: Apache-2.0 Imports: 15 Imported by: 60

Documentation

Overview

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

Index

Examples

Constants

View Source
const (
	LINUX_ARCH      = "Arch"
	LINUX_CENTOS    = "CentOS"
	LINUX_DEBIAN    = "Debian"
	LINUX_FEDORA    = "Fedora"
	LINUX_GENTOO    = "Gentoo"
	LINUX_RHEL      = "RHEL"
	LINUX_SUSE      = "SuSe"
	LINUX_OPEN_SUSE = "openSUSE"
	LINUX_UBUNTU    = "Ubuntu"
	DARWIN_OSX      = "OSX"
)

OS names

Variables

View Source
var (
	// ErrEmptyPath is returned if given path is empty
	ErrEmptyPath = errors.New("Path is empty")

	// ErrEmptyUserName is returned if given user name or uid is empty
	ErrEmptyUserName = errors.New("User name/ID can't be blank")

	// ErrEmptyGroupName is returned if given group name of gid is empty
	ErrEmptyGroupName = errors.New("Group name/ID can't be blank")

	// ErrCantParseIdOutput is returned if id command output has unsupported format
	ErrCantParseIdOutput = errors.New("Can't parse id command output")

	// ErrCantParseGetentOutput is returned if getent command output has unsupported format
	ErrCantParseGetentOutput = errors.New("Can't parse getent command output")
)

Errors

View Source
var CurrentUserCachePeriod = 5 * time.Minute

CurrentUserCachePeriod is cache period for current user info

Functions

func CalculateIOUtil

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

CalculateIOUtil calculates IO utilization for all devices

func CalculateNetworkSpeed

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

CalculateNetworkSpeed calculates network input/output speed in bytes per second for all network interfaces

func CurrentTTY

func CurrentTTY() string

CurrentTTY returns current tty or empty string if error occurred

func GetFSUsage

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

GetFSUsage returns info about 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,
	)
}
Output:

func GetIOStats

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

GetIOStats returns IO statistics as map device -> statistics

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,
	)
}
Output:

func GetIOUtil

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

GetIOUtil returns slice (device -> utilization) with IO utilization

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)
}
Output:

func GetInterfacesStats

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

GetInterfacesStats returns info about network interfaces

func GetNetworkSpeed

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

GetNetworkSpeed returns network input/output speed in bytes per second for all network interfaces

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)
Output:

func GetUptime

func GetUptime() (uint64, error)

GetUptime returns system uptime in seconds

Example
uptime, err := GetUptime()

if err != nil {
	return
}

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

func IsGroupExist

func IsGroupExist(name string) bool

IsGroupExist checks if group exist on system or not

func IsUserExist

func IsUserExist(name string) bool

IsUserExist checks if user exist on system or not

Types

type CPUCount

type CPUCount struct {
	Possible uint32 `json:"possible"`
	Present  uint32 `json:"present"`
	Online   uint32 `json:"online"`
	Offline  uint32 `json:"offline"`
}

CPUCount contains info about number of CPU

func GetCPUCount

func GetCPUCount() (CPUCount, error)

GetCPUCount returns info about CPU

type CPUInfo

type CPUInfo struct {
	Vendor    string    `json:"vendor"`     // Processor vandor name
	Model     string    `json:"model"`      // Common name of the processor
	Cores     int       `json:"cores"`      // Number of cores
	Siblings  int       `json:"siblings"`   // Total number of sibling CPUs on the same physical CPU
	CacheSize uint64    `json:"cache_size"` // Amount of level 2 memory cache available to the processor
	Speed     []float64 `json:"speed"`      // Speed in megahertz for the processor
}

CPUInfo contains info about CPU

func GetCPUInfo

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

GetCPUInfo returns slice with info about CPUs

type CPUStats

type CPUStats struct {
	User   uint64 `json:"user"`
	Nice   uint64 `json:"nice"`
	System uint64 `json:"system"`
	Idle   uint64 `json:"idle"`
	Wait   uint64 `json:"wait"`
	IRQ    uint64 `json:"irq"`
	SRQ    uint64 `json:"srq"`
	Steal  uint64 `json:"steal"`
	Total  uint64 `json:"total"`
	Count  int    `json:"count"`
}

CPUStats contains basic CPU stats

func GetCPUStats

func GetCPUStats() (*CPUStats, error)

GetCPUStats returns basic CPU stats

type CPUUsage

type CPUUsage struct {
	User    float64 `json:"user"`    // Normal processes executing in user mode
	System  float64 `json:"system"`  // Processes executing in kernel mode
	Nice    float64 `json:"nice"`    // Niced processes executing in user mode
	Idle    float64 `json:"idle"`    // Twiddling thumbs
	Wait    float64 `json:"wait"`    // Waiting for I/O to complete
	Average float64 `json:"average"` // Average CPU usage
	Count   int     `json:"count"`   // Number of CPU cores
}

CPUUsage contains info about CPU usage

func CalculateCPUUsage

func CalculateCPUUsage(c1, c2 *CPUStats) *CPUUsage

CalculateCPUUsage calcualtes CPU usage based on CPUStats

func GetCPUUsage

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

GetCPUUsage returns info about CPU usage

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)
Output:

type FSUsage

type FSUsage struct {
	Type    string   `json:"type"`    // FS type (ext4/ntfs/etc...)
	Device  string   `json:"device"`  // Device spec
	Used    uint64   `json:"used"`    // Used space
	Free    uint64   `json:"free"`    // Free space
	Total   uint64   `json:"total"`   // Total space
	IOStats *IOStats `json:"iostats"` // IO statistics
}

FSUsage contains info about FS usage

type Group

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

Group contains information about group

func LookupGroup

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

LookupGroup searches group info by given name

type IOStats

type IOStats struct {
	ReadComplete  uint64 `json:"read_complete"`  // Reads completed successfully
	ReadMerged    uint64 `json:"read_merged"`    // Reads merged
	ReadSectors   uint64 `json:"read_sectors"`   // Sectors read
	ReadMs        uint64 `json:"read_ms"`        // Time spent reading (ms)
	WriteComplete uint64 `json:"write_complete"` // Writes completed
	WriteMerged   uint64 `json:"write_merged"`   // Writes merged
	WriteSectors  uint64 `json:"write_sectors"`  // Sectors written
	WriteMs       uint64 `json:"write_ms"`       // Time spent writing (ms)
	IOPending     uint64 `json:"io_pending"`     // I/Os currently in progress
	IOMs          uint64 `json:"io_ms"`          // Time spent doing I/Os (ms)
	IOQueueMs     uint64 `json:"io_queue_ms"`    // Weighted time spent doing I/Os (ms)
}

IOStats contains information about I/O

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 stats about network interfaces usage

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 information about average system load

func GetLA

func GetLA() (*LoadAvg, error)

GetLA returns loadavg

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)
Output:

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
	Buffers      uint64 `json:"buffers"`      // Relatively temporary storage for raw disk blocks shouldn't get tremendously large (20MB or so)
	Cached       uint64 `json:"cached"`       // In-memory cache for files read from the disk (the pagecache).  Doesn't include SwapCached
	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
	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
	SwapCached   uint64 `json:"swap_cached"`  // Memory that once was swapped out, is swapped back in but
	Dirty        uint64 `json:"dirty"`        // Memory which is waiting to get written back to the disk
	Shmem        uint64 `json:"shmem"`        // Total used shared memory
	Slab         uint64 `json:"slab"`         // In-kernel data structures cache
	SReclaimable uint64 `json:"sreclaimable"` // The part of the Slab that might be reclaimed (such as caches)
}

MemUsage contains info about system memory usage

func GetMemUsage

func GetMemUsage() (*MemUsage, error)

GetMemUsage returns memory usage info

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("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("SwapCached: %d\n", usage.SwapCached)
fmt.Printf("Dirty: %d\n", usage.Dirty)
fmt.Printf("Slab: %d\n", usage.Slab)
Output:

type OSInfo

type OSInfo struct {
	Name            string `json:"name"`
	PrettyName      string `json:"pretty_name"`
	Version         string `json:"version"`
	VersionID       string `json:"version_id"`
	VersionCodename string `json:"version_codename"`
	ID              string `json:"id"`
	IDLike          string `json:"id_like"`
	HomeURL         string `json:"home_url"`
	BugReportURL    string `json:"bugreport_url"`
	SupportURL      string `json:"support_url"`
}

OSInfo contains info about OS

func GetOSInfo

func GetOSInfo() (*OSInfo, error)

GetOSInfo returns info about OS

type SessionInfo

type SessionInfo struct {
	User             *User     `json:"user"`
	LoginTime        time.Time `json:"login_time"`
	LastActivityTime time.Time `json:"last_activity_time"`
}

SessionInfo contains information about all sessions

func Who

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

Who returns info about all active sessions sorted by login time

type SystemInfo

type SystemInfo struct {
	Hostname     string `json:"hostname"`     // Hostname
	OS           string `json:"os"`           // OS name
	Distribution string `json:"distribution"` // OS distribution
	Version      string `json:"version"`      // OS version
	Kernel       string `json:"kernel"`       // Kernel version
	Arch         string `json:"arch"`         // System architecture (i386/i686/x86_64/etc...)
	ArchBits     int    `json:"arch_bits"`    // Architecture bits (32/64)
}

SystemInfo contains info about a system (hostname, OS, arch...)

func GetSystemInfo

func GetSystemInfo() (*SystemInfo, error)

GetSystemInfo returns system info

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)
Output:

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"`
	RealGID  int      `json:"real_gid"`
	RealName string   `json:"real_name"`
}

User contains information about user

func CurrentUser

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

CurrentUser returns struct with info about current user

func LookupUser

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

LookupUser searches user info by given name

func (*User) GroupList

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

GroupList returns slice with user groups names

func (*User) IsRoot

func (u *User) IsRoot() bool

IsRoot checks if current user is root

func (*User) IsSudo

func (u *User) IsSudo() bool

IsSudo checks if it user over sudo command

Directories

Path Synopsis
Package exec provides methods for executing commands
Package exec provides methods for executing commands
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 provide methods for collecting sensors information
Package sensors provide methods for collecting sensors information

Jump to

Keyboard shortcuts

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