hub

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 15 Imported by: 0 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.

Documentation

Overview

Package hub is a GET-only client for a Beszel hub's PocketBase API. Its method set is the allowlist: there is no generic request method.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnauthorized means the hub rejected the token: expired, revoked or wrong.
	ErrUnauthorized = errors.New("hub rejected the token")
	// ErrUnreachable means the request never got an HTTP response.
	ErrUnreachable = errors.New("hub unreachable")
)

Functions

func LogTransport

func LogTransport(next http.RoundTripper, log *slog.Logger) http.RoundTripper

LogTransport logs every request it carries as hub.request: info for a 200, warn for anything else. Wrap it inside otelhttp, so each line carries the request span's trace_id and span_id. Field names are the OTel semantic convention HTTP keys. Headers are never logged: they hold the token. duration_ms runs until the response headers arrive.

func NewTransport

func NewTransport() *http.Transport

NewTransport returns the transport for hub requests: HTTP/2, keep-alive and no proxy from the environment.

Types

type CertInfo

type CertInfo struct {
	Expires int64  `json:"expires"` // Unix ms
	Issuer  string `json:"issuer"`
}

CertInfo is an HTTPS target's certificate.

type Client

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

Client reads from one hub. It is safe for concurrent use.

func New

func New(o Options) *Client

New returns a Client.

func (*Client) ContainerStats

func (c *Client) ContainerStats(ctx context.Context, systemID string, t StatType, since time.Time) ([]ContainerStats, error)

ContainerStats returns a system's container samples of type t created at or after since, oldest first.

func (*Client) Containers

func (c *Client) Containers(ctx context.Context) ([]Container, error)

Containers returns every running container.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (Info, error)

Info returns the hub version. It answers 401 for a bad token, unlike lists.

func (*Client) LastStatsAt

func (c *Client) LastStatsAt(ctx context.Context, systemID string) (time.Time, error)

LastStatsAt returns when the system's newest stats row of any type was created, or the zero time when it has none. Beszel bumps systems.updated when it rewrites the record, so that time is not when data last arrived.

func (*Client) MonitorStats

func (c *Client) MonitorStats(ctx context.Context, systemID string, t StatType, since time.Time) ([]MonitorStats, error)

MonitorStats returns a system's monitor samples of type t created at or after since, oldest first.

func (*Client) Monitors

func (c *Client) Monitors(ctx context.Context) ([]Monitor, error)

Monitors returns every network monitor.

func (*Client) PackageUpdates

func (c *Client) PackageUpdates(ctx context.Context, systemID string) (PackageUpdates, error)

PackageUpdates asks the system's agent for pending updates. It waits on the agent, so it uses the live timeout.

func (*Client) Services

func (c *Client) Services(ctx context.Context) ([]Service, error)

Services returns every systemd unit.

func (*Client) SmartDevices

func (c *Client) SmartDevices(ctx context.Context) ([]SmartDevice, error)

SmartDevices returns every disk's SMART summary.

func (*Client) SystemDetails

func (c *Client) SystemDetails(ctx context.Context) ([]SystemDetails, error)

SystemDetails returns the static facts of every system.

func (*Client) SystemStats

func (c *Client) SystemStats(ctx context.Context, systemID string, t StatType, since time.Time) ([]SystemStats, error)

SystemStats returns a system's samples of type t created at or after since, oldest first.

func (*Client) Systems

func (c *Client) Systems(ctx context.Context) ([]System, error)

Systems returns every system shared with the token's user, by name.

func (*Client) ZfsPools

func (c *Client) ZfsPools(ctx context.Context) ([]ZfsPool, error)

ZfsPools returns every storage pool.

type Container

type Container struct {
	ID        string  `json:"id"`
	System    string  `json:"system"`
	Name      string  `json:"name"`
	Image     string  `json:"image"`
	Ports     string  `json:"ports"`
	Status    string  `json:"status"` // Docker's text, e.g. "Up 3 days (healthy)"
	Health    Health  `json:"health"`
	CPU       float64 `json:"cpu"` // % of the whole host
	MemoryMiB float64 `json:"memory"`
	NetBytes  float64 `json:"net"`     // bytes/s, sent + received
	Updated   int64   `json:"updated"` // Unix ms
	Updatable bool    `json:"updatable"`
}

Container is a running container seen in the last 10 minutes.

type ContainerStat

type ContainerStat struct {
	Name      string    `json:"n"`
	CPU       float64   `json:"c"` // % of the whole host
	MemMiB    float64   `json:"m"`
	Bandwidth [2]uint64 `json:"b"`  // sent, received bytes/s
	SentMB    float64   `json:"ns"` // agents before 0.18.3
	RecvMB    float64   `json:"nr"`
}

