-
Notifications
You must be signed in to change notification settings - Fork 458
/
prometheus.go
102 lines (83 loc) · 2 KB
/
prometheus.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
package telemetry
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
prommetrics "github.com/hashicorp/go-metrics/prometheus"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
type prometheusRunner struct {
c *PrometheusConfig
log logrus.FieldLogger
server *http.Server
sink Sink
}
func newPrometheusRunner(c *MetricsConfig) (sinkRunner, error) {
runner := &prometheusRunner{
c: c.FileConfig.Prometheus,
log: c.Logger,
}
if runner.c == nil {
return runner, nil
}
var err error
runner.sink, err = prommetrics.NewPrometheusSinkFrom(prommetrics.PrometheusOpts{})
if err != nil {
return runner, err
}
handlerOpts := promhttp.HandlerOpts{
ErrorLog: runner.log,
}
handler := promhttp.HandlerFor(prometheus.DefaultGatherer, handlerOpts)
if runner.c.Host == "" {
runner.c.Host = "localhost"
}
if runner.c.Host != "localhost" {
runner.log.Warnf("Agent is now configured to accept remote network connections for Prometheus stats collection. Please ensure access to this port is tightly controlled")
}
runner.server = &http.Server{
Addr: fmt.Sprintf("%s:%d", runner.c.Host, runner.c.Port),
Handler: handler,
ReadHeaderTimeout: time.Second * 10,
}
return runner, nil
}
func (p *prometheusRunner) isConfigured() bool {
return p.c != nil
}
func (p *prometheusRunner) sinks() []Sink {
if !p.isConfigured() {
return []Sink{}
}
return []Sink{p.sink}
}
func (p *prometheusRunner) run(ctx context.Context) error {
if !p.isConfigured() {
return nil
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
err := p.server.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
p.log.Warnf("Prometheus listener stopped unexpectedly: %v", err)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
p.server.Close()
}()
wg.Wait()
return ctx.Err()
}
func (p *prometheusRunner) requiresTypePrefix() bool {
return false
}