-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcollector.go
610 lines (510 loc) · 13.5 KB
/
collector.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package main
import (
"errors"
"fmt"
"log"
"net"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
binrpc "github.com/florentchauveau/go-kamailio-binrpc/v3"
"github.com/prometheus/client_golang/prometheus"
)
/* Sample output
kamcmd> tm.stats
{
current: 1
waiting: 0
total: 9514528
total_local: 2794613
rpl_received: 19902190
rpl_generated: 4965793
rpl_sent: 19908572
6xx: 7782
5xx: 2286589
4xx: 961055
3xx: 0
2xx: 6267549
created: 9514528
freed: 9514527
delayed_free: 0
}
kamcmd> sl.stats
{
200: 666263
202: 0
2xx: 0
300: 0
301: 0
302: 0
400: 5883
401: 0
403: 0
404: 0
407: 0
408: 0
483: 0
4xx: 5621
500: 0
5xx: 0
6xx: 0
xxx: 0
}
kamcmd> core.shmmem
{
total: 67108864
free: 61189608
used: 2590984
real_used: 5919256
max_used: 13323296
fragments: 44546
}
kamcmd> core.tcp_info
{
readers: 8
max_connections: 4096
max_tls_connections: 2048
opened_connections: 595
opened_tls_connections: 401
write_queued_bytes: 0
}
kamcmd dlg.stats_active
{
starting: 152
connecting: 674
answering: 0
ongoing: 512
all: 1338
}
*/
// Collector implements prometheus.Collector (see below).
// it also contains the config of the exporter.
type Collector struct {
URI string
Timeout time.Duration
Methods []string
url *url.URL
mutex sync.Mutex
conn net.Conn
up prometheus.Gauge
failedScrapes prometheus.Counter
totalScrapes prometheus.Counter
}
// Metric is the definition of a metric.
type Metric struct {
Kind prometheus.ValueType
Name string
Help string
Method string // kamailio method associated with the metric
}
// MetricValue is the value of a metric, with its labels.
type MetricValue struct {
Value float64
Labels map[string]string
}
// DispatcherTarget is a target of the dispatcher module.
type DispatcherTarget struct {
URI string
Flags string
SetID int
}
const (
namespace = "kamailio"
)
var (
// this is used to match codes returned by Kamailio
// examples: "200" or "6xx" or even "xxx"
codeRegex = regexp.MustCompile("^[0-9x]{3}$")
// implemented RPC methods
availableMethods = []string{
"tm.stats",
"sl.stats",
"core.shmmem",
"core.uptime",
"core.tcp_info",
"dispatcher.list",
"tls.info",
"dlg.stats_active",
}
metricsList = map[string][]Metric{
"tm.stats": {
NewMetricGauge("current", "Current transactions.", "tm.stats"),
NewMetricGauge("waiting", "Waiting transactions.", "tm.stats"),
NewMetricCounter("total", "Total transactions.", "tm.stats"),
NewMetricCounter("total_local", "Total local transactions.", "tm.stats"),
NewMetricCounter("rpl_received", "Number of reply received.", "tm.stats"),
NewMetricCounter("rpl_generated", "Number of reply generated.", "tm.stats"),
NewMetricCounter("rpl_sent", "Number of reply sent.", "tm.stats"),
NewMetricCounter("created", "Created transactions.", "tm.stats"),
NewMetricCounter("freed", "Freed transactions.", "tm.stats"),
NewMetricCounter("delayed_free", "Delayed free transactions.", "tm.stats"),
NewMetricCounter("codes", "Per-code counters.", "tm.stats"),
},
"sl.stats": {
NewMetricCounter("codes", "Per-code counters.", "sl.stats"),
},
"core.shmmem": {
NewMetricGauge("total", "Total shared memory.", "core.shmmem"),
NewMetricGauge("free", "Free shared memory.", "core.shmmem"),
NewMetricGauge("used", "Used shared memory.", "core.shmmem"),
NewMetricGauge("real_used", "Real used shared memory.", "core.shmmem"),
NewMetricGauge("max_used", "Max used shared memory.", "core.shmmem"),
NewMetricGauge("fragments", "Number of fragments in shared memory.", "core.shmmem"),
},
"core.uptime": {
NewMetricCounter("uptime", "Uptime in seconds.", "core.uptime"),
},
"core.tcp_info": {
NewMetricGauge("readers", "Total TCP readers.", "core.tcp_info"),
NewMetricGauge("max_connections", "Maximum TCP connections", "core.tcp_info"),
NewMetricGauge("max_tls_connections", "Maximum TLS connections.", "core.tcp_info"),
NewMetricGauge("opened_connections", "Opened TCP connections.", "core.tcp_info"),
NewMetricGauge("opened_tls_connections", "Opened TLS connections.", "core.tcp_info"),
NewMetricGauge("write_queued_bytes", "Write queued bytes.", "core.tcp_info"),
},
"dispatcher.list": {
NewMetricGauge("target", "Target status.", "dispatcher.list"),
},
"tls.info": {
NewMetricGauge("opened_connections", "TLS Opened Connections.", "tls.info"),
NewMetricGauge("max_connections", "TLS Max Connections.", "tls.info"),
},
"dlg.stats_active": {
NewMetricGauge("starting", "Dialogs starting.", "dlg.stats_active"),
NewMetricGauge("connecting", "Dialogs connecting.", "dlg.stats_active"),
NewMetricGauge("answering", "Dialogs answering.", "dlg.stats_active"),
NewMetricGauge("ongoing", "Dialogs ongoing.", "dlg.stats_active"),
NewMetricGauge("all", "Dialogs all.", "dlg.stats_active"),
},
}
)
// NewMetricGauge is a helper function to create a gauge.
func NewMetricGauge(name string, help string, method string, labels ...string) Metric {
return Metric{
prometheus.GaugeValue,
name,
help,
method,
}
}
// NewMetricCounter is a helper function to create a counter.
func NewMetricCounter(name string, help string, method string, labels ...string) Metric {
return Metric{
prometheus.CounterValue,
name,
help,
method,
}
}
// NewCollector processes uri, timeout and methods and returns a new Collector.
func NewCollector(uri string, timeout time.Duration, methods string) (*Collector, error) {
c := Collector{}
c.URI = uri
c.Timeout = timeout
var url *url.URL
var err error
if url, err = url.Parse(c.URI); err != nil {
return nil, fmt.Errorf("cannot parse URI: %w", err)
}
c.url = url
c.Methods = strings.Split(methods, ",")
for _, method := range c.Methods {
found := false
for _, m := range availableMethods {
if m == method {
found = true
break
}
}
if !found {
return nil, fmt.Errorf(
`invalid method "%s". available methods are: %s.`,
method,
strings.Join(availableMethods, ","),
)
}
}
c.up = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "up",
Help: "Was the last scrape successful.",
})
c.totalScrapes = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_total_scrapes",
Help: "Number of total kamailio scrapes",
})
c.failedScrapes = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_failed_scrapes",
Help: "Number of failed kamailio scrapes",
})
return &c, nil
}
// ExportedName returns a formatted Prometheus metric name, in the form:
// "namespace_method_metric" for gauge
// "namespace_method_metric_total" for counters
// "meth.od" is transformed into "meth_od"
//
// examples: "kamailio_tm_stats_current"
// "kamailio_tm_stats_created_total"
// "kamailio_sl_stats_200_total"
func (m *Metric) ExportedName() string {
suffix := m.Name
if m.Kind == prometheus.CounterValue {
suffix = m.Name + "_total"
}
return fmt.Sprintf("%s_%s_%s",
namespace,
strings.Replace(m.Method, ".", "_", -1),
suffix,
)
}
// LabelKeys returns the keys of the labels of m
func (m *MetricValue) LabelKeys() []string {
if len(m.Labels) == 0 {
return nil
}
var list []string
for key := range m.Labels {
list = append(list, key)
}
// we need to keep the keys and values in a consistent order
// (a go map does have an order)
sort.Strings(list)
return list
}
// LabelValues returns the values of the labels of m
func (m *MetricValue) LabelValues() []string {
if len(m.Labels) == 0 {
return nil
}
var list []string
for _, key := range m.LabelKeys() {
list = append(list, m.Labels[key])
}
return list
}
// scrape will connect to the kamailio instance if needed, and push metrics to the Prometheus channel.
func (c *Collector) scrape(ch chan<- prometheus.Metric) error {
c.totalScrapes.Inc()
var err error
address := c.url.Host
if c.url.Scheme == "unix" {
address = c.url.Path
}
c.conn, err = net.DialTimeout(c.url.Scheme, address, c.Timeout)
if err != nil {
return err
}
c.conn.SetDeadline(time.Now().Add(c.Timeout))
defer c.conn.Close()
for _, method := range c.Methods {
if _, found := metricsList[method]; !found {
panic("invalid method requested")
}
metricsScraped, err := c.scrapeMethod(method)
if err != nil {
return err
}
for _, metricDef := range metricsList[method] {
metricValues, found := metricsScraped[metricDef.Name]
if !found {
continue
}
for _, metricValue := range metricValues {
metric, err := prometheus.NewConstMetric(
prometheus.NewDesc(metricDef.ExportedName(), metricDef.Help, metricValue.LabelKeys(), nil),
metricDef.Kind,
metricValue.Value,
metricValue.LabelValues()...,
)
if err != nil {
return err
}
ch <- metric
}
}
}
return nil
}
// scrapeMethod will return metrics for one method.
func (c *Collector) scrapeMethod(method string) (map[string][]MetricValue, error) {
records, err := c.fetchBINRPC(method)
if err != nil {
return nil, err
}
// we expect just 1 record of type map
if len(records) == 2 && records[0].Type == binrpc.TypeInt && records[0].Value.(int) == 500 {
return nil, fmt.Errorf(`invalid response for method "%s": [500] %s`, method, records[1].Value.(string))
} else if len(records) != 1 {
return nil, fmt.Errorf(`invalid response for method "%s", expected %d record, got %d`,
method, 1, len(records),
)
}
// all methods implemented in this exporter return a struct
items, err := records[0].StructItems()
if err != nil {
return nil, err
}
metrics := make(map[string][]MetricValue)
switch method {
case "sl.stats":
fallthrough
case "tm.stats":
for _, item := range items {
i, _ := item.Value.Int()
if codeRegex.MatchString(item.Key) {
// this item is a "code" statistic, eg "200" or "6xx"
metrics["codes"] = append(metrics["codes"],
MetricValue{
Value: float64(i),
Labels: map[string]string{
"code": item.Key,
},
},
)
} else {
metrics[item.Key] = []MetricValue{{Value: float64(i)}}
}
}
case "tls.info":
fallthrough
case "core.shmmem":
fallthrough
case "core.tcp_info":
fallthrough
case "dlg.stats_active":
fallthrough
case "core.uptime":
for _, item := range items {
i, _ := item.Value.Int()
metrics[item.Key] = []MetricValue{{Value: float64(i)}}
}
case "dispatcher.list":
targets, err := parseDispatcherTargets(items)
if err != nil {
return nil, err
}
if len(targets) == 0 {
break
}
for _, target := range targets {
mv := MetricValue{
Value: 1,
Labels: map[string]string{
"uri": target.URI,
"flags": target.Flags,
"setid": strconv.Itoa(target.SetID),
},
}
metrics["target"] = append(metrics["target"], mv)
}
}
return metrics, nil
}
// parseDispatcherTargets parses the "dispatcher.list" result and returns a list of targets.
func parseDispatcherTargets(items []binrpc.StructItem) ([]DispatcherTarget, error) {
var result []DispatcherTarget
for _, item := range items {
if item.Key != "RECORDS" {
continue
}
sets, err := item.Value.StructItems()
if err != nil {
return nil, err
}
for _, item = range sets {
if item.Key != "SET" {
continue
}
setItems, err := item.Value.StructItems()
if err != nil {
return nil, err
}
var setID int
var targets []DispatcherTarget
for _, set := range setItems {
if set.Key == "ID" {
if setID, err = set.Value.Int(); err != nil {
return nil, err
}
} else if set.Key == "TARGETS" {
destinations, err := set.Value.StructItems()
if err != nil {
return nil, err
}
for _, destination := range destinations {
if destination.Key != "DEST" {
continue
}
props, err := destination.Value.StructItems()
if err != nil {
return nil, err
}
target := DispatcherTarget{}
for _, prop := range props {
switch prop.Key {
case "URI":
target.URI, _ = prop.Value.String()
case "FLAGS":
target.Flags, _ = prop.Value.String()
}
}
targets = append(targets, target)
}
}
}
if setID == 0 {
return nil, errors.New("missing set ID while parsing dispatcher.list")
}
if len(targets) == 0 {
continue
}
for _, target := range targets {
target.SetID = setID
result = append(result, target)
}
}
}
return result, nil
}
// fetchBINRPC talks to kamailio using the BINRPC protocol.
func (c *Collector) fetchBINRPC(method string) ([]binrpc.Record, error) {
// WritePacket returns the cookie generated
cookie, err := binrpc.WritePacket(c.conn, method)
if err != nil {
return nil, err
}
// the cookie is passed again for verification
// we receive records in response
records, err := binrpc.ReadPacket(c.conn, cookie)
if err != nil {
return nil, err
}
return records, nil
}
// Describe implements prometheus.Collector.
func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(c, ch)
}
// Collect implements prometheus.Collector.
func (c *Collector) Collect(ch chan<- prometheus.Metric) {
c.mutex.Lock()
defer c.mutex.Unlock()
err := c.scrape(ch)
if err != nil {
c.failedScrapes.Inc()
c.up.Set(0)
log.Println("[error]", err)
} else {
c.up.Set(1)
}
ch <- c.up
ch <- c.totalScrapes
ch <- c.failedScrapes
}