forked from bolcom/mesos_exporter
/
main.go
351 lines (299 loc) · 8.08 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
package main
import (
"encoding/json"
"flag"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/antonlindstrom/mesos_stats"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/log"
)
const concurrentFetch = 100
// Commandline flags.
var (
addr = flag.String("web.listen-address", ":9105", "Address to listen on for web interface and telemetry")
autoDiscover = flag.Bool("exporter.discovery", false, "Discover all Mesos slaves")
localURL = flag.String("exporter.local-url", "http://127.0.0.1:5051", "URL to the local Mesos slave")
masterURL = flag.String("exporter.discovery.master-url", "http://mesos-master.example.com:5050", "Mesos master URL")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics")
scrapeInterval = flag.Duration("exporter.interval", (60 * time.Second), "Scrape interval duration")
)
var (
variableLabels = []string{"task", "slave", "framework_id"}
cpuLimitDesc = prometheus.NewDesc(
"mesos_task_cpu_limit",
"Fractional CPU limit.",
variableLabels, nil,
)
cpuSysDesc = prometheus.NewDesc(
"mesos_task_cpu_system_seconds_total",
"Cumulative system CPU time in seconds.",
variableLabels, nil,
)
cpuUsrDesc = prometheus.NewDesc(
"mesos_task_cpu_user_seconds_total",
"Cumulative user CPU time in seconds.",
variableLabels, nil,
)
memLimitDesc = prometheus.NewDesc(
"mesos_task_memory_limit_bytes",
"Task memory limit in bytes.",
variableLabels, nil,
)
memRssDesc = prometheus.NewDesc(
"mesos_task_memory_rss_bytes",
"Task memory RSS usage in bytes.",
variableLabels, nil,
)
)
var httpClient = http.Client{
Timeout: 5 * time.Second,
}
type exporterOpts struct {
autoDiscover bool
interval time.Duration
localURL string
masterURL string
}
type periodicExporter struct {
sync.RWMutex
errors *prometheus.CounterVec
metrics []prometheus.Metric
opts *exporterOpts
slaves struct {
sync.Mutex
urls []string
}
}
func newMesosExporter(opts *exporterOpts) *periodicExporter {
e := &periodicExporter{
errors: prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "mesos_exporter",
Name: "slave_scrape_errors_total",
Help: "Current total scrape errors",
},
[]string{"slave"},
),
opts: opts,
}
e.slaves.urls = []string{e.opts.localURL}
if e.opts.autoDiscover {
log.Info("auto discovery enabled from command line flag.")
// Update nr. of mesos slaves every 10 minutes
e.updateSlaves()
go runEvery(e.updateSlaves, 10*time.Minute)
}
// Fetch slave metrics every interval
go runEvery(e.scrapeSlaves, e.opts.interval)
return e
}
func (e *periodicExporter) Describe(ch chan<- *prometheus.Desc) {
e.rLockMetrics(func() {
for _, m := range e.metrics {
ch <- m.Desc()
}
})
e.errors.MetricVec.Describe(ch)
}
func (e *periodicExporter) Collect(ch chan<- prometheus.Metric) {
e.rLockMetrics(func() {
for _, m := range e.metrics {
ch <- m
}
})
e.errors.MetricVec.Collect(ch)
}
func (e *periodicExporter) fetch(urlChan <-chan string, metricsChan chan<- prometheus.Metric, wg *sync.WaitGroup) {
defer wg.Done()
for u := range urlChan {
u, err := url.Parse(u)
if err != nil {
log.Warn("could not parse slave URL: ", err)
continue
}
host, _, err := net.SplitHostPort(u.Host)
if err != nil {
log.Warn("could not parse network address: ", err)
continue
}
monitorURL := fmt.Sprintf("%s/monitor/statistics.json", u)
resp, err := httpClient.Get(monitorURL)
if err != nil {
log.Warn(err)
e.errors.WithLabelValues(host).Inc()
continue
}
defer resp.Body.Close()
var stats []mesos_stats.Monitor
if err = json.NewDecoder(resp.Body).Decode(&stats); err != nil {
log.Warn("failed to deserialize response: ", err)
e.errors.WithLabelValues(host).Inc()
continue
}
for _, stat := range stats {
metricsChan <- prometheus.MustNewConstMetric(
cpuLimitDesc,
prometheus.GaugeValue,
float64(stat.Statistics.CpusLimit),
stat.Source, host, stat.FrameworkId,
)
metricsChan <- prometheus.MustNewConstMetric(
cpuSysDesc,
prometheus.CounterValue,
float64(stat.Statistics.CpusSystemTimeSecs),
stat.Source, host, stat.FrameworkId,
)
metricsChan <- prometheus.MustNewConstMetric(
cpuUsrDesc,
prometheus.CounterValue,
float64(stat.Statistics.CpusUserTimeSecs),
stat.Source, host, stat.FrameworkId,
)
metricsChan <- prometheus.MustNewConstMetric(
memLimitDesc,
prometheus.GaugeValue,
float64(stat.Statistics.MemLimitBytes),
stat.Source, host, stat.FrameworkId,
)
metricsChan <- prometheus.MustNewConstMetric(
memRssDesc,
prometheus.GaugeValue,
float64(stat.Statistics.MemRssBytes),
stat.Source, host, stat.FrameworkId,
)
}
}
}
func (e *periodicExporter) rLockMetrics(f func()) {
e.RLock()
defer e.RUnlock()
f()
}
func (e *periodicExporter) setMetrics(ch chan prometheus.Metric) {
metrics := make([]prometheus.Metric, 0)
for metric := range ch {
metrics = append(metrics, metric)
}
e.Lock()
e.metrics = metrics
e.Unlock()
}
func (e *periodicExporter) scrapeSlaves() {
e.slaves.Lock()
urls := make([]string, len(e.slaves.urls))
copy(urls, e.slaves.urls)
e.slaves.Unlock()
urlCount := len(urls)
log.Debugf("active slaves: %d", urlCount)
urlChan := make(chan string)
metricsChan := make(chan prometheus.Metric)
go e.setMetrics(metricsChan)
poolSize := concurrentFetch
if urlCount < concurrentFetch {
poolSize = urlCount
}
log.Debugf("creating fetch pool of size %d", poolSize)
var wg sync.WaitGroup
wg.Add(poolSize)
for i := 0; i < poolSize; i++ {
go e.fetch(urlChan, metricsChan, &wg)
}
for _, url := range urls {
urlChan <- url
}
close(urlChan)
wg.Wait()
close(metricsChan)
}
func (e *periodicExporter) updateSlaves() {
log.Debug("discovering slaves...")
// This will redirect us to the elected mesos master
redirectURL := fmt.Sprintf("%s/master/redirect", e.opts.masterURL)
rReq, err := http.NewRequest("GET", redirectURL, nil)
if err != nil {
panic(err)
}
tr := http.Transport{
DisableKeepAlives: true,
}
rresp, err := tr.RoundTrip(rReq)
if err != nil {
log.Warn(err)
return
}
defer rresp.Body.Close()
// This will/should return http://master.ip:5050
masterLoc := rresp.Header.Get("Location")
if masterLoc == "" {
log.Warnf("%d response missing Location header", rresp.StatusCode)
return
}
log.Debugf("current elected master at: %s", masterLoc)
// Find all active slaves
stateURL := fmt.Sprintf("%s/master/state.json", masterLoc)
resp, err := http.Get(stateURL)
if err != nil {
log.Warn(err)
return
}
defer resp.Body.Close()
type slave struct {
Active bool `json:"active"`
Hostname string `json:"hostname"`
Pid string `json:"pid"`
}
var req struct {
Slaves []*slave `json:"slaves"`
}
if err := json.NewDecoder(resp.Body).Decode(&req); err != nil {
log.Warnf("failed to deserialize request: %s", err)
return
}
var slaveURLs []string
for _, slave := range req.Slaves {
if slave.Active {
// Extract slave port from pid
_, port, err := net.SplitHostPort(slave.Pid)
if err != nil {
port = "5051"
}
url := fmt.Sprintf("http://%s:%s", slave.Hostname, port)
slaveURLs = append(slaveURLs, url)
}
}
log.Debugf("%d slaves discovered", len(slaveURLs))
e.slaves.Lock()
e.slaves.urls = slaveURLs
e.slaves.Unlock()
}
func runEvery(f func(), interval time.Duration) {
for _ = range time.NewTicker(interval).C {
f()
}
}
func main() {
flag.Parse()
opts := &exporterOpts{
autoDiscover: *autoDiscover,
interval: *scrapeInterval,
localURL: strings.TrimRight(*localURL, "/"),
masterURL: strings.TrimRight(*masterURL, "/"),
}
exporter := newMesosExporter(opts)
prometheus.MustRegister(exporter)
http.Handle(*metricsPath, prometheus.Handler())
http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "OK")
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, *metricsPath, http.StatusMovedPermanently)
})
log.Info("starting mesos_exporter on ", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}