gohai

command module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 1 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

gohai

An SDK-first Go library for collecting system facts.

release codecov license build powered by conventional commits built with just gitHub commit activity go reference

SDK first, CLI second, one contract for both.

Sixty-two collectors across ten categories, each wrapping a well-maintained library rather than reimplementing it, and each returning a typed struct. Import it, or use the CLI over the same collectors.

Install

curl -fsSL https://github.com/osapi-io/gohai/raw/main/install.sh | bash

Installs to ~/.local/bin (or /usr/local/bin as root). SHA-256 checksums verified. Override with GOHAI_INSTALL_DIR=/some/path or pin a version with GOHAI_VERSION=1.0.0.

Other install methods

Go install

go install github.com/osapi-io/gohai@latest

As a library dependency

go get github.com/osapi-io/gohai

Build from source

git clone https://github.com/osapi-io/gohai.git
cd gohai
go build -o gohai .

Features

Feature Description
πŸ”Œ Pluggable Collectors Enable/disable individual fact collectors
πŸ—οΈ Typed Structs Strongly-typed Go structs for all facts
πŸ“„ JSON Output Nested JSON output for CLI and programmatic use
πŸ—ΊοΈ Flat Map Access Dot-separated key-value access
🐧 Cross-Platform Linux primary, macOS best-effort
πŸ”— Collector Dependencies Automatic dependency resolution between facts
⚑ Concurrent Collection Collectors run concurrently; dependency graph resolves order when any collector declares deps.
⏱️ Per-Collector Timings Opt-in --with-timings / WithTimings() embeds per-collector durations, status, and error messages under _timings in the JSON output
πŸ“Š OCSF + OpenTelemetry + Ohai Field names follow OCSF then OpenTelemetry; data sources mirror Chef Ohai's plugins
πŸ”„ Native OCSF Output --format ocsf produces a standards-compliant OCSF inventory_info event (class_uid 5001), feed directly into SIEMs and data lakes
πŸ”Œ SDK Integration Import as a Go package into any Go service

Collectors

62 collectors across 10 categories. See the Collectors reference for the full catalog, implementation status, default membership, schema mappings, and per-collector docs β€” it lists 65 entries, the other three being deprecated and never implemented.

Collectors are individually toggled using node_exporter-style flags. --collector.<name> to opt in, --no-collector.<name> to opt out. SDK consumers use gohai.WithEnabled(...) / gohai.WithDisabled(...) / gohai.WithCollectors(...).

Defaults are opt-in. gohai.New() returns an empty registry. Pass gohai.WithDefaults() for the recommended set (cheap + near-universal, identity, base hardware, network, load, virt detect). The CLI wires WithDefaults() automatically; pass --no-defaults to skip it and use only explicit --collector.X flags.

Usage

CLI

gohai collect --pretty                          # default collectors, pretty JSON
gohai collect --format ocsf --pretty            # OCSF inventory_info event
gohai collect --flat                            # flat key=value pairs
gohai collect --no-defaults --collector.cpu     # specific collectors only
gohai collect --pretty | gohai validate          # validate against schema
gohai version                                   # build info

SDK

Importers should read the full API reference on pkg.go.dev for every Option, Facts field, and Info struct. That is the authoritative list. The examples below show the two usage shapes.

Collecting facts (producer side):

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/osapi-io/gohai/pkg/gohai"
)

