Convert Figma logo to code with AI

shirou logogopsutil

psutil for golang

10,470
1,580
10,470
199

Top Related Projects

Exporter for machine metrics

16,909

Analyzes resource usage and performance characteristics of running containers.

14,466

Agent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.

Quick Overview

gopsutil is a cross-platform library for retrieving process and system utilization written in Go. It provides an easy-to-use interface for accessing information about CPU, memory, disk, network, and other system resources. The library aims to be a Go equivalent of the Python psutil library.

Pros

  • Cross-platform support (Windows, Linux, macOS, FreeBSD)
  • Comprehensive system information retrieval (CPU, memory, disk, network, etc.)
  • Easy-to-use API with idiomatic Go design
  • Actively maintained with regular updates and bug fixes

Cons

  • Some platform-specific features may not be available on all operating systems
  • Performance overhead for certain operations, especially on Windows
  • Limited documentation for advanced usage scenarios
  • Potential security implications when used with elevated privileges

Code Examples

  1. Get CPU usage percentage:
import "github.com/shirou/gopsutil/v3/cpu"

percent, err := cpu.Percent(time.Second, false)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("CPU usage: %.2f%%\n", percent[0])
  1. Get memory information:
import "github.com/shirou/gopsutil/v3/mem"

vmStat, err := mem.VirtualMemory()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Total memory: %v, Used: %v, Free: %v\n", vmStat.Total, vmStat.Used, vmStat.Free)
  1. List all processes:
import "github.com/shirou/gopsutil/v3/process"

processes, err := process.Processes()
if err != nil {
    log.Fatal(err)
}
for _, p := range processes {
    name, _ := p.Name()
    fmt.Printf("PID: %d, Name: %s\n", p.Pid, name)
}

Getting Started

To use gopsutil in your Go project, follow these steps:

  1. Install the library:

    go get github.com/shirou/gopsutil/v3
    
  2. Import the desired packages in your Go code:

    import (
        "github.com/shirou/gopsutil/v3/cpu"
        "github.com/shirou/gopsutil/v3/mem"
        "github.com/shirou/gopsutil/v3/disk"
    )
    
  3. Start using the library functions in your code as shown in the examples above.

Competitor Comparisons

Exporter for machine metrics

Pros of node_exporter

  • Designed specifically for Prometheus monitoring, offering seamless integration
  • Provides a wide range of exporters for various system metrics out-of-the-box
  • Highly extensible with custom collectors and textfile inputs

Cons of node_exporter

  • Limited to Linux and Unix-like systems, lacking Windows support
  • Focused on exporting metrics rather than providing a general-purpose system information library
  • Requires running as a separate process, which may increase resource usage

Code Comparison

node_exporter (Go):

func (c *cpuCollector) Update(ch chan<- prometheus.Metric) error {
    times, err := c.cpu.Times(false)
    if err != nil {
        return err
    }
    for _, t := range times {
        ch <- prometheus.MustNewConstMetric(c.cpu.User, prometheus.CounterValue, t.User)
    }
    return nil
}

gopsutil (Go):

func CPUTimes(percpu bool) ([]CPUTimesStat, error) {
    var ret []CPUTimesStat
    var err error
    if percpu {
        ret, err = perCPUTimes()
    } else {
        ret, err = allCPUTimes()
    }
    return ret, err
}

Both libraries provide CPU metrics, but node_exporter focuses on exporting Prometheus-compatible metrics, while gopsutil offers a more general-purpose API for retrieving system information.

16,909

Analyzes resource usage and performance characteristics of running containers.

Pros of cAdvisor

  • Provides a web UI for real-time resource usage and performance data visualization
  • Designed specifically for containerized environments, offering deep insights into Docker containers
  • Integrates well with Kubernetes and other container orchestration platforms

Cons of cAdvisor

  • More focused on container metrics, potentially less versatile for general system monitoring
  • Heavier resource footprint compared to gopsutil due to its comprehensive features
  • May require additional setup and configuration for non-containerized environments

Code Comparison

gopsutil:

cpu, _ := cpu.Percent(time.Second, false)
mem, _ := mem.VirtualMemory()
disk, _ := disk.Usage("/")

cAdvisor:

containerInfo, err := client.ContainerInfo("/docker/containerID", &v1.ContainerInfoRequest{NumStats: 1})
cpuUsage := containerInfo.Stats[0].Cpu.Usage.Total
memoryUsage := containerInfo.Stats[0].Memory.Usage

Summary

gopsutil is a lightweight, general-purpose system information library for Go, suitable for various monitoring tasks across different operating systems. cAdvisor, on the other hand, is specialized for container monitoring, offering rich features and visualizations specifically tailored for containerized environments. The choice between the two depends on the specific use case, with gopsutil being more versatile for general system monitoring and cAdvisor excelling in container-centric scenarios.

14,466

Agent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.

