/
collector.go
977 lines (803 loc) · 24.9 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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
package main
import (
"bufio"
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"net"
"net/textproto"
"net/url"
"regexp"
"strconv"
"sync"
"time"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/promlog"
"golang.org/x/net/html/charset"
)
// Collector implements prometheus.Collector (see below).
// it also contains the config of the exporter.
type Collector struct {
URI string
Timeout time.Duration
Password string
rtpEnable bool
conn net.Conn
input *bufio.Reader
url *url.URL
mutex sync.Mutex
up prometheus.Gauge
failedScrapes prometheus.Counter
totalScrapes prometheus.Counter
}
// Metric represents a prometheus metric. It is either fetched from an api command,
// or from "status" parsing (thus the RegexIndex)
type Metric struct {
Name string
Help string
Type prometheus.ValueType
Command string
RegexIndex int
}
const (
namespace = "freeswitch"
)
type Gateways struct {
XMLName xml.Name `xml:"gateways"`
Gateway []Gateway `xml:"gateway"`
}
type Gateway struct {
Name string `xml:"name"`
Profile string `xml:"profile"`
Scheme string `xml:"scheme"`
Realm string `xml:"realm"`
UserName string `xml:"username"`
Password string `xml:"passowrd"`
From string `xml:"from"`
Contact string `xml:"contact"`
Exten string `xml:"exten"`
To string `xml:"to"`
Proxy string `xml:"proxy"`
Context string `xml:"context"`
Expires int `xml:"expires"`
FReq int `xml:"freq"`
Ping int `xml:"ping"`
PingFreq int `xml:"pingfreq"`
PingMin int `xml:"pingmin"`
PingCount int `xml:"pingcount"`
PingMax int `xml:"pingmax"`
PingTime float64 `xml:"pingtime"`
Pinging int `xml:"pinging"`
State string `xml:"state"`
Status string `xml:"status"`
UptimeUsec string `xml:"uptime-usec"`
CallsIn int `xml:"calls-in"`
CallsOut int `xml:"calls-out"`
FailedCallsIn int `xml:"failed-calls-in"`
FailedCallsOut int `xml:"failed-calls-out"`
}
type Registrations struct {
XMLName xml.Name `xml:"result"`
Text string `xml:",chardata"`
RowCount string `xml:"row_count,attr"`
Row []struct {
Text string `xml:",chardata"`
RowID string `xml:"row_id,attr"`
Type struct {
Text string `xml:",chardata"`
} `xml:"type"`
RegUser struct {
Text string `xml:",chardata"`
} `xml:"reg_user"`
Realm struct {
Text string `xml:",chardata"`
} `xml:"realm"`
Token struct {
Text string `xml:",chardata"`
} `xml:"token"`
Url struct {
Text string `xml:",chardata"`
} `xml:"url"`
Expires struct {
Text string `xml:",chardata"`
} `xml:"expires"`
NetworkIp struct {
Text string `xml:",chardata"`
} `xml:"network_ip"`
NetworkPort struct {
Text string `xml:",chardata"`
} `xml:"network_port"`
NetworkProto struct {
Text string `xml:",chardata"`
} `xml:"network_proto"`
Hostname struct {
Text string `xml:",chardata"`
} `xml:"hostname"`
} `xml:"row"`
}
type Configuration struct {
XMLName xml.Name `xml:"configuration"`
Text string `xml:",chardata"`
Name string `xml:"name,attr"`
Description string `xml:"description,attr"`
Modules struct {
Text string `xml:",chardata"`
Load []struct {
Text string `xml:",chardata"`
Module string `xml:"module,attr"`
} `xml:"load"`
} `xml:"modules"`
}
type Result struct {
XMLName xml.Name `xml:"result"`
Text string `xml:",chardata"`
RowCount string `xml:"row_count,attr"`
Row []struct {
Text string `xml:",chardata"`
RowID string `xml:"row_id,attr"`
Type struct {
Text string `xml:",chardata"`
} `xml:"type"`
Name struct {
Text string `xml:",chardata"`
} `xml:"name"`
Ikey struct {
Text string `xml:",chardata"`
} `xml:"ikey"`
} `xml:"row"`
}
type Verto struct {
XMLName xml.Name `xml:"profiles"`
Text string `xml:",chardata"`
Profile []struct {
Text string `xml:",chardata"`
Name struct {
Text string `xml:",chardata"`
} `xml:"name"`
Type struct {
Text string `xml:",chardata"`
} `xml:"type"`
Data struct {
Text string `xml:",chardata"`
} `xml:"data"`
State struct {
Text string `xml:",chardata"`
} `xml:"state"`
} `xml:"profile"`
}
var (
metricList = []Metric{
{Name: "current_calls", Type: prometheus.GaugeValue, Help: "Number of calls active", Command: "api show calls count as json"},
{Name: "detailed_bridged_calls", Type: prometheus.GaugeValue, Help: "Number of detailed_bridged_calls active", Command: "api show detailed_bridged_calls as json"},
{Name: "detailed_calls", Type: prometheus.GaugeValue, Help: "Number of detailed_calls active", Command: "api show detailed_calls as json"},
{Name: "bridged_calls", Type: prometheus.GaugeValue, Help: "Number of bridged_calls active", Command: "api show bridged_calls as json"},
{Name: "registrations", Type: prometheus.GaugeValue, Help: "Number of registrations active", Command: "api show registrations as json"},
{Name: "current_channels", Type: prometheus.GaugeValue, Help: "Number of channels active", Command: "api show channels count as json"},
{Name: "uptime_seconds", Type: prometheus.GaugeValue, Help: "Uptime in seconds", Command: "api uptime s"},
{Name: "time_synced", Type: prometheus.GaugeValue, Help: "Is FreeSWITCH time in sync with exporter host time", Command: "api strepoch"},
{Name: "sessions_total", Type: prometheus.CounterValue, Help: "Number of sessions since startup", RegexIndex: 1},
{Name: "current_sessions", Type: prometheus.GaugeValue, Help: "Number of sessions active", RegexIndex: 2},
{Name: "current_sessions_peak", Type: prometheus.GaugeValue, Help: "Peak sessions since startup", RegexIndex: 3},
{Name: "current_sessions_peak_last_5min", Type: prometheus.GaugeValue, Help: "Peak sessions for the last 5 minutes", RegexIndex: 4},
{Name: "current_sps", Type: prometheus.GaugeValue, Help: "Number of sessions per second", RegexIndex: 5},
{Name: "current_sps_peak", Type: prometheus.GaugeValue, Help: "Peak sessions per second since startup", RegexIndex: 7},
{Name: "current_sps_peak_last_5min", Type: prometheus.GaugeValue, Help: "Peak sessions per second for the last 5 minutes", RegexIndex: 8},
{Name: "max_sps", Type: prometheus.GaugeValue, Help: "Max sessions per second allowed", RegexIndex: 6},
{Name: "max_sessions", Type: prometheus.GaugeValue, Help: "Max sessions allowed", RegexIndex: 9},
{Name: "current_idle_cpu", Type: prometheus.GaugeValue, Help: "CPU idle", RegexIndex: 11},
{Name: "min_idle_cpu", Type: prometheus.GaugeValue, Help: "Minimum CPU idle", RegexIndex: 10},
}
statusRegex = regexp.MustCompile(`(\d+) session\(s\) since startup\s+(\d+) session\(s\) - peak (\d+), last 5min (\d+)\s+(\d+) session\(s\) per Sec out of max (\d+), peak (\d+), last 5min (\d+)\s+(\d+) session\(s\) max\s+min idle cpu (\d+\.\d+)\/(\d+\.\d+)`)
)
// NewCollector processes uri, timeout and methods and returns a new Collector.
func NewCollector(uri string, timeout time.Duration, password string, rtpEnable bool) (*Collector, error) {
var c Collector
c.URI = uri
c.Timeout = timeout
c.Password = password
c.rtpEnable = rtpEnable
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.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: "Current total freeswitch scrapes.",
})
c.failedScrapes = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_failed_scrapes",
Help: "Number of failed freeswitch scrapes.",
})
return &c, nil
}
// scrape will connect to the freeswitch instance and push metrics to the Prometheus channel.
func (c *Collector) scrape(ch chan<- prometheus.Metric) error {
c.totalScrapes.Inc()
address := c.url.Host
if c.url.Scheme == "unix" {
address = c.url.Path
}
var err error
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()
c.input = bufio.NewReader(c.conn)
if err = c.fsAuth(); err != nil {
return err
}
if err = c.scapeMetrics(ch); err != nil {
return err
}
if err = c.scrapeStatus(ch); err != nil {
return err
}
if err = c.sofiaStatusMetrics(ch); err != nil {
return err
}
if err = c.memoryMetrics(ch); err != nil {
return err
}
if err = c.loadModuleMetrics(ch); err != nil {
return err
}
if err = c.endpointMetrics(ch); err != nil {
return err
}
if err = c.codecMetrics(ch); err != nil {
return err
}
if err = c.registrationsMetrics(ch); err != nil {
return err
}
if err = c.vertoMetrics(ch); err != nil {
return err
}
if c.rtpEnable {
if err = c.variableRtpAudioMetrics(ch); err != nil {
return err
}
}
return nil
}
func (c *Collector) variableRtpAudioMetrics(ch chan<- prometheus.Metric) error {
return nil
}
func (c *Collector) scapeMetrics(ch chan<- prometheus.Metric) error {
for _, metricDef := range metricList {
if len(metricDef.Command) == 0 {
// this metric will be fetched by scapeStatus
continue
}
value, err := c.fetchMetric(&metricDef)
if err != nil {
return err
}
metric, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_"+metricDef.Name, metricDef.Help, nil, nil),
metricDef.Type,
value,
)
if err != nil {
return err
}
ch <- metric
}
return nil
}
func (c *Collector) loadModuleMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api xml_locate configuration configuration name modules.conf")
if err != nil {
return err
}
cfgs := Configuration{}
decode := xml.NewDecoder(bytes.NewReader(response))
decode.CharsetReader = charset.NewReaderLabel
err = decode.Decode(&cfgs)
if err != nil {
log.Println("loadModuleMetrics error: &cfgs", err)
}
level.Debug(logger).Log("[response]:", &cfgs)
fsLoadModules := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "freeswitch_load_module",
Help: "freeswitch load module status",
},
[]string{
"module",
},
)
//prometheus.MustRegister(fsLoadModules)
for _, m := range cfgs.Modules.Load {
status, err := c.fsCommand("api module_exists " + m.Module)
if err != nil {
return err
}
load_mudule := 0
if string(status) == "true" {
load_mudule = 1
}
level.Debug(logger).Log("module", m.Module, " load status: ", string(status))
fsLoadModules.WithLabelValues(m.Module).Set(float64(load_mudule))
}
fsLoadModules.MetricVec.Collect(ch)
return nil
}
func (c *Collector) sofiaStatusMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api sofia xmlstatus gateway")
if err != nil {
return err
}
gw := Gateways{}
//err = xml.Unmarshal(response, &gw)
decode := xml.NewDecoder(bytes.NewReader(response))
decode.CharsetReader = charset.NewReaderLabel
err = decode.Decode(&gw)
if err != nil {
log.Println("sofiaStatusMetrics error: &gw", err)
}
level.Debug(logger).Log("[response]:", &gw)
for _, gateway := range gw.Gateway {
status := 0
if gateway.Status == "UP" {
status = 1
}
level.Debug(logger).Log("sofia ", gateway.Name, " status:", status)
fs_status, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_status", "freeswitch gateways status", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile, "context": gateway.Context, "scheme": gateway.Scheme}),
prometheus.GaugeValue,
float64(status),
)
if err != nil {
return err
}
ch <- fs_status
call_in, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_call_in", "freeswitch gateway call-in", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.CallsIn),
)
if err != nil {
return err
}
ch <- call_in
call_out, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_call_out", "freeswitch gateway call-out", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.CallsOut),
)
if err != nil {
return err
}
ch <- call_out
failed_call_in, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_failed_call_in", "freeswitch gateway failed-call-in", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.FailedCallsIn),
)
if err != nil {
return err
}
ch <- failed_call_in
failed_call_out, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_failed_call_out", "freeswitch gateway failed-call-out", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.FailedCallsOut),
)
if err != nil {
return err
}
ch <- failed_call_out
ping, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_ping", "freeswitch gateway ping", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.Ping),
)
if err != nil {
return err
}
ch <- ping
pingfreq, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_pingfreq", "freeswitch gateway pingfreq", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.PingFreq),
)
if err != nil {
return err
}
ch <- pingfreq
pingmin, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_pingmin", "freeswitch gateway pingmin", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.PingMin),
)
if err != nil {
return err
}
ch <- pingmin
pingmax, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_pingmax", "freeswitch gateway pingmax", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.PingMax),
)
if err != nil {
return err
}
ch <- pingmax
pingcount, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_pingcount", "freeswitch gateway pingcount", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.PingCount),
)
if err != nil {
return err
}
ch <- pingcount
pingtime, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_sofia_gateway_pingtime", "freeswitch gateway pingtime", nil, prometheus.Labels{"name": gateway.Name, "proxy": gateway.Proxy, "profile": gateway.Profile}),
prometheus.GaugeValue,
float64(gateway.PingTime),
)
if err != nil {
return err
}
ch <- pingtime
}
return nil
}
func (c *Collector) memoryMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api memory")
if err != nil {
return err
}
scanner := bufio.NewScanner(bytes.NewReader(response))
for scanner.Scan() {
line := scanner.Text()
if line == "+OK" {
break
}
matches := regexp.MustCompile(`(.+?) \((.+?)\):\s+(\d+)`).FindStringSubmatch(line)
if matches == nil {
level.Debug(logger).Log("msg", "Cannot parse memory line", "line", line)
continue
}
help := matches[1]
field := matches[2]
value, err := strconv.ParseFloat(matches[3], 64)
if err != nil {
return fmt.Errorf("error parsing memory: %w", err)
}
metric, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_memory_"+field, help, nil, nil),
prometheus.GaugeValue,
value,
)
if err != nil {
return err
}
ch <- metric
}
return nil
}
func (c *Collector) endpointMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api show endpoint as xml")
if err != nil {
return err
}
rt := Result{}
decode := xml.NewDecoder(bytes.NewReader(response))
decode.CharsetReader = charset.NewReaderLabel
err = decode.Decode(&rt)
if err != nil {
log.Println("endpointMetrics error: &rt", err)
}
level.Debug(logger).Log("[response]:", &rt)
for _, ep := range rt.Row {
ep_load, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_endpoint_status", "freeswitch endpoint status", nil, prometheus.Labels{"type": ep.Type.Text, "name": ep.Name.Text, "ikey": ep.Ikey.Text}),
prometheus.GaugeValue,
float64(1),
)
if err != nil {
return err
}
ch <- ep_load
}
return nil
}
func (c *Collector) registrationsMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api show registrations as xml")
if err != nil {
return err
}
rt := Registrations{}
decode := xml.NewDecoder(bytes.NewReader(response))
decode.CharsetReader = charset.NewReaderLabel
err = decode.Decode(&rt)
if err != nil {
log.Println("registrationsMetrics error: &rt", err)
}
level.Debug(logger).Log("[response]:", &rt)
for _, cc := range rt.Row {
cc_load, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_registration_defails", "freeswitch registration status", nil, prometheus.Labels{"reg_user": cc.RegUser.Text, "hostname": cc.Hostname.Text, "realm": cc.Realm.Text, "token": cc.Token.Text, "url": cc.Url.Text, "expires": cc.Expires.Text, "network_ip": cc.NetworkIp.Text, "network_port": cc.NetworkPort.Text, "network_proto": cc.NetworkProto.Text}),
prometheus.GaugeValue,
float64(1),
)
if err != nil {
return err
}
ch <- cc_load
}
return nil
}
func (c *Collector) codecMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api show codec as xml")
if err != nil {
return err
}
rt := Result{}
decode := xml.NewDecoder(bytes.NewReader(response))
decode.CharsetReader = charset.NewReaderLabel
err = decode.Decode(&rt)
if err != nil {
log.Println("codecMetrics error: &rt", err)
}
level.Debug(logger).Log("[response]:", &rt)
for _, cc := range rt.Row {
cc_load, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_codec_status", "freeswitch endpoint status", nil, prometheus.Labels{"type": cc.Type.Text, "name": cc.Name.Text, "ikey": cc.Ikey.Text}),
prometheus.GaugeValue,
float64(1),
)
if err != nil {
return err
}
ch <- cc_load
}
return nil
}
func (c *Collector) vertoMetrics(ch chan<- prometheus.Metric) error {
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
response, err := c.fsCommand("api verto xmlstatus")
if err != nil {
return err
}
vt := Verto{}
decode := xml.NewDecoder(bytes.NewReader(response))
decode.CharsetReader = charset.NewReaderLabel
err = decode.Decode(&vt)
if err != nil {
log.Println("vertoMetrics error: &rt", err)
}
level.Debug(logger).Log("[response]:", &vt)
for _, cc := range vt.Profile {
vt_status := 0
if cc.State.Text == "RUNNING" {
vt_status = 1
}
vt_load, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_verto_status", "freeswitch endpoint status", nil, prometheus.Labels{"name": cc.Name.Text, "type": cc.Type.Text, "data": cc.Data.Text}),
prometheus.GaugeValue,
float64(vt_status),
)
if err != nil {
return err
}
ch <- vt_load
}
return nil
}
func (c *Collector) scrapeStatus(ch chan<- prometheus.Metric) error {
response, err := c.fsCommand("api status")
if err != nil {
return err
}
matches := statusRegex.FindAllSubmatch(response, -1)
if len(matches) != 1 {
return errors.New("error parsing status")
}
for _, metricDef := range metricList {
if len(metricDef.Command) != 0 {
// this metric will be fetched by fetchMetric
continue
}
if len(matches[0]) < metricDef.RegexIndex {
return errors.New("error parsing status")
}
strValue := string(matches[0][metricDef.RegexIndex])
value, err := strconv.ParseFloat(strValue, 64)
if err != nil {
return fmt.Errorf("error parsing status: %w", err)
}
metric, err := prometheus.NewConstMetric(
prometheus.NewDesc(namespace+"_"+metricDef.Name, metricDef.Help, nil, nil),
metricDef.Type,
value,
)
if err != nil {
return err
}
ch <- metric
}
return nil
}
func (c *Collector) fetchMetric(metricDef *Metric) (float64, error) {
now := time.Now()
response, err := c.fsCommand(metricDef.Command)
if err != nil {
return 0, err
}
switch metricDef.Name {
//case "current_channels":
case "current_calls":
r := struct {
Count float64 `json:"row_count"`
}{}
err = json.Unmarshal(response, &r)
if err != nil {
return 0, fmt.Errorf("cannot read JSON response: %w", err)
}
return r.Count, nil
case "current_channels":
r := struct {
Count float64 `json:"row_count"`
}{}
err = json.Unmarshal(response, &r)
if err != nil {
return 0, fmt.Errorf("cannot read JSON response: %w", err)
}
return r.Count, nil
case "detailed_bridged_calls":
r := struct {
Count float64 `json:"row_count"`
}{}
err = json.Unmarshal(response, &r)
if err != nil {
return 0, fmt.Errorf("cannot read JSON response: %w", err)
}
return r.Count, nil
case "detailed_calls":
r := struct {
Count float64 `json:"row_count"`
}{}
err = json.Unmarshal(response, &r)
if err != nil {
return 0, fmt.Errorf("cannot read JSON response: %w", err)
}
return r.Count, nil
case "registrations":
r := struct {
Count float64 `json:"row_count"`
}{}
err = json.Unmarshal(response, &r)
if err != nil {
return 0, fmt.Errorf("cannot read JSON response: %w", err)
}
return r.Count, nil
case "bridged_calls":
r := struct {
Count float64 `json:"row_count"`
}{}
err = json.Unmarshal(response, &r)
if err != nil {
return 0, fmt.Errorf("cannot read JSON response: %w", err)
}
return r.Count, nil
case "uptime_seconds":
raw := string(response)
if raw[len(raw)-1:] == "\n" {
raw = raw[:len(raw)-1]
}
value, err := strconv.ParseFloat(raw, 64)
if err != nil {
return 0, fmt.Errorf("cannot read uptime: %w", err)
}
return value, nil
case "time_synced":
value, err := strconv.ParseInt(string(response), 10, 64)
if err != nil {
return 0, fmt.Errorf("cannot read FreeSWITCH time: %w", err)
}
if now.Unix() == value {
return 1, nil
}
log.Printf("[warning] time not in sync between system (%v) and FreeSWITCH (%v)\n",
now.Unix(), value)
return 0, nil
}
return 0, fmt.Errorf("unknown metric: %s", metricDef.Name)
}
func (c *Collector) fsCommand(command string) ([]byte, error) {
_, err := io.WriteString(c.conn, command+"\n\n")
if err != nil {
return nil, fmt.Errorf("cannot write command: %w", err)
}
mimeReader := textproto.NewReader(c.input)
message, err := mimeReader.ReadMIMEHeader()
if err != nil {
return nil, fmt.Errorf("cannot read command response: %w", err)
}
value := message.Get("Content-Length")
length, _ := strconv.Atoi(value)
body := make([]byte, length)
_, err = io.ReadFull(c.input, body)
if err != nil {
return nil, err
}
return body, nil
}
func (c *Collector) fsAuth() error {
mimeReader := textproto.NewReader(c.input)
message, err := mimeReader.ReadMIMEHeader()
if err != nil {
return fmt.Errorf("read auth failed: %w", err)
}
if message.Get("Content-Type") != "auth/request" {
return errors.New("auth failed: unknown content-type")
}
_, err = io.WriteString(c.conn, fmt.Sprintf("auth %s\n\n", c.Password))
if err != nil {
return fmt.Errorf("write auth failed: %w", err)
}
message, err = mimeReader.ReadMIMEHeader()
if err != nil {
return fmt.Errorf("read auth failed: %w", err)
}
if message.Get("Content-Type") != "command/reply" {
return errors.New("auth failed: unknown reply")
}
if message.Get("Reply-Text") != "+OK accepted" {
return fmt.Errorf("auth failed: %s", message.Get("Reply-Text"))
}
return 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
}