gopsutil

repository·master·Indexed 11 days ago

https://github.com/shirou/gopsutil

A Go port of the Python psutil library providing cross-platform system monitoring and process utilities. It enables retrieval of CPU, memory, disk, network, and process information without relying on cgo. Supports Go 1.18+ and provides platform-specific extended structs for Linux and Windows, as well as custom path resolution via context or environment variables.

Tokens
1.8K
Snippets
4
Records
8
Agent score
46%

What's inside gopsutil

  1. Enable caching for specific values

    master

    As of v3.24.1, you can enable caching for certain values to improve performance. Note that caching can lead to inconsistencies (e.g., if NTP changes the boot time on Linux). Caching is disabled by default.

    Available cache settings:

    • host package: EnableBootTimeCache
    • process package: EnableBootTimeCache
  2. Pass custom path locations using context

    master

    Starting from v3.23.6, you can pass custom path locations using a context.Context. This is useful for testing or when system directories are in non-standard locations. The priority for location resolution is:

    1. Value set in context via common.EnvMap.
    2. Value from environment variables.
    3. Default system location.

    To use this, import github.com/shirou/gopsutil/v3/common (or the version matching your usage) and use the WithContext variant of the API functions.

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

    master

    To use gopsutil, import the specific sub-package for the resource you want to monitor (e.g., github.com/shirou/gopsutil/v4/mem). Most functions return a struct containing the requested system information. These structs also implement the String() method for easy printing and can be converted to JSON.

    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)
    }
  4. Access platform-specific information using Ex structs

    master

    While gopsutil provides common functions to minimize platform differences, some platforms offer unique information. To access this, use the Ex (Extended) functions and structs provided within specific packages (currently available in mem and sensor).

    These Ex structs are platform-specific. For example:

    • Linux: Use mem.NewExLinux() to get an ExLinux struct.
    • Windows: Use mem.ExWindows() to get an ExWindows struct.

    Using these makes it explicit that the data provided is unique to that specific operating system.

    ex := NewExWindows()
    v, err := ex.VirtualMemory()
    if err != nil {
        panic(err)
    }
    
    fmt.Println(v.VirtualAvail)
    fmt.Println(v.VirtualTotal)
  5. Check platform support for gopsutil metrics

    master

    gopsutil provides system monitoring metrics across multiple operating systems. Use the following status indicators to verify if a specific metric is supported on your target platform:

    • x: Works
    • b: Almost works, but something is broken
    • X: Not supported
    • (blank): Not supported

    Key Metric Groups

    System Metrics

    Includes cpu_times, cpu_count, cpu_percent, virtual_memory, swap_memory, disk_partitions, disk_io_counters, disk_usage, net_io_counters, boot_time, users, pids, pid_exists, net_connections, and net_protocols.

    Process Class Metrics

    Includes pid, ppid, name, cmdline, create_time, status, cwd, exe, uids, gids, terminal, io_counters, nice, num_fds, num_ctx_switches, num_threads, cpu_times, memory_info, memory_maps, open_files, send_signal, suspend, resume, terminate, kill, username, rlimit, num_handlers, threads, cpu_percent, cpu_affinity, memory_percent, parent, children, connections, and page_faults.

    Host and CPU Metrics

    • HostInfo: hostname, uptime, process, os, platform, platformfamily, virtualization.
    • CPU: VendorID, Family, Model, Stepping, PhysicalID, CoreID, Cores, ModelName, Microcode.
    • LoadAvg: Load1, Load5, Load15.

    Docker Metrics

    • GetDockerID: container id (Linux only).
    • CgroupsCPU: user, system (Linux only).
    • CgroupsMem: various (Linux only).
  6. Override system directory locations via environment variables

    master

    You can redirect gopsutil to use alternative paths for system directories by setting the following environment variables:

    Environment VariableSystem Directory
    HOST_PROC/proc
    HOST_SYS/sys
    HOST_ETC/etc
    HOST_VAR/var
    HOST_RUN/run
    HOST_DEV/dev
    HOST_ROOT/
    HOST_PROC_MOUNTINFO/proc/N/mountinfo
  7. Understand Windows-specific integer types in gopsutil

    master

    When working with Windows-specific data returned by gopsutil, you may encounter various integer types that map to Windows API definitions. Understanding these helps in correctly handling bit-width and signedness for system metrics.

    Unsigned Integers

    • DWORD: 32-bit unsigned integer
    • DWORD32: 32-bit unsigned integer
    • DWORD64: 64-bit unsigned integer
    • DWORDLONG: 64-bit unsigned integer
    • WORD: 16-bit unsigned integer

    Signed Integers

    • INT: 32-bit signed integer
    • LONG: 32-bit signed integer
    • LONGLONG: 64-bit signed integer
    • SHORT: 16-bit integer

    Pointer-sized and Size Types

    These types vary based on whether the architecture is 32-bit or 64-bit (_WIN64):

    • DWORD_PTR: Unsigned long type for pointer precision
    • INT_PTR: __int64 on 64-bit, int on 32-bit
    • LONG_PTR: __int64 on 64-bit, long on 32-bit
    • HALF_PTR: int on 64-bit, short on 32-bit
    • SIZE_T: Maximum number of bytes a pointer can point to (ULONG_PTR)
    • SSIZE_T: Signed version of SIZE_T (LONG_PTR)
    DWORD       // 32-bit unsigned
    DWORDLONG   // 64-bit unsigned
    DWORD_PTR   // pointer precision
    DWORD32     // 32-bit unsigned
    DWORD64     // 64-bit unsigned
    HALF_PTR    // _WIN64 = int, else short
    INT         // 32-bit signed
    INT_PTR     // _WIN64 = __int64 else int
    LONG        // 32-bit signed
    LONGLONG    // 64-bit signed
    LONG_PTR    // _WIN64 = __int64 else long
    SHORT       // 16-bit integer
    SIZE_T      // typedef ULONG_PTR SIZE_T
    SSIZE_T     // typedef LONG_PTR SSIZE_T
    WORD        // 16-bit unsigned