-
Notifications
You must be signed in to change notification settings - Fork 735
Expand file tree
/
Copy pathconfig.go
More file actions
409 lines (373 loc) · 11 KB
/
Copy pathconfig.go
File metadata and controls
409 lines (373 loc) · 11 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"regexp"
"time"
"github.com/gosnmp/gosnmp"
"go.yaml.in/yaml/v2"
)
type Auth struct {
Community Secret `yaml:"community,omitempty"`
SecurityLevel string `yaml:"security_level,omitempty"`
Username string `yaml:"username,omitempty"`
Password Secret `yaml:"password,omitempty"`
AuthProtocol string `yaml:"auth_protocol,omitempty"`
PrivProtocol string `yaml:"priv_protocol,omitempty"`
PrivPassword Secret `yaml:"priv_password,omitempty"`
ContextName string `yaml:"context_name,omitempty"`
Version int `yaml:"version,omitempty"`
}
func LoadFile(logger *slog.Logger, paths []string, expandEnvVars bool) (*Config, error) {
cfg := &Config{}
for _, p := range paths {
files, err := filepath.Glob(p)
if err != nil {
return nil, err
}
if len(files) == 0 {
logger.Warn("No file found matching pattern", "file", p)
}
for _, f := range files {
content, err := os.ReadFile(f)
if err != nil {
return nil, err
}
err = yaml.UnmarshalStrict(content, cfg)
if err != nil {
return nil, err
}
}
}
if expandEnvVars {
var err error
for i, auth := range cfg.Auths {
if auth.Username != "" {
cfg.Auths[i].Username, err = substituteEnvVariables(auth.Username)
if err != nil {
return nil, err
}
}
if auth.Password != "" {
password, err := substituteEnvVariables(string(auth.Password))
if err != nil {
return nil, err
}
cfg.Auths[i].Password.Set(password)
}
if auth.PrivPassword != "" {
privPassword, err := substituteEnvVariables(string(auth.PrivPassword))
if err != nil {
return nil, err
}
cfg.Auths[i].PrivPassword.Set(privPassword)
}
}
}
return cfg, nil
}
var (
defaultRetries = 3
DefaultAuth = Auth{
Community: "public",
SecurityLevel: "noAuthNoPriv",
AuthProtocol: "MD5",
PrivProtocol: "DES",
Version: 2,
}
DefaultWalkParams = WalkParams{
MaxRepetitions: 25,
Retries: &defaultRetries,
Timeout: time.Second * 5,
UseUnconnectedUDPSocket: false,
AllowNonIncreasingOIDs: false,
}
DefaultModule = Module{
WalkParams: DefaultWalkParams,
}
DefaultRegexpExtract = RegexpExtract{
Value: "$1",
}
)
// Config for the snmp_exporter.
type Config struct {
Auths map[string]*Auth `yaml:"auths,omitempty"`
Modules map[string]*Module `yaml:"modules,omitempty"`
Version int `yaml:"version,omitempty"`
}
type WalkParams struct {
MaxRepetitions uint32 `yaml:"max_repetitions,omitempty"`
Retries *int `yaml:"retries,omitempty"`
Timeout time.Duration `yaml:"timeout,omitempty"`
UseUnconnectedUDPSocket bool `yaml:"use_unconnected_udp_socket,omitempty"`
AllowNonIncreasingOIDs bool `yaml:"allow_nonincreasing_oids,omitempty"`
}
type Module struct {
// A list of OIDs.
Walk []string `yaml:"walk,omitempty"`
Get []string `yaml:"get,omitempty"`
Metrics []*Metric `yaml:"metrics"`
WalkParams WalkParams `yaml:",inline"`
Filters []DynamicFilter `yaml:"filters,omitempty"`
}
func (c *Module) UnmarshalYAML(unmarshal func(any) error) error {
*c = DefaultModule
if c.WalkParams.Retries != nil {
retries := *c.WalkParams.Retries
c.WalkParams.Retries = &retries
}
type plain Module
return unmarshal((*plain)(c))
}
// ConfigureSNMP sets the various version and auth settings.
func (c Auth) ConfigureSNMP(g *gosnmp.GoSNMP, snmpContext string) {
switch c.Version {
case 1:
g.Version = gosnmp.Version1
case 2:
g.Version = gosnmp.Version2c
case 3:
g.Version = gosnmp.Version3
}
g.Community = string(c.Community)
if snmpContext == "" {
g.ContextName = c.ContextName
} else {
g.ContextName = snmpContext
}
// v3 security settings.
g.SecurityModel = gosnmp.UserSecurityModel
usm := &gosnmp.UsmSecurityParameters{
UserName: c.Username,
}
auth, priv := false, false
switch c.SecurityLevel {
case "noAuthNoPriv":
g.MsgFlags = gosnmp.NoAuthNoPriv
case "authNoPriv":
g.MsgFlags = gosnmp.AuthNoPriv
auth = true
case "authPriv":
g.MsgFlags = gosnmp.AuthPriv
auth = true
priv = true
}
if auth {
usm.AuthenticationPassphrase = string(c.Password)
switch c.AuthProtocol {
case "SHA":
usm.AuthenticationProtocol = gosnmp.SHA
case "SHA224":
usm.AuthenticationProtocol = gosnmp.SHA224
case "SHA256":
usm.AuthenticationProtocol = gosnmp.SHA256
case "SHA384":
usm.AuthenticationProtocol = gosnmp.SHA384
case "SHA512":
usm.AuthenticationProtocol = gosnmp.SHA512
case "MD5":
usm.AuthenticationProtocol = gosnmp.MD5
}
}
if priv {
usm.PrivacyPassphrase = string(c.PrivPassword)
switch c.PrivProtocol {
case "DES":
usm.PrivacyProtocol = gosnmp.DES
case "AES":
usm.PrivacyProtocol = gosnmp.AES
case "AES192":
usm.PrivacyProtocol = gosnmp.AES192
case "AES192C":
usm.PrivacyProtocol = gosnmp.AES192C
case "AES256":
usm.PrivacyProtocol = gosnmp.AES256
case "AES256C":
usm.PrivacyProtocol = gosnmp.AES256C
}
}
g.SecurityParameters = usm
}
type Filters struct {
Static []StaticFilter `yaml:"static,omitempty"`
Dynamic []DynamicFilter `yaml:"dynamic,omitempty"`
}
type StaticFilter struct {
Targets []string `yaml:"targets,omitempty"`
Indices []string `yaml:"indices,omitempty"`
}
type DynamicFilter struct {
Oid string `yaml:"oid"`
Targets []string `yaml:"targets,omitempty"`
Values []string `yaml:"values,omitempty"`
regexps []*regexp.Regexp `yaml:"-"`
}
func (c *DynamicFilter) CompileRegexps() error {
regexps := make([]*regexp.Regexp, 0, len(c.Values))
for _, value := range c.Values {
re, err := regexp.Compile(value)
if err != nil {
return fmt.Errorf("invalid dynamic filter value %q: %w", value, err)
}
regexps = append(regexps, re)
}
c.regexps = regexps
return nil
}
func (c *DynamicFilter) Regexps() []*regexp.Regexp {
return c.regexps
}
func (c *DynamicFilter) UnmarshalYAML(unmarshal func(any) error) error {
type plain DynamicFilter
if err := unmarshal((*plain)(c)); err != nil {
return err
}
return c.CompileRegexps()
}
type Metric struct {
Name string `yaml:"name"`
Oid string `yaml:"oid"`
Type string `yaml:"type"`
Help string `yaml:"help"`
Indexes []*Index `yaml:"indexes,omitempty"`
Lookups []*Lookup `yaml:"lookups,omitempty"`
RegexpExtracts map[string][]RegexpExtract `yaml:"regex_extracts,omitempty"`
DateTimePattern string `yaml:"datetime_pattern,omitempty"`
EnumValues map[int]string `yaml:"enum_values,omitempty"`
Offset float64 `yaml:"offset,omitempty"`
Scale float64 `yaml:"scale,omitempty"`
DisplayHint string `yaml:"display_hint,omitempty"`
}
type Index struct {
Labelname string `yaml:"labelname"`
Type string `yaml:"type"`
FixedSize int `yaml:"fixed_size,omitempty"`
Implied bool `yaml:"implied,omitempty"`
EnumValues map[int]string `yaml:"enum_values,omitempty"`
}
type Lookup struct {
Labels []string `yaml:"labels"`
Labelname string `yaml:"labelname"`
Oid string `yaml:"oid,omitempty"`
Type string `yaml:"type,omitempty"`
DisplayHint string `yaml:"display_hint,omitempty"`
EnumValues map[int]string `yaml:"enum_values,omitempty"`
}
// Secret is a string that must not be revealed on marshaling.
type Secret string
func (s *Secret) Set(value string) {
*s = Secret(value)
}
// Hack for creating snmp.yml with the secret.
var (
DoNotHideSecrets = false
)
// MarshalYAML implements the yaml.Marshaler interface.
func (s Secret) MarshalYAML() (any, error) {
if DoNotHideSecrets {
return string(s), nil
}
if s != "" {
return "<secret>", nil
}
return nil, nil
}
func (c *Auth) UnmarshalYAML(unmarshal func(any) error) error {
*c = DefaultAuth
type plain Auth
if err := unmarshal((*plain)(c)); err != nil {
return err
}
if c.Version < 1 || c.Version > 3 {
return fmt.Errorf("SNMP version must be 1, 2 or 3. Got: %d", c.Version)
}
if c.Version == 3 {
switch c.SecurityLevel {
case "authPriv":
if c.PrivPassword == "" {
return fmt.Errorf("priv password is missing, required for SNMPv3 with priv")
}
if c.PrivProtocol != "DES" && c.PrivProtocol != "AES" && c.PrivProtocol != "AES192" && c.PrivProtocol != "AES192C" && c.PrivProtocol != "AES256" && c.PrivProtocol != "AES256C" {
return fmt.Errorf("priv protocol must be DES or AES")
}
fallthrough
case "authNoPriv":
if c.Password == "" {
return fmt.Errorf("auth password is missing, required for SNMPv3 with auth")
}
if c.AuthProtocol != "MD5" && c.AuthProtocol != "SHA" && c.AuthProtocol != "SHA224" && c.AuthProtocol != "SHA256" && c.AuthProtocol != "SHA384" && c.AuthProtocol != "SHA512" {
return fmt.Errorf("auth protocol must be SHA or MD5")
}
fallthrough
case "noAuthNoPriv":
if c.Username == "" {
return fmt.Errorf("auth username is missing, required for SNMPv3")
}
default:
return fmt.Errorf("security level must be one of authPriv, authNoPriv or noAuthNoPriv")
}
}
return nil
}
type RegexpExtract struct {
Value string `yaml:"value"`
Regex Regexp `yaml:"regex"`
}
func (c *RegexpExtract) UnmarshalYAML(unmarshal func(any) error) error {
*c = DefaultRegexpExtract
type plain RegexpExtract
return unmarshal((*plain)(c))
}
// Regexp encapsulates a regexp.Regexp and makes it YAML marshalable.
type Regexp struct {
*regexp.Regexp
}
// MarshalYAML implements the yaml.Marshaler interface.
func (re Regexp) MarshalYAML() (any, error) {
if re.Regexp != nil {
return re.String(), nil
}
return nil, nil
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (re *Regexp) UnmarshalYAML(unmarshal func(any) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
regex, err := regexp.Compile("^(?:" + s + ")$")
if err != nil {
return err
}
re.Regexp = regex
return nil
}
func substituteEnvVariables(value string) (string, error) {
missingEnv := ""
result := os.Expand(value, func(s string) string {
v, ok := os.LookupEnv(s)
if !ok && missingEnv == "" {
missingEnv = s
}
return v
})
if missingEnv != "" {
return "", errors.New(missingEnv + " environment variable not found")
}
return result, nil
}