You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

140 lines
4.0 KiB

// Package snmpsocket exposes the group-restricted tera-snmpd Unix socket.
package snmpsocket
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"time"
"tera-clone/services/tera-api/internal/snmpagent"
)
const DefaultSocketPath = "/run/tera-snmpd/control.sock"
type request struct {
Action string `json:"action"`
Config snmpagent.Config `json:"config"`
}
type response struct {
Code string `json:"code,omitempty"`
Error string `json:"error,omitempty"`
}
type Server struct{ Controller snmpagent.Controller }
func (s Server) Serve(listener net.Listener) error {
if s.Controller == nil {
return errors.New("SNMP agent controller is required")
}
for {
connection, err := listener.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return nil
}
if temporary, ok := err.(interface{ Temporary() bool }); ok && temporary.Temporary() {
continue
}
return err
}
go s.handle(connection)
}
}
func (s Server) handle(connection net.Conn) {
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(20 * time.Second))
payload, err := bufio.NewReader(io.LimitReader(connection, 65537)).ReadBytes('\n')
if err != nil && !errors.Is(err, io.EOF) || len(payload) == 0 || len(payload) > 65536 || payload[len(payload)-1] != '\n' {
s.write(connection, response{Code: "validation_failed", Error: "invalid SNMP agent request"})
return
}
decoder := json.NewDecoder(bytes.NewReader(payload))
decoder.DisallowUnknownFields()
var command request
if err := decoder.Decode(&command); err != nil {
s.write(connection, response{Code: "validation_failed", Error: "invalid SNMP agent request"})
return
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
s.write(connection, response{Code: "validation_failed", Error: "SNMP agent request must contain one JSON value"})
return
}
if command.Action != "apply" {
s.write(connection, response{Code: "validation_failed", Error: "SNMP agent action is not supported"})
return
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := s.Controller.Apply(ctx, command.Config); err != nil {
code := "snmp_agent_failed"
if snmpagent.IsUnavailable(err) {
code = "snmp_agent_unavailable"
}
s.write(connection, response{Code: code, Error: err.Error()})
return
}
s.write(connection, response{})
}
func (Server) write(connection net.Conn, value response) {
_ = json.NewEncoder(connection).Encode(value)
}
type Client struct {
path string
timeout time.Duration
}
func NewClient(path string) *Client {
if path == "" {
path = DefaultSocketPath
}
return &Client{path: path, timeout: 20 * time.Second}
}
func (c *Client) Health(ctx context.Context) error {
dialer := net.Dialer{Timeout: c.timeout}
connection, err := dialer.DialContext(ctx, "unix", c.path)
if err != nil {
return &snmpagent.UnavailableError{Reason: "tera-snmpd is not reachable"}
}
return connection.Close()
}
func (c *Client) Apply(ctx context.Context, config snmpagent.Config) error {
dialer := net.Dialer{Timeout: c.timeout}
connection, err := dialer.DialContext(ctx, "unix", c.path)
if err != nil {
return &snmpagent.UnavailableError{Reason: "tera-snmpd is not reachable"}
}
defer connection.Close()
deadline := time.Now().Add(c.timeout)
if contextDeadline, ok := ctx.Deadline(); ok && contextDeadline.Before(deadline) {
deadline = contextDeadline
}
_ = connection.SetDeadline(deadline)
if err := json.NewEncoder(connection).Encode(request{Action: "apply", Config: config}); err != nil {
return errors.New("SNMP agent request failed")
}
var result response
if err := json.NewDecoder(io.LimitReader(connection, 65536)).Decode(&result); err != nil {
return &snmpagent.UnavailableError{Reason: "tera-snmpd returned no response"}
}
if result.Error != "" {
if result.Code == "snmp_agent_unavailable" {
return &snmpagent.UnavailableError{Reason: result.Error}
}
return fmt.Errorf("tera-snmpd: %s", result.Error)
}
return nil
}