Pros of Telegraf

  • More comprehensive data collection capabilities, supporting a wide range of input plugins for various systems and services
  • Built-in support for sending data to multiple output destinations, including InfluxDB and other time-series databases
  • Highly configurable and extensible, allowing users to create custom plugins

Cons of Telegraf

  • Larger footprint and more complex setup compared to gopsutil
  • May be overkill for simple system monitoring tasks
  • Steeper learning curve due to its extensive feature set

Code Comparison

gopsutil:

cpu, _ := cpu.Percent(time.Second, false)
mem, _ := mem.VirtualMemory()
disk, _ := disk.Usage("/")

Telegraf:

[[inputs.cpu]]
[[inputs.mem]]
[[inputs.disk]]
  mount_points = ["/"]
[[outputs.influxdb]]
  urls = ["http://localhost:8086"]

Summary

Gopsutil is a lightweight library focused on system information retrieval, ideal for simple monitoring tasks or integration into Go applications. Telegraf, on the other hand, is a full-featured agent for collecting, processing, and outputting metrics, suitable for more complex monitoring scenarios and integration with time-series databases. While gopsutil offers direct programmatic access to system metrics, Telegraf provides a configuration-based approach with extensive plugin support for various data sources and outputs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

gopsutil: psutil for golang

Test Go Reference Calendar Versioning

