hostmetrics

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 15 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

Node observations

Artifact readers consume explicitly supplied io.Reader values. They never open paths, perform network requests, discover hardware, or run privileged probes. The optional Redfish HTTP client below performs explicit bounded requests. Version 1 snapshots retain caller-supplied node/source/version/clock identities and query bounds. Query bounds do not identify sensor sample times. Missing statistics are absent; malformed, oversized, duplicate and overflowing statistics are refused.

Supported source formats, pinned to Linux v6.8:

  • PSI: system cpu/memory/io some/full averages and cumulative microseconds. System CPU full is undefined and omitted. No cgroup PSI interpretation.
  • meminfo: MemTotal, MemAvailable, MemFree, SwapTotal and SwapFree, kB converted to bytes.
  • network statistics: selected rx/tx bytes, packets and errors.
  • RDMA counters: selected port receive/transmit data in four-byte words and packet counts.
  • block statistics: completed reads/writes and 512-byte sectors from a selected device's stat file.

The DMTF Sensor.v1_9_0 schema reader accepts caller-selected URI/ID power (W) and temperature (Cel) projections. It requires implementation metadata and preserves reported status. Missing/null status remains unknown. Numeric readings from inactive sensors are retained in the artifact projection but become unavailable in health composition. Null readings remain unavailable, synthesized readings remain derived, and vendor health remains a reported judgment. ReadingTime is retained verbatim without inventing clock calibration. Other fields are ignored after bounded duplicate/depth checks; this is a typed projection, not a complete Redfish schema validator. The artifact reader issues no BMC requests.

Counter deltas require caller-established source/resource continuity and reset handling. Readers do not derive rates or attribute node activity to GPUs. JoinNodeHealth and JoinRedfishHealth in nvtelemetry require explicit node/device and clock joins. Chassis power is never renamed to GPU power or energy. Health composition leaves sensor time unknown; caller retains the Redfish artifact for vendor health and source timestamp interpretation.

Source-derived unit, overflow and public health composition controls are host verification. Physical PSI/sysfs/RDMA/block/BMC endpoint qualification, authentication and deployment integration remain separate gates.

Explicit Redfish HTTP acquisition

NewRedfishHTTPClient takes an explicit base URL, client, authentication headers, per-response byte bound, request deadline and finite collection/page limits. It copies client/headers, refuses redirects and rejects cross-origin, noncanonical, escaped or out-of-namespace paths before sending credentials. No BMC discovery occurs. Supply HTTPS with verified trust and an explicitly authorized BMC; plaintext HTTP is suitable only when the caller authorizes that transport.

GetSensor uses the existing typed sensor projection with explicit caller context, expected URI and ID. GetCollection follows same-origin next links, refuses page cycles/duplicate members, retains known advertised counts and refuses contradictory or truncated counts. Exceeding bounds returns an error, never a complete partial collection. Missing advertised counts remain unknown. Transport errors omit response bodies, URLs and credentials. Query cancellation is checked before acquisition and return; custom transports must honor context.

Runnable examples and actual local authenticated HTTP fixtures qualify protocol behavior. They do not qualify physical BMC credentials, vendor firmware, sensor calibration, chassis/GPU attribution or production deployment. No skipped test is recorded as a performed hardware test.

Documentation

Overview

Package hostmetrics reads caller-selected Linux node statistics without opening files, discovering devices, or associating a node with a GPU.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Unit

func Unit(name string) (string, bool)

Unit returns the canonical unit of a supported node field.

Example
u, ok := Unit("node.rdma.port_rcv_data")
fmt.Println(u, ok)
Output:
4-byte_words true

Types

type Context

type Context struct {
	NodeID, SourceID, Version, ClockDomain, ClockEpoch string
	QueryStartNanos, QueryEndNanos                     int64
}

Context identifies the source and the caller's query interval. Query times are not sensor timestamps. Version names the source kernel or exporter.

Example
c := fixture()
fmt.Println(c.NodeID, c.QueryStartNanos, c.QueryEndNanos)
Output:
node 10 20

type Metric

type Metric struct {
	Name, Unit, Resource string
	Value                float64
	Integer              bool
	UintValue            uint64
}