ContainerStat is one container in a container_stats record.

type ContainerStats

type ContainerStats struct {
	System  string          `json:"system"`
	Type    StatType        `json:"type"`
	Created Time            `json:"created"`
	Stats   []ContainerStat `json:"stats"`
}

ContainerStats is one container_stats record.

type FsStats

type FsStats struct {
	TotalGB    float64    `json:"d"`
	UsedGB     float64    `json:"du"`
	ReadBytes  uint64     `json:"rb"` // per second
	WriteBytes uint64     `json:"wb"` // per second
	MaxRead    uint64     `json:"rbm"`
	MaxWrite   uint64     `json:"wbm"`
	IOStats    [6]float64 `json:"dios"`
}

FsStats is an extra filesystem in Stats.

type GPU

type GPU struct {
	Name       string  `json:"n"`
	Usage      float64 `json:"u"`  // %
	MemUsedMB  float64 `json:"mu"` // as reported by the agent
	MemTotalMB float64 `json:"mt"`
	PowerW     float64 `json:"p"`
}

GPU is one GPU in Stats.

type Health added in v0.2.0

type Health int

Health is a container's health check result.

const (
	HealthNone Health = iota
	HealthStarting
	HealthHealthy
	HealthUnhealthy
)

The results Beszel records.

func (Health) String added in v0.2.0

func (h Health) String() string

type Info

type Info struct {
	Version string `json:"v"`
}

Info is the hub's /api/beszel/info response.

type Monitor

type Monitor struct {
	ID       string    `json:"id"`
	System   string    `json:"system"`
	Target   string    `json:"target"`
	Protocol string    `json:"protocol"` // icmp, tcp, http or dns
	Port     int       `json:"port"`
	Interval int       `json:"interval"` // seconds
	Res      float64   `json:"res"`      // microseconds
	ResAvg1h float64   `json:"resAvg1h"`
	ResMin1h float64   `json:"resMin1h"`
	ResMax1h float64   `json:"resMax1h"`
	Loss1h   float64   `json:"loss1h"` // %
	Enabled  bool      `json:"enabled"`
	CertInfo *CertInfo `json:"certInfo"`
	Updated  Time      `json:"updated"`
}

Monitor is a network monitor with its last hour of results.

type MonitorStats

type MonitorStats struct {
	Monitor string   `json:"monitor"`
	System  string   `json:"system"`
	Type    StatType `json:"type"`
	Created int64    `json:"created"` // Unix ms, unlike other collections
	Total   int64    `json:"total_count"`
	Success int64    `json:"success_count"`
	ResSum  float64  `json:"res_sum"` // microseconds, successful probes only
	ResMin  float64  `json:"res_min"`
	ResMax  float64  `json:"res_max"`
}

MonitorStats is one network_monitor_stats record.

type OS added in v0.2.0

type OS int

OS is Beszel's operating system code.

const (
	OSLinux   OS = 0
	OSDarwin  OS = 1
	OSWindows OS = 2
	OSFreeBSD OS = 3
)

The OS codes Beszel defines.

type Options

type Options struct {
	BaseURL     *url.URL
	Token       string
	HTTP        *http.Client
	Timeout     time.Duration // per request
	LiveTimeout time.Duration // per request that waits on an agent
	RetryDelay  time.Duration
	MaxParallel int // across all callers
}

Options configures a Client. Zero durations and MaxParallel are invalid.

type Package

type Package struct {
	Name      string `json:"name"`
	Current   string `json:"current"`
	Available string `json:"available"`
	Security  bool   `json:"security"`
}

Package is one pending update.

type PackageUpdates

type PackageUpdates struct {
	Manager       string    `json:"manager"`
	CheckedAt     int64     `json:"checkedAt"` // Unix seconds
	SecurityKnown bool      `json:"securityKnown"`
	Packages      []Package `json:"packages"`
}

PackageUpdates is a live answer from the agent.

type Pool

type Pool struct {
	Name    string  `json:"n"`
	TotalGB float64 `json:"d"`
	UsedGB  float64 `json:"du"`
	Health  string  `json:"h"`
}

Pool is a ZFS or btrfs pool in Stats.

type Scrub

type Scrub struct {
	State    string `json:"state"` // NONE, SCANNING, FINISHED or CANCELED
	Progress string `json:"progress"`
	Errors   uint64 `json:"errors"`
}

