Documentation
¶
Overview ¶
Package agent implements the Beszel monitoring agent that collects and serves system metrics.
The agent runs on monitored systems and communicates collected data to the Beszel hub for centralized monitoring and alerting.
Index ¶
- func DeleteFingerprint(dataDir string) error
- func GetAddress(addr string) string
- func GetDataDir(dataDirs ...string) (string, error)
- func GetFingerprint(dataDir, hostname, cpuModel string) string
- func GetNetwork(addr string) string
- func NewSystemDataCache() *systemDataCache
- func ParseKeys(input string) ([]gossh.PublicKey, error)
- func SaveFingerprint(dataDir, fingerprint string) error
- func Update(useMirror bool) error
- type Agent
- type CheckFingerprintHandler
- type ConnectionEvent
- type ConnectionManager
- type ConnectionState
- type CpuMetrics
- type GPUManager
- type GetContainerInfoHandler
- type GetContainerLogsHandler
- type GetDataHandler
- type GetPackageUpdatesHandler
- type GetSmartDataHandler
- type GetSystemdInfoHandler
- type GetSystemdLogsHandler
- type GetZfsDataHandler
- type HandlerContext
- type HandlerRegistry
- type MonitorManager
- func (pm *MonitorManager) DeleteMonitor(id string)
- func (pm *MonitorManager) GetResults(durationMs uint16) map[string]monitor.Result
- func (pm *MonitorManager) HandleSyncRequest(req monitor.SyncRequest) (monitor.SyncResponse, error)
- func (pm *MonitorManager) Stop()
- func (pm *MonitorManager) SyncMonitors(configs []monitor.Config)
- func (pm *MonitorManager) UpsertMonitor(config monitor.Config, runNow bool) (*monitor.Result, error)
- type NicConfig
- type RequestHandler
- type Responder
- type RocmSmiJson
- type SensorConfig
- type ServerOptions
- type SmartManager
- type StoragePoolManager
- type SyncNetworkMonitorsHandler
- type WebSocketClient
- func (client *WebSocketClient) Close()
- func (client *WebSocketClient) Connect() (err error)
- func (client *WebSocketClient) OnClose(conn *gws.Conn, err error)
- func (client *WebSocketClient) OnMessage(conn *gws.Conn, message *gws.Message)
- func (client *WebSocketClient) OnOpen(conn *gws.Conn)
- func (client *WebSocketClient) OnPing(conn *gws.Conn, message []byte)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DeleteFingerprint ¶ added in v0.18.4
DeleteFingerprint removes the saved fingerprint file from the data directory. Returns nil if the file does not exist (idempotent).
func GetAddress ¶
GetAddress determines the network address to listen on from various sources. It checks the provided address, then environment variables (LISTEN, PORT), and finally defaults to ":45876".
func GetDataDir ¶ added in v0.18.4
GetDataDir returns the path to the data directory for the agent and an error if the directory is not valid. Attempts to find the optimal data directory if no data directories are provided.
func GetFingerprint ¶ added in v0.18.4
GetFingerprint returns the agent fingerprint. It first tries to read a saved fingerprint from the data directory. If not found (or dataDir is empty), it generates one from system properties. The hostname and cpuModel parameters are used as fallback material if host.HostID() fails. If either is empty, they are fetched from the system automatically.
If a new fingerprint is generated and a dataDir is provided, it is saved.
func GetNetwork ¶
GetNetwork determines the network type based on the address format. It checks the NETWORK environment variable first, then infers from the address format: addresses starting with "/" are "unix", others are "tcp".
func NewSystemDataCache ¶ added in v0.13.0
func NewSystemDataCache() *systemDataCache
NewSystemDataCache creates a cache keyed by the polling interval in milliseconds.
func ParseKeys ¶
ParseKeys parses a string containing SSH public keys in authorized_keys format. It returns a slice of ssh.PublicKey and an error if any key fails to parse.
func SaveFingerprint ¶ added in v0.18.4
SaveFingerprint writes the fingerprint to the data directory.
Types ¶
type Agent ¶
type Agent struct {
sync.Mutex // Used to lock agent while collecting data
// contains filtered or unexported fields
}
func NewAgent ¶
NewAgent creates a new agent with the given data directory for persisting data. If the data directory is not set, it will attempt to find the optimal directory.
func (*Agent) Start ¶
func (a *Agent) Start(ctx context.Context, serverOptions ServerOptions) error
Start initializes and starts the agent with optional WebSocket connection. It runs until ctx is cancelled or the process receives SIGINT or SIGTERM.
func (*Agent) StartServer ¶
func (a *Agent) StartServer(opts ServerOptions) error
StartServer starts the SSH server with the provided options. It configures the server with secure defaults, sets up authentication, and begins listening for connections. Returns an error if the server is already running or if there's an issue starting the server.
func (*Agent) StopServer ¶
StopServer stops the SSH server if it's running. It returns an error if the server is not running or if there's an error stopping it.
type CheckFingerprintHandler ¶ added in v0.13.0
type CheckFingerprintHandler struct{}
CheckFingerprintHandler handles authentication challenges
func (*CheckFingerprintHandler) Handle ¶ added in v0.13.0
func (h *CheckFingerprintHandler) Handle(hctx *HandlerContext) error
type ConnectionEvent ¶
type ConnectionEvent uint8
ConnectionEvent represents connection-related events that can occur.
const ( WebSocketConnect ConnectionEvent = iota // WebSocket connection established WebSocketDisconnect // WebSocket connection lost SSHConnect // SSH connection established SSHDisconnect // SSH connection lost )
Connection events
type ConnectionManager ¶
type ConnectionManager struct {
State ConnectionState // Current connection state
// contains filtered or unexported fields
}
ConnectionManager manages the connection state and events for the agent. It handles both WebSocket and SSH connections, automatically switching between them based on availability and managing reconnection attempts.
func (*ConnectionManager) Start ¶
func (c *ConnectionManager) Start(ctx context.Context, serverOptions ServerOptions) error
Start begins connection attempts and enters the main event loop. It handles connection events, periodic health updates, and graceful shutdown.
type ConnectionState ¶
type ConnectionState uint8
ConnectionState represents the current connection state of the agent.
const ( Disconnected ConnectionState = iota // No active connection WebSocketConnected // Connected via WebSocket SSHConnected // Connected via SSH )
Connection states
type CpuMetrics ¶ added in v0.15.3
type CpuMetrics struct {
Total float64
User float64
System float64
Iowait float64
Steal float64
Idle float64
Irq float64
Softirq float64
Nice float64
// contains filtered or unexported fields
}
CpuMetrics contains detailed CPU usage breakdown
type GPUManager ¶
type GPUManager struct {
sync.Mutex
GpuDataMap map[string]*system.GPUData
// contains filtered or unexported fields
}
GPUManager manages data collection for GPUs (either Nvidia or AMD)
func NewGPUManager ¶
func NewGPUManager() (*GPUManager, error)
NewGPUManager creates and initializes a new GPUManager
func (*GPUManager) GetCurrentData ¶
func (gm *GPUManager) GetCurrentData(cacheKey uint16) map[string]system.GPUData
GetCurrentData returns GPU utilization data averaged since the last call with this cacheKey
type GetContainerInfoHandler ¶ added in v0.14.0
type GetContainerInfoHandler struct{}
GetContainerInfoHandler handles container info requests
func (*GetContainerInfoHandler) Handle ¶ added in v0.14.0
func (h *GetContainerInfoHandler) Handle(hctx *HandlerContext) error
type GetContainerLogsHandler ¶ added in v0.14.0
type GetContainerLogsHandler struct{}
GetContainerLogsHandler handles container log requests
func (*GetContainerLogsHandler) Handle ¶ added in v0.14.0
func (h *GetContainerLogsHandler) Handle(hctx *HandlerContext) error
type GetDataHandler ¶ added in v0.13.0
type GetDataHandler struct{}
GetDataHandler handles system data requests
func (*GetDataHandler) Handle ¶ added in v0.13.0
func (h *GetDataHandler) Handle(hctx *HandlerContext) error
type GetPackageUpdatesHandler ¶ added in v0.21.0
type GetPackageUpdatesHandler struct{}
GetPackageUpdatesHandler returns the pending package updates found by the last background check. It never runs a check itself.
func (*GetPackageUpdatesHandler) Handle ¶ added in v0.21.0
func (h *GetPackageUpdatesHandler) Handle(hctx *HandlerContext) error
type GetSmartDataHandler ¶ added in v0.15.0
type GetSmartDataHandler struct{}
GetSmartDataHandler handles SMART data requests
func (*GetSmartDataHandler) Handle ¶ added in v0.15.0
func (h *GetSmartDataHandler) Handle(hctx *HandlerContext) error
type GetSystemdInfoHandler ¶ added in v0.16.0
type GetSystemdInfoHandler struct{}
GetSystemdInfoHandler handles detailed systemd service info requests
func (*GetSystemdInfoHandler) Handle ¶ added in v0.16.0
func (h *GetSystemdInfoHandler) Handle(hctx *HandlerContext) error
type GetSystemdLogsHandler ¶ added in v0.21.0
type GetSystemdLogsHandler struct{}
GetSystemdLogsHandler handles recent systemd service log requests.
func (*GetSystemdLogsHandler) Handle ¶ added in v0.21.0
func (h *GetSystemdLogsHandler) Handle(hctx *HandlerContext) error
type GetZfsDataHandler ¶ added in v0.19.0
type GetZfsDataHandler struct{}
GetZfsDataHandler handles ZFS detail data requests
func (*GetZfsDataHandler) Handle ¶ added in v0.19.0
func (h *GetZfsDataHandler) Handle(hctx *HandlerContext) error
type HandlerContext ¶ added in v0.13.0
type HandlerContext struct {
Client *WebSocketClient
Conn *gws.Conn // WebSocket that carried this request, if any
Agent *Agent
Request *common.HubRequest[cbor.RawMessage]
RequestID *uint32
HubVerified bool
ConnectionType system.ConnectionType // Transport that carried this request
// SendResponse abstracts how a handler sends responses (WS or SSH)
SendResponse func(data any, requestID *uint32) error
}
HandlerContext provides context for request handlers
type HandlerRegistry ¶ added in v0.13.0
type HandlerRegistry struct {
// contains filtered or unexported fields
}
HandlerRegistry manages the mapping between actions and their handlers
func NewHandlerRegistry ¶ added in v0.13.0
func NewHandlerRegistry() *HandlerRegistry
NewHandlerRegistry creates a new handler registry with default handlers
func (*HandlerRegistry) GetHandler ¶ added in v0.13.0
func (hr *HandlerRegistry) GetHandler(action common.WebSocketAction) (RequestHandler, bool)
GetHandler returns the handler for a specific action
func (*HandlerRegistry) Handle ¶ added in v0.13.0
func (hr *HandlerRegistry) Handle(hctx *HandlerContext) error
Handle routes the request to the appropriate handler
func (*HandlerRegistry) Register ¶ added in v0.13.0
func (hr *HandlerRegistry) Register(action common.WebSocketAction, handler RequestHandler)
Register registers a handler for a specific action type
type MonitorManager ¶ added in v0.20.0
type MonitorManager struct {
// contains filtered or unexported fields
}
MonitorManager manages network monitor configurations and task lifetimes.
func (*MonitorManager) DeleteMonitor ¶ added in v0.20.0
func (pm *MonitorManager) DeleteMonitor(id string)
DeleteMonitor stops and removes a single monitor task.
func (*MonitorManager) GetResults ¶ added in v0.20.0
func (pm *MonitorManager) GetResults(durationMs uint16) map[string]monitor.Result
GetResults returns aggregated results for all monitors over the last supplied duration in ms.
func (*MonitorManager) HandleSyncRequest ¶ added in v0.20.0
func (pm *MonitorManager) HandleSyncRequest(req monitor.SyncRequest) (monitor.SyncResponse, error)
HandleSyncRequest applies a full or incremental monitor sync request.
func (*MonitorManager) Stop ¶ added in v0.20.0
func (pm *MonitorManager) Stop()
Stop stops all monitor tasks.
func (*MonitorManager) SyncMonitors ¶ added in v0.20.0
func (pm *MonitorManager) SyncMonitors(configs []monitor.Config)
SyncMonitors replaces all monitor tasks with the given configs.
func (*MonitorManager) UpsertMonitor ¶ added in v0.20.0
func (pm *MonitorManager) UpsertMonitor(config monitor.Config, runNow bool) (*monitor.Result, error)
UpsertMonitor creates or replaces a single monitor task.
type NicConfig ¶ added in v0.12.11
type NicConfig struct {
// contains filtered or unexported fields
}
NicConfig controls inclusion/exclusion of network interfaces via the NICS env var
Behavior mirrors SensorConfig's matching logic: - Leading '-' means blacklist mode; otherwise whitelist mode - Supports '*' wildcards using path.Match - In whitelist mode with an empty list, no NICs are selected - In blacklist mode with an empty list, all NICs are selected
type RequestHandler ¶ added in v0.13.0
type RequestHandler interface {
// Handle processes the request and returns an error if unsuccessful
Handle(hctx *HandlerContext) error
}
RequestHandler defines the interface for handling specific websocket request types
type Responder ¶ added in v0.13.0
Responder sends handler responses back to the hub (over WS or SSH)
type RocmSmiJson ¶
type RocmSmiJson struct {
ID string `json:"GUID"`
Name string `json:"Card series"`
Temperature string `json:"Temperature (Sensor edge) (C)"`
MemoryUsed string `json:"VRAM Total Used Memory (B)"`
MemoryTotal string `json:"VRAM Total Memory (B)"`
Usage string `json:"GPU use (%)"`
PowerPackage string `json:"Average Graphics Package Power (W)"`
PowerSocket string `json:"Current Socket Graphics Package Power (W)"`
}
RocmSmiJson represents the JSON structure of rocm-smi output
type SensorConfig ¶
type SensorConfig struct {
// contains filtered or unexported fields
}
type ServerOptions ¶
type ServerOptions struct {
Addr string // Network address to listen on (e.g., ":45876" or "/path/to/socket")
Network string // Network type ("tcp" or "unix")
Keys []gossh.PublicKey // SSH public keys for authentication
}
ServerOptions contains configuration options for starting the SSH server.
type SmartManager ¶ added in v0.15.0
SmartManager collects SMART data. Every refresh builds the list of targets (smartctl scan, SMART_DEVICES, eMMC and mdraid), queries each one and replaces the collected data, so no per-device state has to be kept in sync.
func NewSmartManager ¶ added in v0.15.0
func NewSmartManager() (*SmartManager, error)
NewSmartManager creates and initializes a new SmartManager
func (*SmartManager) GetCurrentData ¶ added in v0.15.0
func (sm *SmartManager) GetCurrentData() map[string]smart.SmartData
GetCurrentData returns the current SMART data
type StoragePoolManager ¶ added in v0.20.0
type StoragePoolManager struct {
// contains filtered or unexported fields
}
StoragePoolManager combines independent backend inventories. Metrics and dataset usage require the agent lock; GetDetail is safe for concurrent calls.
func (*StoragePoolManager) DatasetUsage ¶ added in v0.20.0
func (m *StoragePoolManager) DatasetUsage() map[string]zfsDatasetUsage
DatasetUsage returns ZFS dataset usage keyed by mountpoint, refreshed at most every datasetUsageRefreshInterval. On failure the previous map is retained and a debug log is emitted.
func (*StoragePoolManager) GetDetail ¶ added in v0.20.0
func (m *StoragePoolManager) GetDetail(force bool) *zfsentity.ZfsData
GetDetail combines backend snapshots, identifying successful inventories so the hub can accept partial updates without deleting failed backend records.
func (*StoragePoolManager) Update ¶ added in v0.20.0
func (m *StoragePoolManager) Update(systemStats *system.Stats)
Update refreshes systemStats.ZfsPools with the latest pool data. I/O throughput and health come from inexpensive kernel kstats on Linux. Pool capacity and dataset usage come from separately cached utility calls. The pool map is empty when both backends are absent.
func (*StoragePoolManager) ZfsMountpoints ¶ added in v0.20.0
func (m *StoragePoolManager) ZfsMountpoints() map[string]bool
ZfsMountpoints returns the set of mountpoints backed by ZFS datasets.
type SyncNetworkMonitorsHandler ¶ added in v0.20.0
type SyncNetworkMonitorsHandler struct{}
SyncNetworkMonitorsHandler handles monitor configuration sync from hub
func (*SyncNetworkMonitorsHandler) Handle ¶ added in v0.20.0
func (h *SyncNetworkMonitorsHandler) Handle(hctx *HandlerContext) error
type WebSocketClient ¶
type WebSocketClient struct {
gws.BuiltinEventHandler
Conn *gws.Conn // Active WebSocket connection
// contains filtered or unexported fields
}
WebSocketClient manages the WebSocket connection between the agent and hub. It handles authentication, message routing, and connection lifecycle management.
func (*WebSocketClient) Close ¶
func (client *WebSocketClient) Close()
Close closes the WebSocket connection gracefully. This method is safe to call multiple times.
func (*WebSocketClient) Connect ¶
func (client *WebSocketClient) Connect() (err error)
Connect establishes a WebSocket connection to the hub. It closes any existing connection before attempting to reconnect.
func (*WebSocketClient) OnClose ¶
func (client *WebSocketClient) OnClose(conn *gws.Conn, err error)
OnClose handles WebSocket connection closure. It logs the closure reason and notifies the connection manager.
func (*WebSocketClient) OnMessage ¶
func (client *WebSocketClient) OnMessage(conn *gws.Conn, message *gws.Message)
OnMessage handles incoming WebSocket messages from the hub. It decodes CBOR messages and routes them to appropriate handlers.
func (*WebSocketClient) OnOpen ¶
func (client *WebSocketClient) OnOpen(conn *gws.Conn)
OnOpen handles WebSocket connection establishment. It sets a deadline for the connection to prevent hanging.
Source Files
¶
- agent.go
- agent_cache.go
- client.go
- connection_manager.go
- cpu.go
- cpu_linux.go
- data_dir.go
- disk.go
- docker.go
- docker_image_updates.go
- docker_names.go
- docker_registry.go
- emmc_common.go
- emmc_linux.go
- fans.go
- fans_linux.go
- fingerprint.go
- gpu.go
- gpu_amd_linux.go
- gpu_darwin_unsupported.go
- gpu_intel.go
- gpu_intel_sysfs_linux.go
- gpu_nvml_unsupported.go
- gpu_nvtop.go
- handlers.go
- mdraid_linux.go
- memory.go
- memory_linux.go
- network.go
- network_counters_linux.go
- network_monitor.go
- network_monitor_cert.go
- network_monitor_history.go
- network_monitor_ping.go
- network_monitor_probe.go
- network_monitor_resume.go
- network_monitor_schedule.go
- network_monitor_task.go
- package_updates.go
- response.go
- sensors.go
- sensors_default.go
- server.go
- smart.go
- smart_nonwindows.go
- smart_parse.go
- storage_pool.go
- system.go
- systemd.go
- update.go
- uptime_linux.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package battery provides battery information for the host and connected devices.
|
Package battery provides battery information for the host and connected devices. |
|
Package btrfs reads btrfs filesystem state from sysfs.
|
Package btrfs reads btrfs filesystem state from sysfs. |
|
Package deltatracker provides a tracker for calculating differences in numeric values over time.
|
Package deltatracker provides a tracker for calculating differences in numeric values over time. |
|
Package health provides functions to check and update the health of the agent.
|
Package health provides functions to check and update the health of the agent. |
|
tools
|
|
|
fetchsmartctl
command
|
|
|
Package utils provides utility functions for the agent.
|
Package utils provides utility functions for the agent. |
|
Package wifi collects only currently associated station interfaces.
|
Package wifi collects only currently associated station interfaces. |
|
Package zfs provides functions to read ZFS statistics.
|
Package zfs provides functions to read ZFS statistics. |