Metric preserves integer counters exactly. Resource is the explicitly selected interface, RDMA port, block device, or pressure resource.

type RedfishCollection

type RedfishCollection struct {
	URI                string   // Base collection URI
	Members            []string // Caller-admitted member @odata.id URIs
	Count              int      // Total collected members count
	AdvertisedCount    int      // Advertised Members@odata.count when provided (-1 if omitted)
	HasAdvertisedCount bool     // True if Members@odata.count was specified by the BMC
}

RedfishCollection represents a complete DMTF Redfish collection aggregated across bounded pagination pages.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	collection := hostmetrics.RedfishCollection{URI: "/redfish/v1/Chassis", Count: 1, Members: []string{"/redfish/v1/Chassis/1"}}
	fmt.Println(collection.Count, collection.HasAdvertisedCount)
}
Output:
1 false

type RedfishCollectionPage

type RedfishCollectionPage struct {
	URI                string
	HasAdvertisedCount bool
	AdvertisedCount    int
	Members            []string
	NextLink           string
}

RedfishCollectionPage contains members and count metadata from a single DMTF Redfish collection response.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	page := hostmetrics.RedfishCollectionPage{URI: "/redfish/v1/Chassis", Members: []string{"/redfish/v1/Chassis/1"}}
	fmt.Println(len(page.Members), page.HasAdvertisedCount)
}
Output:
1 false

func ReadRedfishCollection

func ReadRedfishCollection(r io.Reader, uri string, maxBytes int64) (RedfishCollectionPage, error)

ReadRedfishCollection parses a single DMTF Redfish collection artifact. The URI must equal the caller-expected collection URI.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	raw := `{"@odata.id":"/redfish/v1/Chassis","Members":[{"@odata.id":"/redfish/v1/Chassis/1"}]}`
	page, err := hostmetrics.ReadRedfishCollection(strings.NewReader(raw), "/redfish/v1/Chassis", 4096)
	fmt.Println(len(page.Members), page.HasAdvertisedCount, err)
}
Output:
1 false <nil>

type RedfishHTTPClient

type RedfishHTTPClient struct {
	// contains filtered or unexported fields
}

RedfishHTTPClient fetches caller-selected DMTF Redfish resources from a BMC endpoint using a caller-configured HTTP client and explicit bounds. The zero value is not usable. Construct using NewRedfishHTTPClient.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	var client hostmetrics.RedfishHTTPClient
	_, err := client.GetCollection(context.Background(), "/redfish/v1/Chassis")
	fmt.Println(err != nil)
}
Output:
true

func NewRedfishHTTPClient

func NewRedfishHTTPClient(c RedfishHTTPConfig) (*RedfishHTTPClient, error)

NewRedfishHTTPClient creates a client for fetching Redfish artifacts from an explicit base BMC URL. Redirects are refused to prevent credential leakage to unintended endpoints.

Example
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	_, _ = io.WriteString(w, `{"@odata.type":"#Sensor.v1_9_0.Sensor","@odata.id":"/redfish/v1/Chassis/1/Sensors/power","Id":"power","ReadingType":"Power","ReadingUnits":"W","Implementation":"PhysicalSensor","Status":{"State":"Enabled","Health":"OK"},"Reading":250.0}`)
}))
defer s.Close()

client, err := NewRedfishHTTPClient(RedfishHTTPConfig{
	BaseURL:              s.URL,
	Client:               s.Client(),
	Headers:              http.Header{"X-Auth-Token": []string{"caller-token"}},
	MaxResponseBytes:     4096,
	RequestTimeout:       5 * time.Second,
	MaxCollectionMembers: 64,
	MaxPages:             4,
})
if err != nil {
	panic(err)
}

hostCtx := Context{"node-1", "bmc", "1.0", "mono", "boot", 100, 200}
sensor, err := client.GetSensor(context.Background(), hostCtx, "/redfish/v1/Chassis/1/Sensors/power", "power")
if err != nil {
	panic(err)
}
fmt.Printf("%.1f %s %s\n", *sensor.Reading, sensor.Unit, sensor.Health)
Output:
250.0 W OK

func (*RedfishHTTPClient) GetCollection

func (c *RedfishHTTPClient) GetCollection(ctx context.Context, collectionURI string) (RedfishCollection, error)

