| 1 | package exporter |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/http/httptest" |
| 6 | "net/url" |
| 7 | "os" |
| 8 | "reflect" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/gomodule/redigo/redis" |
| 14 | "github.com/prometheus/client_golang/prometheus" |
| 15 | log "github.com/sirupsen/logrus" |
| 16 | ) |
| 17 | |
| 18 | // defaultCount is used for `SCAN whatever COUNT defaultCount` command |
| 19 | const ( |
| 20 | defaultCount int64 = 10 |
| 21 | invalidCount int64 = 0 |
| 22 | ) |
| 23 | |
| 24 | func TestKeyValuesAndSizes(t *testing.T) { |
| 25 | e, _ := NewRedisExporter( |
| 26 | os.Getenv("TEST_REDIS_URI"), |
| 27 | Options{ |
| 28 | Namespace: "test", |
| 29 | CheckSingleKeys: dbNumStrFull + "=" + url.QueryEscape(testKeys[0]), |
| 30 | }, |
| 31 | ) |
| 32 | ts := httptest.NewServer(e) |
| 33 | defer ts.Close() |
| 34 | |
| 35 | setupTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 36 | defer deleteTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 37 | |
| 38 | body := downloadURL(t, ts.URL+"/metrics") |
| 39 | for _, want := range []string{ |
| 40 | "test_key_size", |
| 41 | "test_key_value", |
| 42 | } { |
| 43 | if !strings.Contains(body, want) { |
| 44 | t.Fatalf("didn't find %s, body: %s", want, body) |
| 45 | return |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | func TestKeyValuesAsLabel(t *testing.T) { |
| 51 | setupTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 52 | defer deleteTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 53 | |
| 54 | for _, exc := range []bool{true, false} { |
| 55 | e, _ := NewRedisExporter( |
| 56 | os.Getenv("TEST_REDIS_URI"), |
| 57 | Options{ |
| 58 | Namespace: "test", |
| 59 | CheckSingleKeys: dbNumStrFull + "=" + url.QueryEscape(TestKeyNameSingleString), |
| 60 | DisableExportingKeyValues: exc, |
| 61 | }, |
| 62 | ) |
| 63 | ts := httptest.NewServer(e) |
| 64 | |
| 65 | body := downloadURL(t, ts.URL+"/metrics") |
| 66 | for _, match := range []string{ |
| 67 | "key_value_as_string", |
| 68 | "test_key_value", |
| 69 | } { |
| 70 | if exc && strings.Contains(body, match) { |
| 71 | t.Fatalf("didn't expect %s with DisableExportingKeyValues enabled, body: %s", match, body) |
| 72 | } else if !exc && !strings.Contains(body, match) { |
| 73 | t.Fatalf("didn't find %s with DisableExportingKeyValues disabled, body: %s", match, body) |
| 74 | } |
| 75 | } |
| 76 | ts.Close() |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | func TestClusterKeyValuesAndSizes(t *testing.T) { |
| 81 | clusterUri := os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI") |
| 82 | if clusterUri == "" { |
| 83 | t.Skipf("Skipping TestClusterKeyValuesAndSizes, don't have env var TEST_REDIS_CLUSTER_MASTER_URI") |
| 84 | } |
| 85 | setupTestKeysCluster(t, clusterUri) |
| 86 | defer deleteTestKeysCluster(t, clusterUri) |
| 87 | |
| 88 | for _, disableExportingValues := range []bool{true, false} { |
| 89 | e, _ := NewRedisExporter( |
| 90 | clusterUri, |
| 91 | Options{ |
| 92 | Namespace: "test", DisableExportingKeyValues: disableExportingValues, |
| 93 | CheckSingleKeys: fmt.Sprintf( |
| 94 | "%s=%s,%s=%s", |
| 95 | dbNumStrFull, url.QueryEscape(testKeys[0]), |
| 96 | dbNumStrFull, url.QueryEscape(TestKeyNameSet), |
| 97 | ), |
| 98 | IsCluster: true, |
| 99 | }, |
| 100 | ) |
| 101 | |
| 102 | chM := make(chan prometheus.Metric) |
| 103 | go func() { |
| 104 | e.Collect(chM) |
| 105 | close(chM) |
| 106 | }() |
| 107 | |
| 108 | foundExpectedKey := map[string]bool{ |
| 109 | "test_key_size": false, |
| 110 | "test_key_value": false, |
| 111 | "test_key_memory_usage_bytes": false, |
| 112 | } |
| 113 | |
| 114 | for m := range chM { |
| 115 | for k := range foundExpectedKey { |
| 116 | if strings.Contains(m.Desc().String(), k) { |
| 117 | foundExpectedKey[k] = true |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | for k, found := range foundExpectedKey { |
| 122 | if k == "test_key_value" { |
| 123 | if found && disableExportingValues { |
| 124 | t.Errorf("didn't expect %s with DisableExportingKeyValues enabled", k) |
| 125 | } else if !found && !disableExportingValues { |
| 126 | t.Errorf("didn't find %s with DisableExportingKeyValues disabled", k) |
| 127 | } |
| 128 | } else if !found { |
| 129 | t.Errorf("didn't find %s", k) |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | func TestParseKeyArg(t *testing.T) { |
| 136 | for _, test := range []struct { |
| 137 | name string |
| 138 | keyArgs string |
| 139 | expected []dbKeyPair |
| 140 | expectSuccess bool |
| 141 | }{ |
| 142 | // positive tests |
| 143 | {"empty_args", "", []dbKeyPair{}, true}, |
| 144 | {"default_database", "my-key", []dbKeyPair{{"0", "my-key"}}, true}, |
| 145 | {"prefixed_database", "db0=my-key", []dbKeyPair{{"0", "my-key"}}, true}, |
| 146 | {"indexed_database", "0=my-key", []dbKeyPair{{"0", "my-key"}}, true}, |
| 147 | {"triple_key", "check-key-01", []dbKeyPair{{"0", "check-key-01"}}, true}, |
| 148 | { |
| 149 | name: "default_database_multiple_keys", |
| 150 | keyArgs: "my-key1,my-key2", |
| 151 | expected: []dbKeyPair{ |
| 152 | {"0", "my-key1"}, |
| 153 | {"0", "my-key2"}, |
| 154 | }, |
| 155 | expectSuccess: true, |
| 156 | }, |
| 157 | { |
| 158 | name: "key_with_leading_space", |
| 159 | keyArgs: "my-key-noSpace, my-key-withSpace", |
| 160 | expected: []dbKeyPair{ |
| 161 | {"0", "my-key-noSpace"}, |
| 162 | {"0", "my-key-withSpace"}, |
| 163 | }, |
| 164 | expectSuccess: true, |
| 165 | }, |
| 166 | { |
| 167 | name: "key_with_spaces", |
| 168 | keyArgs: "my-key-noSpace1, my-key-withSpaces ,my-key-noSpace2", |
| 169 | expected: []dbKeyPair{ |
| 170 | {"0", "my-key-noSpace1"}, |
| 171 | {"0", "my-key-withSpaces"}, |
| 172 | {"0", "my-key-noSpace2"}, |
| 173 | }, |
| 174 | expectSuccess: true, |
| 175 | }, |
| 176 | { |
| 177 | name: "different_databases", |
| 178 | keyArgs: "db0=key1,db1=key1", |
| 179 | expected: []dbKeyPair{ |
| 180 | {"0", "key1"}, |
| 181 | {"1", "key1"}, |
| 182 | }, |
| 183 | expectSuccess: true, |
| 184 | }, |
| 185 | { |
| 186 | name: "dbdb_replace", |
| 187 | keyArgs: "dbdbdb0=key1,db1=key1", |
| 188 | expected: []dbKeyPair{ |
| 189 | {"0", "key1"}, |
| 190 | {"1", "key1"}, |
| 191 | }, |
| 192 | expectSuccess: true, |
| 193 | }, |
| 194 | { |
| 195 | name: "default_database_with_another", |
| 196 | keyArgs: "key1,db1=key1", |
| 197 | expected: []dbKeyPair{ |
| 198 | {"0", "key1"}, |
| 199 | {"1", "key1"}, |
| 200 | }, |
| 201 | expectSuccess: true, |
| 202 | }, |
| 203 | { |
| 204 | "invalid_args_with_args_separator_skipped", |
| 205 | "=", []dbKeyPair{}, true, |
| 206 | }, |
| 207 | { |
| 208 | "empty_args_with_comma_separators_skipped", |
| 209 | ",,,my-key", []dbKeyPair{{"0", "my-key"}}, true, |
| 210 | }, |
| 211 | { |
| 212 | "multiple_invalid_args_skipped", |
| 213 | "=,=,,0=my-key", []dbKeyPair{{"0", "my-key"}}, true, |
| 214 | }, |
| 215 | { |
| 216 | "empty_key_with_args_separator_skipped", |
| 217 | "0=", []dbKeyPair{}, true, |
| 218 | }, |
| 219 | { |
| 220 | "empty_database_with_args_separator_skipped", |
| 221 | "=my-key", []dbKeyPair{}, true, |
| 222 | }, |
| 223 | // negative tests |
| 224 | { |
| 225 | "string_database_index", |
| 226 | "wrong=my-key", []dbKeyPair{}, false, |
| 227 | }, |
| 228 | { |
| 229 | "prefixed_string_database_index", |
| 230 | "dbwrong=my-key", []dbKeyPair{}, false, |
| 231 | }, |
| 232 | { |
| 233 | "wrong_args_count", |
| 234 | "wrong=wrong=wrong", []dbKeyPair{}, false, |
| 235 | }, |
| 236 | { |
| 237 | "wrong_args", |
| 238 | "wrong=wrong=1", []dbKeyPair{}, false, |
| 239 | }, |
| 240 | { |
| 241 | "negative_database_index", |
| 242 | "db-1=my-key", []dbKeyPair{}, false, |
| 243 | }, |
| 244 | } { |
| 245 | t.Run(test.name, func(t *testing.T) { |
| 246 | parsed, err := parseKeyArg(test.keyArgs) |
| 247 | if test.expectSuccess && err != nil { |
| 248 | t.Errorf("Expected success for test: %s, got err: %s", test.name, err) |
| 249 | return |
| 250 | } |
| 251 | if len(parsed) != len(test.expected) { |
| 252 | t.Errorf("Parsed elements count don't match expected: parsed %d; expected %d", len(parsed), len(test.expected)) |
| 253 | return |
| 254 | } |
| 255 | for i, pair := range test.expected { |
| 256 | if pair != parsed[i] { |
| 257 | t.Errorf("Parsed elements don't match expected dbKeyPair:\n parsed %#v;\nexpected %#v", parsed[i], pair) |
| 258 | return |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if !test.expectSuccess && err == nil { |
| 263 | t.Errorf("Expected failure for test: %s, got no err", test.name) |
| 264 | return |
| 265 | } |
| 266 | if !test.expectSuccess && err != nil { |
| 267 | t.Logf("Expected failure for test: %s, got err: %s", test.name, err) |
| 268 | return |
| 269 | } |
| 270 | }) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | type keyFixture struct { |
| 275 | command string |
| 276 | key string |
| 277 | args []any |
| 278 | } |
| 279 | |
| 280 | func newKeyFixture(command string, key string, args ...any) keyFixture { |
| 281 | return keyFixture{command, key, args} |
| 282 | } |
| 283 | |
| 284 | func createKeyFixtures(t *testing.T, c redis.Conn, fixtures []keyFixture) { |
| 285 | for _, f := range fixtures { |
| 286 | args := append([]any{f.key}, f.args...) |
| 287 | if _, err := c.Do(f.command, args...); err != nil { |
| 288 | t.Fatalf("Error creating fixture: %#v, %#v", f, err) |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | func deleteKeyFixtures(t *testing.T, c redis.Conn, fixtures []keyFixture) { |
| 294 | for _, f := range fixtures { |
| 295 | if _, err := c.Do("DEL", f.key); err != nil { |
| 296 | t.Errorf("Error deleting fixture: %#v, %#v", f, err) |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | func TestScanKeys(t *testing.T) { |
| 302 | numKeys := 1000 |
| 303 | var fixtures []keyFixture |
| 304 | |
| 305 | // Make 1000 keys that match |
| 306 | for i := range numKeys { |
| 307 | key := fmt.Sprintf("get_keys_test_shouldmatch_%v", i) |
| 308 | fixtures = append(fixtures, newKeyFixture("SET", key, "Woohoo!")) |
| 309 | } |
| 310 | |
| 311 | // And 1000 that don't |
| 312 | for i := range numKeys { |
| 313 | key := fmt.Sprintf("get_keys_test_shouldnotmatch_%v", i) |
| 314 | fixtures = append(fixtures, newKeyFixture("SET", key, "Rats!")) |
| 315 | } |
| 316 | |
| 317 | addr := os.Getenv("TEST_REDIS_URI") |
| 318 | db := dbNumStr |
| 319 | |
| 320 | c, err := redis.DialURL(addr) |
| 321 | if err != nil { |
| 322 | t.Fatalf("Couldn't connect to %#v: %#v", addr, err) |
| 323 | } |
| 324 | _, err = c.Do("SELECT", db) |
| 325 | if err != nil { |
| 326 | t.Errorf("Couldn't select database %#v", db) |
| 327 | } |
| 328 | |
| 329 | defer func() { |
| 330 | deleteKeyFixtures(t, c, fixtures) |
| 331 | c.Close() |
| 332 | }() |
| 333 | |
| 334 | createKeyFixtures(t, c, fixtures) |
| 335 | |
| 336 | matches, err := redis.Strings(scanKeys(c, "get_keys_test_*shouldmatch*", defaultCount)) |
| 337 | if err != nil { |
| 338 | t.Errorf("Error getting keys matching a pattern: %#v", err) |
| 339 | } |
| 340 | |
| 341 | numMatches := len(matches) |
| 342 | if numMatches != numKeys { |
| 343 | t.Errorf("Expected %#v matches, got %#v.", numKeys, numMatches) |
| 344 | } |
| 345 | |
| 346 | for _, match := range matches { |
| 347 | if !strings.HasPrefix(match, "get_keys_test_shouldmatch") { |
| 348 | t.Errorf("Expected match to have prefix: get_keys_test_shouldmatch") |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | // Test expected errors separately |
| 353 | invalidFixtures := map[string]int64{ |
| 354 | // empty string is a string after all |
| 355 | "": 100, |
| 356 | "pattern": invalidCount, |
| 357 | } |
| 358 | for pattern, count := range invalidFixtures { |
| 359 | got, err := redis.Strings(scanKeys(c, pattern, count)) |
| 360 | if err != nil { |
| 361 | t.Logf("\"Passed\" expected, got error: %#v", err) |
| 362 | if pattern == "" && err.Error() != "pattern shouldn't be empty" { |
| 363 | t.Errorf("\"Empty pattern\" error message expected, but got: %s", err.Error()) |
| 364 | } |
| 365 | } else { |
| 366 | if len(got) >= 0 { |
| 367 | t.Errorf("Error expected, got valid response: %#v", got) |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | func TestGetKeysFromPatterns(t *testing.T) { |
| 374 | addr := os.Getenv("TEST_REDIS_URI") |
| 375 | dbMain := dbNumStr |
| 376 | dbAlt := altDBNumStr |
| 377 | dbInvalid := invalidDBNumStr |
| 378 | |
| 379 | dbMainFixtures := []keyFixture{ |
| 380 | newKeyFixture("SET", "dbMainNoPattern1", "woohoo!"), |
| 381 | newKeyFixture("SET", "dbMainSomePattern1", "woohoo!"), |
| 382 | newKeyFixture("SET", "dbMainSomePattern2", "woohoo!"), |
| 383 | } |
| 384 | |
| 385 | dbAltFixtures := []keyFixture{ |
| 386 | newKeyFixture("SET", "dbAltNoPattern1", "woohoo!"), |
| 387 | newKeyFixture("SET", "dbAltSomePattern1", "woohoo!"), |
| 388 | newKeyFixture("SET", "dbAltSomePattern2", "woohoo!"), |
| 389 | } |
| 390 | |
| 391 | keys := []dbKeyPair{ |
| 392 | {db: dbMain, key: "dbMainNoPattern1"}, |
| 393 | {db: dbMain, key: "*SomePattern*"}, |
| 394 | {db: dbAlt, key: "dbAltNoPattern1"}, |
| 395 | {db: dbAlt, key: "*SomePattern*"}, |
| 396 | } |
| 397 | invalidKeys := []dbKeyPair{ |
| 398 | {db: dbInvalid, key: "someUnusedPattern*"}, |
| 399 | } |
| 400 | |
| 401 | c, err := redis.DialURL(addr) |
| 402 | if err != nil { |
| 403 | t.Fatalf("Couldn't connect to %#v: %#v", addr, err) |
| 404 | } |
| 405 | |
| 406 | defer func() { |
| 407 | _, err = c.Do("SELECT", dbMain) |
| 408 | if err != nil { |
| 409 | t.Errorf("Couldn't select database %#v", dbMain) |
| 410 | } |
| 411 | deleteKeyFixtures(t, c, dbMainFixtures) |
| 412 | |
| 413 | _, err = c.Do("SELECT", dbAlt) |
| 414 | if err != nil { |
| 415 | t.Errorf("Couldn't select database %#v", dbAlt) |
| 416 | } |
| 417 | deleteKeyFixtures(t, c, dbAltFixtures) |
| 418 | c.Close() |
| 419 | }() |
| 420 | |
| 421 | _, err = c.Do("SELECT", dbMain) |
| 422 | if err != nil { |
| 423 | t.Errorf("Couldn't select database %#v", dbMain) |
| 424 | } |
| 425 | createKeyFixtures(t, c, dbMainFixtures) |
| 426 | |
| 427 | _, err = c.Do("SELECT", dbAlt) |
| 428 | if err != nil { |
| 429 | t.Errorf("Couldn't select database %#v", dbAlt) |
| 430 | } |
| 431 | createKeyFixtures(t, c, dbAltFixtures) |
| 432 | |
| 433 | expandedKeys, err := getKeysFromPatterns(c, keys, defaultCount) |
| 434 | if err != nil { |
| 435 | t.Errorf("Error getting keys from patterns: %#v", err) |
| 436 | } |
| 437 | |
| 438 | expectedKeys := []dbKeyPair{ |
| 439 | {db: dbMain, key: "dbMainNoPattern1"}, |
| 440 | {db: dbMain, key: "dbMainSomePattern1"}, |
| 441 | {db: dbMain, key: "dbMainSomePattern2"}, |
| 442 | {db: dbAlt, key: "dbAltNoPattern1"}, |
| 443 | {db: dbAlt, key: "dbAltSomePattern1"}, |
| 444 | {db: dbAlt, key: "dbAltSomePattern2"}, |
| 445 | } |
| 446 | |
| 447 | sort.Slice(expectedKeys, func(i, j int) bool { |
| 448 | return (expectedKeys[i].db + expectedKeys[i].key) < (expectedKeys[j].db + expectedKeys[j].key) |
| 449 | }) |
| 450 | |
| 451 | sort.Slice(expandedKeys, func(i, j int) bool { |
| 452 | return (expandedKeys[i].db + expandedKeys[i].key) < (expandedKeys[j].db + expandedKeys[j].key) |
| 453 | }) |
| 454 | |
| 455 | if !reflect.DeepEqual(expectedKeys, expandedKeys) { |
| 456 | t.Errorf("When expanding keys:\nexpected: %#v\nactual: %#v", expectedKeys, expandedKeys) |
| 457 | } |
| 458 | |
| 459 | got, err := getKeysFromPatterns(c, invalidKeys, defaultCount) |
| 460 | if err != nil { |
| 461 | t.Logf("Expected error - \"invalid DB\": %#v", err) |
| 462 | } else { |
| 463 | if len(got) != 0 { |
| 464 | t.Errorf("Error expected with invalid database %#v, got valid response: %#v", invalidKeys, got) |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | func TestKeySizeList(t *testing.T) { |
| 470 | s := dbNumStrFull + "=" + testKeysList[0] |
| 471 | e, _ := NewRedisExporter( |
| 472 | os.Getenv("TEST_REDIS_URI"), |
| 473 | Options{Namespace: "test", CheckSingleKeys: s}, |
| 474 | ) |
| 475 | |
| 476 | setupTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 477 | defer deleteTestKeys(t, os.Getenv("TEST_REDIS_URI")) |
| 478 | |
| 479 | chM := make(chan prometheus.Metric) |
| 480 | go func() { |
| 481 | e.Collect(chM) |
| 482 | close(chM) |
| 483 | }() |
| 484 | |
| 485 | found := false |
| 486 | for m := range chM { |
| 487 | if strings.Contains(m.Desc().String(), "test_key_size") { |
| 488 | found = true |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | if !found { |
| 493 | t.Errorf("didn't find the key") |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | func TestKeyValueInvalidDB(t *testing.T) { |
| 498 | e, _ := NewRedisExporter( |
| 499 | os.Getenv("TEST_REDIS_URI"), |
| 500 | Options{ |
| 501 | Namespace: "test", |
| 502 | CheckSingleKeys: "999=" + url.QueryEscape(testKeys[0]), |
| 503 | }, |
| 504 | ) |
| 505 | |
| 506 | chM := make(chan prometheus.Metric) |
| 507 | go func() { |
| 508 | e.Collect(chM) |
| 509 | close(chM) |
| 510 | }() |
| 511 | |
| 512 | dontWant := map[string]bool{"test_key_size": false} |
| 513 | for m := range chM { |
| 514 | switch m.(type) { |
| 515 | case prometheus.Gauge: |
| 516 | for k := range dontWant { |
| 517 | if strings.Contains(m.Desc().String(), k) { |
| 518 | log.Println(m.Desc().String()) |
| 519 | dontWant[k] = true |
| 520 | } |
| 521 | } |
| 522 | default: |
| 523 | log.Debugf("default: m: %#v", m) |
| 524 | } |
| 525 | } |
| 526 | for k, found := range dontWant { |
| 527 | if found { |
| 528 | t.Errorf("we found %s but it shouldn't be there", k) |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | func TestCheckKeys(t *testing.T) { |
| 534 | for _, tst := range []struct { |
| 535 | SingleCheckKey string |
| 536 | CheckKeys string |
| 537 | ExpectSuccess bool |
| 538 | }{ |
| 539 | {"", "", true}, |
| 540 | {"db1=key3", "", true}, |
| 541 | {"check-key-01", "", true}, |
| 542 | {"", "check-key-02", true}, |
| 543 | {"wrong=wrong=1", "", false}, |
| 544 | {"", "wrong=wrong=2", false}, |
| 545 | } { |
| 546 | _, err := NewRedisExporter(os.Getenv("TEST_REDIS_URI"), Options{Namespace: "test", CheckSingleKeys: tst.SingleCheckKey, CheckKeys: tst.CheckKeys}) |
| 547 | if tst.ExpectSuccess && err != nil { |
| 548 | t.Errorf("Expected success for test: %#v, got err: %s", tst, err) |
| 549 | return |
| 550 | } |
| 551 | |
| 552 | if !tst.ExpectSuccess && err == nil { |
| 553 | t.Errorf("Expected failure for test: %#v, got no err", tst) |
| 554 | return |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | func TestCheckSingleKeyDefaultsTo0(t *testing.T) { |
| 560 | uri := os.Getenv("TEST_REDIS_URI") |
| 561 | e, _ := NewRedisExporter(uri, Options{Namespace: "test", CheckSingleKeys: "single"}) |
| 562 | ts := httptest.NewServer(e) |
| 563 | defer ts.Close() |
| 564 | |
| 565 | setupTestKeys(t, uri) |
| 566 | defer deleteTestKeys(t, uri) |
| 567 | |
| 568 | body := downloadURL(t, ts.URL+"/metrics") |
| 569 | if !strings.Contains(body, `test_key_size{db="db0",key="single"} 0`) { |
| 570 | t.Errorf("Expected metric `test_key_size` with key=`single` and value 0 but got:\n%s", body) |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | func TestCheckKeysMultipleDBs(t *testing.T) { |
| 575 | uri := os.Getenv("TEST_REDIS_URI") |
| 576 | e, _ := NewRedisExporter(uri, |
| 577 | Options{Namespace: "test", |
| 578 | CheckSingleKeys: "single," + |
| 579 | dbNumStr + "=" + testKeys[0] + "," + |
| 580 | dbNumStr + "=" + TestKeyNameSingleString + "," + |
| 581 | altDBNumStr + "=" + TestKeysHllName + "," + |
| 582 | altDBNumStr + "=" + TestKeyNameSingleString + "," + |
| 583 | anotherAltDbNumStr + "=" + testKeys[0], |
| 584 | CheckKeys: dbNumStr + "=" + "test*", |
| 585 | CheckKeysBatchSize: 1000, |
| 586 | }) |
| 587 | ts := httptest.NewServer(e) |
| 588 | defer ts.Close() |
| 589 | |
| 590 | setupTestKeys(t, uri) |
| 591 | defer deleteTestKeys(t, uri) |
| 592 | |
| 593 | body := downloadURL(t, ts.URL+"/metrics") |
| 594 | |
| 595 | for _, k := range []string{ |
| 596 | `test_key_size{db="db0",key="single"} 0`, // non-existent key |
| 597 | |
| 598 | fmt.Sprintf(`test_key_size{db="db%s",key="%s"} 16`, dbNumStr, TestKeyNameSingleString), |
| 599 | fmt.Sprintf(`test_key_size{db="db%s",key="%s"} 2`, dbNumStr, TestKeysZSetName), |
| 600 | fmt.Sprintf(`test_key_size{db="db%s",key="%s"} 4`, dbNumStr, TestKeysHashName), |
| 601 | fmt.Sprintf(`test_key_size{db="db%s",key="%s"} 3`, altDBNumStr, TestKeysHllName), |
| 602 | fmt.Sprintf(`test_key_size{db="db%s",key="%s"} 16`, altDBNumStr, TestKeyNameSingleString), |
| 603 | fmt.Sprintf(`test_key_size{db="db%s",key="%s"} 7`, anotherAltDbNumStr, testKeys[0]), |
| 604 | |
| 605 | fmt.Sprintf(`test_key_value{db="db%s",key="%s"} 1234.56`, dbNumStr, testKeys[0]), |
| 606 | fmt.Sprintf(`test_key_value{db="db%s",key="%s"} 1234.56`, anotherAltDbNumStr, testKeys[0]), |
| 607 | |
| 608 | fmt.Sprintf(`key_memory_usage_bytes{db="db%s",key="%s"}`, dbNumStr, TestKeyNameSingleString), |
| 609 | fmt.Sprintf(`key_memory_usage_bytes{db="db%s",key="%s"}`, altDBNumStr, TestKeyNameSingleString), |
| 610 | fmt.Sprintf(`key_memory_usage_bytes{db="db%s",key="%s"}`, anotherAltDbNumStr, testKeys[0]), |
| 611 | } { |
| 612 | if !strings.Contains(body, k) { |
| 613 | t.Errorf("Expected metric: %s but got:\n%s", k, body) |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | func TestClusterGetKeyInfo(t *testing.T) { |
| 619 | clusterUri := os.Getenv("TEST_REDIS_CLUSTER_MASTER_URI") |
| 620 | if clusterUri == "" { |
| 621 | t.Skipf("Skipping TestClusterKeyValuesAndSizes, don't have env var TEST_REDIS_CLUSTER_MASTER_URI") |
| 622 | } |
| 623 | |
| 624 | e, _ := NewRedisExporter( |
| 625 | clusterUri, |
| 626 | Options{ |
| 627 | Namespace: "test", |
| 628 | CheckSingleKeys: strings.Join(AllTestKeys, ","), |
| 629 | IsCluster: true, |
| 630 | }, |
| 631 | ) |
| 632 | ts := httptest.NewServer(e) |
| 633 | defer ts.Close() |
| 634 | |
| 635 | setupTestKeysCluster(t, clusterUri) |
| 636 | defer deleteTestKeysCluster(t, clusterUri) |
| 637 | |
| 638 | body := downloadURL(t, ts.URL+"/metrics") |
| 639 | for _, want := range []string{ |
| 640 | "key_value_as_string", |
| 641 | `test_key_size{db="db0",key="test-hll"} 3`, |
| 642 | } { |
| 643 | if !strings.Contains(body, want) { |
| 644 | t.Errorf("Expected metric: %s but got:\n%s", want, body) |
| 645 | } |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | func TestRedis88ClusterArrayGetKeyInfo(t *testing.T) { |
| 650 | clusterUri := os.Getenv("TEST_REDIS88_CLUSTER_MASTER_URI") |
| 651 | if clusterUri == "" { |
| 652 | t.Skipf("Skipping TestRedis88ClusterGetKeyInfo, don't have env var TEST_REDIS88_CLUSTER_MASTER_URI") |
| 653 | } |
| 654 | |
| 655 | e, _ := NewRedisExporter( |
| 656 | clusterUri, |
| 657 | Options{ |
| 658 | Namespace: "test", |
| 659 | CheckSingleKeys: "array_test,events:1", |
| 660 | IsCluster: true, |
| 661 | }, |
| 662 | ) |
| 663 | ts := httptest.NewServer(e) |
| 664 | defer ts.Close() |
| 665 | |
| 666 | fixtures := []keyFixture{ |
| 667 | {"ARMSET", "array_test", []any{"0", "10", "5", "20", "100", "30"}}, |
| 668 | {"ARSET", "events:1", []any{"0", "login", "click", "purchase", "logout"}}, |
| 669 | } |
| 670 | |
| 671 | c := getClusterConn(t, clusterUri) |
| 672 | |
| 673 | createKeyFixtures(t, c, fixtures) |
| 674 | |
| 675 | defer func() { |
| 676 | deleteKeyFixtures(t, c, fixtures) |
| 677 | c.Close() |
| 678 | }() |
| 679 | |
| 680 | body := downloadURL(t, ts.URL+"/metrics") |
| 681 | for _, want := range []string{ |
| 682 | `test_key_size{db="db0",key="array_test"} 3`, |
| 683 | `test_key_size{db="db0",key="events:1"} 4`, |
| 684 | } { |
| 685 | if !strings.Contains(body, want) { |
| 686 | t.Errorf("Expected metric: %s but got:\n%s", want, body) |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | func TestGetKeyInfoWithMissingKey(t *testing.T) { |
| 692 | /* |
| 693 | https://github.com/oliver006/redis_exporter/issues/1008 |
| 694 | |
| 695 | CheckSingleKeys contains a bunch of keys but the first one is missing |
| 696 | and the rest is still expected to be present in the metrics |
| 697 | */ |
| 698 | |
| 699 | uri := os.Getenv("TEST_REDIS_URI") |
| 700 | if uri == "" { |
| 701 | t.Skipf("Skipping TestGetKeyInfoWithMissingKey, don't have env var TEST_REDIS_URI") |
| 702 | } |
| 703 | |
| 704 | keys := []string{dbNumStrFull + "=" + "i-dont-exist"} |
| 705 | for idx := range testKeys { |
| 706 | keys = append(keys, dbNumStrFull+"="+testKeys[idx]) |
| 707 | if idx == 3 { |
| 708 | keys = append(keys, dbNumStrFull+"="+"another-missing-key") |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | e, _ := NewRedisExporter( |
| 713 | uri, |
| 714 | Options{ |
| 715 | Namespace: "test", |
| 716 | CheckSingleKeys: strings.Join(keys, ","), |
| 717 | }, |
| 718 | ) |
| 719 | ts := httptest.NewServer(e) |
| 720 | defer ts.Close() |
| 721 | |
| 722 | setupTestKeys(t, uri) |
| 723 | defer deleteTestKeys(t, uri) |
| 724 | |
| 725 | body := downloadURL(t, ts.URL+"/metrics") |
| 726 | for _, k := range testKeys { |
| 727 | for _, w := range []string{ |
| 728 | `test_key_memory_usage_bytes{db="%s",key="%s"}`, |
| 729 | `test_key_size{db="%s",key="%s"}`, |
| 730 | `test_key_value{db="%s",key="%s"}`, |
| 731 | } { |
| 732 | want := fmt.Sprintf(w, dbNumStrFull, k) |
| 733 | if !strings.Contains(body, want) { |
| 734 | t.Errorf("Expected metric: %s but got:\n%s", want, body) |
| 735 | } |
| 736 | } |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | func TestGetKeysCount(t *testing.T) { |
| 741 | addr := os.Getenv("TEST_REDIS_URI") |
| 742 | db := dbNumStr |
| 743 | |
| 744 | c, err := redis.DialURL(addr) |
| 745 | if err != nil { |
| 746 | t.Fatalf("Couldn't connect to %#v: %#v", addr, err) |
| 747 | } |
| 748 | _, err = c.Do("SELECT", db) |
| 749 | if err != nil { |
| 750 | t.Errorf("Couldn't select database %#v", db) |
| 751 | } |
| 752 | |
| 753 | fixtures := []keyFixture{ |
| 754 | {"SET", "count_test:keys_count_test_string1", []any{"Woohoo!"}}, |
| 755 | {"SET", "count_test:keys_count_test_string2", []any{"!oohooW"}}, |
| 756 | {"LPUSH", "count_test:keys_count_test_list1", []any{"listval1", "listval2", "listval3"}}, |
| 757 | {"LPUSH", "count_test:keys_count_test_list2", []any{"listval1", "listval2", "listval3"}}, |
| 758 | {"LPUSH", "count_test:keys_count_test_list3", []any{"listval1", "listval2", "listval3"}}, |
| 759 | } |
| 760 | |
| 761 | createKeyFixtures(t, c, fixtures) |
| 762 | defer func() { |
| 763 | deleteKeyFixtures(t, c, fixtures) |
| 764 | c.Close() |
| 765 | }() |
| 766 | |
| 767 | expectedCount := map[string]int{ |
| 768 | "count_test:keys_count_test_string*": 2, |
| 769 | "count_test:keys_count_test_list*": 3, |
| 770 | "count_test:*": 5, |
| 771 | } |
| 772 | |
| 773 | for pattern, count := range expectedCount { |
| 774 | actualCount, err := getKeysCount(c, pattern, defaultCount) |
| 775 | if err != nil { |
| 776 | t.Errorf("Error getting count for pattern \"%#v\"", pattern) |
| 777 | } |
| 778 | |
| 779 | if actualCount != count { |
| 780 | t.Errorf("Wrong count for pattern \"%#v\". Expected: %#v; Actual: %#v", pattern, count, actualCount) |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | got, err := getKeysCount(c, "pattern", invalidCount) |
| 785 | if err != nil { |
| 786 | t.Logf("Expected error - \"error retrieving keys\": %#v", err) |
| 787 | } else { |
| 788 | if got >= 0 { |
| 789 | t.Errorf("Error expected with invalidCount option \"%#v\", got valid response: %#v", invalidCount, got) |
| 790 | } |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | func TestRedis88ArrayGetKeyInfo(t *testing.T) { |
| 795 | addr := os.Getenv("TEST_REDIS88_URI") |
| 796 | if addr == "" { |
| 797 | t.Skipf("Skipping TestRedis88ArrayGetKeyInfo, don't have env var TEST_REDIS88_URI") |
| 798 | } |
| 799 | db := dbNumStr |
| 800 | |
| 801 | c, err := redis.DialURL(addr) |
| 802 | if err != nil { |
| 803 | t.Fatalf("Couldn't connect to %#v: %#v", addr, err) |
| 804 | } |
| 805 | _, err = c.Do("SELECT", db) |
| 806 | if err != nil { |
| 807 | t.Errorf("Couldn't select database %#v", db) |
| 808 | } |
| 809 | |
| 810 | fixtures := []keyFixture{ |
| 811 | {"ARMSET", "array_test", []any{"0", "10", "5", "20", "100", "30"}}, |
| 812 | } |
| 813 | |
| 814 | createKeyFixtures(t, c, fixtures) |
| 815 | |
| 816 | defer func() { |
| 817 | deleteKeyFixtures(t, c, fixtures) |
| 818 | c.Close() |
| 819 | }() |
| 820 | |
| 821 | e, _ := NewRedisExporter( |
| 822 | addr, |
| 823 | Options{ |
| 824 | Namespace: "test", |
| 825 | CheckSingleKeys: dbNumStr + "=" + "array_test", |
| 826 | }, |
| 827 | ) |
| 828 | ts := httptest.NewServer(e) |
| 829 | defer ts.Close() |
| 830 | |
| 831 | body := downloadURL(t, ts.URL+"/metrics") |
| 832 | for _, want := range []string{ |
| 833 | `test_key_size{db="` + dbNumStrFull + `",key="array_test"} 3`, |
| 834 | } { |
| 835 | if !strings.Contains(body, want) { |
| 836 | t.Errorf("Expected metric: %s but got:\n%s", want, body) |
| 837 | } |
| 838 | } |
| 839 | } |