This is a port of psutil (https://github.com/giampaolo/psutil). The challenge is porting all psutil functions on some architectures.

migration

v4 migration

There are some breaking changes. Please see v4 release note.

Tag semantics

gopsutil tag policy is almost same as Semantic Versioning, but automatically increases like Ubuntu versioning.

For example, v4.24.04 means

  • v4: major version
  • 24: release year, 2024
  • 04: release month

gopsutil aims to keep backwards compatibility until major version change.

Tagged at every end of month, but if there are only a few commits, it can be skipped.

Available Architectures

  • FreeBSD i386/amd64/arm
  • Linux i386/amd64/arm(raspberry pi)
  • Windows i386/amd64/arm/arm64
  • Darwin amd64/arm64
  • OpenBSD i386/amd64/armv7/arm64/riscv64 (Thank you @mpfz0r!)
  • Solaris amd64 (developed and tested on SmartOS/Illumos, Thank you @jen20!)

These have partial support:

  • CPU on DragonFly BSD (#893, Thank you @gballet!)
  • host on Linux RISC-V (#896, Thank you @tklauser!)

All works are implemented without cgo by porting C structs to golang structs.

Usage

package main

import (
    "fmt"

    "github.com/shirou/gopsutil/v4/mem"
)

func main() {
    v, _ := mem.VirtualMemory()

    // almost every return value is a struct
    fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)

    // convert to JSON. String() is also implemented
    fmt.Println(v)
}

The output is below.

Total: 3179569152, Free:284233728, UsedPercent:84.508194%
{"total":3179569152,"available":492572672,"used":2895335424,"usedPercent":84.50819439828305, (snip...)}

You can set an alternative location to /proc by setting the HOST_PROC environment variable.

You can set an alternative location to /sys by setting the HOST_SYS environment variable.

You can set an alternative location to /etc by setting the HOST_ETC environment variable.

You can set an alternative location to /var by setting the HOST_VAR environment variable.

You can set an alternative location to /run by setting the HOST_RUN environment variable.

You can set an alternative location to /dev by setting the HOST_DEV environment variable.

You can set an alternative location to / by setting the HOST_ROOT environment variable.

You can set an alternative location to /proc/N/mountinfo by setting the HOST_PROC_MOUNTINFO environment variable.

Adding settings using context (from v3.23.6)

As of v3.23.6, it is now possible to pass a path location using context: import "github.com/shirou/gopsutil/v3/common" and pass a context with common.EnvMap set to common.EnvKey, and the location will be used within each function.

	ctx := context.WithValue(context.Background(), 
		common.EnvKey, common.EnvMap{common.HostProcEnvKey: "/myproc"},
	)
	v, err := mem.VirtualMemoryWithContext(ctx)

First priority is given to the value set in context, then the value from the environment variable, and finally the default location.

Caching

As of v3.24.1, it is now possible to cached some values. These values default to false, not cached.

Be very careful that enabling the cache may cause inconsistencies. For example, if you enable caching of boottime on Linux, be aware that unintended values may be returned if the boottime is changed by NTP after booted.

  • host
    • EnableBootTimeCache
  • process
    • EnableBootTimeCache

Ex struct (from v4.24.5)

gopsutil is designed to work across multiple platforms. However, there are differences in the information available on different platforms, such as memory information that exists on Linux but not on Windows.

As of v4.24.5, to access this platform-specific information, gopsutil provides functions named Ex within the package. Currently, these functions are available in the mem and sensor packages.

The Ex structs are specific to each platform. For example, on Linux, there is an ExLinux struct, which can be obtained using the mem.NewExLinux() function. On Windows, it's mem.ExWindows(). These Ex structs provide platform-specific information.

ex := NewExWindows()
v, err := ex.VirtualMemory()
if err != nil {
    panic(err)
}

fmt.Println(v.VirtualAvail)
fmt.Println(v.VirtualTotal)

// Output:
// 140731958648832
// 140737488224256

gopsutil aims to minimize platform differences by offering common functions. However, there are many requests to obtain unique information for each platform. The Ex structs are designed to meet those requests. Additional functionalities might be added in the future. The use of these structures makes it clear that the information they provide is specific to each platform, which is why they have been designed in this way.

Documentation

See https://pkg.go.dev/github.com/shirou/gopsutil/v4 or https://godocs.io/github.com/shirou/gopsutil/v4

Requirements

  • go1.18 or above is required.

More Info

Several methods have been added which are not present in psutil, but will provide useful information.

  • host/HostInfo() (linux)
    • Hostname
    • Uptime
    • Procs
    • OS (ex: "linux")
    • Platform (ex: "ubuntu", "arch")
    • PlatformFamily (ex: "debian")
    • PlatformVersion (ex: "Ubuntu 13.10")
    • VirtualizationSystem (ex: "LXC")
    • VirtualizationRole (ex: "guest"/"host")
  • IOCounters
  • cpu/CPUInfo() (linux, freebsd)
    • CPU (ex: 0, 1, ...)
    • VendorID (ex: "GenuineIntel")
    • Family
    • Model
    • Stepping
    • PhysicalID
    • CoreID
    • Cores (ex: 2)
    • ModelName (ex: "Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz")
    • Mhz
    • CacheSize
    • Flags (ex: "fpu vme de pse tsc msr pae mce cx8 ...")
    • Microcode
  • load/Avg() (linux, freebsd, solaris)
    • Load1
    • Load5
    • Load15
  • docker/GetDockerIDList() (linux only)
    • container id list ([]string)
  • docker/CgroupCPU() (linux only)
    • user
    • system
  • docker/CgroupMem() (linux only)
    • various status
  • net_protocols (linux only)
    • system wide stats on network protocols (i.e IP, TCP, UDP, etc.)
    • sourced from /proc/net/snmp
  • iptables nf_conntrack (linux only)
    • system wide stats on netfilter conntrack module
    • sourced from /proc/sys/net/netfilter/nf_conntrack_count

Some code is ported from Ohai. Many thanks.

Current Status

  • x: works
  • b: almost works, but something is broken
  • c: works in CGO only
nameLinuxFreeBSDOpenBSDmacOSWindowsSolarisPlan 9AIX
cpu_timesxxxxxbx
cpu_countxxxxxxx
cpu_percentxxxxxx
cpu_times_percentxxxxxx
virtual_memoryxxxxxbxx
swap_memoryxxxxxX
disk_partitionsxxxxxx
disk_io_countersxxx
disk_usagexxxxxx
net_io_countersxxxbx
boot_timexxxxxX
usersxxxxxx
pidsxxxxx
pid_existsxxxxx
net_connectionsxxxxx
net_protocolsxx
net_if_addrsx
net_if_statsx
netfilter_conntrackx

Process class

nameLinuxFreeBSDOpenBSDmacOSWindows
pidxxxxx
ppidxxxxx
namexxxxx
cmdlinexxxx
create_timexxx
statusxxxx
cwdxxx
exexxxx
uidsxxxx
gidsxxxx
terminalxxx
io_countersxxxx
nicexxxxx
num_fdsx
num_ctx_switchesx
num_threadsxxxxx
cpu_timesxx
memory_infoxxxxx
memory_info_exx
memory_mapsx
open_filesx
send_signalxxxx
suspendxxxx
resumexxxx
terminatexxxxx
killxxxx
usernamexxxxx
ionice
rlimitx
num_handlers
threadsx
cpu_percentxxxx
cpu_affinity
memory_percentxx
parentxxxx
childrenxxxxx
connectionsxxx
is_running
page_faultsx

Original Metrics

itemLinuxFreeBSDOpenBSDmacOSWindowsSolarisAIX
HostInfo
hostnamexxxxxxX
uptimexxxxxx
processxxxx
osxxxxxxx
platformxxxxxx
platformfamilyxxxxxx
virtualizationx
CPU
VendorIDxxxxxxx
Familyxxxxxxx
Modelxxxxxxx
Steppingxxxxxx
PhysicalIDxx
CoreIDxx
Coresxxxx
ModelNamexxxxxxx
Microcodexx
LoadAvg
Load1xxxxx
Load5xxxxx
Load15xxxxx
GetDockerID
container idxnononono
CgroupsCPU
userxnononono
systemxnononono
CgroupsMem
variousxnononono
  • future work
    • process_iter
    • wait_procs
    • Process class
      • as_dict
      • wait
    • AIX processes

License

New BSD License (same as psutil)

Related Works

I have been influenced by the following great works:

How to Contribute

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

English is not my native language, so PRs correcting grammar or spelling are welcome and appreciated.