forked from QubitProducts/exporter_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
572 lines (489 loc) · 14.8 KB
/
main.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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright 2016 Qubit Ltd.
// 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 main
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"net"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"golang.org/x/sync/errgroup"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
var (
printVersion = flag.Bool("version", false, "Print the version and exit")
cfgFile = flag.String("config.file", "expexp.yaml", "The path to the configuration file.")
cfgDirs StringSliceFlag
skipDirs = flag.Bool("config.skip-dirs", false, "Skip non existent -config.dirs entries instead of terminating.")
addr = flag.String("web.listen-address", ":9999", "The address to listen on for HTTP requests.")
bearerToken = flag.String("web.bearer.token", "", "Bearer authentication token.")
bearerTokenFile = flag.String("web.bearer.token-file", "", "File containing the Bearer authentication token.")
acl IPNetSliceFlag
certPath = flag.String("web.tls.cert", "cert.pem", "Path to cert")
keyPath = flag.String("web.tls.key", "key.pem", "Path to key")
caPath = flag.String("web.tls.ca", "ca.pem", "Path to CA to auth clients against")
verify = flag.Bool("web.tls.verify", false, "Enable client verification")
certMatch = flag.String("web.tls.certmatch", "", "if set, this is used as a regexp that is matched against any certificate subject, dnsname or email address, only certs with a match are verified. web.tls.verify must also be set")
tlsAddr = flag.String("web.tls.listen-address", "", "The address to listen on for HTTPS requests.")
tPath = flag.String("web.telemetry-path", "/metrics", "The address to listen on for HTTP requests.")
pPath = flag.String("web.proxy-path", "/proxy", "The address to listen on for HTTP requests.")
logLevel = LogLevelFlag(log.WarnLevel)
logJSON = flag.Bool("log.json", false, "Serialize log messages in JSON")
proxyDuration = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "expexp_proxy_duration_seconds",
Help: "Duration of proxying requests to configured exporters",
},
[]string{"module"},
)
proxyErrorCount = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "expexp_proxy_errors_total",
Help: "Counts of errors",
},
[]string{"module"},
)
proxyTimeoutCount = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "expexp_proxy_timeout_errors_total",
Help: "Counts of the number of times a proxy timeout occurred",
},
[]string{"module"},
)
proxyMalformedCount = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "expexp_malformed_content_errors_total",
Help: "Counts of unparsable scrape content errors",
},
[]string{"module"},
)
)
func init() {
// register the collector metrics in the default
// registry.
prometheus.MustRegister(proxyDuration)
prometheus.MustRegister(proxyTimeoutCount)
prometheus.MustRegister(proxyErrorCount)
prometheus.MustRegister(proxyMalformedCount)
prometheus.MustRegister(cmdStartsCount)
prometheus.MustRegister(cmdFailsCount)
flag.Var(&cfgDirs, "config.dirs", "The path to directories of configuration files, can be specified multiple times.")
flag.Var(&acl, "allow.net", "Allow connection from this network specified in CIDR notation. Can be specified multiple times.")
flag.Var(&logLevel, "log.level", "Log level")
}
func setup() (*config, error) {
cfg := &config{
Modules: make(map[string]*moduleConfig),
XXX: make(map[string]interface{}),
}
if *cfgFile != "" {
r, err := os.Open(*cfgFile)
if err != nil {
return nil, err
}
defer r.Close()
cfg, err = readConfig(r)
if err != nil {
return nil, err
}
for mn := range cfg.Modules {
log.Debugf("read module config '%s' from: %s", mn, *cfgFile)
}
}
cfgDirs:
for _, cfgDir := range cfgDirs {
mfs, err := os.ReadDir(cfgDir)
if err != nil {
if *skipDirs && os.IsNotExist(err) {
log.Warnf("skipping non existent config.dirs entry '%s'", cfgDir)
continue cfgDirs
}
return nil, fmt.Errorf("failed reading directory: %s, %v", cfgDir, err)
}
yamlSuffixes := map[string]bool{
".yml": true,
".yaml": true,
}
for _, mf := range mfs {
fullpath := filepath.Join(cfgDir, mf.Name())
if mf.IsDir() || !yamlSuffixes[filepath.Ext(mf.Name())] {
log.Warnf("skipping non-yaml file %v", fullpath)
continue
}
mn := strings.TrimSuffix(mf.Name(), filepath.Ext(mf.Name()))
if _, ok := cfg.Modules[mn]; ok {
return nil, fmt.Errorf("module %s is already defined", mn)
}
r, err := os.Open(fullpath)
if err != nil {
return nil, fmt.Errorf("failed to open config file %s, %w", fullpath, err)
}
defer r.Close()
mcfg, err := readModuleConfig(mn, r)
if err != nil {
return nil, fmt.Errorf("failed reading configs %s, %w", fullpath, err)
}
log.Debugf("read module config '%s' from: %s", mn, fullpath)
cfg.Modules[mn] = mcfg
}
}
if len(cfg.Modules) == 0 {
log.Errorln("no modules loaded from any config file")
}
if *bearerToken != "" {
cfg.bearerToken = *bearerToken
}
if *bearerTokenFile != "" {
if *bearerToken != "" {
return nil, errors.New(("web.bearer.token and web.bearer.token-file are mutually exclusive options"))
}
bs, err := os.ReadFile(*bearerTokenFile)
if err != nil {
return nil, fmt.Errorf("failed reading bearer file %s, %w", *bearerTokenFile, err)
}
t := strings.TrimSpace(string(bs))
if len(t) == 0 {
return nil, errors.New("token file should not be empty")
}
cfg.bearerToken = t
}
cfg.proxyPath = path.Clean("/" + *pPath)
cfg.telemetryPath = path.Clean("/" + *tPath)
if cfg.proxyPath == cfg.telemetryPath {
return nil, fmt.Errorf("flags -web.proxy-path and -web.telemetry-path can not be set to the same value")
}
return cfg, nil
}
func getClientValidator(r *regexp.Regexp, helloInfo *tls.ClientHelloInfo) func([][]byte, [][]*x509.Certificate) error {
return func(_ [][]byte, verifiedChains [][]*x509.Certificate) error {
for _, c := range verifiedChains {
leaf := c[0]
if r.MatchString(leaf.Subject.CommonName) {
return nil
}
for _, name := range leaf.DNSNames {
if r.MatchString(name) {
return nil
}
}
for _, name := range leaf.EmailAddresses {
if r.MatchString(name) {
return nil
}
}
}
return errors.New("no client certificate subject or email address matched")
}
}
func setupTLS() (*tls.Config, error) {
var tlsConfig *tls.Config
if *tlsAddr == "" {
return nil, nil
}
cert, err := tls.LoadX509KeyPair(*certPath, *keyPath)
if err != nil {
return nil, fmt.Errorf("could not parse key/cert, %w", err)
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
},
}
tlsConfig.BuildNameToCertificate()
if *verify {
pool := x509.NewCertPool()
cabs, err := os.ReadFile(*caPath)
if err != nil {
return nil, fmt.Errorf("could not open ca file, %w", err)
}
ok := pool.AppendCertsFromPEM(cabs)
if !ok {
return nil, errors.New("failed loading ca certs")
}
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
tlsConfig.ClientCAs = pool
if *certMatch != "" {
rx, err := regexp.Compile(*certMatch)
if err != nil {
return nil, fmt.Errorf("tls.web.certmatch is not a valid regexp, %w", err)
}
tlsConfig.GetConfigForClient = func(hi *tls.ClientHelloInfo) (*tls.Config, error) {
serverConf := tlsConfig.Clone()
serverConf.VerifyPeerCertificate = getClientValidator(rx, hi)
return serverConf, nil
}
}
} else {
if *certMatch != "" {
return nil, errors.New("tls.web.verify must be set to use certificate matching")
}
}
return tlsConfig, nil
}
func runListener(ctx context.Context, name string, lsnr net.Listener, handler http.Handler) error {
srvr := http.Server{
Handler: handler,
}
go func() {
<-ctx.Done()
srvr.Shutdown(context.Background())
}()
if err := srvr.Serve(lsnr); err != nil {
return fmt.Errorf("listener %s stopped, %w", name, err)
}
return nil
}
func main() {
var err error
defer func() {
if err != nil {
log.Errorln(err.Error())
os.Exit(1)
}
}()
flag.Parse()
manageService()
if *printVersion {
fmt.Fprintf(os.Stderr, "Version: %s\n", versionStr())
return
}
cfg, err := setup()
if err != nil {
return
}
tlsConfig, err := setupTLS()
if err != nil {
return
}
if *addr == "" && *tlsAddr == "" {
log.Info("No web addresses to listen on, nothing to do!")
os.Exit(0)
}
var lsnr net.Listener
if *addr != "" {
lsnr, err = net.Listen("tcp", *addr)
if err != nil {
return
}
}
var tlsLsnr net.Listener
if *tlsAddr != "" {
tlsLsnr, err = net.Listen("tcp", *tlsAddr)
if err != nil {
return
}
tlsLsnr = tls.NewListener(tlsLsnr, tlsConfig)
}
http.HandleFunc(cfg.proxyPath, cfg.doProxy)
http.HandleFunc("/", cfg.listModules)
http.Handle(cfg.telemetryPath, promhttp.Handler())
handler := http.Handler(http.DefaultServeMux)
if cfg.bearerToken != "" {
handler = &BearerAuthMiddleware{handler, cfg.bearerToken}
}
if len(acl) > 0 {
log.Infof("Allowing connections only from %v", acl)
handler = &IPAddressAuthMiddleware{handler, acl}
}
log.SetLevel(log.Level(logLevel))
if *logJSON {
log.SetFormatter(&log.JSONFormatter{})
}
handler = &AccessLogMiddleware{handler}
eg, ctx := errgroup.WithContext(context.Background())
if lsnr != nil {
eg.Go(func() error {
return runListener(ctx, "http", lsnr, handler)
})
}
if tlsLsnr != nil {
eg.Go(func() error {
return runListener(ctx, "https", tlsLsnr, handler)
})
}
err = eg.Wait()
}
type responseWriterWithStatus struct {
http.ResponseWriter
status int
}
func (w *responseWriterWithStatus) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
// AccessLogMiddleware logs all request at Info level
type AccessLogMiddleware struct {
http.Handler
}
func (middleware AccessLogMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
start = time.Now()
statusWriter = &responseWriterWithStatus{w, http.StatusOK}
)
defer func() {
remoteHost, _, _ := net.SplitHostPort(r.RemoteAddr)
log.Infof(
"%s - %s \"%s\" %d %s (took %s)",
remoteHost, r.Method, r.URL.RequestURI(), statusWriter.status,
http.StatusText(statusWriter.status), time.Since(start),
)
}()
middleware.Handler.ServeHTTP(statusWriter, r)
}
func (cfg *config) doProxy(w http.ResponseWriter, r *http.Request) {
mod, ok := r.URL.Query()["module"]
if !ok && cfg.DefaultModule == "" {
log.Errorf("no module given")
http.Error(w, fmt.Sprintf("require parameter module is missing%v\n", mod), http.StatusBadRequest)
return
}
if len(mod) == 0 {
mod = append(mod, cfg.DefaultModule)
}
log.Debugf("running module %v\n", mod[0])
var h http.Handler
m, ok := cfg.Modules[mod[0]]
if !ok {
proxyErrorCount.WithLabelValues("unknown").Inc()
log.Warnf("unknown module requested %v\n", mod)
http.Error(w, fmt.Sprintf("unknown module %v\n", mod), http.StatusNotFound)
return
}
h = m
h.ServeHTTP(w, r)
}
func (cfg *config) listModules(w http.ResponseWriter, r *http.Request) {
switch r.Header.Get("Accept") {
case "application/json":
log.Debugf("Listing modules in json")
moduleJSON, err := json.Marshal(cfg.Modules)
if err != nil {
log.Error(err)
http.Error(w, "Failed to produce JSON", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(moduleJSON)
default:
log.Debugf("Listing modules in html")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl := template.Must(template.New("modules").Parse(`
<h2>Exporters:</h2>
<ul>
{{range $name, $cfg := .Modules}}
<li><a href="/proxy?module={{$name}}">{{$name}}</a></li>
{{end}}
</ul>`))
err := tmpl.Execute(w, cfg)
if err != nil {
log.Error(err)
http.Error(w, "Can't execute the template", http.StatusInternalServerError)
}
}
}
func (m moduleConfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
st := time.Now()
defer func() {
proxyDuration.WithLabelValues(m.name).Observe(float64(time.Since(st)) / float64(time.Second))
}()
nr := r
cancel := func() {}
if m.Timeout != 0 {
log.Debugf("setting module %v timeout to %v", m.name, m.Timeout)
var ctx context.Context
ctx, cancel = context.WithTimeout(r.Context(), m.Timeout)
nr = r.WithContext(ctx)
}
defer cancel()
switch m.Method {
case "exec":
m.Exec.mcfg = &m
m.Exec.ServeHTTP(w, nr)
case "http":
m.HTTP.mcfg = &m
m.HTTP.ServeHTTP(w, nr)
case "file":
m.File.mcfg = &m
m.File.ServeHTTP(w, nr)
default:
log.Errorf("unknown module method %v\n", m.Method)
proxyErrorCount.WithLabelValues(m.name).Inc()
http.Error(w, fmt.Sprintf("unknown module method %v\n", m.Method), http.StatusNotFound)
return
}
}
// StringSliceFlag collects multiple uses of a named flag into a slice.
type StringSliceFlag []string
func (s *StringSliceFlag) String() string {
// Just some representation output, not actually used to parse the input,
// the flag is instead supposed to be specified multiple times.
return strings.Join(*s, ", ")
}
// Set fullfills the flag.Value interface
func (s *StringSliceFlag) Set(value string) error {
*s = append(*s, value)
return nil
}
// IPNetSliceFlag parses IP network in CIDR notation into net.IPNet. Can be set
// multiple times
type IPNetSliceFlag []net.IPNet
func (nets IPNetSliceFlag) String() string {
netsStr := make([]string, len(nets))
for i := range nets {
netsStr[i] = fmt.Sprint(nets[i].String())
}
return strings.Join(netsStr, ", ")
}
// Set fullfills the flag.Value interface
func (nets *IPNetSliceFlag) Set(value string) error {
_, net, err := net.ParseCIDR(value)
if err != nil {
return err
}
*nets = append(*nets, *net)
return nil
}
// LogLevelFlag implements a flag.Value that sets the logging level
type LogLevelFlag log.Level
func (level LogLevelFlag) String() string {
return log.Level(level).String()
}
// Set fullfills the flag.Value interface
func (level *LogLevelFlag) Set(value string) error {
lvl, err := log.ParseLevel(value)
if err != nil {
return err
}
*level = LogLevelFlag(lvl)
return nil
}