-
Notifications
You must be signed in to change notification settings - Fork 2
/
puppetdb_exporter.go
1466 lines (1289 loc) · 45.9 KB
/
puppetdb_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
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"flag"
"fmt"
"github.com/Jeffail/gabs"
"io/ioutil"
"log"
"net/http"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
// TODO don't use your fork
"github.com/negast/go-puppetdb"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/yaml.v2"
)
// START MODELS AND VARIABLES
var (
addr = flag.String("listen-address", ":8156", "The address to listen on for HTTP requests.")
conf = flag.String("conf", "puppetdb-facts.yaml", "The path to the config file.")
endP = flag.String("endpoint", "/metrics", "The path to display the metrics on default /metrics")
)
// Conf the configuration file object for this exporter
type Conf struct {
Facts []string `yaml:"facts"`
FactBundles map[string][]string `yaml:"fact_bundles"`
Nodes bool `yaml:"nodes"`
Host string `yaml:"host"`
Port int `yaml:"port"`
MasterEnable bool `yaml:"masterEnable"`
MasterHost string `yaml:"masterHost"`
MasterPort int `yaml:"masterPort"`
SSL bool `yaml:"ssl"`
Key string `yaml:"key"`
Ca string `yaml:"ca"`
Cert string `yaml:"cert"`
Interval int `yaml:"interval"`
Debug bool `yaml:"debug"`
Timeout int `yaml:"timeout"`
ClientTimeout int `yaml:"client_timeout"`
}
func (c *Conf) getConf(configFile string) *Conf {
yamlFile, err := ioutil.ReadFile(configFile)
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
// FactGuageEntry Contains the information for one fact entry
type FactGuageEntry struct {
Name string
Environment string
CertName string
Set float64
}
// FactNodeGuageEntry Contains the information for one node fact entry
type FactNodeGuageEntry struct {
Name string
Environment string
Value string
CertName string
Set float64
}
// FactNodeGuageEntry Contains the information for one node fact entry
type FactBundleNodeGuageEntry struct {
Name string
Environment string
Values []LabelValue
CertName string
}
// LabelValue holds the data for a value combined with the label mostly this is the fact name for bundles
type LabelValue struct {
Name string
Value string
}
// ReportsMetricEntry Holds data for an entry in the reports metric api
type ReportsMetricEntry struct {
Name string
Environment string
Certname string
Value float64
}
// NodeStatusEntry Holds data for a nodes status
type NodeStatusEntry struct {
Status string
Value string
Environment string
Certname string
}
// END MODELS AND VARIABLES
// START GUAGES
var bundleGuages map[string]*prometheus.GaugeVec
var puppetDBGuage = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "puppetdb_connection_up",
Help: "The check to see if the client settings are ok to connect with",
},
)
var factGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_facts_quage",
Help: "Automated gauge for the specified fact",
},
[]string{"fact", "puppet_environment", "node"},
)
var factNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_facts_node_quage",
Help: "Displays the nodes holding the value for the total gauge",
},
[]string{"fact", "puppet_environment", "node", "value"},
)
var factTotal = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_facts_total",
Help: "Automated count for the specified fact",
},
[]string{"fact", "value"},
)
var statusTotal = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_status_total",
Help: "Automated count for the specified report status",
},
[]string{"status", "puppet_environment"},
)
var statusNodesGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_status_node_guage",
Help: "Automated count for the report status per node",
},
[]string{"status", "puppet_environment", "node"},
)
var resourcesNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_report_resources_node_guage",
Help: "Automated count for the report resources per node",
},
[]string{"name", "puppet_environment", "node"},
)
var timeNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_report_time_node_guage",
Help: "Automated count for the report time per node",
},
[]string{"name", "puppet_environment", "node"},
)
var eventNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_report_event_node_guage",
Help: "Automated count for the report time per node",
},
[]string{"name", "puppet_environment", "node"},
)
var timeLastReportNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_last_report_time_node_guage",
Help: "Automated guage for the last report time of a node",
},
[]string{"puppet_environment", "node", "date"},
)
var timeLastReportStartNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_last_report_start_time_node_guage",
Help: "Automated guage for the last start report time of a node",
},
[]string{"puppet_environment", "node", "date"},
)
var timeLastReportEndNodeGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppetdb_last_report_end_time_node_guage",
Help: "Automated guage for the last end report time of a node",
},
[]string{"puppet_environment", "node", "date"},
)
var masterHTTPGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_http_guage",
Help: "Http stats for the master",
},
[]string{"master", "route", "type"},
)
var masterHTTPClientGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_http_client_guage",
Help: "Http client stats for the master",
},
[]string{"master", "metric_name", "type", "metric_id"},
)
var masterJVMGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_jvm_guage",
Help: "jvm stats for the master",
},
[]string{"master", "metric"},
)
var masterMemoryGuage = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_memory_guage",
Help: "memory stats for the master both heap and non heap memory",
},
[]string{"master", "is_heap", "type"},
)
var masterGCCount = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_gc_count",
Help: "GC count for the master",
},
[]string{"master", "ps_type"},
)
var masterGCTime = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_gc_time",
Help: "GC time in ms for the master",
},
[]string{"master", "ps_type"},
)
var masterGCDuration = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_gc_duration",
Help: "jDuration since the last info in ms",
},
[]string{"master", "ps_type"},
)
var masterFile = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_file_guage",
Help: "file descriptors count",
},
[]string{"master", "name"},
)
var masterThread = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_thread_guage",
Help: "Thread count for the puppet master",
},
[]string{"master", "name"},
)
var masterRuby = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_jruby_guage",
Help: "Thread count for the puppet master",
},
[]string{"master", "name"},
)
var masterBorrowedInstance = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_borrowed_instance_time",
Help: " count for the puppet master",
},
[]string{"master", "uri", "method", "routeId"},
)
var masterBorrowedInstanceDuration = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_borrowed_instance_duration_ms",
Help: "Borrowed instance metrics for the puppet master",
},
[]string{"master", "uri", "method", "routeId"},
)
var masterFunction = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_profiler_function_guage",
Help: "Profiler function metrics for the puppet master",
},
[]string{"master", "function", "type"},
)
var masterResource = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_profiler_resource_guage",
Help: "Profiler resource metrics for the puppet master",
},
[]string{"master", "resource", "type"},
)
var masterCatalog = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_profiler_catalog_guage",
Help: "Profiler catalog metrics for the puppet master",
},
[]string{"master", "metric", "type"},
)
var masterPuppetdb = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_profiler_puppetdb_guage",
Help: "Profiler puppetdb metrics for the puppet master",
},
[]string{"master", "metric", "type"},
)
var masterState = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "puppet_master_state_guage",
Help: "Profiler puppetdb metrics for the puppet master",
},
[]string{"master", "service_version", "service_state", "detail_level"},
)
// END GUAGES
// START FACT GATHERING METHODS
// GenerateFactsMetrics Scrapes the facts metrics defined in the yaml file and exports them to the prometheus exporter
func GenerateFactsMetrics(c *puppetdb.Client, conf Conf) {
// collect metrics
if bundleGuages != nil {
certnames := GetAllCertnames(c)
for key, g := range bundleGuages {
// Steps
// 1 Loop trough all fact names in a bundle
facts_to_collect := conf.FactBundles[key]
sort.Strings(facts_to_collect)
_, arr2G, arr2G2 := GatherMetricArrays(facts_to_collect, conf, c, true)
// 2 we need to check if each node in each array and then we need to collect this data in ine entry
mapy := getBundleEntriesFromArrays(arr2G, arr2G2, facts_to_collect, certnames, key)
setBundleFactMetrics(mapy, g)
}
}
factArr, arrG, arrG2 := GatherMetricArrays(conf.Facts, conf, c, true)
setFactMetrics(factArr, arrG, arrG2, conf.Nodes)
}
// GetAllCertnames get all the certnames for the nodes in your env
func GetAllCertnames(c *puppetdb.Client) []string {
certnames := []string{}
nodes, err := c.Nodes()
if err == nil {
for _, n := range nodes {
if !stringInSlice(n.Certname, certnames) {
certnames = append(certnames, n.Certname)
}
}
}
return certnames
}
func getBundleEntriesFromArrays(arr1 [][]FactGuageEntry, arr2 [][]FactNodeGuageEntry, facts []string, certnames []string, bundleName string) map[string]FactBundleNodeGuageEntry {
mapy := map[string]FactBundleNodeGuageEntry{}
mapy_to_return := map[string]FactBundleNodeGuageEntry{}
numberofHits := len(facts)
for _, certname := range certnames {
for _, arr := range arr1 {
val := getStructFromFactGaugeArray(certname, arr)
if val != nil {
str := fmt.Sprintf("%.2f", val.Set)
lbl := LabelValue{
Name: val.Name,
Value: str,
}
if _, ok := mapy[certname]; ok {
v := mapy[certname]
v.Values = append(mapy[certname].Values, lbl)
mapy[certname] = v
} else {
v := FactBundleNodeGuageEntry{
Name: bundleName,
Environment: val.Environment,
Values: []LabelValue{lbl},
CertName: certname,
}
mapy[certname] = v
}
}
}
for _, arr := range arr2 {
val := getStructFromNodeFactGaugeArray(certname, arr)
if val != nil {
lbl := LabelValue{
Name: val.Name,
Value: val.Value,
}
if _, ok := mapy[certname]; ok {
v := mapy[certname]
v.Values = append(mapy[certname].Values, lbl)
mapy[certname] = v
} else {
v := FactBundleNodeGuageEntry{
Name: bundleName,
Environment: val.Environment,
Values: []LabelValue{lbl},
CertName: certname,
}
mapy[certname] = v
}
}
}
}
// 3 filter out all values that don't have all the label values?
for key, val := range mapy {
if len(val.Values) == numberofHits {
mapy_to_return[key] = val
}
}
return mapy_to_return
}
func getStructFromFactGaugeArray(cert string, arr1 []FactGuageEntry) *FactGuageEntry {
for _, entry := range arr1 {
if entry.CertName == cert {
return &entry
}
}
return nil
}
func getStructFromNodeFactGaugeArray(cert string, arr1 []FactNodeGuageEntry) *FactNodeGuageEntry {
for _, entry := range arr1 {
if entry.CertName == cert {
return &entry
}
}
return nil
}
// GatherMetricArrays gather the needed arrays for a bunch of facts
func GatherMetricArrays(facts []string, conf Conf, c *puppetdb.Client, allowWildCard bool) (map[string]map[string]int, [][]FactGuageEntry, [][]FactNodeGuageEntry) {
factArr := map[string]map[string]int{}
arrG := [][]FactGuageEntry{}
arrG2 := [][]FactNodeGuageEntry{}
for _, fact := range facts {
fA := strings.Split(fact, ".")
if strings.Contains(fact, "*") {
if allowWildCard {
wildCardMetric(fact, c, conf.Nodes, &factArr, &arrG, &arrG2)
}
} else {
if len(fA) == 1 {
facts2, _ := getBaseMetric(fA[0], c)
gatherMetrics(facts2, "", conf.Nodes, &factArr, &arrG, &arrG2)
} else if len(fA) > 1 {
facts2, _ := getBaseMetric(fA[0], c)
pathA := append(fA[:0], fA[0+1:]...)
path := strings.Join(pathA, ".")
gatherMetrics(facts2, path, conf.Nodes, &factArr, &arrG, &arrG2)
}
}
}
return factArr, arrG, arrG2
}
func wildCardMetric(factStr string, c *puppetdb.Client, nodes bool, factArr *map[string]map[string]int, arrG *[][]FactGuageEntry, arrG2 *[][]FactNodeGuageEntry) {
pathBase := strings.Split(factStr, ".")
facts, _ := c.FactPerNode(pathBase[0])
for _, fact := range facts {
getAllPathsForFact(*fact.Value, pathBase[0], factStr, fact, nodes, factArr, arrG, arrG2)
}
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func getAllPathsForFact(fact gabs.Container, path string, regex string, factEntry puppetdb.FactJSON, nodes bool,
totalArr *map[string]map[string]int, arrG *[][]FactGuageEntry, arrG2 *[][]FactNodeGuageEntry) {
cont := fact.ChildrenMap()
for key, val := range cont {
check := reflect.TypeOf(val.Data()).String()
//println(path, check)
if check == "string" || check == "bool" {
match, _ := regexp.MatchString(regex, path+"."+key)
if match {
// adding stuff
strValue := ""
value := val.Data()
switch value.(type) {
case bool:
strValue = fmt.Sprintf("%v", value)
case string:
strValue = value.(string)
default:
strValue = fmt.Sprintf("%v", value)
}
//value := factEntry.Value.Data().(string)
if _, ok := (*totalArr)[path+"."+key]; ok {
if _, ok := (*totalArr)[path+"."+key][strValue]; ok {
(*totalArr)[path+"."+key][strValue] = (*totalArr)[path+"."+key][strValue] + 1
} else {
(*totalArr)[path+"."+key][strValue] = 1
}
} else {
(*totalArr)[path+"."+key] = map[string]int{
strValue: 1,
}
}
if nodes {
ae := FactNodeGuageEntry{Name: path + "." + key, Environment: factEntry.Environment,
Value: strValue, CertName: factEntry.CertName, Set: 1}
aeA := []FactNodeGuageEntry{ae}
*arrG2 = append(*arrG2, aeA)
}
}
} else if check == "float64" {
match, _ := regexp.MatchString(regex, path+"."+key)
if match {
// adding stuff
nd := FactGuageEntry{path + "." + key, factEntry.Environment,
factEntry.CertName, val.Data().(float64)}
aeA := []FactGuageEntry{nd}
*arrG = append(*arrG, aeA)
}
} else if check == "int" {
match, _ := regexp.MatchString(regex, path+"."+key)
if match {
// adding stuff
nd := FactGuageEntry{path + "." + key, factEntry.Environment,
factEntry.CertName, val.Data().(float64)}
aeA := []FactGuageEntry{nd}
*arrG = append(*arrG, aeA)
}
} else if check == "map[string]interface {}" {
getAllPathsForFact(*val, path+"."+key, regex, factEntry, nodes, totalArr, arrG, arrG2)
} else if check == "[]interface {}" {
arr := val.Children()
for index, val2 := range arr {
str1 := fmt.Sprintf("%s.%s[%d]", path, key, index)
getAllPathsForFact(*val2, str1, regex, factEntry, nodes, totalArr, arrG, arrG2)
}
}
}
}
func evalPath(fact puppetdb.FactJSON, path string, first bool) {
factN := fact.Value.S(path)
if first {
factN = fact.Value
}
if factN != nil {
check := reflect.TypeOf(factN.Data()).String()
//println(path, check)
if check == "string" {
println(path + ": " + factN.String())
} else if check == "float64" {
println(path + ": " + factN.String())
}
}
}
// gatherMetrics Scrapes the apis and returns the values
func gatherMetrics(facts []puppetdb.FactJSON, path string, nodes bool, factArr *map[string]map[string]int, arrG *[][]FactGuageEntry, arrG2 *[][]FactNodeGuageEntry) {
arr := []FactGuageEntry{}
arr2 := []FactNodeGuageEntry{}
var value interface{}
if len(facts) > 0 {
if path != "" {
value = facts[0].Value.Path(path).Data()
} else {
value = facts[0].Value.Data()
}
check := reflect.TypeOf(value).String()
switch check {
case "int":
addGaugeMetricfactsIntOrFloatPath2(facts, path, &arr)
*arrG = append(*arrG, arr)
case "bool":
addGaugeMetricfactsStringPath2(facts, path, nodes, &arr2, factArr)
*arrG2 = append(*arrG2, arr2)
case "string":
addGaugeMetricfactsStringPath2(facts, path, nodes, &arr2, factArr)
*arrG2 = append(*arrG2, arr2)
case "float64":
addGaugeMetricfactsIntOrFloatPath2(facts, path, &arr)
*arrG = append(*arrG, arr)
default:
fmt.Println("Skipping fact because not of type int, float or string")
}
}
}
// getBaseMetric Gets the fact for each of the given metric path(assuming correct path is given)
func getBaseMetric(fact string, c *puppetdb.Client) ([]puppetdb.FactJSON, error) {
facts, err := c.FactPerNode(fact)
if err != nil {
log.Println(err)
puppetDBGuage.Set(0)
} else {
puppetDBGuage.Set(1)
}
return facts, err
}
// addGaugeMetricfactsIntOrFloatPath2 If given metric was a float this will add a FactGaugeEntry to the array
func addGaugeMetricfactsIntOrFloatPath2(facts []puppetdb.FactJSON, path string, arr *[]FactGuageEntry) {
for _, fact := range facts {
var value interface{}
if path != "" {
value = fact.Value.Path(path).Data()
inter := fmt.Sprintf("%v", value)
f, err := strconv.ParseFloat(inter, 64)
if err != nil {
f = 0.0
}
*arr = append(*arr, FactGuageEntry{fact.Name + "." + path, fact.Environment, fact.CertName, f})
} else {
value = fact.Value.Data()
inter := fmt.Sprintf("%v", value)
f, err := strconv.ParseFloat(inter, 64)
if err != nil {
f = 0.0
}
*arr = append(*arr, FactGuageEntry{fact.Name, fact.Environment, fact.CertName, f})
}
}
}
// addGaugeMetricfactsStringPath2 If given metric was a float this will add a FactNodeGaugeEntry to the array and a total fact entry
func addGaugeMetricfactsStringPath2(facts []puppetdb.FactJSON, path string, nodes bool, arr *[]FactNodeGuageEntry, totalArr *map[string]map[string]int) {
for _, fact := range facts {
var value interface{}
var strValue string
if path != "" {
value = fact.Value.Path(path).Data()
switch value.(type) {
case bool:
strValue = fmt.Sprintf("%v", value)
case string:
strValue = value.(string)
default:
strValue = fmt.Sprintf("%v", value)
}
if _, ok := (*totalArr)[fact.Name+"."+path]; ok {
if _, ok := (*totalArr)[fact.Name+"."+path][strValue]; ok {
(*totalArr)[fact.Name+"."+path][strValue] = (*totalArr)[fact.Name+"."+path][strValue] + 1
} else {
(*totalArr)[fact.Name+"."+path][strValue] = 1
}
} else {
(*totalArr)[fact.Name+"."+path] = map[string]int{
strValue: 1,
}
}
if nodes {
*arr = append(*arr, FactNodeGuageEntry{Name: fact.Name + "." + path, Environment: fact.Environment, Value: strValue, CertName: fact.CertName, Set: 1})
}
} else {
var value interface{}
var strValue string
value = fact.Value.Data()
switch value.(type) {
case bool:
strValue = fmt.Sprintf("%v", value)
case string:
strValue = value.(string)
default:
strValue = fmt.Sprintf("%v", value)
}
if _, ok := (*totalArr)[fact.Name]; ok {
if _, ok := (*totalArr)[fact.Name][strValue]; ok {
(*totalArr)[fact.Name][strValue] = (*totalArr)[fact.Name][strValue] + 1
} else {
(*totalArr)[fact.Name][strValue] = 1
}
} else {
(*totalArr)[fact.Name] = map[string]int{
strValue: 1,
}
}
if nodes {
*arr = append(*arr, FactNodeGuageEntry{Name: fact.Name, Environment: fact.Environment, Value: strValue, CertName: fact.CertName, Set: 1})
}
}
}
}
// setFactMetrics Resets the gauges and exports the given metrics
func setFactMetrics(factArr map[string]map[string]int, arrG [][]FactGuageEntry, arrG2 [][]FactNodeGuageEntry, nodes bool) {
factTotal.Reset()
factGuage.Reset()
factNodeGuage.Reset()
for key := range factArr {
for key2, value2 := range factArr[key] {
factTotal.WithLabelValues(key, key2).Set(float64(value2))
}
}
for _, arr := range arrG {
for _, nf := range arr {
factGuage.WithLabelValues(nf.Name, nf.Environment, nf.CertName).Set(nf.Set)
}
}
if nodes {
for _, arr := range arrG2 {
for _, nf := range arr {
factNodeGuage.WithLabelValues(nf.Name, nf.Environment, nf.CertName, nf.Value).Set(1)
}
}
}
}
// setBundleFactMetrics Resets the gauges and exports the given metrics
func setBundleFactMetrics(mapy map[string]FactBundleNodeGuageEntry, g *prometheus.GaugeVec) {
g.Reset()
for _, val := range mapy {
//"bundlename", "puppet_environment", "node"
sort.Slice(val.Values[:], func(i, j int) bool {
return val.Values[i].Name < val.Values[j].Name
})
arr := []string{val.Name, val.Environment, val.CertName}
for _, a := range val.Values {
arr = append(arr, a.Value)
}
g.WithLabelValues(arr...).Set(1.0)
}
}
// END FACT GATHERING METHODS
// START REPORTS GATHERING METHODS
// GenerateReportsMetrics Gathers puppetdb reports metrics and exports them to the exporter
func GenerateReportsMetrics(c *puppetdb.Client, nodes bool, debug bool, timeout int) {
if debug {
log.Println("Retrieving nodes.")
}
nodesArr, err := c.Nodes()
if err != nil {
log.Println(err)
}
if debug {
i := len(nodesArr)
log.Printf("Nodes collected found %d nodes", i)
log.Println("Ressting status and node metrics interfaces.")
}
// Reset nodes values
if debug {
log.Println("Done resetting the interfaces")
}
var statusArr map[string]map[string]int = map[string]map[string]int{}
var timeArr *[]ReportsMetricEntry = &[]ReportsMetricEntry{}
var eventArr *[]ReportsMetricEntry = &[]ReportsMetricEntry{}
var resourceArr *[]ReportsMetricEntry = &[]ReportsMetricEntry{}
var nodeStatusArr *[]NodeStatusEntry = &[]NodeStatusEntry{}
t1 := time.Now()
for _, node := range nodesArr {
// set the report time
addLastReportTimeMetric(node)
if node.ReportTimestamp != "" {
// eval time
layout := "2006-01-02T15:04:05.000Z"
t, err := time.Parse(layout, node.ReportTimestamp)
if err != nil {
log.Println(err.Error())
}
duration := time.Since(t)
timeout := float64(timeout)
// if timeout reached we do not parse this node
if duration.Seconds() > timeout {
setState(node, nodes, debug, int(timeout), &statusArr, nodeStatusArr)
// if node is okay we parse it
} else {
res, err := c.ReportByHash(node.LatestReportHash)
if debug {
log.Printf("Retrieving report for node: %s of environment: %s latest report hash is: %s latest report status is %s latest report time is %s", node.Certname, node.ReportEnvironment, node.LatestReportHash, node.LatestReportStatus, node.ReportTimestamp)
}
addGaugeMetricStatusString(res, nodes, node, statusArr, timeArr, eventArr, resourceArr, nodeStatusArr)
if err != nil {
log.Println(err)
}
}
} else {
setState(node, nodes, debug, int(timeout), &statusArr, nodeStatusArr)
}
}
if debug {
t2 := time.Now()
diff := t2.Sub(t1)
log.Println("Retrieving metrics took: " + diff.String())
//fmt.Println(diff)
}
statusTotal.Reset()
for key := range statusArr {
for key2, value2 := range statusArr[key] {
statusTotal.WithLabelValues(key2, key).Set(float64(value2))
}
}
resourcesNodeGuage.Reset()
t1 = time.Now()
for _, entry := range *resourceArr {
resourcesNodeGuage.WithLabelValues(entry.Name, entry.Environment, entry.Certname).Set(entry.Value)
}
if debug {
t2 := time.Now()
diff := t2.Sub(t1)
log.Println("Populating resource metrics took: " + diff.String())
}
eventNodeGuage.Reset()
for _, entry := range *timeArr {
eventNodeGuage.WithLabelValues(entry.Name, entry.Environment, entry.Certname).Set(entry.Value)
}
timeNodeGuage.Reset()
for _, entry := range *timeArr {
timeNodeGuage.WithLabelValues(entry.Name, entry.Environment, entry.Certname).Set(entry.Value)
}
statusNodesGuage.Reset()
for _, entry := range *nodeStatusArr {
if s, err := strconv.ParseFloat(entry.Value, 64); err == nil {
statusNodesGuage.WithLabelValues(entry.Status, entry.Environment, entry.Certname).Set(s)
}
}
}
// addGaugeMetricStatusString Fills in metrics for the reports and fills the status array
func addGaugeMetricStatusString(reports []puppetdb.ReportJSON, nodes bool, node puppetdb.NodeJSON,
statusArr map[string]map[string]int, timeArr *[]ReportsMetricEntry, eventArr *[]ReportsMetricEntry, resourceArr *[]ReportsMetricEntry,
nodeStatusArr *[]NodeStatusEntry) {
for _, report := range reports {
failed := 0.0
corChanges := 0.0
changes := 0.0
addLastReportStartTimeMetric(report, node)
addLastReportEndTimeMetric(report, node)
for _, metric := range report.Metrics.Data {
if metric.Category == "time" {
*timeArr = append(*timeArr, ReportsMetricEntry{metric.Name, report.Environment, report.CertName, metric.Value})
} else if metric.Category == "events" {
//eventNodeGuage.WithLabelValues(metric.Name, report.Environment, report.CertName).Set(metric.Value)
*eventArr = append(*timeArr, ReportsMetricEntry{metric.Name, report.Environment, report.CertName, metric.Value})
} else if metric.Category == "resources" {
//resourcesNodeGuage.WithLabelValues(metric.Name, report.Environment, report.CertName).Set(metric.Value)
*resourceArr = append(*timeArr, ReportsMetricEntry{metric.Name, report.Environment, report.CertName, metric.Value})
if metric.Name == "failed" {
failed = metric.Value
}
if metric.Name == "changed" {
changes = metric.Value
}
if metric.Name == "corrective_change" {
corChanges = metric.Value
}
}
}
stat := node.LatestReportStatus
if stat == "changed" {
if corChanges > 0.0 {
stat = "corrective_changes"
}
}
if _, ok := statusArr["All"]; ok {
if _, ok := statusArr["All"][stat]; ok {
statusArr["All"][stat] = statusArr["All"][stat] + 1
} else {
statusArr["All"][stat] = 1
}
} else {
statusArr["All"] = map[string]int{
stat: 1,
}
}
if _, ok := statusArr[node.ReportEnvironment]; ok {
if _, ok := statusArr[node.ReportEnvironment][stat]; ok {
statusArr[node.ReportEnvironment][stat] = statusArr[node.ReportEnvironment][stat] + 1
} else {
statusArr[node.ReportEnvironment][stat] = 1
}
} else {
statusArr[node.ReportEnvironment] = map[string]int{
stat: 1,
}
}
if nodes {
if node.LatestReportStatus == "unchanged" {
//statusNodesGuage.WithLabelValues(report.Status, "1", report.Environment, report.CertName).Inc()
*nodeStatusArr = append(*nodeStatusArr, NodeStatusEntry{report.Status, "1", report.Environment, report.CertName})
}
if node.LatestReportStatus == "failed" {
value := strconv.Itoa(int(failed))
*nodeStatusArr = append(*nodeStatusArr, NodeStatusEntry{report.Status, value, report.Environment, report.CertName})
//statusNodesGuage.WithLabelValues(report.Status, value, report.Environment, report.CertName).Inc()
}
if node.LatestReportStatus == "changed" {
if corChanges > 0 {
value := strconv.Itoa(int(corChanges))
*nodeStatusArr = append(*nodeStatusArr, NodeStatusEntry{"corrective_change", value, report.Environment, report.CertName})
//statusNodesGuage.WithLabelValues("corrective_change", value, report.Environment, report.CertName).Inc()
}
if changes > 0 {
value := strconv.Itoa(int(changes))
*nodeStatusArr = append(*nodeStatusArr, NodeStatusEntry{"changed", value, report.Environment, report.CertName})
//statusNodesGuage.WithLabelValues("changed", value, report.Environment, report.CertName).Inc()
}
}
}
}
}
func setState(node puppetdb.NodeJSON, nodes bool, debug bool, timeout int, statusArr *map[string]map[string]int, nodeStatusArr *[]NodeStatusEntry) {
if node.ReportTimestamp != "" {
// eval time
layout := "2006-01-02T15:04:05.000Z"
t, err := time.Parse(layout, node.ReportTimestamp)
if err != nil {
log.Println(err.Error())
}
duration := time.Since(t)
timeout2 := float64(timeout)
if duration.Seconds() > timeout2 {
if debug {
log.Printf("Node %s has reached the timeout and is in unresponsive state latest report was %s", node.Certname, node.ReportTimestamp)
}
timeoutString := strconv.Itoa(int(duration.Seconds()))
if nodes {
*nodeStatusArr = append(*nodeStatusArr, NodeStatusEntry{"unresponsive", timeoutString, node.ReportEnvironment, node.Certname})
//statusNodesGuage.WithLabelValues("unresponsive", timeoutString, node.ReportEnvironment, node.Certname).Inc()
}