GetCollection fetches a DMTF Redfish collection resource from the BMC, following same-origin pagination nextLinks up to the configured MaxPages and MaxCollectionMembers. Cross-origin nextLinks, redirect responses, and pagination cycles are refused. Advertised member counts are preserved and enforced against collected totals.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, `{"@odata.id":"/redfish/v1/Chassis","Members@odata.count":1,"Members":[{"@odata.id":"/redfish/v1/Chassis/1"}]}`)
	}))
	defer server.Close()
	client, err := hostmetrics.NewRedfishHTTPClient(hostmetrics.RedfishHTTPConfig{BaseURL: server.URL, Client: server.Client(), MaxResponseBytes: 4096, RequestTimeout: time.Second, MaxCollectionMembers: 16, MaxPages: 2})
	if err != nil {
		fmt.Println(err)
		return
	}
	collection, err := client.GetCollection(context.Background(), "/redfish/v1/Chassis")
	fmt.Println(collection.Count, collection.HasAdvertisedCount, err)
}
Output:
1 true <nil>

func (*RedfishHTTPClient) GetSensor

func (c *RedfishHTTPClient) GetSensor(ctx context.Context, hostCtx Context, uri, id string) (RedfishSensor, error)

GetSensor fetches a DMTF Sensor.v1_9_0 resource from the BMC and validates it against the provided host Context, expected URI, and sensor ID. BMC timestamps are retained verbatim and do not constitute sensor calibration proof. Transport errors and HTTP status errors never leak URLs, query parameters, or credentials.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, `{"@odata.type":"#Sensor.v1_9_0.Sensor","@odata.id":"/redfish/v1/Chassis/1/Sensors/power","Id":"power","ReadingType":"Power","ReadingUnits":"W","Implementation":"PhysicalSensor","Reading":250}`)
	}))
	defer server.Close()
	client, err := hostmetrics.NewRedfishHTTPClient(hostmetrics.RedfishHTTPConfig{BaseURL: server.URL, Client: server.Client(), MaxResponseBytes: 4096, RequestTimeout: time.Second, MaxCollectionMembers: 16, MaxPages: 2})
	if err != nil {
		fmt.Println(err)
		return
	}
	source := hostmetrics.Context{NodeID: "node-1", SourceID: "bmc-1", Version: "fixture", ClockDomain: "process", ClockEpoch: "epoch-1", QueryStartNanos: 0, QueryEndNanos: 1}
	sensor, err := client.GetSensor(context.Background(), source, "/redfish/v1/Chassis/1/Sensors/power", "power")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(*sensor.Reading, sensor.Unit)
}
Output:
250 W

type RedfishHTTPConfig

type RedfishHTTPConfig struct {
	BaseURL              string        // Base BMC URL (e.g. "https://bmc.example.internal"); scheme must be http or https, no query/user/fragment
	Client               *http.Client  // Caller-supplied HTTP client (must be non-nil)
	Headers              http.Header   // Cloned headers for authentication (e.g. X-Auth-Token, Authorization)
	MaxResponseBytes     int64         // Maximum bytes to read per response (1 <= MaxResponseBytes <= 1<<20)
	RequestTimeout       time.Duration // Per-request timeout (1ms <= RequestTimeout <= 60s)
	MaxCollectionMembers int           // Maximum members admitted in a collection (1 <= MaxCollectionMembers <= 1024)
	MaxPages             int           // Maximum pagination pages admitted (1 <= MaxPages <= 32)
}

RedfishHTTPConfig supplies explicit connection and bounds settings for fetching DMTF Redfish artifacts from a caller-selected BMC endpoint. No credentials or endpoints are discovered automatically. Live physical BMC qualification requires physical BMC endpoint hardware and authenticated credentials which remain an external qualification gate.

Example
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/tmc/lib/ebpfhost/hostmetrics"
)

func main() {
	config := hostmetrics.RedfishHTTPConfig{BaseURL: "https://bmc.example", Client: http.DefaultClient, MaxResponseBytes: 4096, RequestTimeout: time.Second, MaxCollectionMembers: 16, MaxPages: 2}
	_, err := hostmetrics.NewRedfishHTTPClient(config)
	fmt.Println(err)
}
Output:
<nil>

