Documentation
¶
Overview ¶
Package nut provides a Golang interface for interacting with Network UPS Tools (NUT).
It communicates with NUT over the TCP protocol and supports TLS/SSL via STARTTLS
Index ¶
- type Client
- func (c *Client) Authenticate(username, password string) (bool, error)
- func (c *Client) Close() error
- func (c *Client) Disconnect() (bool, error)
- func (c *Client) GetMetrics() ClientMetrics
- func (c *Client) GetNetworkProtocolVersion() (string, error)
- func (c *Client) GetUPSList() ([]UPS, error)
- func (c *Client) GetVersion() (string, error)
- func (c *Client) Help() (string, error)
- func (c *Client) ReadResponse(endLine string, multiLineResponse bool) (resp []string, err error)
- func (c *Client) SendCommand(cmd string) (resp []string, err error)
- func (c *Client) SendCommandWithContext(ctx context.Context, cmd string) (resp []string, err error)
- func (c *Client) StartTLS() error
- type ClientMetrics
- type ClientOption
- type Command
- type Pool
- type PoolConfig
- type UPS
- func (u *UPS) CheckIfMaster() (bool, error)
- func (u *UPS) ForceShutdown() (bool, error)
- func (u *UPS) GetClients() ([]string, error)
- func (u *UPS) GetCommandDescription(commandName string) (string, error)
- func (u *UPS) GetCommands() ([]Command, error)
- func (u *UPS) GetDescription() (string, error)
- func (u *UPS) GetNumberOfLogins() (int, error)
- func (u *UPS) GetVariableDescription(variableName string) (string, error)
- func (u *UPS) GetVariableType(variableName string) (string, bool, int, error)
- func (u *UPS) GetVariables() ([]Variable, error)
- func (u *UPS) SendCommand(commandName string) (bool, error)
- func (u *UPS) SetVariable(variableName, value string) (bool, error)
- type Variable
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
Version string
ProtocolVersion string
Hostname net.Addr
UseTLS bool
TLSConfig *tls.Config
ConnectTimeout time.Duration
ReadTimeout time.Duration
Logger *log.Logger // Optional logger for debugging
// contains filtered or unexported fields
}
Client contains information about the NUT server as well as the connection.
func Connect ¶
Connect accepts a hostname/IP string and an optional port, then creates a connection to NUT, returning a Client.
Example ¶
This example demonstrates how to connect to NUT, authenticate, and list UPS devices.
// Connect to NUT server (typically running on port 3493)
client, err := Connect("127.0.0.1")
if err != nil {
log.Fatal(err)
}
// Authenticate
authenticated, err := client.Authenticate("username", "password")
if err != nil || !authenticated {
log.Fatal("authentication failed")
}
// Get list of UPS devices
upsList, err := client.GetUPSList()
if err != nil {
log.Fatal(err)
}
fmt.Println("Available UPS devices:", len(upsList))
if len(upsList) > 0 {
fmt.Println("First UPS:", upsList[0].Name)
}
// Clean disconnect
client.Disconnect()
func ConnectWithOptions ¶
ConnectWithOptions creates a connection with custom options and context support.
Example ¶
ExampleConnectWithOptions demonstrates using custom options
package main
import (
"context"
"fmt"
"log"
"time"
nut "github.com/bearx3f/go.nut"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Create logger
logger := log.New(log.Writer(), "[NUT] ", log.LstdFlags)
// Connect with custom options
client, err := nut.ConnectWithOptionsAndConfig(ctx, "localhost", []nut.ClientOption{
nut.WithConnectTimeout(5 * time.Second),
nut.WithReadTimeout(3 * time.Second),
nut.WithLogger(logger),
}, 3493)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect()
// Use context for command execution
resp, err := client.SendCommandWithContext(ctx, "VER")
if err != nil {
log.Fatal(err)
}
if len(resp) > 0 {
fmt.Printf("Server version: %s\n", resp[0])
}
}
func ConnectWithOptionsAndConfig ¶
func ConnectWithOptionsAndConfig(ctx context.Context, hostname string, opts []ClientOption, port ...int) (*Client, error)
ConnectWithOptionsAndConfig creates a connection with full configuration support.
func (*Client) Authenticate ¶
Authenticate accepts a username and passwords and uses them to authenticate the existing NUT session.
func (*Client) Close ¶
Close closes the connection without sending LOGOUT command. Use this if you just want to close the connection immediately.
func (*Client) Disconnect ¶
Disconnect gracefully disconnects from NUT by sending the LOGOUT command.
func (*Client) GetMetrics ¶
func (c *Client) GetMetrics() ClientMetrics
GetMetrics returns a copy of the current metrics
func (*Client) GetNetworkProtocolVersion ¶
GetNetworkProtocolVersion returns the version of the network protocol currently in use.
func (*Client) GetUPSList ¶
GetUPSList returns a list of all UPSes provided by this NUT instance.
func (*Client) GetVersion ¶
GetVersion returns the the version of the server currently in use.
func (*Client) ReadResponse ¶
ReadResponse is a convenience function for reading newline delimited responses.
func (*Client) SendCommand ¶
SendCommand sends the string cmd to the device, and returns the response.
func (*Client) SendCommandWithContext ¶
SendCommandWithContext sends a command with context support for cancellation.
type ClientMetrics ¶
type ClientMetrics struct {
CommandsSent uint64
CommandsFailed uint64
BytesSent uint64
BytesReceived uint64
Reconnects uint64
LastCommandTime atomic.Value // time.Time
}
ClientMetrics holds statistics for a client connection
Example ¶
ExampleClientMetrics demonstrates monitoring client metrics
package main
import (
"fmt"
"log"
nut "github.com/bearx3f/go.nut"
)
func main() {
client, err := nut.Connect("localhost")
if err != nil {
log.Fatal(err)
}
defer client.Disconnect()
// Authenticate
_, err = client.Authenticate("monuser", "secret")
if err != nil {
log.Fatal(err)
}
// Perform some operations
upsList, err := client.GetUPSList()
if err != nil {
log.Fatal(err)
}
for _, ups := range upsList {
vars, _ := ups.GetVariables()
fmt.Printf("UPS %s has %d variables\n", ups.Name, len(vars))
}
// Get metrics
metrics := client.GetMetrics()
fmt.Printf("Commands sent: %d\n", metrics.CommandsSent)
fmt.Printf("Commands failed: %d\n", metrics.CommandsFailed)
fmt.Printf("Bytes sent: %d\n", metrics.BytesSent)
fmt.Printf("Bytes received: %d\n", metrics.BytesReceived)
fmt.Printf("Reconnects: %d\n", metrics.Reconnects)
}
type ClientOption ¶
type ClientOption func(*Client)
ClientOption is a function that configures a Client
func WithConnectTimeout ¶
func WithConnectTimeout(timeout time.Duration) ClientOption
WithConnectTimeout sets a custom connection timeout
func WithLogger ¶
func WithLogger(logger *log.Logger) ClientOption
WithLogger sets a logger for debugging
func WithReadTimeout ¶
func WithReadTimeout(timeout time.Duration) ClientOption
WithReadTimeout sets a custom read timeout
func WithTLSConfig ¶
func WithTLSConfig(config *tls.Config) ClientOption
WithTLSConfig sets a custom TLS configuration
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool manages a pool of Client connections for high-concurrency scenarios.
Example ¶
ExamplePool demonstrates using connection pool for high-concurrency scenarios
package main
import (
"context"
"fmt"
"log"
"time"
nut "github.com/bearx3f/go.nut"
)
func main() {
// Create a connection pool
pool, err := nut.NewPool(nut.PoolConfig{
Hostname: "localhost",
Port: 3493,
MaxSize: 10, // Maximum 10 connections
ClientOptions: []nut.ClientOption{
nut.WithConnectTimeout(5 * time.Second),
nut.WithReadTimeout(2 * time.Second),
nut.WithLogger(log.Default()),
},
})
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// Get a client from the pool
ctx := context.Background()
client, err := pool.Get(ctx)
if err != nil {
log.Fatal(err)
}
// Use the client
upsList, err := client.GetUPSList()
if err != nil {
pool.Put(client) // Return even on error
log.Fatal(err)
}
for _, ups := range upsList {
fmt.Printf("UPS: %s\n", ups.Name)
}
// Return client to pool for reuse
if err := pool.Put(client); err != nil {
log.Printf("Failed to return client: %v", err)
}
// Check pool statistics
idle, active := pool.Stats()
fmt.Printf("Pool stats - Idle: %d, Active: %d\n", idle, active)
}
func NewPool ¶
func NewPool(config PoolConfig) (*Pool, error)
NewPool creates a new connection pool with the given configuration.
func (*Pool) Close ¶
Close closes all clients in the pool and prevents new clients from being created.
type PoolConfig ¶
type PoolConfig struct {
MaxSize int // Maximum number of connections in pool
Hostname string // NUT server hostname
Port int // NUT server port (default 3493)
ClientOptions []ClientOption // Options to apply to each client
}
PoolConfig contains configuration for connection pool
type UPS ¶
type UPS struct {
Name string
Description string
Master bool
NumberOfLogins int
Clients []string
Variables []Variable
Commands []Command
// contains filtered or unexported fields
}
UPS contains information about a specific UPS provided by the NUT instance.
func (*UPS) CheckIfMaster ¶
CheckIfMaster returns true if the session is authenticated with the master permission set.
func (*UPS) ForceShutdown ¶
ForceShutdown sets the FSD flag on the UPS.
This requires "upsmon master" in upsd.users, or "FSD" action granted in upsd.users
upsmon in master mode is the primary user of this function. It sets this "forced shutdown" flag on any UPS when it plans to power it off. This is done so that slave systems will know about it and shut down before the power disappears.
Setting this flag makes "FSD" appear in a STATUS request for this UPS. Finding "FSD" in a status request should be treated just like a "OB LB".
It should be noted that FSD is currently a latch - once set, there is no way to clear it short of restarting upsd or dropping then re-adding it in the ups.conf. This may cause issues when upsd is running on a system that is not shut down due to the UPS event.
func (*UPS) GetClients ¶
GetClients returns a list of NUT clients.
func (*UPS) GetCommandDescription ¶
GetCommandDescription returns a string that gives a brief explanation for the given commandName.
func (*UPS) GetCommands ¶
GetCommands returns a slice of Command structs for the UPS.
func (*UPS) GetDescription ¶
GetDescription the value of "desc=" from ups.conf for this UPS. If it is not set, upsd will return "Unavailable".
func (*UPS) GetNumberOfLogins ¶
GetNumberOfLogins returns the number of clients which have done LOGIN for this UPS.
func (*UPS) GetVariableDescription ¶
GetVariableDescription returns a string that gives a brief explanation for the given variableName. upsd may return "Unavailable" if the file which provides this description is not installed.
func (*UPS) GetVariableType ¶
GetVariableType returns the variable type, writeability and maximum length for the given variableName.
func (*UPS) GetVariables ¶
GetVariables returns a slice of Variable structs for the UPS.
func (*UPS) SendCommand ¶
SendCommand sends a command to the UPS.