summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/upsd/client.go
blob: a1b8f288e951ed98dca8bd8ab6c8611ffb599625 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// SPDX-License-Identifier: GPL-3.0-or-later

package upsd

import (
	"encoding/csv"
	"errors"
	"fmt"
	"strings"

	"github.com/netdata/netdata/go/go.d.plugin/pkg/socket"
)

const (
	commandUsername = "USERNAME %s"
	commandPassword = "PASSWORD %s"
	commandListUPS  = "LIST UPS"
	commandListVar  = "LIST VAR %s"
	commandLogout   = "LOGOUT"
)

// https://github.com/networkupstools/nut/blob/81fca30b2998fa73085ce4654f075605ff0b9e01/docs/net-protocol.txt#L647
var errUpsdCommand = errors.New("upsd command error")

type upsUnit struct {
	name string
	vars map[string]string
}

func newUpsdConn(conf Config) upsdConn {
	return &upsdClient{conn: socket.New(socket.Config{
		ConnectTimeout: conf.Timeout.Duration(),
		ReadTimeout:    conf.Timeout.Duration(),
		WriteTimeout:   conf.Timeout.Duration(),
		Address:        conf.Address,
	})}
}

type upsdClient struct {
	conn socket.Client
}

func (c *upsdClient) connect() error {
	return c.conn.Connect()
}

func (c *upsdClient) disconnect() error {
	_, _ = c.sendCommand(commandLogout)
	return c.conn.Disconnect()
}

func (c *upsdClient) authenticate(username, password string) error {
	cmd := fmt.Sprintf(commandUsername, username)
	resp, err := c.sendCommand(cmd)
	if err != nil {
		return err
	}
	if resp[0] != "OK" {
		return errors.New("authentication failed: invalid username")
	}

	cmd = fmt.Sprintf(commandPassword, password)
	resp, err = c.sendCommand(cmd)
	if err != nil {
		return err
	}
	if resp[0] != "OK" {
		return errors.New("authentication failed: invalid password")
	}

	return nil
}

func (c *upsdClient) upsUnits() ([]upsUnit, error) {
	resp, err := c.sendCommand(commandListUPS)
	if err != nil {
		return nil, err
	}

	var upsNames []string

	for _, v := range resp {
		if !strings.HasPrefix(v, "UPS ") {
			continue
		}
		parts := splitLine(v)
		if len(parts) < 2 {
			continue
		}
		name := parts[1]
		upsNames = append(upsNames, name)
	}

	var upsUnits []upsUnit

	for _, name := range upsNames {
		cmd := fmt.Sprintf(commandListVar, name)
		resp, err := c.sendCommand(cmd)
		if err != nil {
			return nil, err
		}

		ups := upsUnit{
			name: name,
			vars: make(map[string]string),
		}

		upsUnits = append(upsUnits, ups)

		for _, v := range resp {
			if !strings.HasPrefix(v, "VAR ") {
				continue
			}
			parts := splitLine(v)
			if len(parts) < 4 {
				continue
			}
			n, v := parts[2], parts[3]
			ups.vars[n] = v
		}
	}

	return upsUnits, nil
}

func (c *upsdClient) sendCommand(cmd string) ([]string, error) {
	var resp []string
	var errMsg string
	endLine := getEndLine(cmd)

	err := c.conn.Command(cmd+"\n", func(bytes []byte) bool {
		line := string(bytes)
		resp = append(resp, line)

		if strings.HasPrefix(line, "ERR ") {
			errMsg = strings.TrimPrefix(line, "ERR ")
		}

		return line != endLine && errMsg == ""
	})
	if err != nil {
		return nil, err
	}
	if errMsg != "" {
		return nil, fmt.Errorf("%w: %s (cmd: '%s')", errUpsdCommand, errMsg, cmd)
	}

	return resp, nil
}

func getEndLine(cmd string) string {
	px, _, _ := strings.Cut(cmd, " ")

	switch px {
	case "USERNAME", "PASSWORD", "VER":
		return "OK"
	}
	return fmt.Sprintf("END %s", cmd)
}

func splitLine(s string) []string {
	r := csv.NewReader(strings.NewReader(s))
	r.Comma = ' '

	parts, _ := r.Read()

	return parts
}