Documentation
¶
Overview ¶
Package smartmontools provides Go bindings for interfacing with smartmontools to monitor and manage storage device health using S.M.A.R.T. data.
The library wraps the smartctl command-line utility and provides a clean, idiomatic Go API for accessing SMART information from storage devices.
Features ¶
- Device scanning and discovery
- SMART health status checking
- Detailed SMART attribute reading
- Disk type detection (SSD, HDD, NVMe, Unknown)
- Rotation rate (RPM) information for HDDs
- Temperature monitoring
- Power-on time tracking
- Self-test execution and progress monitoring
- Device information retrieval
- SMART support detection and management
- Self-test availability checking
- Standby mode detection (ATA devices only)
Prerequisites ¶
This library requires smartctl (part of smartmontools) to be installed:
Linux:
sudo apt-get install smartmontools # Debian/Ubuntu sudo yum install smartmontools # RHEL/CentOS/Fedora sudo pacman -S smartmontools # Arch Linux
macOS:
brew install smartmontools
Windows:
Download from https://www.smartmontools.org/
Basic Usage ¶
package main
import (
"fmt"
"log"
"github.com/dianlight/smartmontools-go"
)
func main() {
// Create a new client
client, err := smartmontools.NewClient()
if err != nil {
log.Fatal(err)
}
// Scan for devices
devices, err := client.ScanDevices()
if err != nil {
log.Fatal(err)
}
// Check health of first device
if len(devices) > 0 {
healthy, _ := client.CheckHealth(devices[0].Name)
if healthy {
fmt.Println("Device is healthy")
}
}
}
Standby Mode Handling ¶
For ATA devices (ata, sat, sata, scsi), the library automatically adds the --nocheck=standby flag to smartctl commands. This prevents waking up devices that are in standby/sleep mode, which is especially useful for power-saving scenarios.
When a device is in standby mode:
- GetSMARTInfo will return a SMARTInfo with InStandby set to true
- CheckHealth will return an error indicating the device is in standby
- GetDeviceInfo will return an error indicating the device is in standby
- GetAvailableSelfTests will return an error indicating the device is in standby
NVMe devices do not support standby mode detection and do not receive the --nocheck=standby flag.
Permissions ¶
Many operations require elevated privileges (root/administrator) to access disk devices. The library will return errors if permissions are insufficient.
Thread Safety ¶
The Client type is safe for concurrent use by multiple goroutines.
Package smartmontools provides Go bindings for interfacing with smartmontools to monitor and manage storage device health using S.M.A.R.T. data.
This file contains functions for parsing and managing the embedded drivedb.h database from smartmontools, which includes USB bridge device mappings.
Package smartmontools provides Go bindings for interfacing with smartmontools to monitor and manage storage device health using S.M.A.R.T. data.
The library wraps the smartctl command-line utility and provides a clean, idiomatic Go API for accessing SMART information from storage devices.
Index ¶
- Constants
- type AtaSmartData
- type Capabilities
- type CapabilitiesOutput
- type Client
- func (c *Client) AbortSelfTest(ctx context.Context, devicePath string) error
- func (c *Client) CheckHealth(ctx context.Context, devicePath string) (bool, error)
- func (c *Client) DisableSMART(ctx context.Context, devicePath string) error
- func (c *Client) EnableSMART(ctx context.Context, devicePath string) error
- func (c *Client) GetAvailableSelfTests(ctx context.Context, devicePath string) (*SelfTestInfo, error)
- func (c *Client) GetDeviceInfo(ctx context.Context, devicePath string) (map[string]interface{}, error)
- func (c *Client) GetSMARTInfo(ctx context.Context, devicePath string) (*SMARTInfo, error)
- func (c *Client) IsSMARTSupported(ctx context.Context, devicePath string) (*SmartSupport, error)
- func (c *Client) RunSelfTest(ctx context.Context, devicePath string, testType string) error
- func (c *Client) RunSelfTestWithProgress(ctx context.Context, devicePath string, testType string, ...) error
- func (c *Client) ScanDevices(ctx context.Context) ([]Device, error)
- type ClientOption
- type Cmd
- type Commander
- type Device
- type Flags
- type Message
- type NvmeControllerCapabilities
- type NvmeOptionalAdminCommands
- type NvmeSmartHealth
- type NvmeSmartTestLog
- type OfflineDataCollection
- type PollingMinutes
- type PowerOnTime
- type ProgressCallback
- type Raw
- type SMARTInfo
- type SelfTest
- type SelfTestInfo
- type SmartAttribute
- type SmartClient
- type SmartStatus
- type SmartSupport
- type SmartctlInfo
- type StatusField
- type Temperature
- type UserCapacity
Constants ¶
const ( SmartAttrSSDLifeLeft = 231 // SSD Life Left attribute SmartAttrSandForceInternal = 233 // SandForce Internal (SSD-specific) SmartAttrTotalLBAsWritten = 234 // Total LBAs Written (SSD-specific) )
SMART attribute IDs for SSD detection
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AtaSmartData ¶
type AtaSmartData struct {
OfflineDataCollection *OfflineDataCollection `json:"offline_data_collection,omitempty"`
SelfTest *SelfTest `json:"self_test,omitempty"`
Capabilities *Capabilities `json:"capabilities,omitempty"`
Table []SmartAttribute `json:"table,omitempty"`
}
AtaSmartData represents ATA SMART attributes
type Capabilities ¶
type Capabilities struct {
Values []int `json:"values,omitempty"`
ExecOfflineImmediate bool `json:"exec_offline_immediate_supported,omitempty"`
SelfTestsSupported bool `json:"self_tests_supported,omitempty"`
ConveyanceSelfTestSupported bool `json:"conveyance_self_test_supported,omitempty"`
}
Capabilities represents SMART capabilities
type CapabilitiesOutput ¶
type CapabilitiesOutput struct {
AtaSmartData *AtaSmartData `json:"ata_smart_data,omitempty"`
NvmeControllerCapabilities *NvmeControllerCapabilities `json:"nvme_controller_capabilities,omitempty"`
NvmeOptionalAdminCommands *NvmeOptionalAdminCommands `json:"nvme_optional_admin_commands,omitempty"`
}
CapabilitiesOutput represents the output of smartctl -c -j
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a smartmontools client
func (*Client) AbortSelfTest ¶
AbortSelfTest aborts a running self-test on a device
func (*Client) CheckHealth ¶
CheckHealth checks if a device is healthy according to SMART
func (*Client) DisableSMART ¶
DisableSMART disables SMART monitoring on a device
func (*Client) EnableSMART ¶
EnableSMART enables SMART monitoring on a device
func (*Client) GetAvailableSelfTests ¶
func (c *Client) GetAvailableSelfTests(ctx context.Context, devicePath string) (*SelfTestInfo, error)
GetAvailableSelfTests returns the list of available self-test types and their durations for a device
func (*Client) GetDeviceInfo ¶
func (c *Client) GetDeviceInfo(ctx context.Context, devicePath string) (map[string]interface{}, error)
GetDeviceInfo retrieves basic device information
func (*Client) GetSMARTInfo ¶
GetSMARTInfo retrieves SMART information for a device
func (*Client) IsSMARTSupported ¶
IsSMARTSupported checks if SMART is supported on a device and if it's enabled
func (*Client) RunSelfTest ¶
RunSelfTest initiates a SMART self-test
func (*Client) RunSelfTestWithProgress ¶
func (c *Client) RunSelfTestWithProgress(ctx context.Context, devicePath string, testType string, callback ProgressCallback) error
RunSelfTestWithProgress starts a SMART self-test and reports progress
type ClientOption ¶ added in v0.1.1
type ClientOption func(*Client)
ClientOption is a function that configures a Client
func WithCommander ¶ added in v0.1.1
func WithCommander(commander Commander) ClientOption
WithCommander sets a custom commander for testing purposes
func WithContext ¶ added in v0.1.1
func WithContext(ctx context.Context) ClientOption
WithContext sets a default context to use when methods are called with nil context
func WithLogHandler ¶ added in v0.1.1
func WithLogHandler(logger *slog.Logger) ClientOption
WithLogHandler sets a custom slog.Logger for the client.
func WithSmartctlPath ¶ added in v0.1.1
func WithSmartctlPath(path string) ClientOption
WithSmartctlPath sets a custom path to the smartctl binary
func WithTLogHandler ¶ added in v0.1.4
func WithTLogHandler(logger *tlog.Logger) ClientOption
WithTLogHandler sets a custom tlog.Logger for the client.
type Commander ¶
type Commander interface {
Command(ctx context.Context, logger logAdapter, name string, arg ...string) Cmd
}
Commander interface for executing commands
type Flags ¶
type Flags struct {
Value int `json:"value"`
String string `json:"string"`
PreFailure bool `json:"prefailure"`
UpdatedOnline bool `json:"updated_online"`
Performance bool `json:"performance"`
ErrorRate bool `json:"error_rate"`
EventCount bool `json:"event_count"`
AutoKeep bool `json:"auto_keep"`
}
Flags represents attribute flags
type NvmeControllerCapabilities ¶
type NvmeControllerCapabilities struct {
SelfTest bool `json:"self_test,omitempty"`
}
NvmeControllerCapabilities represents NVMe controller capabilities
type NvmeOptionalAdminCommands ¶
type NvmeOptionalAdminCommands struct {
SelfTest bool `json:"self_test,omitempty"`
}
NvmeOptionalAdminCommands represents NVMe optional admin commands
type NvmeSmartHealth ¶
type NvmeSmartHealth struct {
CriticalWarning int `json:"critical_warning,omitempty"`
Temperature int `json:"temperature,omitempty"`
AvailableSpare int `json:"available_spare,omitempty"`
AvailableSpareThresh int `json:"available_spare_threshold,omitempty"`
PercentageUsed int `json:"percentage_used,omitempty"`
DataUnitsRead int64 `json:"data_units_read,omitempty"`
DataUnitsWritten int64 `json:"data_units_written,omitempty"`
HostReadCommands int64 `json:"host_read_commands,omitempty"`
HostWriteCommands int64 `json:"host_write_commands,omitempty"`
ControllerBusyTime int64 `json:"controller_busy_time,omitempty"`
PowerCycles int64 `json:"power_cycles,omitempty"`
PowerOnHours int64 `json:"power_on_hours,omitempty"`
UnsafeShutdowns int64 `json:"unsafe_shutdowns,omitempty"`
MediaErrors int64 `json:"media_errors,omitempty"`
NumErrLogEntries int64 `json:"num_err_log_entries,omitempty"`
WarningTempTime int `json:"warning_temp_time,omitempty"`
CriticalCompTime int `json:"critical_comp_time,omitempty"`
TemperatureSensors []int `json:"temperature_sensors,omitempty"`
}
NvmeSmartHealth represents NVMe SMART health information
type NvmeSmartTestLog ¶ added in v0.2.3
type OfflineDataCollection ¶
type OfflineDataCollection struct {
Status *StatusField `json:"status,omitempty"`
CompletionSeconds int `json:"completion_seconds,omitempty"`
}
OfflineDataCollection represents offline data collection status
type PollingMinutes ¶
type PollingMinutes struct {
Short int `json:"short,omitempty"`
Extended int `json:"extended,omitempty"`
Conveyance int `json:"conveyance,omitempty"`
}
PollingMinutes represents polling minutes for different test types
type PowerOnTime ¶
type PowerOnTime struct {
Hours int `json:"hours"`
}
PowerOnTime represents power on time
type ProgressCallback ¶
ProgressCallback is a function type for reporting progress
type SMARTInfo ¶
type SMARTInfo struct {
Device Device `json:"device"`
ModelFamily string `json:"model_family,omitempty"`
ModelName string `json:"model_name,omitempty"`
SerialNumber string `json:"serial_number,omitempty"`
Firmware string `json:"firmware_version,omitempty"`
UserCapacity *UserCapacity `json:"user_capacity,omitempty"`
RotationRate *int `json:"rotation_rate,omitempty"` // Rotation rate in RPM (0 for SSDs, >0 for HDDs, nil if not available or not applicable)
DiskType string `json:"-"` // Computed disk type: "SSD", "HDD", "NVMe", or "Unknown"
InStandby bool `json:"in_standby,omitempty"` // True if device is in standby/sleep mode (ATA only)
SmartStatus SmartStatus `json:"smart_status,omitempty"`
SmartSupport *SmartSupport `json:"smart_support,omitempty"`
AtaSmartData *AtaSmartData `json:"ata_smart_data,omitempty"`
NvmeSmartHealth *NvmeSmartHealth `json:"nvme_smart_health_information_log,omitempty"`
NvmeSmartTestLog *NvmeSmartTestLog `json:"nvme_smart_test_log,omitempty"`
NvmeControllerCapabilities *NvmeControllerCapabilities `json:"nvme_controller_capabilities,omitempty"`
Temperature *Temperature `json:"temperature,omitempty"`
PowerOnTime *PowerOnTime `json:"power_on_time,omitempty"`
PowerCycleCount int `json:"power_cycle_count,omitempty"`
Smartctl *SmartctlInfo `json:"smartctl,omitempty"`
}
SMARTInfo represents comprehensive SMART information for a storage device
type SelfTest ¶
type SelfTest struct {
Status *StatusField `json:"status,omitempty"`
PollingMinutes *PollingMinutes `json:"polling_minutes,omitempty"`
}
SelfTest represents self-test information
type SelfTestInfo ¶
type SelfTestInfo struct {
Available []string `json:"available"`
Durations map[string]int `json:"durations"`
}
SelfTestInfo represents available self-tests and their durations
type SmartAttribute ¶
type SmartAttribute struct {
ID int `json:"id"`
Name string `json:"name"`
Value int `json:"value"`
Worst int `json:"worst"`
Thresh int `json:"thresh"`
WhenFailed string `json:"when_failed,omitempty"`
Flags Flags `json:"flags"`
Raw Raw `json:"raw"`
}
SmartAttribute represents a single SMART attribute
type SmartClient ¶
type SmartClient interface {
ScanDevices(ctx context.Context) ([]Device, error)
GetSMARTInfo(ctx context.Context, devicePath string) (*SMARTInfo, error)
CheckHealth(ctx context.Context, devicePath string) (bool, error)
GetDeviceInfo(ctx context.Context, devicePath string) (map[string]interface{}, error)
RunSelfTest(ctx context.Context, devicePath string, testType string) error
RunSelfTestWithProgress(ctx context.Context, devicePath string, testType string, callback ProgressCallback) error
GetAvailableSelfTests(ctx context.Context, devicePath string) (*SelfTestInfo, error)
IsSMARTSupported(ctx context.Context, devicePath string) (*SmartSupport, error)
EnableSMART(ctx context.Context, devicePath string) error
DisableSMART(ctx context.Context, devicePath string) error
AbortSelfTest(ctx context.Context, devicePath string) error
}
SmartClient interface defines the methods for interacting with smartmontools
func NewClient ¶
func NewClient(opts ...ClientOption) (SmartClient, error)
NewClient creates a new smartmontools client with optional configuration. If no smartctl path is provided, it will search for smartctl in PATH. If no log handler is provided, it will use a tlog debug-level logger for diagnostic output. If no context is provided, context.Background() will be used as the default.
type SmartStatus ¶
type SmartStatus struct {
Running bool `json:"running"`
Passed bool `json:"passed"`
Damaged bool `json:"damaged,omitempty"`
Critical bool `json:"critical,omitempty"`
}
SmartStatus represents the overall SMART health status
type SmartSupport ¶
SmartSupport represents SMART availability and enablement status.
type SmartctlInfo ¶
type SmartctlInfo struct {
Version []int `json:"version,omitempty"`
Messages []Message `json:"messages,omitempty"`
ExitStatus int `json:"exit_status,omitempty"`
}
SmartctlInfo represents smartctl metadata and messages
type StatusField ¶
type StatusField struct {
Value int `json:"value"`
String string `json:"string"`
Passed *bool `json:"passed,omitempty"`
RemainingPercent *int `json:"remaining_percent,omitempty"`
}
StatusField represents a status field that can be either a simple string or a complex object
func (*StatusField) UnmarshalJSON ¶
func (s *StatusField) UnmarshalJSON(data []byte) error
UnmarshalJSON allows StatusField to be parsed from either a JSON string (e.g., "completed") or a structured object with fields {value, string, passed, remaining_percent}.
type Temperature ¶
type Temperature struct {
Current int `json:"current"`
}
Temperature represents device temperature
type UserCapacity ¶
UserCapacity represents storage device capacity information