/
lokistack.go
96 lines (79 loc) · 2.3 KB
/
lokistack.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
package metrics
import (
"context"
"github.com/go-logr/logr"
"github.com/prometheus/client_golang/prometheus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
lokiv1 "github.com/grafana/loki/operator/apis/loki/v1"
)
const (
metricsPrefix = "lokistack_"
)
var (
metricsCommonLabels = []string{
"stack_namespace",
"stack_name",
"size",
}
lokiStackInfoDesc = prometheus.NewDesc(
metricsPrefix+"info",
"Information about deployed LokiStack instances. Value is always 1.",
metricsCommonLabels, nil,
)
lokiStackConditionsCountDesc = prometheus.NewDesc(
metricsPrefix+"status_condition",
"Counts the current status conditions of the LokiStack.",
append(metricsCommonLabels, "condition", "reason", "status"), nil,
)
)
func RegisterLokiStackCollector(log logr.Logger, k8sClient client.Client, registry prometheus.Registerer) error {
metrics := &lokiStackCollector{
log: log,
k8sClient: k8sClient,
}
return registry.Register(metrics)
}
type lokiStackCollector struct {
log logr.Logger
k8sClient client.Client
}
func (l *lokiStackCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- lokiStackInfoDesc
ch <- lokiStackConditionsCountDesc
}
func (l *lokiStackCollector) Collect(m chan<- prometheus.Metric) {
ctx := context.TODO()
stackList := &lokiv1.LokiStackList{}
err := l.k8sClient.List(ctx, stackList)
if err != nil {
l.log.Error(err, "failed to get list of LokiStacks for metrics")
return
}
for _, stack := range stackList.Items {
labels := []string{
stack.Namespace,
stack.Name,
string(stack.Spec.Size),
}
m <- prometheus.MustNewConstMetric(lokiStackInfoDesc, prometheus.GaugeValue, 1.0, labels...)
for _, c := range stack.Status.Conditions {
activeValue := 0.0
if c.Status == metav1.ConditionTrue {
activeValue = 1.0
}
// This mirrors the behavior of kube_state_metrics, which creates two metrics for each condition,
// one for each status (true/false).
m <- prometheus.MustNewConstMetric(
lokiStackConditionsCountDesc,
prometheus.GaugeValue, activeValue,
append(labels, c.Type, c.Reason, "true")...,
)
m <- prometheus.MustNewConstMetric(
lokiStackConditionsCountDesc,
prometheus.GaugeValue, 1.0-activeValue,
append(labels, c.Type, c.Reason, "false")...,
)
}
}
}