-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
891 lines (795 loc) · 23.7 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
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
package main
import (
"bufio"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const promNamespace = "pbs"
const versionApi = "/api2/json/version"
const datastoreUsageApi = "/api2/json/status/datastore-usage"
const datastoreApi = "/api2/json/admin/datastore"
const nodeApi = "/api2/json/nodes"
// These variables are set in build step
var Version = "v0.0.0-dev.0"
var Commit = "none"
var BuildTime = "unknown"
var (
tr = &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
}
client = &http.Client{
Transport: tr,
}
// Flags
endpoint = flag.String("pbs.endpoint", "",
"Proxmox Backup Server endpoint")
username = flag.String("pbs.username", "root@pam",
"Proxmox Backup Server username")
apitoken = flag.String("pbs.api.token", "",
"Proxmox Backup Server API token")
apitokenname = flag.String("pbs.api.token.name", "pbs-exporter",
"Proxmox Backup Server API token name")
timeout = flag.String("pbs.timeout", "5s",
"Proxmox Backup Server timeout")
insecure = flag.String("pbs.insecure", "false",
"Proxmox Backup Server insecure")
metricsPath = flag.String("pbs.metrics-path", "/metrics",
"Path under which to expose metrics")
listenAddress = flag.String("pbs.listen-address", ":10019",
"Address on which to expose metrics")
loglevel = flag.String("pbs.loglevel", "info",
"Loglevel")
// Metrics
up = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "up"),
"Was the last query of PBS successful.",
nil, nil,
)
version = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "version"),
"Version of the PBS installation.",
[]string{"version", "repoid", "release"}, nil,
)
available = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "available"),
"The available bytes of the underlying storage.",
[]string{"datastore"}, nil,
)
size = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "size"),
"The size of the underlying storage in bytes.",
[]string{"datastore"}, nil,
)
used = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "used"),
"The used bytes of the underlying storage.",
[]string{"datastore"}, nil,
)
snapshot_count = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "snapshot_count"),
"The total number of backups.",
[]string{"datastore", "namespace"}, nil,
)
snapshot_vm_count = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "snapshot_vm_count"),
"The total number of backups per VM.",
[]string{"datastore", "namespace", "vm_id", "vm_name"}, nil,
)
snapshot_vm_last_timestamp = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "snapshot_vm_last_timestamp"),
"The timestamp of the last backup of a VM.",
[]string{"datastore", "namespace", "vm_id", "vm_name"}, nil,
)
snapshot_vm_last_verify = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "snapshot_vm_last_verify"),
"The verify status of the last backup of a VM.",
[]string{"datastore", "namespace", "vm_id", "vm_name"}, nil,
)
host_cpu_usage = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_cpu_usage"),
"The CPU usage of the host.",
nil, nil,
)
host_memory_free = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_memory_free"),
"The free memory of the host.",
nil, nil,
)
host_memory_total = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_memory_total"),
"The total memory of the host.",
nil, nil,
)
host_memory_used = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_memory_used"),
"The used memory of the host.",
nil, nil,
)
host_swap_free = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_swap_free"),
"The free swap of the host.",
nil, nil,
)
host_swap_total = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_swap_total"),
"The total swap of the host.",
nil, nil,
)
host_swap_used = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_swap_used"),
"The used swap of the host.",
nil, nil,
)
host_disk_available = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_disk_available"),
"The available disk of the local root disk in bytes.",
nil, nil,
)
host_disk_total = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_disk_total"),
"The total disk of the local root disk in bytes.",
nil, nil,
)
host_disk_used = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_disk_used"),
"The used disk of the local root disk in bytes.",
nil, nil,
)
host_uptime = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_uptime"),
"The uptime of the host.",
nil, nil,
)
host_io_wait = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_io_wait"),
"The io wait of the host.",
nil, nil,
)
host_load1 = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_load1"),
"The load for 1 minute of the host.",
nil, nil,
)
host_load5 = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_load5"),
"The load for 5 minutes of the host.",
nil, nil,
)
host_load15 = prometheus.NewDesc(
prometheus.BuildFQName(promNamespace, "", "host_load15"),
"The load for 15 minutes of the host.",
nil, nil,
)
)
type VersionResponse struct {
Data struct {
Release string `json:"release"`
Repoid string `json:"repoid"`
Version string `json:"version"`
} `json:"data"`
}
type DatastoreResponse struct {
Data []struct {
Avail int64 `json:"avail"`
Store string `json:"store"`
Total int64 `json:"total"`
Used int64 `json:"used"`
Namespace string `json:"ns"`
} `json:"data"`
}
type Datastore struct {
Avail int64 `json:"avail"`
Store string `json:"store"`
Total int64 `json:"total"`
Used int64 `json:"used"`
Namespace string `json:"ns"`
}
type NamespaceResponse struct {
Data []struct {
Namespace string `json:"ns"`
} `json:"data"`
}
type SnapshotResponse struct {
Data []struct {
BackupID string `json:"backup-id"`
BackupTime int64 `json:"backup-time"`
VMName string `json:"comment"`
Verification struct {
State string `json:"state"`
} `json:"verification"`
} `json:"data"`
}
type HostResponse struct {
Data struct {
CPU float64 `json:"cpu"`
Mem struct {
Free int64 `json:"free"`
Total int64 `json:"total"`
Used int64 `json:"used"`
} `json:"memory"`
Swap struct {
Free int64 `json:"free"`
Total int64 `json:"total"`
Used int64 `json:"used"`
} `json:"swap"`
Disk struct {
Avail int64 `json:"avail"`
Total int64 `json:"total"`
Used int64 `json:"used"`
} `json:"root"`
Load []float64 `json:"loadavg"`
Uptime int64 `json:"uptime"`
Wait float64 `json:"wait"`
} `json:"data"`
}
type Exporter struct {
endpoint string
authorizationHeader string
}
func ReadSecretFile(secretfilename string) string {
file, err := os.Open(filepath.Clean(secretfilename))
// flag to check the file format
if err != nil {
log.Fatal(err)
}
// Close the file
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
// Read the first line
line := bufio.NewScanner(file)
line.Scan()
return line.Text()
}
func NewExporter(endpoint string, username string, apitoken string, apitokenname string) *Exporter {
return &Exporter{
endpoint: endpoint,
authorizationHeader: "PBSAPIToken=" + username + "!" + apitokenname + ":" + apitoken,
}
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- up
ch <- version
ch <- available
ch <- size
ch <- used
ch <- snapshot_count
ch <- snapshot_vm_count
ch <- snapshot_vm_last_timestamp
ch <- snapshot_vm_last_verify
ch <- host_cpu_usage
ch <- host_memory_free
ch <- host_memory_total
ch <- host_memory_used
ch <- host_swap_free
ch <- host_swap_total
ch <- host_swap_used
ch <- host_disk_available
ch <- host_disk_total
ch <- host_disk_used
ch <- host_uptime
ch <- host_io_wait
ch <- host_load1
ch <- host_load5
ch <- host_load15
}
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
err := e.collectFromAPI(ch)
if err != nil {
ch <- prometheus.MustNewConstMetric(
up, prometheus.GaugeValue, 0,
)
log.Println(err)
return
}
ch <- prometheus.MustNewConstMetric(
up, prometheus.GaugeValue, 1,
)
}
func (e *Exporter) collectFromAPI(ch chan<- prometheus.Metric) error {
// get version
err := e.getVersion(ch)
if err != nil {
return err
}
// get datastores
req, err := http.NewRequest("GET", e.endpoint+datastoreUsageApi, nil)
if err != nil {
return err
}
// add Authorization header
req.Header.Set("Authorization", e.authorizationHeader)
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Request URL: %s", req.URL)
// log.Printf("DEBUG: Request Header: %s", vmID)
}
// make request and show output
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(resp.Body)
if err := resp.Body.Close(); err != nil {
log.Printf("Error closing response body: %v", err)
}
if err != nil {
return err
}
// check if status code is 200
if resp.StatusCode != 200 {
return fmt.Errorf("ERROR: Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
}
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
//log.Printf("DEBUG: Response body: %s", string(body))
}
// parse json
var response DatastoreResponse
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
// for each datastore collect metrics
for _, datastore := range response.Data {
err := e.getDatastoreMetric(datastore, ch)
if err != nil {
return err
}
}
// get node metrics
err = e.getNodeMetrics(ch)
if err != nil {
return err
}
return nil
}
func (e *Exporter) getVersion(ch chan<- prometheus.Metric) error {
// get version
req, err := http.NewRequest("GET", e.endpoint+versionApi, nil)
if err != nil {
return err
}
// add Authorization header
req.Header.Set("Authorization", e.authorizationHeader)
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Request URL: %s", req.URL)
// log.Printf("DEBUG: Request Header: %s", vmID)
}
// make request and show output
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(resp.Body)
if err := resp.Body.Close(); err != nil {
log.Printf("Error closing response body: %v", err)
}
if err != nil {
return err
}
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
//log.Printf("DEBUG: Response body: %s", string(body))
}
// check if status code is 200
if resp.StatusCode != 200 {
return fmt.Errorf("ERROR: Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
}
// parse json
var response VersionResponse
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
version, prometheus.GaugeValue, 1, response.Data.Version, response.Data.Repoid, response.Data.Release,
)
return nil
}
func (e *Exporter) getNodeMetrics(ch chan<- prometheus.Metric) error {
// NOTE: According to the api documentation, we have to provide the node name (won't work with the node ip),
// but it seems to work with any name, so we just use "localhost" here.
// see: https://pbs.proxmox.com/docs/api-viewer/index.html#/nodes/{node}
req, err := http.NewRequest("GET", e.endpoint+nodeApi+"/localhost/status", nil)
if err != nil {
return err
}
// add Authorization header
req.Header.Set("Authorization", e.authorizationHeader)
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Request URL: %s", req.URL)
//log.Printf("DEBUG: Request Header: %s", vmID)
}
// make request and show output
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(resp.Body)
if err := resp.Body.Close(); err != nil {
log.Printf("Error closing response body: %v", err)
}
if err != nil {
return err
}
// check if status code is 200
if resp.StatusCode != 200 {
return fmt.Errorf("ERROR: Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
}
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
//log.Printf("DEBUG: Response body: %s", string(body))
}
// parse json
var response HostResponse
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
// set host metrics
ch <- prometheus.MustNewConstMetric(
host_cpu_usage, prometheus.GaugeValue, float64(response.Data.CPU),
)
ch <- prometheus.MustNewConstMetric(
host_memory_free, prometheus.GaugeValue, float64(response.Data.Mem.Free),
)
ch <- prometheus.MustNewConstMetric(
host_memory_total, prometheus.GaugeValue, float64(response.Data.Mem.Total),
)
ch <- prometheus.MustNewConstMetric(
host_memory_used, prometheus.GaugeValue, float64(response.Data.Mem.Used),
)
ch <- prometheus.MustNewConstMetric(
host_swap_free, prometheus.GaugeValue, float64(response.Data.Swap.Free),
)
ch <- prometheus.MustNewConstMetric(
host_swap_total, prometheus.GaugeValue, float64(response.Data.Swap.Total),
)
ch <- prometheus.MustNewConstMetric(
host_swap_used, prometheus.GaugeValue, float64(response.Data.Swap.Used),
)
ch <- prometheus.MustNewConstMetric(
host_disk_available, prometheus.GaugeValue, float64(response.Data.Disk.Avail),
)
ch <- prometheus.MustNewConstMetric(
host_disk_total, prometheus.GaugeValue, float64(response.Data.Disk.Total),
)
ch <- prometheus.MustNewConstMetric(
host_disk_used, prometheus.GaugeValue, float64(response.Data.Disk.Used),
)
ch <- prometheus.MustNewConstMetric(
host_uptime, prometheus.GaugeValue, float64(response.Data.Uptime),
)
ch <- prometheus.MustNewConstMetric(
host_io_wait, prometheus.GaugeValue, float64(response.Data.Wait),
)
ch <- prometheus.MustNewConstMetric(
host_load1, prometheus.GaugeValue, float64(response.Data.Load[0]),
)
ch <- prometheus.MustNewConstMetric(
host_load5, prometheus.GaugeValue, float64(response.Data.Load[1]),
)
ch <- prometheus.MustNewConstMetric(
host_load15, prometheus.GaugeValue, float64(response.Data.Load[2]),
)
return nil
}
func (e *Exporter) getDatastoreMetric(datastore Datastore, ch chan<- prometheus.Metric) error {
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: --Store %s", datastore.Store)
log.Printf("DEBUG: --Avail %d", datastore.Avail)
log.Printf("DEBUG: --Total %d", datastore.Total)
log.Printf("DEBUG: --Used %d", datastore.Used)
}
// set datastore metrics
ch <- prometheus.MustNewConstMetric(
available, prometheus.GaugeValue, float64(datastore.Avail), datastore.Store,
)
ch <- prometheus.MustNewConstMetric(
size, prometheus.GaugeValue, float64(datastore.Total), datastore.Store,
)
ch <- prometheus.MustNewConstMetric(
used, prometheus.GaugeValue, float64(datastore.Used), datastore.Store,
)
// get namespaces of datastore
req, err := http.NewRequest("GET", e.endpoint+datastoreApi+"/"+datastore.Store+"/namespace", nil)
if err != nil {
return err
}
// add Authorization header
req.Header.Set("Authorization", e.authorizationHeader)
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: --Request URL: %s", req.URL)
//log.Printf("DEBUG: --Request Header: %s", vmID)
}
// make request and show output
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(resp.Body)
if err := resp.Body.Close(); err != nil {
log.Printf("Error closing response body: %v", err)
}
if err != nil {
return err
}
// check if status code is 200
if resp.StatusCode != 200 {
if resp.StatusCode == 400 {
// check if datastore is being deleted
isBeingDeleted, err := regexp.MatchString("(?i)datastore is being deleted", string(body[:]))
if err != nil {
return err
}
if isBeingDeleted {
log.Printf("INFO: Datastore: %s is being deleted, Skip scrape datastore metric", datastore.Store)
return nil
}
}
return fmt.Errorf("ERROR: --Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
}
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: --Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
//log.Printf("DEBUG: Response body: %s", string(body))
}
// parse json
var response NamespaceResponse
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
// for each namespace collect metrics
for _, namespace := range response.Data {
err := e.getNamespaceMetric(datastore.Store, namespace.Namespace, ch)
if err != nil {
return err
}
}
return nil
}
func (e *Exporter) getNamespaceMetric(datastore string, namespace string, ch chan<- prometheus.Metric) error {
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: ----Namespace %s", namespace)
}
// get snapshots of datastore
req, err := http.NewRequest("GET", e.endpoint+datastoreApi+"/"+datastore+"/snapshots?ns="+namespace, nil)
if err != nil {
return err
}
// add Authorization header
req.Header.Set("Authorization", e.authorizationHeader)
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: ----Request URL: %s", req.URL)
//log.Printf("DEBUG: ----Request Header: %s", vmID)
}
// make request and show output
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := io.ReadAll(resp.Body)
if err := resp.Body.Close(); err != nil {
log.Printf("Error closing response body: %v", err)
}
if err != nil {
return err
}
// check if status code is 200
if resp.StatusCode != 200 {
return fmt.Errorf("ERROR: ----Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
}
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: ----Status code %d returned from endpoint: %s", resp.StatusCode, e.endpoint)
//log.Printf("DEBUG: Response body: %s", string(body))
}
// parse json
var response SnapshotResponse
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
// set total snapshot metrics
ch <- prometheus.MustNewConstMetric(
snapshot_count, prometheus.GaugeValue, float64(len(response.Data)), datastore, namespace,
)
// set snapshot metrics per vm
vmNameMapping := make(map[string]string)
vmCount := make(map[string]int)
for _, snapshot := range response.Data {
// get vm name from snapshot
vmID := snapshot.BackupID
vmNameMapping[vmID] = snapshot.VMName
vmCount[vmID]++
}
// set snapshot metrics per vm
for vmID, count := range vmCount {
ch <- prometheus.MustNewConstMetric(
snapshot_vm_count, prometheus.GaugeValue, float64(count), datastore, namespace, vmID, vmNameMapping[vmID],
)
// find last snapshot with backupID
lastTimeStamp, lastVerify, err := findLastSnapshotWithBackupID(response, vmID)
if err != nil {
return err
}
lastVerifyBool := 0
if lastVerify == "ok" {
lastVerifyBool = 1
}
ch <- prometheus.MustNewConstMetric(
snapshot_vm_last_timestamp, prometheus.GaugeValue, float64(lastTimeStamp), datastore, namespace, vmID, vmNameMapping[vmID],
)
ch <- prometheus.MustNewConstMetric(
snapshot_vm_last_verify, prometheus.GaugeValue, float64(lastVerifyBool), datastore, namespace, vmID, vmNameMapping[vmID],
)
}
return nil
}
func findLastSnapshotWithBackupID(response SnapshotResponse, backupID string) (int64, string, error) {
// find biggest value of backupTime of backupID in response array
var lastTimeStamp int64
var lastVerify string
for _, snapshot := range response.Data {
if snapshot.BackupID == backupID {
if snapshot.BackupTime > lastTimeStamp {
lastTimeStamp = snapshot.BackupTime
lastVerify = snapshot.Verification.State
}
}
}
// if lastTimeStamp is still 0, no snapshot was found
if lastTimeStamp != 0 {
return lastTimeStamp, lastVerify, nil
}
return 0, "", fmt.Errorf("ERROR: No snapshot found with backupID %s", backupID)
}
func main() {
flag.Parse()
// log build information
log.Printf("INFO: Starting PBS Exporter %s, commit %s, built at %s", Version, Commit, BuildTime)
// if env variable is set, it will overwrite defaults or flags
if os.Getenv("PBS_LOGLEVEL") != "" {
*loglevel = os.Getenv("PBS_LOGLEVEL")
}
if os.Getenv("PBS_ENDPOINT") != "" {
*endpoint = os.Getenv("PBS_ENDPOINT")
}
if os.Getenv("PBS_USERNAME") != "" {
*username = os.Getenv("PBS_USERNAME")
} else {
if os.Getenv("PBS_USERNAME_FILE") != "" {
*username = ReadSecretFile(os.Getenv("PBS_USERNAME_FILE"))
}
}
if os.Getenv("PBS_API_TOKEN_NAME") != "" {
*apitokenname = os.Getenv("PBS_API_TOKEN_NAME")
} else {
if os.Getenv("PBS_API_TOKEN_NAME_FILE") != "" {
*apitokenname = ReadSecretFile(os.Getenv("PBS_API_TOKEN_NAME_FILE"))
}
}
if os.Getenv("PBS_API_TOKEN") != "" {
*apitoken = os.Getenv("PBS_API_TOKEN")
} else {
if os.Getenv("PBS_API_TOKEN_FILE") != "" {
*apitoken = ReadSecretFile(os.Getenv("PBS_API_TOKEN_FILE"))
}
}
if os.Getenv("PBS_TIMEOUT") != "" {
*timeout = os.Getenv("PBS_TIMEOUT")
}
if os.Getenv("PBS_INSECURE") != "" {
*insecure = os.Getenv("PBS_INSECURE")
}
if os.Getenv("PBS_METRICS_PATH") != "" {
*metricsPath = os.Getenv("PBS_METRICS_PATH")
}
if os.Getenv("PBS_LISTEN_ADDRESS") != "" {
*listenAddress = os.Getenv("PBS_LISTEN_ADDRESS")
}
// convert flags
insecureBool, err := strconv.ParseBool(*insecure)
if err != nil {
log.Fatalf("ERROR: Unable to parse insecure: %s", err)
}
// set insecure
if insecureBool {
tr.TLSClientConfig.InsecureSkipVerify = true
}
// set timeout
timeoutDuration, err := time.ParseDuration(*timeout)
if err != nil {
log.Fatalf("ERROR: Unable to parse timeout: %s", err)
}
client.Timeout = timeoutDuration
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Using connection endpoint: %s", *endpoint)
log.Printf("DEBUG: Using connection username: %s", *username)
log.Printf("DEBUG: Using connection apitoken: %s", *apitoken)
log.Printf("DEBUG: Using connection apitokenname: %s", *apitokenname)
log.Printf("DEBUG: Using connection timeout: %s", client.Timeout)
log.Printf("DEBUG: Using connection insecure: %t", tr.TLSClientConfig.InsecureSkipVerify)
log.Printf("DEBUG: Using metrics path: %s", *metricsPath)
log.Printf("DEBUG: Using listen address: %s", *listenAddress)
}
if *endpoint != "" {
log.Printf("INFO: Using fix connection endpoint: %s", *endpoint)
}
log.Printf("INFO: Listening on: %s", *listenAddress)
log.Printf("INFO: Metrics path: %s", *metricsPath)
// start http server
http.HandleFunc(*metricsPath, func(w http.ResponseWriter, r *http.Request) {
target := ""
// if endpoint was not set as flag or env variable, we try to get it from "target" query parameter
if *endpoint != "" {
target = *endpoint
} else {
target = r.URL.Query().Get("target")
if target == "" {
// if target is not set, we use the default
target = "http://localhost:8007"
}
}
// debug
if *loglevel == "debug" {
log.Printf("DEBUG: Using connection endpoint %s", target)
}
exporter := NewExporter(target, *username, *apitoken, *apitokenname)
// catch if register of exporter fails
err := prometheus.Register(exporter)
if err != nil {
// if register fails, we log the error and return
log.Printf("ERROR: %s", err)
}
promhttp.Handler().ServeHTTP(w, r) // Serve the metrics
prometheus.Unregister(exporter) // Clean up after serving
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(`<html>
<head><title>PBS Exporter</title></head>
<body>
<h1>Proxmox Backup Server Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
if err != nil {
log.Printf("ERROR: Failed to write response: %s", err)
}
})
server := &http.Server{
Addr: *listenAddress,
Handler: nil,
ReadTimeout: time.Second * 10,
WriteTimeout: time.Second * 10,
}
log.Fatal(server.ListenAndServe())
}