Scrub is a pool's last scrub.

type Service

type Service struct {
	System  string       `json:"system"`
	Name    string       `json:"name"`
	State   ServiceState `json:"state"`
	Sub     ServiceSub   `json:"sub"`
	CPU     float64      `json:"cpu"`
	CPUPeak float64      `json:"cpuPeak"`
	Memory  uint64       `json:"memory"` // bytes
	MemPeak uint64       `json:"memPeak"`
	Updated int64        `json:"updated"` // Unix ms
}

Service is a systemd unit.

type ServiceState added in v0.2.0

type ServiceState int

ServiceState is a systemd unit's active state.

const (
	ServiceActive ServiceState = iota
	ServiceInactive
	ServiceFailed
	ServiceActivating
	ServiceDeactivating
	ServiceReloading
)

The states Beszel records.

func (ServiceState) String added in v0.2.0

func (s ServiceState) String() string

type ServiceSub added in v0.2.0

type ServiceSub int

ServiceSub is a systemd unit's sub-state.

const (
	SubDead ServiceSub = iota
	SubRunning
	SubExited
	SubFailed
	SubUnknown
)

The sub-states Beszel records.

func (ServiceSub) String added in v0.2.0

func (s ServiceSub) String() string

type SmartAttr

type SmartAttr struct {
	ID         int    `json:"id"`
	Name       string `json:"n"`
	Value      int    `json:"v"`
	Worst      int    `json:"w"`
	Threshold  int    `json:"t"`
	Raw        uint64 `json:"rv"`
	RawString  string `json:"rs"`
	WhenFailed string `json:"wf"` // non-empty when the attribute failed
}

SmartAttr is one SMART attribute.

type SmartDevice

type SmartDevice struct {
	System     string      `json:"system"`
	Name       string      `json:"name"`
	Model      string      `json:"model"`
	Type       string      `json:"type"`
	State      SmartState  `json:"state"`
	Capacity   uint64      `json:"capacity"` // bytes
	Temp       float64     `json:"temp"`
	Hours      uint64      `json:"hours"`
	Cycles     uint64      `json:"cycles"`
	Attributes []SmartAttr `json:"attributes"`
	Updated    Time        `json:"updated"`
}

SmartDevice is a disk's SMART summary.

type SmartState added in v0.2.0

type SmartState string

SmartState is a drive's overall SMART result.

const (
	SmartPassed  SmartState = "PASSED"
	SmartWarning SmartState = "WARNING"
	SmartFailed  SmartState = "FAILED"
	SmartUnknown SmartState = "UNKNOWN"
)

The SMART results the agent reports.

type StatType

type StatType string

StatType is a Beszel stats resolution. Each record averages this window; rows are kept for 1h, 12h, 24h, 7d and 30d respectively.

const (
	Stat1m   StatType = "1m"
	Stat10m  StatType = "10m"
	Stat20m  StatType = "20m"
	Stat120m StatType = "120m"
	Stat480m StatType = "480m"
)

Stats resolutions.

type Stats

type Stats struct {
	CPU          float64              `json:"cpu"`
	MaxCPU       float64              `json:"cpum"` // rollups only
	CPUBreakdown []float64            `json:"cpub"` // user, system, iowait, steal, idle, irq, softirq, nice
	CPUCores     []uint16             `json:"cpus"` // busy % per core
	MemPct       float64              `json:"mp"`
	Mem          [4]uint64            `json:"mem"`  // total, used, buff/cache, ZFS ARC bytes
	MaxMemUsed   uint64               `json:"memm"` // rollups only
	Swap         [2]uint64            `json:"swap"` // total, used bytes
	MemGB        float64              `json:"m"`
	MemUsedGB    float64              `json:"mu"`
	SwapGB       float64              `json:"s"`
	SwapUsedGB   float64              `json:"su"`
	DiskGB       float64              `json:"d"`
	DiskUsedGB   float64              `json:"du"`
	DiskPct      float64              `json:"dp"`
	DiskIO       [2]uint64            `json:"dio"`  // read, write bytes/s
	MaxDiskIO    [2]uint64            `json:"diom"` // rollups only
	DiskIOStats  [6]float64           `json:"dios"`
	Bandwidth    [2]uint64            `json:"b"`  // sent, received bytes/s
	MaxBandwidth [2]uint64            `json:"bm"` // rollups only
	Interfaces   map[string][4]uint64 `json:"ni"` // up, down bytes/s; total up, down bytes
	LoadAvg      [3]float64           `json:"la"`
	Temps        map[string]float64   `json:"t"`
	Fans         map[string]uint16    `json:"f"` // RPM
	ExtraFs      map[string]FsStats   `json:"efs"`
	GPU          map[string]GPU       `json:"g"`
	Battery      [2]uint8             `json:"bat"`
	Pools        map[string]Pool      `json:"z"`
	WiFi         map[string]int8      `json:"wf"` // RSSI dBm
}