type RedfishSensor

type RedfishSensor struct {
	Context                                                                    Context
	ID, URI, ReadingType, Unit, ImplementationType, State, Health, ReadingTime string
	Reading                                                                    *float64
}

RedfishSensor is the bounded Sensor.v1_9_0 power/temperature projection. Vendor health is a reported judgment, not an independently measured result. ReadingTime is retained verbatim; no host-clock calibration is inferred. Empty State means absent or null vendor state. A numeric Reading can be retained while the sensor is inactive; it is not then an available reading.

func ReadRedfishSensor

func ReadRedfishSensor(r io.Reader, c Context, uri, id string, maxBytes int64) (RedfishSensor, error)

ReadRedfishSensor reads a supplied DMTF Sensor.v1_9_0 artifact. URI and ID must equal caller-selected identities. Other schema fields are ignored after duplicate/depth checks. No requests, discovery, or sensor controls occur.

Example
s, _ := ReadRedfishSensor(strings.NewReader(sensor), fixture(), "/redfish/v1/Chassis/1/Sensors/power", "power", 1024)
fmt.Println(*s.Reading, s.Health)
Output:
125.5 Warning

func (RedfishSensor) Validate

func (s RedfishSensor) Validate() error

Validate checks the supported Redfish projection without interpreting health.

Example
s, _ := ReadRedfishSensor(strings.NewReader(sensor), fixture(), "/redfish/v1/Chassis/1/Sensors/power", "power", 1024)
fmt.Println(s.Validate())
Output:
<nil>

type Snapshot

type Snapshot struct {
	Version int
	Context Context
	Metrics []Metric
}

Snapshot is version 1 node evidence. A failed read returns no snapshot; missing fields are absent, never synthesized as zero.

func ReadBlockStat

func ReadBlockStat(r io.Reader, c Context, resource string, maxBytes int64) (Snapshot, error)

ReadBlockStat reads /sys/block/<selected-device>/stat. It accepts Linux's documented 11, 15 or 17 fields and preserves sectors as 512-byte sectors.

Example
s, _ := ReadBlockStat(strings.NewReader("1 0 2 0 3 0 4 0 0 0 0"), fixture(), "sda", 128)
fmt.Println(s.Metrics[1].Unit)
Output:
512-byte_sectors

func ReadCounter

func ReadCounter(r io.Reader, c Context, name, resource string, maxBytes int64) (Snapshot, error)

ReadCounter reads one explicitly selected network or RDMA sysfs counter. RDMA data units are four-byte words, not bytes. The caller selects and opens the path; this function never enumerates interfaces or devices.

Example
s, _ := ReadCounter(strings.NewReader("9007199254740993"), fixture(), "node.net.rx_bytes", "eth0", 128)
fmt.Println(s.Metrics[0].UintValue)
Output:
9007199254740993

func ReadMeminfo

func ReadMeminfo(r io.Reader, c Context, maxBytes int64) (Snapshot, error)

ReadMeminfo reads selected fields from /proc/meminfo. Linux kB values are converted to bytes with overflow checks; absent selected fields stay absent.

Example
s, _ := ReadMeminfo(strings.NewReader("MemTotal: 2 kB"), fixture(), 128)
fmt.Println(s.Metrics[0].UintValue)
Output:
2048

func ReadPSI

func ReadPSI(r io.Reader, c Context, resource string, maxBytes int64) (Snapshot, error)

ReadPSI reads /proc/pressure/{cpu,memory,io}. The system CPU full line is undefined by Linux and is omitted even when the kernel emits compatibility zeros. This reader does not accept cgroup PSI semantics.

Example
s, _ := ReadPSI(strings.NewReader("some avg10=1.25 avg60=0 avg300=0 total=42"), fixture(), "cpu", 512)
fmt.Println(s.Metrics[0].Value, s.Metrics[3].UintValue)
Output:
1.25 42

func (Snapshot) Validate

func (s Snapshot) Validate() error

Validate checks identities, supported units, finite values and duplicates.

Example
s, _ := ReadCounter(strings.NewReader("1"), fixture(), "node.net.rx_bytes", "eth0", 128)
fmt.Println(s.Validate())
Output:
<nil>

Jump to

Keyboard shortcuts

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