/
ntpq.go
304 lines (268 loc) · 6.88 KB
/
ntpq.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
298
299
300
301
302
303
304
//go:generate ../../../tools/readme_config_includer/generator
package ntpq
import (
"bufio"
"bytes"
_ "embed"
"fmt"
"math/bits"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/kballard/go-shellquote"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal/choice"
"github.com/influxdata/telegraf/plugins/inputs"
)
//go:embed sample.conf
var sampleConfig string
// Due to problems with a parsing, we have to use regexp expression in order
// to remove string that starts from '(' and ends with space
// see: https://github.com/influxdata/telegraf/issues/2386
var reBrackets = regexp.MustCompile(`\s+\([\S]*`)
type elementType int64
const (
None elementType = iota
Tag
FieldFloat
FieldDuration
FieldIntDecimal
FieldIntOctal
FieldIntRatio8
FieldIntBits
)
type column struct {
name string
etype elementType
}
// Mapping of ntpq header names to tag keys
var tagHeaders = map[string]string{
"remote": "remote",
"refid": "refid",
"st": "stratum",
"t": "type",
}
// Mapping of fields
var fieldElements = map[string]elementType{
"delay": FieldFloat,
"jitter": FieldFloat,
"offset": FieldFloat,
"reach": FieldIntDecimal,
"poll": FieldDuration,
"when": FieldDuration,
}
type NTPQ struct {
DNSLookup bool `toml:"dns_lookup" deprecated:"1.24.0;add '-n' to 'options' instead to skip DNS lookup"`
Options string `toml:"options"`
Servers []string `toml:"servers"`
ReachFormat string `toml:"reach_format"`
runQ func(string) ([]byte, error)
}
func (*NTPQ) SampleConfig() string {
return sampleConfig
}
func (n *NTPQ) Init() error {
if len(n.Servers) == 0 {
n.Servers = []string{""}
}
if n.runQ == nil {
options, err := shellquote.Split(n.Options)
if err != nil {
return fmt.Errorf("splitting options failed: %w", err)
}
if !n.DNSLookup {
if !choice.Contains("-n", options) {
options = append(options, "-n")
}
}
n.runQ = func(server string) ([]byte, error) {
bin, err := exec.LookPath("ntpq")
if err != nil {
return nil, err
}
// Needs to be last argument
var args []string
args = append(args, options...)
if server != "" {
args = append(args, server)
}
cmd := exec.Command(bin, args...)
return cmd.Output()
}
}
switch n.ReachFormat {
case "", "octal":
n.ReachFormat = "octal"
// Interpret the field as decimal integer returning
// the raw (octal) representation
fieldElements["reach"] = FieldIntDecimal
case "decimal":
// Interpret the field as octal integer returning
// decimal number representation
fieldElements["reach"] = FieldIntOctal
case "count":
// Interpret the field as bits set returning
// the number of bits set
fieldElements["reach"] = FieldIntBits
case "ratio":
// Interpret the field as ratio between the number of
// bits set and the maximum available bits set (8).
fieldElements["reach"] = FieldIntRatio8
default:
return fmt.Errorf("unknown 'reach_format' %q", n.ReachFormat)
}
return nil
}
func (n *NTPQ) Gather(acc telegraf.Accumulator) error {
for _, server := range n.Servers {
n.gatherServer(acc, server)
}
return nil
}
func (n *NTPQ) gatherServer(acc telegraf.Accumulator, server string) {
var msgPrefix string
if server != "" {
msgPrefix = fmt.Sprintf("[%s] ", server)
}
out, err := n.runQ(server)
if err != nil {
acc.AddError(fmt.Errorf("%s%w", msgPrefix, err))
return
}
scanner := bufio.NewScanner(bytes.NewReader(out))
// Look for the header
var columns []column
for scanner.Scan() {
line := scanner.Text()
_, elements := processLine(line)
if len(elements) < 2 {
continue
}
for _, el := range elements {
// Check if the element is a tag
if name, isTag := tagHeaders[el]; isTag {
columns = append(columns, column{
name: name,
etype: Tag,
})
continue
}
// Add a field
if etype, isField := fieldElements[el]; isField {
columns = append(columns, column{
name: el,
etype: etype,
})
continue
}
// Skip the column if not found
columns = append(columns, column{etype: None})
}
break
}
for scanner.Scan() {
line := scanner.Text()
prefix, elements := processLine(line)
if len(elements) != len(columns) {
continue
}
tags := make(map[string]string)
fields := make(map[string]interface{})
if prefix != "" {
tags["state_prefix"] = prefix
}
if server != "" {
tags["source"] = server
}
for i, raw := range elements {
col := columns[i]
switch col.etype {
case None:
continue
case Tag:
tags[col.name] = raw
case FieldFloat:
value, err := strconv.ParseFloat(raw, 64)
if err != nil {
msg := fmt.Sprintf("%sparsing %q (%v) as float failed", msgPrefix, col.name, raw)
acc.AddError(fmt.Errorf("%s: %w", msg, err))
continue
}
fields[col.name] = value
case FieldDuration:
// Ignore fields only containing a minus
if raw == "-" {
continue
}
factor := int64(1)
suffix := raw[len(raw)-1:]
switch suffix {
case "d":
factor = 24 * 3600
case "h":
factor = 3600
case "m":
factor = 60
default:
suffix = ""
}
value, err := strconv.ParseInt(strings.TrimSuffix(raw, suffix), 10, 64)
if err != nil {
msg := fmt.Sprintf("%sparsing %q (%v) as duration failed", msgPrefix, col.name, raw)
acc.AddError(fmt.Errorf("%s: %w", msg, err))
continue
}
fields[col.name] = value * factor
case FieldIntDecimal:
value, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
acc.AddError(fmt.Errorf("parsing %q (%v) as int failed: %w", col.name, raw, err))
continue
}
fields[col.name] = value
case FieldIntOctal:
value, err := strconv.ParseInt(raw, 8, 64)
if err != nil {
acc.AddError(fmt.Errorf("parsing %q (%v) as int failed: %w", col.name, raw, err))
continue
}
fields[col.name] = value
case FieldIntBits:
value, err := strconv.ParseUint(raw, 8, 64)
if err != nil {
acc.AddError(fmt.Errorf("parsing %q (%v) as int failed: %w", col.name, raw, err))
continue
}
fields[col.name] = bits.OnesCount64(value)
case FieldIntRatio8:
value, err := strconv.ParseUint(raw, 8, 64)
if err != nil {
acc.AddError(fmt.Errorf("parsing %q (%v) as int failed: %w", col.name, raw, err))
continue
}
fields[col.name] = float64(bits.OnesCount64(value)) / float64(8)
}
}
acc.AddFields("ntpq", fields, tags)
}
}
func processLine(line string) (string, []string) {
// if there is an ntpq state prefix, remove it and make it it's own tag
// see https://github.com/influxdata/telegraf/issues/1161
var prefix string
if strings.ContainsAny(string(line[0]), "*#o+x.-") {
prefix = string(line[0])
line = strings.TrimLeft(line, "*#o+x.-")
}
line = reBrackets.ReplaceAllString(line, "")
return prefix, strings.Fields(line)
}
func init() {
inputs.Add("ntpq", func() telegraf.Input {
return &NTPQ{
DNSLookup: true,
Options: "-p",
}
})
}