-
Notifications
You must be signed in to change notification settings - Fork 22
/
firehose_exporter.go
284 lines (235 loc) · 10.5 KB
/
firehose_exporter.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
package main
import (
"expvar"
"net/http"
"net/http/pprof"
"strings"
"time"
"code.cloudfoundry.org/go-loggregator/v8"
"github.com/alecthomas/kingpin/v2"
"github.com/cloudfoundry/firehose_exporter/collectors"
"github.com/cloudfoundry/firehose_exporter/metricmaker"
"github.com/cloudfoundry/firehose_exporter/metrics"
"github.com/cloudfoundry/firehose_exporter/nozzle"
"github.com/prometheus/common/version"
log "github.com/sirupsen/logrus"
)
var (
retroCompatDisable = kingpin.Flag("retro_compat.disable", "Disable retro compatibility").Envar("FIREHOSE_EXPORTER_RETRO_COMPAT_DISABLE").Default("false").Bool()
enableRetroCompatDelta = kingpin.Flag("retro_compat.enable_delta", "Enable retro compatibility delta in counter").Envar("FIREHOSE_EXPORTER_RETRO_COMPAT_ENABLE_DELTA").Default("false").Bool()
loggingURL = kingpin.Flag(
"logging.url", "Cloud Foundry Logging endpoint ($FIREHOSE_EXPORTER_LOGGING_URL)",
).Envar("FIREHOSE_EXPORTER_LOGGING_URL").Required().String()
loggingTLSCa = kingpin.Flag(
"logging.tls.ca", "Path to ca cert to connect to rlp",
).Envar("FIREHOSE_EXPORTER_LOGGING_TLS_CA").Default("").String()
loggingTLSCert = kingpin.Flag(
"logging.tls.cert", "Path to cert to connect to rlp in mtls",
).Envar("FIREHOSE_EXPORTER_LOGGING_TLS_CERT").Default("").String()
loggingTLSKey = kingpin.Flag(
"logging.tls.key", "Path to key to connect to rlp in mtls",
).Envar("FIREHOSE_EXPORTER_LOGGING_TLS_KEY").Default("").String()
metricsNamespace = kingpin.Flag(
"metrics.namespace", "Metrics Namespace ($FIREHOSE_EXPORTER_METRICS_NAMESPACE)",
).Envar("FIREHOSE_EXPORTER_METRICS_NAMESPACE").Default("firehose").String()
metricsBatchSize = kingpin.Flag(
"metrics.batch_size", "Batch size for nozzle envelop buffer ($FIREHOSE_EXPORTER_METRICS_NAMESPACE)",
).Envar("FIREHOSE_EXPORTER_METRICS_BATCH_SIZE").Default("-1").Int()
metricsShardID = kingpin.Flag(
"metrics.shard_id", "The sharding group name to use for egress from RLP ($FIREHOSE_EXPORTER_SHARD_ID)",
).Envar("FIREHOSE_EXPORTER_SHARD_ID").Default("firehose_exporter").String()
metricsNodeIndex = kingpin.Flag(
"metrics.node_index", "Node index to use ($FIREHOSE_EXPORTER_NODE_INDEX)",
).Envar("FIREHOSE_EXPORTER_NODE_INDEX").Default("0").Int()
metricsTimerRollup = kingpin.Flag(
"metrics.timer_rollup_buffer_size", "The number of envelopes that will be allowed to be buffered while timer metric aggregations are running ($FIREHOSE_EXPORTER_TIMER_ROLLUP_BUFFER_SIZE)",
).Envar("FIREHOSE_EXPORTER_TIMER_ROLLUP_BUFFER_SIZE").Default("16384").Uint()
metricsEnvironment = kingpin.Flag(
"metrics.environment", "Environment label to be attached to metrics ($FIREHOSE_EXPORTER_METRICS_ENVIRONMENT)",
).Envar("FIREHOSE_EXPORTER_METRICS_ENVIRONMENT").Required().String()
metricExpiration = kingpin.Flag(
"metrics.expiration", "How long a Cloud Foundry metric is valid ($FIREHOSE_EXPORTER_METRICS_EXPIRATION)",
).Envar("FIREHOSE_EXPORTER_METRICS_EXPIRATION").Default("10m").Duration()
skipSSLValidation = kingpin.Flag(
"skip-ssl-verify", "Disable SSL Verify ($FIREHOSE_EXPORTER_SKIP_SSL_VERIFY)",
).Envar("FIREHOSE_EXPORTER_SKIP_SSL_VERIFY").Default("false").Bool()
filterDeployments = kingpin.Flag(
"filter.deployments", "Comma separated deployments to filter ($FIREHOSE_EXPORTER_FILTER_DEPLOYMENTS)",
).Envar("FIREHOSE_EXPORTER_FILTER_DEPLOYMENTS").Default("").String()
filterEvents = kingpin.Flag(
"filter.events", "Comma separated events to filter (ContainerMetric,CounterEvent,ValueMetric,Http) ($FIREHOSE_EXPORTER_FILTER_EVENTS)",
).Envar("FIREHOSE_EXPORTER_FILTER_EVENTS").Default("").String()
listenAddress = kingpin.Flag(
"web.listen-address", "Address to listen on for web interface and telemetry ($FIREHOSE_EXPORTER_WEB_LISTEN_ADDRESS)",
).Envar("FIREHOSE_EXPORTER_WEB_LISTEN_ADDRESS").Default(":9186").String()
metricsPath = kingpin.Flag(
"web.telemetry-path", "Path under which to expose Prometheus metrics ($FIREHOSE_EXPORTER_WEB_TELEMETRY_PATH)",
).Envar("FIREHOSE_EXPORTER_WEB_TELEMETRY_PATH").Default("/metrics").String()
authUsername = kingpin.Flag(
"web.auth.username", "Username for web interface basic auth ($FIREHOSE_EXPORTER_WEB_AUTH_USERNAME)",
).Envar("FIREHOSE_EXPORTER_WEB_AUTH_USERNAME").String()
authPassword = kingpin.Flag(
"web.auth.password", "Password for web interface basic auth ($FIREHOSE_EXPORTER_WEB_AUTH_PASSWORD)",
).Envar("FIREHOSE_EXPORTER_WEB_AUTH_PASSWORD").String()
tlsCertFile = kingpin.Flag(
"web.tls.cert_file", "Path to a file that contains the TLS certificate (PEM format). If the certificate is signed by a certificate authority, the file should be the concatenation of the server's certificate, any intermediates, and the CA's certificate ($FIREHOSE_EXPORTER_WEB_TLS_CERTFILE)",
).Envar("FIREHOSE_EXPORTER_WEB_TLS_CERTFILE").ExistingFile()
tlsKeyFile = kingpin.Flag(
"web.tls.key_file", "Path to a file that contains the TLS private key (PEM format) ($FIREHOSE_EXPORTER_WEB_TLS_KEYFILE)",
).Envar("FIREHOSE_EXPORTER_WEB_TLS_KEYFILE").ExistingFile()
enableProfiler = kingpin.Flag("profiler.enable", "Enable pprof profiling on app on /debug/pprof").Envar("FIREHOSE_EXPORTER_ENABLE_PROFILER").Default("false").Bool()
logLevel = kingpin.Flag("log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal]").Envar("FIREHOSE_EXPORTER_LOG_LEVEL").Default("info").String()
logInJSON = kingpin.Flag("log.in_json", "Log in json").Envar("FIREHOSE_EXPORTER_LOG_IN_JSON").Default("false").Bool()
)
type basicAuthHandler struct {
handler http.HandlerFunc
username string
password string
}
func (h *basicAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || username != h.username || password != h.password {
log.Errorf("Invalid HTTP auth from `%s`", r.RemoteAddr)
w.Header().Set("WWW-Authenticate", "Basic realm=\"metrics\"")
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}
h.handler(w, r)
}
func initLog() {
logLvl, err := log.ParseLevel(*logLevel)
if err != nil {
log.Panic(err.Error())
}
log.SetLevel(logLvl)
if *logInJSON {
log.SetFormatter(&log.JSONFormatter{})
}
}
func initMetricMaker() {
metricmaker.SetEnableEnvelopCounterDelta(*enableRetroCompatDelta)
metricmaker.PrependMetricConverter(metricmaker.AddNamespace(*metricsNamespace))
metricmaker.PrependMetricConverter(metricmaker.InjectMapLabel(map[string]string{
"environment": *metricsEnvironment,
}))
if !*retroCompatDisable {
metricmaker.PrependMetricConverter(metricmaker.RetroCompatMetricNames)
} else {
metricmaker.PrependMetricConverter(metricmaker.SuffixCounterWithTotal)
}
}
func MakeStreamer() (*loggregator.EnvelopeStreamConnector, error) {
loggregatorTLSConfig, err := loggregator.NewEgressTLSConfig(*loggingTLSCa, *loggingTLSCert, *loggingTLSKey)
if err != nil {
return nil, err
}
loggregatorTLSConfig.InsecureSkipVerify = *skipSSLValidation
return loggregator.NewEnvelopeStreamConnector(
*loggingURL,
loggregatorTLSConfig,
loggregator.WithEnvelopeStreamLogger(log.StandardLogger()),
loggregator.WithEnvelopeStreamBuffer(10000, func(missed int) {
log.Infof("dropped %d envelope batches", missed)
}),
), nil
}
func main() {
kingpin.Version(version.Print("firehose_exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
initLog()
initMetricMaker()
log.Info("Starting firehose_exporter", version.Info())
log.Info("Build context", version.BuildContext())
var pointBuffer chan []*metrics.RawMetric
if *metricsBatchSize <= 0 {
pointBuffer = make(chan []*metrics.RawMetric)
} else {
pointBuffer = make(chan []*metrics.RawMetric, *metricsBatchSize)
}
streamer, err := MakeStreamer()
if err != nil {
log.Panicf("Could not create streamer: %s", err.Error())
}
var events []string
if *filterEvents != "" {
events = strings.Split(*filterEvents, ",")
}
var deployments []string
if *filterDeployments != "" {
deployments = strings.Split(*filterDeployments, ",")
}
im := metrics.NewInternalMetrics(*metricsNamespace, *metricsEnvironment)
nozz := nozzle.NewNozzle(
streamer,
*metricsShardID,
*metricsNodeIndex,
pointBuffer,
im,
nozzle.WithNozzleTimerRollup(
10*time.Second,
[]string{
"status_code", "app_name", "app_id", "space_name",
"space_id", "organization_name", "organization_id",
"process_id", "process_instance_id", "process_type",
"instance_id", "method", "scheme", "host",
},
[]string{
"app_name", "app_id", "space_name", "space_id",
"organization_name", "organization_id", "process_id",
"process_instance_id", "process_type", "instance_id",
"method", "scheme", "host",
},
),
nozzle.WithNozzleTimerRollupBufferSize(*metricsTimerRollup),
nozzle.WithFilterSelector(nozzle.NewFilterSelector(events...)),
nozzle.WithFilterDeployment(nozzle.NewFilterDeployment(deployments...)),
)
collector := collectors.NewRawMetricsCollector(pointBuffer, *metricExpiration)
nozz.Start()
collector.Start()
router := http.NewServeMux()
router.Handle(*metricsPath, prometheusHandler(collector))
if *enableProfiler {
router.HandleFunc("/debug/pprof/", pprof.Index)
router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
router.HandleFunc("/debug/pprof/profile", pprof.Profile)
router.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
router.HandleFunc("/debug/pprof/trace", pprof.Trace)
router.Handle("/debug/vars", expvar.Handler())
}
router.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`<html>
<head><title>Cloud Foundry Firehose Exporter</title></head>
<body>
<h1>Cloud Foundry Firehose Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
server := &http.Server{
Addr: *listenAddress,
ReadTimeout: time.Second * 5,
ReadHeaderTimeout: time.Second * 10,
Handler: router,
}
if *tlsCertFile != "" && *tlsKeyFile != "" {
log.Infoln("Listening TLS on", *listenAddress)
err = server.ListenAndServeTLS(*tlsCertFile, *tlsKeyFile)
} else {
log.Infoln("Listening on", *listenAddress)
err = server.ListenAndServe()
}
log.Fatal(err)
}
func prometheusHandler(collector *collectors.RawMetricsCollector) http.Handler {
var handler http.Handler = http.HandlerFunc(collector.RenderExpFmt)
if *authUsername != "" && *authPassword != "" {
handler = &basicAuthHandler{
handler: handler.ServeHTTP,
username: *authUsername,
password: *authPassword,
}
}
return handler
}