Stats is one system_stats sample. Beszel deprecates the memory GB fields.

type Status added in v0.2.0

type Status string

Status is a system's state as Beszel reports it. Other values can arrive on the wire; switches name all four and handle the rest in a default.

const (
	StatusUp      Status = "up"
	StatusDown    Status = "down"
	StatusPaused  Status = "paused"
	StatusPending Status = "pending"
)

The statuses Beszel sets.

type StatusError

type StatusError struct {
	Code int
	Body string // first 512 bytes
}

StatusError is an unexpected HTTP status from the hub.

func (*StatusError) Error

func (e *StatusError) Error() string

type System

type System struct {
	ID      string     `json:"id"`
	Name    string     `json:"name"`
	Host    string     `json:"host"`
	Port    string     `json:"port"`
	Status  Status     `json:"status"`
	Info    SystemInfo `json:"info"`
	Updated Time       `json:"updated"`
}

System is a monitored host with its latest summary.

type SystemDetails

type SystemDetails struct {
	System   string `json:"system"`
	Hostname string `json:"hostname"`
	OS       OS     `json:"os"`
	OSName   string `json:"os_name"`
	Kernel   string `json:"kernel"`
	CPU      string `json:"cpu"`
	Arch     string `json:"arch"`
	Cores    int    `json:"cores"`
	Threads  int    `json:"threads"`
	Sockets  int    `json:"sockets"`
	Memory   uint64 `json:"memory"` // bytes
	Podman   bool   `json:"podman"`
}

SystemDetails holds the static facts about a host.

type SystemInfo

type SystemInfo struct {
	Uptime         uint64             `json:"u"` // seconds
	CPU            float64            `json:"cpu"`
	MemPct         float64            `json:"mp"`
	DiskPct        float64            `json:"dp"`
	BandwidthBytes uint64             `json:"bb"` // bytes/s, sent + received
	AgentVersion   string             `json:"v"`
	LoadAvg        [3]float64         `json:"la"`
	Threads        int                `json:"t"`
	GPUPct         float64            `json:"g"`
	DashTemp       float64            `json:"dt"`  // hottest sensor, C
	ExtraFsPct     map[string]float64 `json:"efs"` // used %
	Services       []uint16           `json:"sv"`  // [total, failed]
	Battery        [2]uint8           `json:"bat"` // [percent, state]
	PackageUpdates []uint16           `json:"pu"`  // [total, security]; security may be absent
	RootDiskName   string             `json:"rdn"`
}

SystemInfo is the summary from the latest poll.

type SystemStats

type SystemStats struct {
	System  string   `json:"system"`
	Type    StatType `json:"type"`
	Created Time     `json:"created"`
	Stats   Stats    `json:"stats"`
}

SystemStats is one system_stats record.

type Time

type Time struct{ time.Time }

Time is a PocketBase date such as "2026-10-30 22:18:50.483Z".

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON parses a PocketBase date; "" is the zero time.

type Vdev

type Vdev struct {
	Name         string `json:"name"`
	State        string `json:"state"`
	ReadErrs     uint64 `json:"readErrs"`
	WriteErrs    uint64 `json:"writeErrs"`
	ChecksumErrs uint64 `json:"checksumErrs"`
}

Vdev is one device of a pool.

type ZfsPool

type ZfsPool struct {
	System      string `json:"system"`
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	Health      string `json:"health"` // ONLINE, DEGRADED, FAULTED, ...
	Status      string `json:"status"` // zpool status message
	Size        uint64 `json:"size"`   // bytes
	Alloc       uint64 `json:"alloc"`
	Free        uint64 `json:"free"`
	Scrub       *Scrub `json:"scrub"`
	Vdevs       []Vdev `json:"vdevs"`
	Raw         bool   `json:"raw"` // sizes are physical, not usable
	Updated     Time   `json:"updated"`
}

ZfsPool is a storage pool; btrfs pool names start with "b:".

Directories

Path Synopsis
Package hubtest loads the hub fixtures in internal/hub/testdata for tests in other packages.
Package hubtest loads the hub fixtures in internal/hub/testdata for tests in other packages.

Jump to

Keyboard shortcuts

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