ghw

repository·main·Indexed 22 days ago

https://github.com/jaypipes/ghw

A Go library for hardware inspection and discovery on Linux, Windows, and partially MacOSX. ghw focuses on reporting hardware capacity and capabilities—such as CPU, RAM, block storage, network interfaces, and PCI devices—rather than real-time usage metrics.

Tokens
12K
Snippets
24
Records
65
Agent score
81%

What's inside ghw

  1. Overview of ghw hardware discovery

    main
    ghw is a Go library designed for hardware inspection and discovery on Linux and Windows. It also provides partial support for MacOSX. The library is intended to help developers programmatically discover the capacity and capabilities of host hardware.
  2. Inspect host hardware with ghw

    main

    The ghw library provides functions to inspect various hardware domains on a host system. Each function returns an Info object containing structured data about that specific hardware component.

    Available inspection functions include:

    • ghw.CPU(): CPU information
    • ghw.Memory(): RAM information
    • ghw.Block(): Block storage (disks and partitions)
    • ghw.Topology(): Processor architecture, NUMA topology, and memory cache hierarchy
    • ghw.Network(): Network interfaces
    • ghw.PCI(): PCI devices
    • ghw.GPU(): Graphical processing units
    • ghw.Accelerator(): AI/processing accelerators
    • ghw.Chassis(): Chassis information
    • ghw.BIOS(): BIOS information
    • ghw.Baseboard(): Baseboard information
    • ghw.Product(): Product information
  3. Snapshot design constraints and scope

    main

    Snapshots in ghw are designed to be transparent, safe, and easy to use.

    Scope

    • Platform Support: Snapshots are currently supported only on Linux platforms. Using snapshots on other platforms is unsupported and may break in future releases.

    Content Constraints

    To ensure reliability and safety, snapshots must adhere to these rules:

    1. Information Parity: A snapshot MUST contain the same information as a live system.
    2. No Post-Processing: Aside from unpacking the .tar.gz into the correct directory and pointing ghw to it, no other processing should be required.
    3. Transparency: ghw should treat a snapshot exactly like a live system without requiring special code paths.
    4. Data Only: Snapshots MUST contain only data and no executable code, making them safe to share.
    5. Privacy: Snapshots MUST NOT contain any personally-identifiable data (PII).
  4. Understand MemoryArea and MemoryCache in Topology

    main

    Within the topology structure, memory and caches are described using the following types:

    ghw.MemoryArea

    Describes a collection of physical RAM. In complex systems like NUMA, multiple memory areas may exist (e.g., one per NUMA cell).

    • ghw.MemoryArea.TotalPhysicalBytes: Total physical memory in the area.
    • ghw.MemoryArea.TotalUsableBytes: Memory the system can actually use (accounts for kernel resident memory and reserved bits). Note: This is NOT the amount of memory currently used by processes.

    ghw.MemoryCache

    Represents low-level caches associated with processors and cores.

    • ghw.MemoryCache.Type: Enum (ghw.DATA, ghw.INSTRUCTION, or ghw.UNIFIED).
    • ghw.MemoryCache.Level: Positive integer indicating proximity to the processor (lower is closer/faster).
    • ghw.MemoryCache.SizeBytes: Size of the cache in bytes.
    • ghw.MemoryCache.LogicalProcessors: Array of integers representing logical processors using this cache.
  5. Understand the difference between inspection and monitoring in ghw

    main

    It is critical to distinguish between hardware inspection (what ghw does) and system monitoring (what ghw does NOT do):

    • Use ghw for: Gathering information about hardware capacity and capabilities (e.g., how much RAM is installed, what CPU model is present).
    • Do NOT use ghw for: Tracking usage or metrics that change over time (e.g., current CPU load, memory utilization, or disk I/O throughput). For these tasks, use a monitoring system like Prometheus.
  6. Privilege requirements and warning management in ghw

    main

    ghw is designed to work without root privileges for most discovery tasks. It avoids relying on shellouts to programs like dmidecode which typically require elevated permissions.

    Key behaviors:

    • If certain hardware information requires elevated privileges and is inaccessible, ghw will not return an error. Instead, it will print a warning message to the console.
    • You can suppress these warning messages by setting the GHW_DISABLE_WARNINGS environment variable.

    To ensure your application remains silent even when hardware data is partially unavailable, use:

    export GHW_DISABLE_WARNINGS=true
  7. Create and consume ghw snapshots

    main

    A snapshot is a partial clone of the /proc and /sys subtrees from a Linux machine. You can use snapshots to provide ghw with hardware information from a different machine, which is useful for testing and troubleshooting.

    To create a snapshot, use the ghwc snapshot command. Snapshots created with this tool are guaranteed to be compatible with ghw.

    To consume a snapshot and display hardware information from it, use the ghwc CLI with the -s flag, providing the path to the snapshot file.

  8. Configure ghw for containerized environments

    main

    Because ghw relies on the udev runtime database and sysfs paths, running it inside a container requires specific bind mounts to ensure it can access hardware information.

    To ensure ghw works correctly in a container, you must bind mount the following paths from the host into the container:

    • /dev/disk
    • /run
  9. Control ghw log output and levels

    main

    By default, ghw writes WARN level messages to stderr. You can customize this behavior.

    Via CLI:

    • Change Log Level: Set GHW_LOG_LEVEL to values like debug or error. Setting it to error effectively disables warnings.
    • Use logfmt format: Set GHW_LOG_LOGFMT=1 to output logs in the logfmt standard.

    Programmatically:

    • Change Log Level: Use the ghw.WithLogLevel(slog.Level) modifier.
    • Use logfmt format: Use the ghw.WithLogLogfmt() modifier.
    • Custom Logger: Use the ghw.WithLogger(logger) modifier to provide your own *slog.Logger instance.
    import (
        "log/slog"
    
    	"github.com/jaypipes/ghw"
    )
    
    // Change log level
    bb, err := ghw.Baseboard(ghw.WithLogLevel(slog.LevelDebug))
    
    // Use logfmt
    bb, err := ghw.Baseboard(ghw.WithLogLogfmt())
    
    // Use custom logger
    logger := slog.New(myHandler)
    bb, err := ghw.Baseboard(ghw.WithLogger(logger))
  10. Override root mountpoint or specific paths (Linux)

    main

    If running ghw in an environment with a non-standard root (like a container), you can redirect where ghw looks for system files (e.g., /proc, /sys).

    Via CLI: Set the GHW_CHROOT environment variable to the alternate root path.

    Programmatically:

    • Override Root: Use ghw.WithChroot(path) to set a new root mountpoint.
    • Override Specific Paths: Use ghw.WithPathOverrides(mapping) to provide a ghw.PathOverrides map, which allows mapping specific directories (e.g., /proc to /host-proc). This is composable with WithChroot.

    Note: These features are specifically useful for containers where host filesystems are bind-mounted to non-standard locations.

    // Override root
    cpu, err := ghw.CPU(ghw.WithChroot("/host"))
    
    // Override specific paths
    cpu, err := ghw.CPU(ghw.WithPathOverrides(ghw.PathOverrides{
    	"/proc": "/host-proc",
    	"/sys": "/host-sys",
    }))
  11. Disable warning messages in ghw

    main

    When ghw cannot retrieve certain hardware information, it may output warnings to stderr.

    Via CLI: Set the GHW_DISABLE_WARNINGS environment variable to 1.

    Programmatically: Use the ghw.WithDisableWarnings() modifier when calling discovery functions.

    $ GHW_DISABLE_WARNINGS=1 ghwc memory
  12. Disable external tool calls in ghw

    main

    By default, ghw may execute external programs (such as ethtool) to retrieve hardware capabilities. If you are processing a hardware snapshot on a different host, or if you want to rely exclusively on pseudo-filesystems like sysfs, you should disable this behavior to prevent inconsistent data.

    WARNING: Disabling external tools will result in less data being returned. There is no fallback mechanism if a tool is disabled. Specifically, on MacOSX/Darwin, disabling external tools disables block storage support entirely.