summaryrefslogtreecommitdiff
path: root/service/metrics/config.go
blob: c2f8520198317a7b6f7603b6622da3cc2f5e5d51 (plain)
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
package metrics

import (
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/spiral/roadrunner/service"
)

// Config configures metrics service.
type Config struct {
	// Address to listen
	Address string

	// Collect define application specific metrics.
	Collect map[string]Collector
}

// Collector describes single application specific metric.
type Collector struct {
	// Namespace of the metric.
	Namespace string

	// Subsystem of the metric.
	Subsystem string

	// Collector type (histogram, gauge, counter, summary).
	Type string

	// Help of collector.
	Help string

	// Labels for vectorized metrics.
	Labels []string

	// Buckets for histogram metric.
	Buckets []float64
}

// Hydrate configuration.
func (c *Config) Hydrate(cfg service.Config) error {
	return cfg.Unmarshal(c)
}

// register application specific metrics.
func (c *Config) getCollectors() (map[string]prometheus.Collector, error) {
	if c.Collect == nil {
		return nil, nil
	}

	collectors := make(map[string]prometheus.Collector)

	for name, m := range c.Collect {
		var collector prometheus.Collector
		switch m.Type {
		case "histogram":
			opts := prometheus.HistogramOpts{
				Name:      name,
				Namespace: m.Namespace,
				Subsystem: m.Subsystem,
				Help:      m.Help,
				Buckets:   m.Buckets,
			}

			if len(m.Labels) != 0 {
				collector = prometheus.NewHistogramVec(opts, m.Labels)
			} else {
				collector = prometheus.NewHistogram(opts)
			}
		case "gauge":
			opts := prometheus.GaugeOpts{
				Name:      name,
				Namespace: m.Namespace,
				Subsystem: m.Subsystem,
				Help:      m.Help,
			}

			if len(m.Labels) != 0 {
				collector = prometheus.NewGaugeVec(opts, m.Labels)
			} else {
				collector = prometheus.NewGauge(opts)
			}
		case "counter":
			opts := prometheus.CounterOpts{
				Name:      name,
				Namespace: m.Namespace,
				Subsystem: m.Subsystem,
				Help:      m.Help,
			}

			if len(m.Labels) != 0 {
				collector = prometheus.NewCounterVec(opts, m.Labels)
			} else {
				collector = prometheus.NewCounter(opts)
			}
		case "summary":
			opts := prometheus.SummaryOpts{
				Name:      name,
				Namespace: m.Namespace,
				Subsystem: m.Subsystem,
				Help:      m.Help,
			}

			if len(m.Labels) != 0 {
				collector = prometheus.NewSummaryVec(opts, m.Labels)
			} else {
				collector = prometheus.NewSummary(opts)
			}
		default:
			return nil, fmt.Errorf("invalid metric type `%s` for `%s`", m.Type, name)
		}

		collectors[name] = collector
	}

	return collectors, nil
}