forked from flashcatcloud/categraf
/
instances.go
382 lines (319 loc) · 8.75 KB
/
instances.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
package cadvisor
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
dto "github.com/prometheus/client_model/go"
"flashcat.cloud/categraf/config"
"flashcat.cloud/categraf/pkg/cache"
"flashcat.cloud/categraf/pkg/filter"
"flashcat.cloud/categraf/pkg/kubernetes"
util "flashcat.cloud/categraf/pkg/metrics"
"flashcat.cloud/categraf/pkg/tls"
"flashcat.cloud/categraf/types"
)
const (
acceptHeader = `application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.7,text/plain;version=0.0.4;q=0.3,*/*;q=0.1`
cadvisorPath = "/metrics/cadvisor"
)
const (
ContainerType CadvisorType = "cadvisor"
NodeType CadvisorType = "kubelet"
)
type (
CadvisorType string
Instance struct {
config.InstanceConfig
URL string `toml:"url"`
Type CadvisorType `toml:"type"`
u *url.URL
NamePrefix string `toml:"name_prefix"`
BearerTokenString string `toml:"bearer_token_string"`
BearerTokeFile string `toml:"bearer_token_file"`
Username string `toml:"username"`
Password string `toml:"password"`
Timeout config.Duration `toml:"timeout"`
IgnoreMetrics []string `toml:"ignore_metrics"`
IgnoreLabelKeys []string `toml:"ignore_label_keys"`
Headers []string `toml:"headers"`
ChooseLabelKeys []string `toml:"choose_label_keys"`
config.UrlLabel
ignoreMetricsFilter filter.Filter
ignoreLabelKeysFilter filter.Filter
chooseLabelKeysFilter filter.Filter
tls.ClientConfig
client *http.Client
*cache.BasicCache
stop chan struct{}
}
)
func (ins *Instance) Empty() bool {
if len(ins.URL) > 0 {
return false
}
return true
}
func (ins *Instance) Init() error {
if ins.Empty() {
return types.ErrInstancesEmpty
}
ins.URL = strings.Replace(ins.URL, "$hostname", config.Config.GetHostname(), -1)
ins.URL = strings.Replace(ins.URL, "$ip", config.Config.Global.IP, -1)
ins.URL = os.Expand(ins.URL, config.GetEnv)
u, err := url.Parse(ins.URL)
if err != nil {
return fmt.Errorf("failed to parse scrape url: %s, error: %s", ins.URL, err)
}
ins.u = u
if ins.u.Path == "" {
ins.u.Path = cadvisorPath
ins.Type = NodeType
}
ins.stop = make(chan struct{})
ins.BasicCache = cache.NewBasicCache()
go ins.cache()
if ins.Timeout <= 0 {
ins.Timeout = config.Duration(time.Second * 3)
}
client, err := ins.createHTTPClient()
if err != nil {
return err
} else {
ins.client = client
}
if len(ins.IgnoreMetrics) > 0 {
ins.ignoreMetricsFilter, err = filter.Compile(ins.IgnoreMetrics)
if err != nil {
return err
}
}
if len(ins.IgnoreLabelKeys) > 0 {
ins.ignoreLabelKeysFilter, err = filter.Compile(ins.IgnoreLabelKeys)
if err != nil {
return err
}
}
if len(ins.ChooseLabelKeys) > 0 {
ins.chooseLabelKeysFilter, err = filter.Compile(ins.ChooseLabelKeys)
if err != nil {
return err
}
}
if err := ins.PrepareUrlTemplate(); err != nil {
return err
}
return nil
}
func (ins *Instance) cache() {
if ins.Type == ContainerType {
return
}
podUrl := *ins.u
podUrl.Path = "/pods"
req, err := http.NewRequest("GET", podUrl.String(), nil)
if err != nil {
log.Println("E! failed to new request for url:", podUrl.String(), "error:", err)
return
}
ins.setHeaders(req)
timer := time.NewTimer(0 * time.Second)
defer timer.Stop()
for {
select {
case <-timer.C:
resp, err := ins.client.Do(req)
if err != nil {
log.Println("E! failed to request for url:", podUrl.String(), "error:", err)
continue
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("E! failed to read body for url:", podUrl.String(), "error:", err)
continue
}
resp.Body.Close()
pods := kubernetes.PodList{}
err = json.Unmarshal(body, &pods)
if err != nil {
log.Println("E! unmarshal pods info", err)
continue
}
for _, pod := range pods.Items {
ins.BasicCache.Add(cacheKey(pod.Metadata.Namespace, pod.Metadata.Name), pod)
}
timer.Reset(1 * time.Minute)
case <-ins.stop:
return
}
}
}
func cacheKey(ns, pod string) string {
return ns + "||" + pod
}
func (ins *Instance) Drop() {
log.Println("I! cadvisor instance stop")
close(ins.stop)
}
func (ins *Instance) createHTTPClient() (*http.Client, error) {
trans := &http.Transport{}
if ins.UseTLS {
tlsConfig, err := ins.ClientConfig.TLSConfig()
if err != nil {
return nil, err
}
trans.TLSClientConfig = tlsConfig
}
client := &http.Client{
Transport: trans,
Timeout: time.Duration(ins.Timeout),
}
return client, nil
}
func (ins *Instance) Gather(slist *types.SampleList) {
req, err := http.NewRequest("GET", ins.u.String(), nil)
if err != nil {
log.Println("E! failed to new request for url:", ins.u.String(), "error:", err)
return
}
ins.setHeaders(req)
labels := map[string]string{}
urlKey, urlVal, err := ins.GenerateLabel(ins.u)
if err != nil {
log.Println("E! failed to generate url label value:", err)
return
}
labels[urlKey] = urlVal
res, err := ins.client.Do(req)
if err != nil {
slist.PushFront(types.NewSample("", "up", 0, labels))
log.Println("E! failed to query url:", ins.u.String(), "error:", err)
return
}
if res.StatusCode != http.StatusOK {
slist.PushFront(types.NewSample("", "up", 0, labels))
log.Println("E! failed to query url:", ins.u.String(), "status code:", res.StatusCode)
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
slist.PushFront(types.NewSample("", "up", 0, labels))
log.Println("E! failed to read response body, url:", ins.u.String(), "error:", err)
return
}
slist.PushFront(types.NewSample("", "up", 1, labels))
ins.gather(body, res.Header, labels, slist)
}
func (ins *Instance) gather(buf []byte, header http.Header, defaultLabels map[string]string, slist *types.SampleList) {
metricFamilies, err := util.Parse(buf, header)
if err != nil {
log.Println("E! failed to parse metrics, url:", ins.u.String(), "error:", err)
return
}
for metricName, mf := range metricFamilies {
if ins.ignoreMetricsFilter != nil && ins.ignoreMetricsFilter.Match(metricName) {
continue
}
for _, m := range mf.Metric {
// reading tags
tags := ins.makeLabels(m, defaultLabels)
if mf.GetType() == dto.MetricType_SUMMARY {
util.HandleSummary(ins.NamePrefix, m, tags, metricName, nil, slist)
} else if mf.GetType() == dto.MetricType_HISTOGRAM {
util.HandleHistogram(ins.NamePrefix, m, tags, metricName, nil, slist)
} else {
util.HandleGaugeCounter(ins.NamePrefix, m, tags, metricName, nil, slist)
}
}
}
}
func (ins *Instance) ignoreLabel(label string) bool {
if ins.chooseLabelKeysFilter != nil {
if ins.chooseLabelKeysFilter.Match(label) {
return false
} else {
return true
}
}
if ins.ignoreLabelKeysFilter != nil && ins.ignoreLabelKeysFilter.Match(label) {
return true
}
return false
}
func (ins *Instance) makeLabels(m *dto.Metric, defaultLabels map[string]string) map[string]string {
var (
podName, namespace string
result = map[string]string{}
)
for _, label := range m.Label {
if ins.ignoreLabel(label.GetName()) {
continue
}
result[label.GetName()] = label.GetValue()
if ins.Type == NodeType {
if label.GetName() != "pod" && label.GetName() != "namespace" {
continue
}
if label.GetName() == "pod" {
podName = label.GetValue()
}
if label.GetName() == "namespace" {
namespace = label.GetValue()
}
if strings.TrimSpace(podName) == "" || strings.TrimSpace(namespace) == "" {
continue
}
if val, ok := ins.BasicCache.Get(cacheKey(namespace, podName)); ok {
if pod, ok := val.(*kubernetes.Pod); ok {
for k, v := range pod.Metadata.Labels {
if ins.ignoreLabel(k) {
continue
}
result[k] = v
}
for k, v := range pod.Metadata.Annotations {
if ins.ignoreLabel(k) {
continue
}
result[k] = v
}
}
} else {
if config.Config.DebugMode {
log.Println(cacheKey(namespace, podName), "not in cache")
}
}
}
}
for key, value := range defaultLabels {
result[key] = value
}
return result
}
func (ins *Instance) setHeaders(req *http.Request) {
if ins.Username != "" && ins.Password != "" {
req.SetBasicAuth(ins.Username, ins.Password)
}
if ins.BearerTokeFile != "" {
content, err := os.ReadFile(ins.BearerTokeFile)
if err != nil {
log.Println("E! failed to read bearer token file:", ins.BearerTokeFile, "error:", err)
return
}
ins.BearerTokenString = strings.TrimSpace(string(content))
}
if ins.BearerTokenString != "" {
req.Header.Set("Authorization", "Bearer "+ins.BearerTokenString)
}
req.Header.Set("Accept", acceptHeader)
for i := 0; i < len(ins.Headers); i += 2 {
req.Header.Set(ins.Headers[i], ins.Headers[i+1])
}
}