forked from robinmarechal/asterisk_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
228 lines (195 loc) · 8.73 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
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
"github.com/prometheus/common/version"
"github.com/prometheus/exporter-toolkit/web"
kingpin "gopkg.in/alecthomas/kingpin.v2"
"github.com/robinmarechal/asterisk_exporter/cmd"
"github.com/robinmarechal/asterisk_exporter/collector"
)
var (
listenAddress = kingpin.Flag("web.listen-address", "The address to listen on for HTTP requests.").Default(":9815").String()
asteriskPath = kingpin.Flag("asterisk.path", "Path to Asterisk binary").Default("/usr/sbin/asterisk").String()
prefix = kingpin.Flag("metrics.prefix", "Prefix of exposed metrics").Default("asterisk").String()
metricsPath = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String()
enableExporterMetrics = kingpin.Flag("web.enable-exporter-metrics", "Include metrics about the exporter itself (process_*, go_*).").Default("false").Bool()
enablePromHttpMetrics = kingpin.Flag("web.enable-promhttp-metrics", "Include metrics about the http server itself (promhttp_*)").Default("true").Bool()
maxRequests = kingpin.Flag("web.max-requests", "Maximum number of parallel scrape requests. Use 0 to disable.").Default("40").Int()
enableAgentsCollector = kingpin.Flag("collector.agents", "Enable agents collector").Default("false").Bool()
enableCoreCollector = kingpin.Flag("collector.core", "Enable core collector").Default("true").Bool()
enableSipCollector = kingpin.Flag("collector.sip", "Enable sip collector").Default("true").Bool()
enableBridgeCollector = kingpin.Flag("collector.bridges", "Enable bridge collector").Default("false").Bool()
enableCalendarCollector = kingpin.Flag("collector.calendars", "Enable calendar collector").Default("false").Bool()
enableConfbridgeCollector = kingpin.Flag("collector.confbridges", "Enable confbridge collector").Default("false").Bool()
enableIax2Collector = kingpin.Flag("collector.iax2", "Enable iax2 collector").Default("false").Bool()
enableModuleCollector = kingpin.Flag("collector.modules", "Enable module collector").Default("true").Bool()
)
func main() {
os.Exit(run())
}
func run() int {
promlogConfig := &promlog.Config{}
flag.AddFlags(kingpin.CommandLine, promlogConfig)
kingpin.Version(version.Print("asterisk_exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
logger := promlog.New(promlogConfig)
level.Info(logger).Log("msg", "starting asterisk_exporter", "version", version.Info())
level.Info(logger).Log("build_context", version.BuildContext())
http.Handle(*metricsPath, newHandler(*enableExporterMetrics, *enablePromHttpMetrics, *maxRequests, logger))
handleHealth(logger)
handleRoot(logger)
return startServer(logger)
}
func startServer(logger log.Logger) int {
srv := &http.Server{Addr: *listenAddress}
srvc := make(chan struct{})
term := make(chan os.Signal, 1)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
go func() {
level.Info(logger).Log("msg", "Listening on address", "address", *listenAddress)
if err := web.ListenAndServe(srv, "", logger); err != http.ErrServerClosed {
level.Error(logger).Log("msg", "Error starting HTTP server", "err", err)
close(srvc)
}
}()
for {
select {
case <-term:
level.Info(logger).Log("msg", "Received SIGTERM, exiting gracefully...")
return 0
case <-srvc:
return 1
}
}
}
func handleHealth(logger log.Logger) {
http.HandleFunc("/-/healthy", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Healthy"))
})
}
func handleRoot(logger log.Logger) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<html>
<head><title>Asterisk Exporter</title></head>
<body>
<h1>Asterisk Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
}
// handler wraps an unfiltered http.Handler but uses a filtered handler,
// created on the fly, if filtering is requested. Create instances with
// newHandler.
type handler struct {
unfilteredHandler http.Handler
// exporterMetricsRegistry is a separate registry for the metrics about
// the exporter itself.
exporterMetricsRegistry *prometheus.Registry
includeExporterMetrics bool
includePromHttpMetrics bool
maxRequests int
logger log.Logger
}
func newHandler(includeExporterMetrics bool, enablePromHttpMetrics bool, maxRequests int, logger log.Logger) *handler {
h := &handler{
exporterMetricsRegistry: prometheus.NewRegistry(),
includeExporterMetrics: includeExporterMetrics,
includePromHttpMetrics: enablePromHttpMetrics,
maxRequests: maxRequests,
logger: logger,
}
if h.includeExporterMetrics {
h.exporterMetricsRegistry.MustRegister(
prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),
prometheus.NewGoCollector(),
)
}
if innerHandler, err := h.innerHandler(logger); err != nil {
panic(fmt.Sprintf("Couldn't create metrics handler: %s", err))
} else {
h.unfilteredHandler = innerHandler
}
return h
}
// ServeHTTP implements http.Handler.
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// No filters, use the prepared unfiltered handler.
h.unfilteredHandler.ServeHTTP(w, r)
}
// innerHandler is used to create both the one unfiltered http.Handler to be
// wrapped by the outer handler and also the filtered handlers created on the
// fly. The former is accomplished by calling innerHandler without any arguments
// (in which case it will log all the collectors enabled via command-line
// flags).
func (h *handler) innerHandler(logger log.Logger) (http.Handler, error) {
r := prometheus.NewRegistry()
r.MustRegister(version.NewCollector("asterisk_exporter"))
collectorError := prometheus.NewDesc(
prometheus.BuildFQName(*prefix, "exporter", "collector_error"),
"Collector errors. 0 = no error, 1 = error occurred",
[]string{"collector"}, nil,
)
cmdRunner := cmd.NewCmdRunner(*asteriskPath, logger)
registerAllCollectors(r, cmdRunner, logger, collectorError)
level.Info(logger).Log("msg", "all collectors registered")
handler := promhttp.HandlerFor(
prometheus.Gatherers{h.exporterMetricsRegistry, r},
promhttp.HandlerOpts{
ErrorHandling: promhttp.ContinueOnError,
MaxRequestsInFlight: h.maxRequests,
Registry: h.exporterMetricsRegistry,
},
)
if h.includePromHttpMetrics {
// Note that we have to use h.exporterMetricsRegistry here to
// use the same promhttp metrics for all expositions.
handler = promhttp.InstrumentMetricHandler(
h.exporterMetricsRegistry, handler,
)
}
return handler, nil
}
func registerCollector(registry *prometheus.Registry, c collector.Collector, logger log.Logger) {
if err := registry.Register(c); err != nil {
level.Error(logger).Log("cmd", "failed to register collector", "collector", c.Name(), "err", err)
} else {
level.Info(logger).Log("msg", "collector registered", "collector", c.Name())
}
}
func registerAllCollectors(registry *prometheus.Registry, cmdRunner *cmd.CmdRunner, logger log.Logger, collectorError *prometheus.Desc) {
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableAgentsCollector, collector.NewAgentCollector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableCoreCollector, collector.NewCoreCollector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableBridgeCollector, collector.NewBridgeCollector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableCalendarCollector, collector.NewCalendarCollector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableConfbridgeCollector, collector.NewConfbridgeCollector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableIax2Collector, collector.NewdIax2Collector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableModuleCollector, collector.NewModuleCollector)
genericRegisterCollector(registry, *prefix, cmdRunner, logger, collectorError, *enableSipCollector, collector.NewSipCollector)
}
func genericRegisterCollector(
registry *prometheus.Registry,
prefix string,
cmdRunner *cmd.CmdRunner,
logger log.Logger,
collectorError *prometheus.Desc,
enabled bool,
factory collector.CollectorFactory) {
if enabled {
collector := factory(prefix, cmdRunner, logger, collectorError)
registerCollector(registry, collector, logger)
}
}