1package main 2 3import ( 4 "github.com/prometheus/client_golang/prometheus" 5 "gopkg.in/yaml.v2" 6 "io/ioutil" 7 "log" 8 "regexp" 9 "strings" 10) 11 12var stringToValueType = map[string]prometheus.ValueType{ 13 "counter": prometheus.CounterValue, 14 "gauge": prometheus.GaugeValue, 15 "untyped": prometheus.UntypedValue, 16} 17 18type metricConfig struct { 19 Metrics map[string]*metric `yaml:"metrics"` 20 LabelMetrics map[string]*labelMetric `yaml:"label_metrics"` 21} 22 23type metric struct { 24 Help string `yaml:"help"` 25 Type prometheus.ValueType `yaml:"type"` 26} 27 28type labelMetric struct { 29 Help string `yaml:"help"` 30 Name string `yaml:"name"` 31 Labels []string `yaml:"labels"` 32 Type prometheus.ValueType `yaml:"type"` 33 Regex *regexp.Regexp 34} 35 36// Convert config to prom types 37func stringToPromType(s string) prometheus.ValueType { 38 valueType, ok := stringToValueType[strings.ToLower(s)] 39 if !ok { 40 log.Println("Invalid type:", s, "Assuming Gauge") 41 valueType = prometheus.GaugeValue 42 } 43 return valueType 44} 45 46// Serialize YAML into correct types 47func (m *metric) UnmarshalYAML(unmarshal func(interface{}) error) error { 48 var tmp struct { 49 Help string 50 Type string 51 } 52 53 err := unmarshal(&tmp) 54 if err != nil { 55 return err 56 } 57 m.Help = tmp.Help 58 m.Type = stringToPromType(tmp.Type) 59 return nil 60} 61 62func (m *labelMetric) UnmarshalYAML(unmarshal func(interface{}) error) error { 63 var tmp struct { 64 Name string 65 Help string 66 Type string 67 Labels []string 68 } 69 70 err := unmarshal(&tmp) 71 if err != nil { 72 return err 73 } 74 75 m.Name = tmp.Name 76 m.Help = tmp.Help 77 m.Labels = tmp.Labels 78 m.Type = stringToPromType(tmp.Type) 79 return nil 80} 81 82func loadConfig(path string, metricConf *metricConfig) error { 83 var b []byte 84 if path == "" { 85 var err error 86 b, err = Asset("config.yaml") 87 if err != nil { 88 return err 89 } 90 } else { 91 var err error 92 b, err = ioutil.ReadFile(*metricConfigPath) 93 if err != nil { 94 return err 95 } 96 } 97 err := yaml.Unmarshal(b, metricConf) 98 if err != nil { 99 return err 100 } 101 for k, v := range metricConf.LabelMetrics { 102 v.Regex, err = regexp.Compile(k) 103 if err != nil { 104 return err 105 } 106 } 107 return nil 108} 109