forked from aws/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipmi.go
297 lines (264 loc) · 8.27 KB
/
ipmi.go
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package ipmi_sensor
import (
"bufio"
"bytes"
"fmt"
"log"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
var (
execCommand = exec.Command // execCommand is used to mock commands in tests.
re_v1_parse_line = regexp.MustCompile(`^(?P<name>[^|]*)\|(?P<description>[^|]*)\|(?P<status_code>.*)`)
re_v2_parse_line = regexp.MustCompile(`^(?P<name>[^|]*)\|[^|]+\|(?P<status_code>[^|]*)\|(?P<entity_id>[^|]*)\|(?:(?P<description>[^|]+))?`)
re_v2_parse_description = regexp.MustCompile(`^(?P<analogValue>-?[0-9.]+)\s(?P<analogUnit>.*)|(?P<status>.+)|^$`)
re_v2_parse_unit = regexp.MustCompile(`^(?P<realAnalogUnit>[^,]+)(?:,\s*(?P<statusDesc>.*))?`)
)
// Ipmi stores the configuration values for the ipmi_sensor input plugin
type Ipmi struct {
Path string
Privilege string
Servers []string
Timeout internal.Duration
MetricVersion int
UseSudo bool
}
var sampleConfig = `
## optionally specify the path to the ipmitool executable
# path = "/usr/bin/ipmitool"
##
## Setting 'use_sudo' to true will make use of sudo to run ipmitool.
## Sudo must be configured to allow the telegraf user to run ipmitool
## without a password.
# use_sudo = false
##
## optionally force session privilege level. Can be CALLBACK, USER, OPERATOR, ADMINISTRATOR
# privilege = "ADMINISTRATOR"
##
## optionally specify one or more servers via a url matching
## [username[:password]@][protocol[(address)]]
## e.g.
## root:passwd@lan(127.0.0.1)
##
## if no servers are specified, local machine sensor stats will be queried
##
# servers = ["USERID:PASSW0RD@lan(192.168.1.1)"]
## Recommended: use metric 'interval' that is a multiple of 'timeout' to avoid
## gaps or overlap in pulled data
interval = "30s"
## Timeout for the ipmitool command to complete
timeout = "20s"
## Schema Version: (Optional, defaults to version 1)
metric_version = 2
`
// SampleConfig returns the documentation about the sample configuration
func (m *Ipmi) SampleConfig() string {
return sampleConfig
}
// Description returns a basic description for the plugin functions
func (m *Ipmi) Description() string {
return "Read metrics from the bare metal servers via IPMI"
}
// Gather is the main execution function for the plugin
func (m *Ipmi) Gather(acc telegraf.Accumulator) error {
if len(m.Path) == 0 {
return fmt.Errorf("ipmitool not found: verify that ipmitool is installed and that ipmitool is in your PATH")
}
if len(m.Servers) > 0 {
wg := sync.WaitGroup{}
for _, server := range m.Servers {
wg.Add(1)
go func(a telegraf.Accumulator, s string) {
defer wg.Done()
err := m.parse(a, s)
if err != nil {
a.AddError(err)
}
}(acc, server)
}
wg.Wait()
} else {
err := m.parse(acc, "")
if err != nil {
return err
}
}
return nil
}
func (m *Ipmi) parse(acc telegraf.Accumulator, server string) error {
opts := make([]string, 0)
hostname := ""
if server != "" {
conn := NewConnection(server, m.Privilege)
hostname = conn.Hostname
opts = conn.options()
}
opts = append(opts, "sdr")
if m.MetricVersion == 2 {
opts = append(opts, "elist")
}
name := m.Path
if m.UseSudo {
// -n - avoid prompting the user for input of any kind
opts = append([]string{"-n", name}, opts...)
name = "sudo"
}
cmd := execCommand(name, opts...)
out, err := internal.CombinedOutputTimeout(cmd, m.Timeout.Duration)
timestamp := time.Now()
if err != nil {
return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
}
if m.MetricVersion == 2 {
return parseV2(acc, hostname, out, timestamp)
}
return parseV1(acc, hostname, out, timestamp)
}
func parseV1(acc telegraf.Accumulator, hostname string, cmdOut []byte, measured_at time.Time) error {
// each line will look something like
// Planar VBAT | 3.05 Volts | ok
scanner := bufio.NewScanner(bytes.NewReader(cmdOut))
for scanner.Scan() {
ipmiFields := extractFieldsFromRegex(re_v1_parse_line, scanner.Text())
if len(ipmiFields) != 3 {
continue
}
tags := map[string]string{
"name": transform(ipmiFields["name"]),
}
// tag the server is we have one
if hostname != "" {
tags["server"] = hostname
}
fields := make(map[string]interface{})
if strings.EqualFold("ok", trim(ipmiFields["status_code"])) {
fields["status"] = 1
} else {
fields["status"] = 0
}
description := ipmiFields["description"]
// handle hex description field
if strings.HasPrefix(description, "0x") {
descriptionInt, err := strconv.ParseInt(description, 0, 64)
if err != nil {
continue
}
fields["value"] = float64(descriptionInt)
} else if strings.Index(description, " ") > 0 {
// split middle column into value and unit
valunit := strings.SplitN(description, " ", 2)
var err error
fields["value"], err = aToFloat(valunit[0])
if err != nil {
continue
}
if len(valunit) > 1 {
tags["unit"] = transform(valunit[1])
}
} else {
fields["value"] = 0.0
}
acc.AddFields("ipmi_sensor", fields, tags, measured_at)
}
return scanner.Err()
}
func parseV2(acc telegraf.Accumulator, hostname string, cmdOut []byte, measured_at time.Time) error {
// each line will look something like
// CMOS Battery | 65h | ok | 7.1 |
// Temp | 0Eh | ok | 3.1 | 55 degrees C
// Drive 0 | A0h | ok | 7.1 | Drive Present
scanner := bufio.NewScanner(bytes.NewReader(cmdOut))
for scanner.Scan() {
ipmiFields := extractFieldsFromRegex(re_v2_parse_line, scanner.Text())
if len(ipmiFields) < 3 || len(ipmiFields) > 4 {
continue
}
tags := map[string]string{
"name": transform(ipmiFields["name"]),
}
// tag the server is we have one
if hostname != "" {
tags["server"] = hostname
}
tags["entity_id"] = transform(ipmiFields["entity_id"])
tags["status_code"] = trim(ipmiFields["status_code"])
fields := make(map[string]interface{})
descriptionResults := extractFieldsFromRegex(re_v2_parse_description, trim(ipmiFields["description"]))
// This is an analog value with a unit
if descriptionResults["analogValue"] != "" && len(descriptionResults["analogUnit"]) >= 1 {
var err error
fields["value"], err = aToFloat(descriptionResults["analogValue"])
if err != nil {
continue
}
// Some implementations add an extra status to their analog units
unitResults := extractFieldsFromRegex(re_v2_parse_unit, descriptionResults["analogUnit"])
tags["unit"] = transform(unitResults["realAnalogUnit"])
if unitResults["statusDesc"] != "" {
tags["status_desc"] = transform(unitResults["statusDesc"])
}
} else {
// This is a status value
fields["value"] = 0.0
// Extended status descriptions aren't required, in which case for consistency re-use the status code
if descriptionResults["status"] != "" {
tags["status_desc"] = transform(descriptionResults["status"])
} else {
tags["status_desc"] = transform(ipmiFields["status_code"])
}
}
acc.AddFields("ipmi_sensor", fields, tags, measured_at)
}
return scanner.Err()
}
// extractFieldsFromRegex consumes a regex with named capture groups and returns a kvp map of strings with the results
func extractFieldsFromRegex(re *regexp.Regexp, input string) map[string]string {
submatches := re.FindStringSubmatch(input)
results := make(map[string]string)
subexpNames := re.SubexpNames()
if len(subexpNames) > len(submatches) {
log.Printf("D! No matches found in '%s'", input)
return results
}
for i, name := range subexpNames {
if name != input && name != "" && input != "" {
results[name] = trim(submatches[i])
}
}
return results
}
// aToFloat converts string representations of numbers to float64 values
func aToFloat(val string) (float64, error) {
f, err := strconv.ParseFloat(val, 64)
if err != nil {
return 0.0, err
}
return f, nil
}
func trim(s string) string {
return strings.TrimSpace(s)
}
func transform(s string) string {
s = trim(s)
s = strings.ToLower(s)
return strings.Replace(s, " ", "_", -1)
}
func init() {
m := Ipmi{}
path, _ := exec.LookPath("ipmitool")
if len(path) > 0 {
m.Path = path
}
m.Timeout = internal.Duration{Duration: time.Second * 20}
inputs.Add("ipmi_sensor", func() telegraf.Input {
m := m
return &m
})
}