/
etcd.go
185 lines (147 loc) · 3.85 KB
/
etcd.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
package collector
import (
"context"
_ "embed"
"fmt"
"strings"
"time"
"github.com/giantswarm/microerror"
"github.com/giantswarm/micrologger"
"github.com/prometheus/client_golang/prometheus"
"go.etcd.io/etcd/clientv3"
)
var (
k8sResourcesDesc = prometheus.NewDesc(
prometheus.BuildFQName(MetricsNamespace, "resources", "count"),
"Count of kubernetes resources stored in etcd.",
[]string{
"namespace",
"kind",
},
nil,
)
)
type EtcdConfig struct {
Logger micrologger.Logger
EtcdClientConfig *clientv3.Config
EtcdPrefix string
}
type Etcd struct {
logger micrologger.Logger
cache []cacheEntry
etcdClientConfig *clientv3.Config
etcdPrefix string
}
type cacheEntry struct {
count float64
kind string
namespace string
}
// NewEtcd exposes metrics about the number of k8s resources stored in etcd.
func NewEtcd(config EtcdConfig) (*Etcd, error) {
if config.Logger == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
}
if config.EtcdClientConfig == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.EtcdClientConfig must not be empty", config)
}
if !strings.HasSuffix(config.EtcdPrefix, "/") || !strings.HasPrefix(config.EtcdPrefix, "/") {
return nil, microerror.Maskf(invalidConfigError, "%T.EtcdPrefix has to start and end with a '/'", config)
}
d := &Etcd{
logger: config.Logger,
cache: make([]cacheEntry, 0),
etcdClientConfig: config.EtcdClientConfig,
etcdPrefix: config.EtcdPrefix,
}
go func() {
for {
err := d.refreshCache()
if err != nil {
d.logger.Errorf(context.Background(), err, "Error refreshing cache")
}
time.Sleep(30 * time.Second)
}
}()
return d, nil
}
func (d *Etcd) Collect(ch chan<- prometheus.Metric) error {
for _, entry := range d.cache {
ch <- prometheus.MustNewConstMetric(
k8sResourcesDesc,
prometheus.GaugeValue,
entry.count,
entry.namespace,
entry.kind,
)
}
return nil
}
func (d *Etcd) Describe(ch chan<- *prometheus.Desc) error {
ch <- k8sResourcesDesc
return nil
}
func (d *Etcd) refreshCache() error {
grouped := map[string]map[string]int64{}
newCache := make([]cacheEntry, 0)
cli, err := clientv3.New(*d.etcdClientConfig)
if err != nil {
return microerror.Mask(err)
}
defer cli.Close()
resp, err := cli.Get(context.Background(), "/", clientv3.WithPrefix(), clientv3.WithKeysOnly())
if err != nil {
return microerror.Mask(err)
}
for _, kv := range resp.Kvs {
line := string(kv.Key)
line = strings.TrimPrefix(line, d.etcdPrefix)
namespace, kind, err := parseLine(line)
if IsEmptyLine(err) {
continue
} else if err != nil {
d.logger.Debugf(context.Background(), "Error parsing line %q: %s", line, err)
continue
}
if _, found := grouped[kind]; !found {
grouped[kind] = make(map[string]int64)
}
grouped[kind][namespace] = grouped[kind][namespace] + 1
}
for kind, namespacedCount := range grouped {
for namespace, count := range namespacedCount {
newCache = append(newCache, cacheEntry{
count: float64(count),
kind: kind,
namespace: namespace,
})
}
}
d.cache = newCache
return nil
}
func parseLine(line string) (namespace string, kind string, err error) {
err = nil
// Strip etcd prefix
line = strings.TrimRight(line, "\n")
if line == "" {
err = microerror.Maskf(emptyLineError, "Line was empty")
return
}
// cert-manager.io/clusterissuers/letsencrypt-giantswarm
tokens := strings.Split(line, "/")
namespace = "Not namespaced"
kind = tokens[0]
if strings.Contains(tokens[0], ".") {
// the first token contains a dot, we consider this an api version of non namespaced objects.
kind = fmt.Sprintf("%s.%s", tokens[1], tokens[0])
if len(tokens) > 3 {
namespace = tokens[2]
}
return
}
if len(tokens) > 2 {
namespace = tokens[1]
}
return
}