Debian Codegraph @

exporter/info_test.go

raw symbols SCIP
1 package exporter
2
3 import (
4 "fmt"
5 "net/http/httptest"
6 "os"
7 "reflect"
8 "regexp"
9 "strings"
10 "testing"
11
12 "github.com/prometheus/client_golang/prometheus"
13 log "github.com/sirupsen/logrus"
14 )
15
16 func TestKeyspaceStringParser(t *testing.T) {
17 tsts := []struct {
18 db string
19 stats string
20 keysTotal, keysEx, keysCached, avgTTL float64
21 ok bool
22 }{
23 {db: "xxx", stats: "", ok: false},
24 {db: "xxx", stats: "keys=1,expires=0,avg_ttl=0", ok: false},
25 {db: "db0", stats: "xxx", ok: false},
26 {db: "db1", stats: "keys=abcd,expires=0,avg_ttl=0", ok: false},
27 {db: "db2", stats: "keys=1234=1234,expires=0,avg_ttl=0", ok: false},
28
29 {db: "db3", stats: "keys=abcde,expires=0", ok: false},
30 {db: "db3", stats: "keys=213,expires=xxx", ok: false},
31 {db: "db3", stats: "keys=123,expires=0,avg_ttl=zzz", ok: false},
32 {db: "db3", stats: "keys=1,expires=0,avg_ttl=zzz,cached_keys=0", ok: false},
33 {db: "db3", stats: "keys=1,expires=0,avg_ttl=0,cached_keys=zzz", ok: false},
34 {db: "db3", stats: "keys=1,expires=0,avg_ttl=0,cached_keys=0,extra=0", keysTotal: 1, keysEx: 0, avgTTL: 0, keysCached: 0, ok: true},
35
36 {db: "db0", stats: "keys=1,expires=0,avg_ttl=0", keysTotal: 1, keysEx: 0, avgTTL: 0, keysCached: -1, ok: true},
37 {db: "db0", stats: "keys=1,expires=0,avg_ttl=0,cached_keys=0", keysTotal: 1, keysEx: 0, avgTTL: 0, keysCached: 0, ok: true},
38
39 {
40 db: "db0", stats: "keys=25714011,expires=25091314,avg_ttl=685620459,subexpiry=0",
41 keysTotal: 25714011, keysEx: 25091314, keysCached: 0, avgTTL: 685620.459000,
42 ok: true,
43 },
44 }
45
46 for _, tst := range tsts {
47 if kt, kx, ttl, kc, ok := parseDBKeyspaceString(tst.db, tst.stats); true {
48
49 if ok != tst.ok {
50 t.Errorf("failed for: db:%s stats:%s", tst.db, tst.stats)
51 continue
52 }
53
54 if ok && (kt != tst.keysTotal || kx != tst.keysEx || kc != tst.keysCached || ttl != tst.avgTTL) {
55 t.Errorf("values not matching, db:%s stats:%s %f != %f %f != %f %f != %f %f != %f",
56 tst.db, tst.stats,
57 kt, tst.keysTotal,
58 kx, tst.keysEx,
59 kc, tst.keysCached,
60 ttl, tst.avgTTL)
61 }
62 }
63 }
64 }
65
66 type slaveData struct {
67 k, v string
68 ip, state, port string
69 offset float64
70 lag float64
71 ok bool
72 }
73
74 func TestParseConnectedSlaveString(t *testing.T) {
75 tsts := []slaveData{
76 {k: "slave0", v: "ip=10.254.11.1,port=6379,state=online,offset=1751844676,lag=0", offset: 1751844676, ip: "10.254.11.1", port: "6379", state: "online", ok: true, lag: 0},
77 {k: "slave0", v: "ip=2a00:1450:400e:808::200e,port=6379,state=online,offset=1751844676,lag=0", offset: 1751844676, ip: "2a00:1450:400e:808::200e", port: "6379", state: "online", ok: true, lag: 0},
78 {k: "slave1", v: "offset=1,lag=0", offset: 1, ok: true},
79 {k: "slave1", v: "offset=1", offset: 1, ok: true, lag: -1},
80 {k: "slave2", v: "ip=1.2.3.4,state=online,offset=123,lag=42", offset: 123, ip: "1.2.3.4", state: "online", ok: true, lag: 42},
81
82 {k: "slave", v: "offset=1751844676,lag=0", ok: false},
83 {k: "slaveA", v: "offset=1751844676,lag=0", ok: false},
84 {k: "slave0", v: "offset=abc,lag=0", ok: false},
85 {k: "slave0", v: "offset=0,lag=abc", ok: false},
86 }
87
88 for _, tst := range tsts {
89 t.Run(fmt.Sprintf("%s---%s", tst.k, tst.v), func(t *testing.T) {
90 offset, ip, port, state, lag, ok := parseConnectedSlaveString(tst.k, tst.v)
91
92 if ok != tst.ok {
93 t.Errorf("failed for: db:%s stats:%s", tst.k, tst.v)
94 return
95 }
96 if offset != tst.offset || ip != tst.ip || port != tst.port || state != tst.state || lag != tst.lag {
97 t.Errorf("values not matching, string:%s %f %s %s %s %f", tst.v, offset, ip, port, state, lag)
98 }
99 })
100 }
101 }
102
103 func TestCommandStats(t *testing.T) {
104 defaultAddr := os.Getenv("TEST_REDIS_URI")
105 e := getTestExporterWithAddr(defaultAddr)
106 setupTestKeys(t, defaultAddr)
107
108 want := map[string]bool{"test_commands_duration_seconds_total": false, "test_commands_total": false}
109 commandStatsCheck(t, e, want)
110 deleteTestKeys(t, defaultAddr)
111
112 redisSixTwoAddr := os.Getenv("TEST_REDIS6_URI")
113 if redisSixTwoAddr != "" {
114 // Since Redis v6.2 we should expect extra failed calls and rejected calls
115 e = getTestExporterWithAddr(redisSixTwoAddr)
116 setupTestKeys(t, redisSixTwoAddr)
117
118 want = map[string]bool{"test_commands_duration_seconds_total": false, "test_commands_total": false, "commands_failed_calls_total": false, "commands_rejected_calls_total": false, "errors_total": false}
119 commandStatsCheck(t, e, want)
120 deleteTestKeys(t, redisSixTwoAddr)
121 }
122 }
123
124 func commandStatsCheck(t *testing.T, e *Exporter, want map[string]bool) {
125 chM := make(chan prometheus.Metric)
126 go func() {
127 e.Collect(chM)
128 close(chM)
129 }()
130
131 for m := range chM {
132 for k := range want {
133 if strings.Contains(m.Desc().String(), k) {
134 want[k] = true
135 }
136 }
137 }
138 for k, found := range want {
139 if !found {
140 t.Errorf("didn't find %s", k)
141 }
142 }
143 }
144
145 func TestInclMetricsForEmptyDatabases(t *testing.T) {
146 addr := os.Getenv("TEST_REDIS_URI")
147 if addr == "" {
148 t.Skipf("TEST_REDIS_URI not set - skipping")
149 }
150
151 for _, inclMetrics := range []bool{true, false} {
152 t.Run(fmt.Sprintf("inclMetrics:%t", inclMetrics), func(t *testing.T) {
153 e, _ := NewRedisExporter(addr,
154 Options{
155 Namespace: "test",
156 InclMetricsForEmptyDatabases: inclMetrics,
157 })
158 ts := httptest.NewServer(e)
159 defer ts.Close()
160
161 body := downloadURL(t, ts.URL+"/metrics")
162 if inclMetrics {
163 if !strings.Contains(body, `test_db_keys{db="db10"} 0`) {
164 t.Errorf("Expected to find test_db_keys")
165 }
166 } else {
167 if strings.Contains(body, `test_db_keys{db="db10"} 0`) {
168 t.Errorf("Expected to not find test_db_keys")
169 }
170 }
171 })
172 }
173 }
174
175 func TestClusterMaster(t *testing.T) {
176 if os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI") == "" {
177 t.Skipf("TEST_REDIS_CLUSTER_MASTER_URI not set - skipping")
178 }
179
180 addr := os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI")
181 e, _ := NewRedisExporter(addr, Options{Namespace: "test"})
182 ts := httptest.NewServer(e)
183 defer ts.Close()
184
185 body := downloadURL(t, ts.URL+"/metrics")
186 log.Debugf("master - body: %s", body)
187 for _, want := range []string{
188 "test_instance_info{",
189 "test_master_repl_offset",
190 } {
191 if !strings.Contains(body, want) {
192 t.Errorf("Did not find key [%s] \nbody: %s", want, body)
193 }
194 }
195 }
196
197 func TestClusterSkipCheckKeysIfMaster(t *testing.T) {
198 uriMaster := os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI")
199 uriSlave := os.Getenv("TEST_REDIS_CLUSTER_SLAVE_URI")
200 if uriMaster == "" || uriSlave == "" {
201 t.Skipf("TEST_REDIS_CLUSTER_MASTER_URI or slave not set - skipping")
202 }
203
204 setupTestKeysCluster(t, uriMaster)
205 defer deleteTestKeysCluster(t, uriMaster)
206
207 for _, uri := range []string{uriMaster, uriSlave} {
208 for _, skip := range []bool{true, false} {
209 e, _ := NewRedisExporter(
210 uri,
211 Options{Namespace: "test",
212 CheckKeys: TestKeyNameHll,
213 SkipCheckKeysForRoleMaster: skip,
214 IsCluster: true,
215 })
216 ts := httptest.NewServer(e)
217
218 body := downloadURL(t, ts.URL+"/metrics")
219
220 expectedMetricPresent := true
221 if skip && uri == uriMaster {
222 expectedMetricPresent = false
223 }
224 t.Logf("skip: %#v uri: %s uri == uriMaster: %#v", skip, uri, uri == uriMaster)
225 t.Logf("expectedMetricPresent: %#v", expectedMetricPresent)
226
227 want := `test_key_size{db="db0",key="test-hll"} 3`
228
229 if expectedMetricPresent {
230 if !strings.Contains(body, want) {
231 t.Fatalf("expectedMetricPresent but missing. metric: %s body: %s\n", want, body)
232 }
233 } else {
234 if strings.Contains(body, want) {
235 t.Fatalf("should have skipped it but found it, body:\n%s", body)
236 }
237 }
238
239 ts.Close()
240 }
241 }
242 }
243
244 func TestClusterSlave(t *testing.T) {
245 if os.Getenv("TEST_REDIS_CLUSTER_SLAVE_URI") == "" {
246 t.Skipf("TEST_REDIS_CLUSTER_SLAVE_URI not set - skipping")
247 }
248
249 addr := os.Getenv("TEST_REDIS_CLUSTER_SLAVE_URI")
250 e, _ := NewRedisExporter(addr, Options{Namespace: "test"})
251 ts := httptest.NewServer(e)
252 defer ts.Close()
253
254 body := downloadURL(t, ts.URL+"/metrics")
255 log.Debugf("slave - body: %s", body)
256 for _, want := range []string{
257 "test_instance_info",
258 "test_master_last_io_seconds",
259 "test_slave_info",
260 } {
261 if !strings.Contains(body, want) {
262 t.Errorf("Did not find key [%s] \nbody: %s", want, body)
263 }
264 }
265 hostReg, _ := regexp.Compile(`master_host="([0,1]?\d{1,2}|2([0-4][0-9]|5[0-5]))(\.([0,1]?\d{1,2}|2([0-4][0-9]|5[0-5]))){3}"`)
266 masterHost := hostReg.FindString(body)
267 portReg, _ := regexp.Compile(`master_port="(\d+)"`)
268 masterPort := portReg.FindString(body)
269 for wantedKey, wantedVal := range map[string]int{
270 masterHost: 5,
271 masterPort: 5,
272 } {
273 if res := strings.Count(body, wantedKey); res != wantedVal {
274 t.Errorf("Result: %s -> %d, Wanted: %d \nbody: %s", wantedKey, res, wantedVal, body)
275 }
276 }
277 }
278
279 func TestParseCommandStats(t *testing.T) {
280
281 for _, tst := range []struct {
282 fieldKey string
283 fieldValue string
284
285 wantSuccess bool
286 wantExtraStats bool
287 wantCmd string
288 wantCalls float64
289 wantRejectedCalls float64
290 wantFailedCalls float64
291 wantUsecTotal float64
292 }{
293 {
294 fieldKey: "cmdstat_get",
295 fieldValue: "calls=21,usec=175,usec_per_call=8.33",
296 wantSuccess: true,
297 wantCmd: "get",
298 wantCalls: 21,
299 wantUsecTotal: 175,
300 },
301 {
302 fieldKey: "cmdstat_georadius_ro",
303 fieldValue: "calls=75,usec=1260,usec_per_call=16.80",
304 wantSuccess: true,
305 wantCmd: "georadius_ro",
306 wantCalls: 75,
307 wantUsecTotal: 1260,
308 },
309 {
310 fieldKey: "borked_stats",
311 fieldValue: "calls=75,usec=1260,usec_per_call=16.80",
312 wantSuccess: false,
313 },
314 {
315 fieldKey: "cmdstat_georadius_ro",
316 fieldValue: "borked_values",
317 wantSuccess: false,
318 },
319
320 {
321 fieldKey: "cmdstat_georadius_ro",
322 fieldValue: "usec_per_call=16.80",
323 wantSuccess: false,
324 },
325 {
326 fieldKey: "cmdstat_georadius_ro",
327 fieldValue: "calls=ABC,usec=1260,usec_per_call=16.80",
328 wantSuccess: false,
329 },
330 {
331 fieldKey: "cmdstat_georadius_ro",
332 fieldValue: "calls=75,usec=DEF,usec_per_call=16.80",
333 wantSuccess: false,
334 },
335 {
336 fieldKey: "cmdstat_georadius_ro",
337 fieldValue: "calls=75,usec=1024,usec_per_call=16.80,rejected_calls=5,failed_calls=10",
338 wantCmd: "georadius_ro",
339 wantCalls: 75,
340 wantUsecTotal: 1024,
341 wantSuccess: true,
342 wantExtraStats: true,
343 wantFailedCalls: 10,
344 wantRejectedCalls: 5,
345 },
346 {
347 fieldKey: "cmdstat_georadius_ro",
348 fieldValue: "calls=75,usec=1024,usec_per_call=16.80,rejected_calls=ABC,failed_calls=10",
349 wantSuccess: false,
350 },
351 {
352 fieldKey: "cmdstat_georadius_ro",
353 fieldValue: "calls=75,usec=1024,usec_per_call=16.80,rejected_calls=5,failed_calls=ABC",
354 wantSuccess: false,
355 },
356 } {
357 t.Run(tst.fieldKey+tst.fieldValue, func(t *testing.T) {
358
359 cmd, calls, rejectedCalls, failedCalls, usecTotal, _, err := parseMetricsCommandStats(tst.fieldKey, tst.fieldValue)
360
361 if tst.wantSuccess && err != nil {
362 t.Fatalf("err: %s", err)
363 return
364 }
365
366 if !tst.wantSuccess && err == nil {
367 t.Fatalf("expected err!")
368 return
369 }
370
371 if !tst.wantSuccess {
372 return
373 }
374
375 if cmd != tst.wantCmd {
376 t.Fatalf("cmd not matching, got: %s, wanted: %s", cmd, tst.wantCmd)
377 }
378
379 if calls != tst.wantCalls {
380 t.Fatalf("cmd not matching, got: %f, wanted: %f", calls, tst.wantCalls)
381 }
382 if rejectedCalls != tst.wantRejectedCalls {
383 t.Fatalf("cmd not matching, got: %f, wanted: %f", rejectedCalls, tst.wantRejectedCalls)
384 }
385 if failedCalls != tst.wantFailedCalls {
386 t.Fatalf("cmd not matching, got: %f, wanted: %f", failedCalls, tst.wantFailedCalls)
387 }
388 if usecTotal != tst.wantUsecTotal {
389 t.Fatalf("cmd not matching, got: %f, wanted: %f", usecTotal, tst.wantUsecTotal)
390 }
391 })
392 }
393
394 }
395
396 func TestParseErrorStats(t *testing.T) {
397
398 for _, tst := range []struct {
399 fieldKey string
400 fieldValue string
401
402 wantSuccess bool
403 wantErrorPrefix string
404 wantCount float64
405 }{
406 {
407 fieldKey: "errorstat_ERR",
408 fieldValue: "count=4",
409 wantSuccess: true,
410 wantErrorPrefix: "ERR",
411 wantCount: 4,
412 },
413 {
414 fieldKey: "borked_stats",
415 fieldValue: "count=4",
416 wantSuccess: false,
417 },
418 {
419 fieldKey: "errorstat_ERR",
420 fieldValue: "borked_values",
421 wantSuccess: false,
422 },
423
424 {
425 fieldKey: "errorstat_ERR",
426 fieldValue: "count=ABC",
427 wantSuccess: false,
428 },
429 } {
430 t.Run(tst.fieldKey+tst.fieldValue, func(t *testing.T) {
431
432 errorPrefix, count, err := parseMetricsErrorStats(tst.fieldKey, tst.fieldValue)
433
434 if tst.wantSuccess && err != nil {
435 t.Fatalf("err: %s", err)
436 return
437 }
438
439 if !tst.wantSuccess && err == nil {
440 t.Fatalf("expected err!")
441 return
442 }
443
444 if !tst.wantSuccess {
445 return
446 }
447
448 if errorPrefix != tst.wantErrorPrefix {
449 t.Fatalf("cmd not matching, got: %s, wanted: %s", errorPrefix, tst.wantErrorPrefix)
450 }
451
452 if count != tst.wantCount {
453 t.Fatalf("cmd not matching, got: %f, wanted: %f", count, tst.wantCount)
454 }
455 })
456 }
457
458 }
459
460 func Test_parseMetricsLatencyStats(t *testing.T) {
461 type args struct {
462 fieldKey string
463 fieldValue string
464 }
465 tests := []struct {
466 name string
467 args args
468 wantCmd string
469 wantPercentileMap map[float64]float64
470 wantErr bool
471 }{
472 {
473 name: "simple",
474 args: args{fieldKey: "latency_percentiles_usec_ping", fieldValue: "p50=0.001,p99=1.003,p99.9=3.007"},
475 wantCmd: "ping",
476 wantPercentileMap: map[float64]float64{50.0: 0.001, 99.0: 1.003, 99.9: 3.007},
477 wantErr: false,
478 },
479 {
480 name: "single-percentile",
481 args: args{fieldKey: "latency_percentiles_usec_ping", fieldValue: "p50=0.001"},
482 wantCmd: "ping",
483 wantPercentileMap: map[float64]float64{50.0: 0.001},
484 wantErr: false,
485 },
486 {
487 name: "empty",
488 args: args{fieldKey: "latency_percentiles_usec_ping", fieldValue: ""},
489 wantCmd: "ping",
490 wantPercentileMap: map[float64]float64{0: 0},
491 wantErr: false,
492 },
493 {
494 name: "invalid-percentile",
495 args: args{fieldKey: "latency_percentiles_usec_ping", fieldValue: "p50=a"},
496 wantCmd: "ping",
497 wantPercentileMap: map[float64]float64{},
498 wantErr: true,
499 },
500 {
501 name: "invalid prefix",
502 args: args{fieldKey: "wrong_prefix_", fieldValue: "p50=0.001,p99=1.003,p99.9=3.007"},
503 wantCmd: "",
504 wantPercentileMap: map[float64]float64{},
505 wantErr: true,
506 },
507 {
508 name: "empty-percentile-key",
509 args: args{fieldKey: "latency_percentiles_usec_ping", fieldValue: "=1.0,p99=2.0"},
510 wantCmd: "ping",
511 wantPercentileMap: map[float64]float64{},
512 wantErr: true,
513 },
514 }
515 for _, tt := range tests {
516 t.Run(tt.name, func(t *testing.T) {
517 gotCmd, gotPercentileMap, err := parseMetricsLatencyStats(tt.args.fieldKey, tt.args.fieldValue)
518 if (err != nil) != tt.wantErr {
519 t.Errorf("test %s. parseMetricsLatencyStats() error = %v, wantErr %v", tt.name, err, tt.wantErr)
520 return
521 }
522 if gotCmd != tt.wantCmd {
523 t.Errorf("parseMetricsLatencyStats() gotCmd = %v, want %v", gotCmd, tt.wantCmd)
524 }
525 if !reflect.DeepEqual(gotPercentileMap, tt.wantPercentileMap) {
526 t.Errorf("parseMetricsLatencyStats() gotPercentileMap = %v, want %v", gotPercentileMap, tt.wantPercentileMap)
527 }
528 })
529 }
530 }