func main() {
    g, err := gohai.New(
        gohai.WithDefaults(),                      // the recommended set
        gohai.WithEnabled("process", "packages"),  // plus these two
    )
    if err != nil {
        log.Fatal(err)
    }

    facts, err := g.Collect(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    // Typed access β€” pkg.go.dev documents every Info struct's fields.
    fmt.Printf("OS:     %s %s\n", facts.Platform.Name, facts.Platform.Version)
    fmt.Printf("Cores:  %d\n", facts.CPU.Cores)
    fmt.Printf("Memory: %d bytes\n", facts.Memory.Total)

    // Serialize for transport / storage.
    b, _ := facts.PrettyJSON()
    fmt.Println(string(b))
}

Consuming stored facts (decoder side, e.g. a server that received a fact blob from an agent):

var facts gohai.Facts
if err := json.Unmarshal(payload, &facts); err != nil {
    log.Fatal(err)
}

// Typed access on the decoded value β€” no map[string]any guessing.
fmt.Println(facts.Platform.Name, facts.CPU.Cores)
fmt.Println(facts.Network.DefaultInterface)

Per-collector timings + error messages can be embedded in Facts by adding gohai.WithTimings() to gohai.New(...), useful for debugging slow collectors or seeing why a collector failed without blocking the run. See the Timings field on pkg.go.dev.

Detecting which cloud you're on. Enable the cloud collectors (WithCategory("cloud")) and switch on Facts.Cloud(), which returns a *Cloud with Name set to a provider identifier, or nil when no cloud was detected. Use the exported gohai.CloudAWS / CloudGCE / CloudAzure / etc. constants instead of raw strings:

g, _ := gohai.New(gohai.WithCategory("cloud"))
facts, _ := g.Collect(ctx)

cloud := facts.Cloud()
if cloud == nil { return } // not on a supported cloud

switch cloud.Name {
case gohai.CloudAWS:
    fmt.Println(facts.Ec2.Region, facts.Ec2.IAMInfo.InstanceProfileArn)
case gohai.CloudGCE:
    fmt.Println(facts.Gce.ProjectID, facts.Gce.Zone)
}

Rich per-provider data lives on the typed Facts.Ec2 / Facts.Gce / etc. field. See docs/collectors/cloud.md for the full pattern.

Examples

Each example is a standalone Go program you can read and run.

Example What it shows
default-collection Collect the default set and print it as JSON
select-collectors Restrict collection to named collectors
categories Select by category, then subtract one
typed-facts Read results as typed fields, by key path, and as a flat map
timings Surface per-collector duration and failure
list-collectors Enumerate collectors without collecting

Documentation

  • Package documentation on pkg.go.dev. Generated API reference. Every Option, Facts field, and Info struct is documented there. This is the authoritative SDK reference.
  • Collectors reference. One doc per collector with fields, schema mappings (OCSF + OpenTelemetry), and Ohai source alignment.
  • Schemas. JSON Schema, field-naming strategy (OCSF > OTel > convention), OCSF gap analysis, and cloud canonical overlay.
  • Contributing. Prerequisites, setup, testing, commit conventions.
  • Collector methodology. Library selection, field naming, and data sources.

gohai builds on the following projects, as methodology references, as backing libraries we wrap, or as peers solving adjacent problems:

Fact collectors (direct peers):

  • Chef Ohai. The canonical reference. Ruby-based plugin-driven fact collector; every gohai collector cross-references the corresponding Ohai plugin for data sources and per-distro edge cases.
  • Puppet Facter. Puppet's equivalent. Different JSON shape, overlapping fact surface.
  • osquery. Meta's SQL-based endpoint visibility. Different abstraction (SQL), same data space; common reference point when evaluating an inventory tool.
  • Ansible setup is Ansible's built-in fact gathering, exposed as ansible_facts in playbooks.
  • Salt Grains. SaltStack's static facts.

Backing libraries (we import these):

  • gopsutil. Primary source for dynamic runtime state (memory, network I/O, process enumeration, virtualization detection).
  • ghw. Canonical for physical hardware topology (CPU NUMA, DIMMs, block devices, DMI, GPU, PCI).
  • procfs. Linux /proc and /sys parsing when a library doesn't cover a field.
  • go-sysinfo. Elastic's alternative for host/platform/kernel facts.
  • avfs. Virtual filesystem abstraction used in every collector that reads files, so tests can run against in-memory fixtures.

Other Go libraries in the space:

  • gosigar. Cloud Foundry's Go port of Hyperic Sigar. Historical reference for Go-based host metrics.
  • go-ps. Narrow process-listing library. gopsutil supersedes it for our use.
  • goprocinfo. Lightweight /proc parser. gopsutil + procfs cover the same ground for us.

Methodology references (we read, don't import):

  • node_exporter. The reference we check against for tricky Linux /proc and /sys parsing. Apache-2, but we rewrite in our style rather than import.
  • psutil. The Python library gopsutil is a port of; the original design reference for the dynamic-state facts.

Contributing

See the Contributing guide for prerequisites, setup, conventions, and the PR workflow.

License

The MIT License.

Documentation ΒΆ

Overview ΒΆ

Command gohai collects system facts and prints them as JSON.

Directories ΒΆ

Path Synopsis
Package cmd implements the gohai CLI.
Package cmd implements the gohai CLI.
internal
cli
Package cli holds CLI-only output helpers β€” never imported by the SDK under pkg/gohai/, only by cmd/.
Package cli holds CLI-only output helpers β€” never imported by the SDK under pkg/gohai/, only by cmd/.
cloudmetadata
Package cloudmetadata is the shared HTTP client every cloud-provider collector (ec2, gce, azure, digital_ocean, openstack, oci, linode, alibaba, scaleway) uses to talk to its provider's link-local metadata endpoint.
Package cloudmetadata is the shared HTTP client every cloud-provider collector (ec2, gce, azure, digital_ocean, openstack, oci, linode, alibaba, scaleway) uses to talk to its provider's link-local metadata endpoint.
collector
Package collector defines the Collector interface gohai uses to plug fact collectors into the registry.
Package collector defines the Collector interface gohai uses to plug fact collectors into the registry.
collector/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
executor
Package executor abstracts OS command execution.
Package executor abstracts OS command execution.
executor/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
platform
Package platform provides cross-platform OS/distro detection used by gohai collectors to dispatch to the correct per-OS implementation.
Package platform provides cross-platform OS/distro detection used by gohai collectors to dispatch to the correct per-OS implementation.
validate
Package validate provides JSON Schema validation for gohai output.
Package validate provides JSON Schema validation for gohai output.
pkg
gohai
Package gohai is the public SDK for collecting system facts.
Package gohai is the public SDK for collecting system facts.
gohai/collectors/alibaba
Package alibaba collects Alibaba Cloud ECS instance metadata from the link-local metadata server at http://100.100.100.200/.
Package alibaba collects Alibaba Cloud ECS instance metadata from the link-local metadata server at http://100.100.100.200/.
gohai/collectors/azure
Package azure collects Azure instance metadata from the link-local metadata server at http://169.254.169.254/metadata/instance.
Package azure collects Azure instance metadata from the link-local metadata server at http://169.254.169.254/metadata/instance.
gohai/collectors/block_device
Package blockdevice reports block device sysfs attributes for each device found under /sys/block.
Package blockdevice reports block device sysfs attributes for each device found under /sys/block.
gohai/collectors/command
Package command provides Ohai command/ps parity: runs `ps -ef` and stores its raw output lines.
Package command provides Ohai command/ps parity: runs `ps -ef` and stores its raw output lines.
gohai/collectors/cpu
Package cpu collects CPU topology, model, feature flags, cache layout, NUMA layout, and hardware vulnerability mitigation status.
Package cpu collects CPU topology, model, feature flags, cache layout, NUMA layout, and hardware vulnerability mitigation status.
gohai/collectors/digital_ocean
Package digital_ocean collects DigitalOcean droplet metadata from the link-local metadata server at http://169.254.169.254/metadata/v1.json.
Package digital_ocean collects DigitalOcean droplet metadata from the link-local metadata server at http://169.254.169.254/metadata/v1.json.
gohai/collectors/disk
Package disk collects per-device disk I/O counters (node_exporter-style).
Package disk collects per-device disk I/O counters (node_exporter-style).
gohai/collectors/dmi
Package dmi reports SMBIOS / DMI data β€” BIOS, baseboard, chassis, and product identity.
Package dmi reports SMBIOS / DMI data β€” BIOS, baseboard, chassis, and product identity.
gohai/collectors/docker
Package docker reports Docker server version, containers, and images on the host.
Package docker reports Docker server version, containers, and images on the host.
gohai/collectors/ec2
Package ec2 collects AWS EC2 instance metadata from the link-local metadata server at http://169.254.169.254/.
Package ec2 collects AWS EC2 instance metadata from the link-local metadata server at http://169.254.169.254/.
gohai/collectors/filesystem
Package filesystem collects filesystems known to the host, both mounted and (on Linux, via lsblk) unmounted.
Package filesystem collects filesystems known to the host, both mounted and (on Linux, via lsblk) unmounted.
gohai/collectors/fips
Package fips reports whether the kernel is running in FIPS mode (FIPS 140-2 / 140-3).
Package fips reports whether the kernel is running in FIPS mode (FIPS 140-2 / 140-3).
gohai/collectors/gce
Package gce collects instance and project metadata from the Google Compute Engine metadata server (http://metadata.google.internal/).
Package gce collects instance and project metadata from the Google Compute Engine metadata server (http://metadata.google.internal/).
gohai/collectors/gpu
Package gpu reports graphics / compute cards present on the host.
Package gpu reports graphics / compute cards present on the host.
gohai/collectors/grub2
Package grub2 reads the GRUB2 environment block and reports the key=value pairs it contains.
Package grub2 reads the GRUB2 environment block and reports the key=value pairs it contains.
gohai/collectors/hardware
Package hardware collects macOS-specific hardware facts β€” the identity, memory, and firmware fields surfaced by `system_profiler SPHardwareDataType`, attached storage from `SPStorageDataType`, and battery / AC charger info from `SPPowerDataType`.
Package hardware collects macOS-specific hardware facts β€” the identity, memory, and firmware fields surfaced by `system_profiler SPHardwareDataType`, attached storage from `SPStorageDataType`, and battery / AC charger info from `SPPowerDataType`.
gohai/collectors/hostname
Package hostname collects the short hostname, fully qualified domain name, DNS domain, and friendly machine name.
Package hostname collects the short hostname, fully qualified domain name, DNS domain, and friendly machine name.
gohai/collectors/hostnamectl
Package hostnamectl parses `hostnamectl` output on Linux to report static hostname, chassis type, deployment environment, kernel info, and hardware model.
Package hostnamectl parses `hostnamectl` output on Linux to report static hostname, chassis type, deployment environment, kernel info, and hardware model.
gohai/collectors/init
Package initd detects the init system a Linux host is using β€” systemd, upstart, sysvinit, openrc, or runit β€” by reading /proc/1/comm.
Package initd detects the init system a Linux host is using β€” systemd, upstart, sysvinit, openrc, or runit β€” by reading /proc/1/comm.
gohai/collectors/interrupts
Package interrupts reports IRQ statistics and per-CPU event counts as found in /proc/interrupts on Linux.
Package interrupts reports IRQ statistics and per-CPU event counts as found in /proc/interrupts on Linux.
gohai/collectors/ipc
Package ipc reports Linux IPC subsystem kernel parameters: semaphore limits, message queue limits, and shared memory limits, all read from the /proc/sys/kernel/ sysctl tree.
Package ipc reports Linux IPC subsystem kernel parameters: semaphore limits, message queue limits, and shared memory limits, all read from the /proc/sys/kernel/ sysctl tree.
gohai/collectors/kernel
Package kernel reports kernel identity (name, release, version, machine, processor, high-level OS) plus macOS Rosetta 2 translation state.
Package kernel reports kernel identity (name, release, version, machine, processor, high-level OS) plus macOS Rosetta 2 translation state.
gohai/collectors/kernel_modules
Package kernelmodules enumerates loaded kernel modules (Linux) / kexts (macOS).
Package kernelmodules enumerates loaded kernel modules (Linux) / kexts (macOS).
gohai/collectors/languages
Package languages reports installed programming language runtimes on the host.
Package languages reports installed programming language runtimes on the host.
gohai/collectors/libvirt
Package libvirt collects libvirt domain information from a KVM/QEMU host.
Package libvirt collects libvirt domain information from a KVM/QEMU host.
gohai/collectors/linode
Package linode detects Linode hosts and reports their public / private IPs.
Package linode detects Linode hosts and reports their public / private IPs.
gohai/collectors/livepatch
Package livepatch reports the status of kernel livepatches loaded on a Linux host.
Package livepatch reports the status of kernel livepatches loaded on a Linux host.
gohai/collectors/load
Package load collects system load averages (1/5/15-minute).
Package load collects system load averages (1/5/15-minute).
gohai/collectors/lsb
Package lsb reports Linux Standard Base identification fields via the `lsb_release` CLI β€” matches Ohai's linux/lsb plugin.
Package lsb reports Linux Standard Base identification fields via the `lsb_release` CLI β€” matches Ohai's linux/lsb plugin.
gohai/collectors/machine_id
Package machineid reports the host's stable machine identifier.
Package machineid reports the host's stable machine identifier.
gohai/collectors/mdadm
Package mdadm reports Linux software RAID arrays discovered via /proc/mdstat and enriched with `mdadm --detail /dev/<device>`.
Package mdadm reports Linux software RAID arrays discovered via /proc/mdstat and enriched with `mdadm --detail /dev/<device>`.
gohai/collectors/memory
Package memory reports system memory totals, usage buckets, kernel allocations, page-cache state, and hugepages / DirectMap layout on Linux; on macOS it adds the wired / speculative / compressed buckets that the Darwin VM reports.
Package memory reports system memory totals, usage buckets, kernel allocations, page-cache state, and hugepages / DirectMap layout on Linux; on macOS it adds the wired / speculative / compressed buckets that the Darwin VM reports.
gohai/collectors/network
Package network reports network interfaces, structured per-address data (family / prefix / scope / netmask / broadcast), per-interface I/O counters, the routing table, and top-level default interface + gateway facts (v4 + v6).
Package network reports network interfaces, structured per-address data (family / prefix / scope / netmask / broadcast), per-interface I/O counters, the routing table, and top-level default interface + gateway facts (v4 + v6).
gohai/collectors/oci
Package oci collects Oracle Cloud Infrastructure instance metadata from the link-local metadata server at http://169.254.169.254/opc/v2.
Package oci collects Oracle Cloud Infrastructure instance metadata from the link-local metadata server at http://169.254.169.254/opc/v2.
gohai/collectors/openstack
Package openstack collects OpenStack (Nova) instance metadata from the link-local metadata server at http://169.254.169.254/.
Package openstack collects OpenStack (Nova) instance metadata from the link-local metadata server at http://169.254.169.254/.
gohai/collectors/os_release
Package osrelease parses /etc/os-release into typed fields.
Package osrelease parses /etc/os-release into typed fields.
gohai/collectors/package_mgr
Package packagemgr detects which package manager the host is configured to use β€” apt on Debian-family, dnf/yum on RHEL-family, brew on macOS, etc.
Package packagemgr detects which package manager the host is configured to use β€” apt on Debian-family, dnf/yum on RHEL-family, brew on macOS, etc.
gohai/collectors/packages
Package packages reports the list of installed packages on the host.
Package packages reports the list of installed packages on the host.
gohai/collectors/pci
Package pci enumerates PCI devices attached to the host.
Package pci enumerates PCI devices attached to the host.
gohai/collectors/platform
Package platform reports OS identification β€” canonical name, version, family, and architecture.
Package platform reports OS identification β€” canonical name, version, family, and architecture.
gohai/collectors/process
Package process collects a snapshot of running processes.
Package process collects a snapshot of running processes.
gohai/collectors/root_group
Package rootgroup reports the primary group name for the root user.
Package rootgroup reports the primary group name for the root user.
gohai/collectors/rpm
Package rpm reports RPM macro definitions from `rpm --showrc`.
Package rpm reports RPM macro definitions from `rpm --showrc`.
gohai/collectors/scaleway
Package scaleway collects Scaleway instance metadata from the link-local metadata server at http://169.254.42.42/.
Package scaleway collects Scaleway instance metadata from the link-local metadata server at http://169.254.42.42/.
gohai/collectors/scsi
Package scsi enumerates SCSI devices visible to the host by parsing the output of `lsscsi`.
Package scsi enumerates SCSI devices visible to the host by parsing the output of `lsscsi`.
gohai/collectors/selinux
Package selinux reports SELinux status, mode, and policy information.
Package selinux reports SELinux status, mode, and policy information.
gohai/collectors/services
Package services reports systemd service states on Linux.
Package services reports systemd service states on Linux.
gohai/collectors/sessions
Package sessions reports currently logged-in user sessions.
Package sessions reports currently logged-in user sessions.
gohai/collectors/shard
Package shard derives a deterministic shard seed from stable host identity.
Package shard derives a deterministic shard seed from stable host identity.
gohai/collectors/shells
Package shells reports the list of valid login shells installed on the host (contents of /etc/shells).
Package shells reports the list of valid login shells installed on the host (contents of /etc/shells).
gohai/collectors/ssh
Package ssh collects SSH host key fingerprints from /etc/ssh/.
Package ssh collects SSH host key fingerprints from /etc/ssh/.
gohai/collectors/sysconf
Package sysconf reports POSIX sysconf(3) values for clock tick rate, page size, and processor counts.
Package sysconf reports POSIX sysconf(3) values for clock tick rate, page size, and processor counts.
gohai/collectors/sysctl
Package sysctl collects kernel parameters by running `sysctl -a`.
Package sysctl collects kernel parameters by running `sysctl -a`.
gohai/collectors/systemd_paths
Package systemdpaths reports standard systemd directory paths by running `systemd-path` and parsing its "name: /path" output.
Package systemdpaths reports standard systemd directory paths by running `systemd-path` and parsing its "name: /path" output.
gohai/collectors/tc
Package tc reports Linux traffic control (qdisc) configuration via `tc -s qdisc show`.
Package tc reports Linux traffic control (qdisc) configuration via `tc -s qdisc show`.
gohai/collectors/timezone
Package timezone collects the system timezone (IANA name, short abbreviation, and offset from UTC).
Package timezone collects the system timezone (IANA name, short abbreviation, and offset from UTC).
gohai/collectors/uptime
Package uptime collects system uptime, boot time, and (on Linux) aggregate CPU idle time.
Package uptime collects system uptime, boot time, and (on Linux) aggregate CPU idle time.
gohai/collectors/users
Package users enumerates system user and group accounts from /etc/passwd and /etc/group, plus the effective current user.
Package users enumerates system user and group accounts from /etc/passwd and /etc/group, plus the effective current user.
gohai/collectors/virtualbox
Package virtualbox collects VirtualBox guest additions data from a guest VM.
Package virtualbox collects VirtualBox guest additions data from a guest VM.
gohai/collectors/virtualization
Package virtualization detects every hypervisor and container runtime the host participates in β€” as guest, host, or both.
Package virtualization detects every hypervisor and container runtime the host participates in β€” as guest, host, or both.
gohai/collectors/vmware
Package vmware collects VMware Tools data from a VMware guest VM.
Package vmware collects VMware Tools data from a VMware guest VM.
gohai/collectors/zpools
Package zpools reports ZFS pool status by running `zpool list -H -o name,size,alloc,free,health,altroot`.
Package zpools reports ZFS pool status by running `zpool list -H -o name,size,alloc,free,health,altroot`.
gohai/ocsf
Package ocsf provides OCSF-shaped output for gohai's system facts.
Package ocsf provides OCSF-shaped output for gohai's system facts.
Package schemas embeds the generated JSON Schema for gohai.Facts.
Package schemas embeds the generated JSON Schema for gohai.Facts.
gen command
Package main generates schemas/gohai.schema.json from gohai.Facts.
Package main generates schemas/gohai.schema.json from gohai.Facts.

Jump to

Keyboard shortcuts

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