| 1 | package exporter |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/http" |
| 6 | "net/url" |
| 7 | "runtime" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | // see https://github.com/prometheus/client_golang/releases/tag/v1.22.0 |
| 14 | _ "github.com/prometheus/client_golang/prometheus/promhttp/zstd" |
| 15 | |
| 16 | "github.com/gomodule/redigo/redis" |
| 17 | "github.com/prometheus/client_golang/prometheus" |
| 18 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 19 | log "github.com/sirupsen/logrus" |
| 20 | ) |
| 21 | |
| 22 | type BuildInfo struct { |
| 23 | Version string |
| 24 | CommitSha string |
| 25 | Date string |
| 26 | } |
| 27 | |
| 28 | // Exporter implements the prometheus.Exporter interface, and exports Redis metrics. |
| 29 | type Exporter struct { |
| 30 | sync.Mutex |
| 31 | |
| 32 | redisAddr string |
| 33 | instanceRole string |
| 34 | |
| 35 | totalScrapes prometheus.Counter |
| 36 | scrapeDuration prometheus.Summary |
| 37 | targetScrapeRequestErrors prometheus.Counter |
| 38 | |
| 39 | metricDescriptions map[string]*prometheus.Desc |
| 40 | |
| 41 | options Options |
| 42 | |
| 43 | metricMapCounters map[string]string |
| 44 | metricMapGauges map[string]string |
| 45 | |
| 46 | mux *http.ServeMux |
| 47 | |
| 48 | buildInfo BuildInfo |
| 49 | } |
| 50 | |
| 51 | type Options struct { |
| 52 | User string |
| 53 | Password string |
| 54 | Namespace string |
| 55 | PasswordMap map[string]string |
| 56 | ConfigCommandName string |
| 57 | CheckKeys string |
| 58 | CheckSingleKeys string |
| 59 | CheckStreams string |
| 60 | CheckSingleStreams string |
| 61 | StreamsExcludeConsumerMetrics bool |
| 62 | CheckKeysBatchSize int64 |
| 63 | CheckKeyGroups string |
| 64 | MaxDistinctKeyGroups int64 |
| 65 | CountKeys string |
| 66 | LuaScript map[string][]byte |
| 67 | LuaScriptReadOnly bool |
| 68 | ClientCertFile string |
| 69 | ClientKeyFile string |
| 70 | CaCertFile string |
| 71 | InclConfigMetrics bool |
| 72 | InclModulesMetrics bool |
| 73 | InclSearchIndexesMetrics bool |
| 74 | InclSentinelPeerInfo bool |
| 75 | CheckSearchIndexes string |
| 76 | DisableExportingKeyValues bool |
| 77 | ExcludeLatencyHistogramMetrics bool |
| 78 | RedactConfigMetrics bool |
| 79 | InclSystemMetrics bool |
| 80 | InclRdbFileSizeMetric bool |
| 81 | SkipTLSVerification bool |
| 82 | SetClientName bool |
| 83 | IsTile38 bool |
| 84 | IsCluster bool |
| 85 | ClusterDiscoverHostnames bool |
| 86 | ExportClientList bool |
| 87 | ExportClientsInclPort bool |
| 88 | ConnectionTimeouts time.Duration |
| 89 | MetricsPath string |
| 90 | RedisMetricsOnly bool |
| 91 | PingOnConnect bool |
| 92 | RedisPwdFile string |
| 93 | Registry *prometheus.Registry |
| 94 | BuildInfo BuildInfo |
| 95 | BasicAuthUsername string |
| 96 | BasicAuthPassword string |
| 97 | BasicAuthHashPassword string |
| 98 | SkipCheckKeysForRoleMaster bool |
| 99 | InclMetricsForEmptyDatabases bool |
| 100 | AppendInstanceRoleLabel bool |
| 101 | DisableScrapeEndpoint bool |
| 102 | } |
| 103 | |
| 104 | func getInstanceRoleFromInfo(info string) string { |
| 105 | for line := range strings.SplitSeq(info, "\n") { |
| 106 | line = strings.TrimSpace(line) |
| 107 | if strings.HasPrefix(line, "role:") { |
| 108 | split := strings.SplitN(line, ":", 2) |
| 109 | return split[1] |
| 110 | } |
| 111 | } |
| 112 | return "" |
| 113 | } |
| 114 | |
| 115 | // NewRedisExporter returns a new exporter of Redis metrics. |
| 116 | func NewRedisExporter(uri string, opts Options) (*Exporter, error) { |
| 117 | log.Debugf("NewRedisExporter options: %#v", opts) |
| 118 | |
| 119 | switch { |
| 120 | case strings.HasPrefix(uri, "valkey://"): |
| 121 | uri = strings.Replace(uri, "valkey://", "redis://", 1) |
| 122 | case strings.HasPrefix(uri, "valkeys://"): |
| 123 | uri = strings.Replace(uri, "valkeys://", "rediss://", 1) |
| 124 | } |
| 125 | |
| 126 | log.Debugf("NewRedisExporter = using redis uri: %s", uri) |
| 127 | |
| 128 | if opts.Registry == nil { |
| 129 | opts.Registry = prometheus.NewRegistry() |
| 130 | } |
| 131 | |
| 132 | e := &Exporter{ |
| 133 | redisAddr: uri, |
| 134 | options: opts, |
| 135 | |
| 136 | buildInfo: opts.BuildInfo, |
| 137 | |
| 138 | totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{ |
| 139 | Namespace: opts.Namespace, |
| 140 | Name: "exporter_scrapes_total", |
| 141 | Help: "Current total redis scrapes.", |
| 142 | }), |
| 143 | |
| 144 | scrapeDuration: prometheus.NewSummary(prometheus.SummaryOpts{ |
| 145 | Namespace: opts.Namespace, |
| 146 | Name: "exporter_scrape_duration_seconds", |
| 147 | Help: "Durations of scrapes by the exporter", |
| 148 | }), |
| 149 | |
| 150 | targetScrapeRequestErrors: prometheus.NewCounter(prometheus.CounterOpts{ |
| 151 | Namespace: opts.Namespace, |
| 152 | Name: "target_scrape_request_errors_total", |
| 153 | Help: "Errors in requests to the exporter", |
| 154 | }), |
| 155 | |
| 156 | metricMapGauges: map[string]string{ |
| 157 | // # Server |
| 158 | "uptime_in_seconds": "uptime_in_seconds", |
| 159 | "process_id": "process_id", |
| 160 | "io_threads_active": "io_threads_active", |
| 161 | |
| 162 | // # Clients |
| 163 | "connected_clients": "connected_clients", |
| 164 | "blocked_clients": "blocked_clients", |
| 165 | "maxclients": "max_clients", |
| 166 | "tracking_clients": "tracking_clients", |
| 167 | "clients_in_timeout_table": "clients_in_timeout_table", |
| 168 | "pubsub_clients": "pubsub_clients", // Added in Redis 7.4 |
| 169 | "watching_clients": "watching_clients", // Added in Redis 7.4 |
| 170 | "total_watched_keys": "total_watched_keys", // Added in Redis 7.4 |
| 171 | "total_blocking_keys": "total_blocking_keys", // Added in Redis 7.2 |
| 172 | "total_blocking_keys_on_nokey": "total_blocking_keys_on_nokey", // Added in Redis 7.2 |
| 173 | |
| 174 | // redis 2,3,4.x |
| 175 | "client_longest_output_list": "client_longest_output_list", |
| 176 | "client_biggest_input_buf": "client_biggest_input_buf", |
| 177 | |
| 178 | // the above two metrics were renamed in redis 5.x |
| 179 | "client_recent_max_output_buffer": "client_recent_max_output_buffer_bytes", |
| 180 | "client_recent_max_input_buffer": "client_recent_max_input_buffer_bytes", |
| 181 | |
| 182 | // # Memory |
| 183 | "allocator_active": "allocator_active_bytes", |
| 184 | "allocator_allocated": "allocator_allocated_bytes", |
| 185 | "allocator_resident": "allocator_resident_bytes", |
| 186 | "allocator_frag_ratio": "allocator_frag_ratio", |
| 187 | "allocator_frag_bytes": "allocator_frag_bytes", |
| 188 | "allocator_muzzy": "allocator_muzzy_bytes", |
| 189 | "allocator_rss_ratio": "allocator_rss_ratio", |
| 190 | "allocator_rss_bytes": "allocator_rss_bytes", |
| 191 | |
| 192 | "used_memory": "memory_used_bytes", |
| 193 | "used_memory_rss": "memory_used_rss_bytes", |
| 194 | "used_memory_peak": "memory_used_peak_bytes", |
| 195 | "used_memory_lua": "memory_used_lua_bytes", |
| 196 | "used_memory_vm_eval": "memory_used_vm_eval_bytes", // Added in Redis 7.0 |
| 197 | "used_memory_scripts_eval": "memory_used_scripts_eval_bytes", // Added in Redis 7.0 |
| 198 | "used_memory_overhead": "memory_used_overhead_bytes", |
| 199 | "used_memory_startup": "memory_used_startup_bytes", |
| 200 | "used_memory_dataset": "memory_used_dataset_bytes", |
| 201 | "number_of_cached_scripts": "number_of_cached_scripts", // Added in Redis 7.0 |
| 202 | "number_of_functions": "number_of_functions", // Added in Redis 7.0 |
| 203 | "number_of_libraries": "number_of_libraries", // Added in Redis 7.4 |
| 204 | "used_memory_vm_functions": "memory_used_vm_functions_bytes", // Added in Redis 7.0 |
| 205 | "used_memory_scripts": "memory_used_scripts_bytes", // Added in Redis 7.0 |
| 206 | "used_memory_functions": "memory_used_functions_bytes", // Added in Redis 7.0 |
| 207 | "used_memory_vm_total": "memory_used_vm_total", // Added in Redis 7.0 |
| 208 | "maxmemory": "memory_max_bytes", |
| 209 | |
| 210 | "maxmemory_reservation": "memory_max_reservation_bytes", |
| 211 | "maxmemory_desired_reservation": "memory_max_reservation_desired_bytes", |
| 212 | |
| 213 | "maxfragmentationmemory_reservation": "memory_max_fragmentation_reservation_bytes", |
| 214 | "maxfragmentationmemory_desired_reservation": "memory_max_fragmentation_reservation_desired_bytes", |
| 215 | |
| 216 | "mem_fragmentation_ratio": "mem_fragmentation_ratio", |
| 217 | "mem_fragmentation_bytes": "mem_fragmentation_bytes", |
| 218 | "mem_clients_slaves": "mem_clients_slaves", |
| 219 | "mem_clients_normal": "mem_clients_normal", |
| 220 | "mem_cluster_links": "mem_cluster_links_bytes", |
| 221 | "mem_aof_buffer": "mem_aof_buffer_bytes", |
| 222 | "mem_replication_backlog": "mem_replication_backlog_bytes", |
| 223 | |
| 224 | "expired_stale_perc": "expired_stale_percentage", |
| 225 | |
| 226 | // https://github.com/antirez/redis/blob/17bf0b25c1171486e3a1b089f3181fff2bc0d4f0/src/evict.c#L349-L352 |
| 227 | // ... the sum of AOF and slaves buffer ... |
| 228 | "mem_not_counted_for_evict": "mem_not_counted_for_eviction_bytes", |
| 229 | "mem_total_replication_buffers": "mem_total_replication_buffers_bytes", // Added in Redis 7.0 |
| 230 | "mem_overhead_db_hashtable_rehashing": "mem_overhead_db_hashtable_rehashing_bytes", // Added in Redis 7.4 |
| 231 | |
| 232 | "lazyfree_pending_objects": "lazyfree_pending_objects", |
| 233 | "lazyfreed_objects": "lazyfreed_objects", |
| 234 | "active_defrag_running": "active_defrag_running", |
| 235 | |
| 236 | "migrate_cached_sockets": "migrate_cached_sockets_total", |
| 237 | |
| 238 | "active_defrag_hits": "defrag_hits", |
| 239 | "active_defrag_misses": "defrag_misses", |
| 240 | "active_defrag_key_hits": "defrag_key_hits", |
| 241 | "active_defrag_key_misses": "defrag_key_misses", |
| 242 | |
| 243 | // # Persistence |
| 244 | "loading": "loading_dump_file", |
| 245 | "async_loading": "async_loading", // Added in Redis 7.0 |
| 246 | "rdb_changes_since_last_save": "rdb_changes_since_last_save", |
| 247 | "rdb_bgsave_in_progress": "rdb_bgsave_in_progress", |
| 248 | "rdb_last_save_time": "rdb_last_save_timestamp_seconds", |
| 249 | "rdb_last_bgsave_status": "rdb_last_bgsave_status", |
| 250 | "rdb_last_bgsave_time_sec": "rdb_last_bgsave_duration_sec", |
| 251 | "rdb_current_bgsave_time_sec": "rdb_current_bgsave_duration_sec", |
| 252 | "rdb_saves": "rdb_saves_total", |
| 253 | "rdb_last_cow_size": "rdb_last_cow_size_bytes", |
| 254 | "rdb_last_load_keys_expired": "rdb_last_load_expired_keys", // Added in Redis 7.0 |
| 255 | "rdb_last_load_keys_loaded": "rdb_last_load_loaded_keys", // Added in Redis 7.0 |
| 256 | "aof_enabled": "aof_enabled", |
| 257 | "aof_rewrite_in_progress": "aof_rewrite_in_progress", |
| 258 | "aof_rewrite_scheduled": "aof_rewrite_scheduled", |
| 259 | "aof_last_rewrite_time_sec": "aof_last_rewrite_duration_sec", |
| 260 | "aof_current_rewrite_time_sec": "aof_current_rewrite_duration_sec", |
| 261 | "aof_last_cow_size": "aof_last_cow_size_bytes", |
| 262 | "aof_current_size": "aof_current_size_bytes", |
| 263 | "aof_base_size": "aof_base_size_bytes", |
| 264 | "aof_pending_rewrite": "aof_pending_rewrite", |
| 265 | "aof_buffer_length": "aof_buffer_length", |
| 266 | "aof_rewrite_buffer_length": "aof_rewrite_buffer_length", // Added in Redis 7.0 |
| 267 | "aof_pending_bio_fsync": "aof_pending_bio_fsync", |
| 268 | "aof_delayed_fsync": "aof_delayed_fsync", |
| 269 | "aof_last_bgrewrite_status": "aof_last_bgrewrite_status", |
| 270 | "aof_last_write_status": "aof_last_write_status", |
| 271 | "module_fork_in_progress": "module_fork_in_progress", |
| 272 | "module_fork_last_cow_size": "module_fork_last_cow_size", |
| 273 | |
| 274 | // # Stats |
| 275 | "current_eviction_exceeded_time": "current_eviction_exceeded_time_ms", |
| 276 | "pubsub_channels": "pubsub_channels", |
| 277 | "pubsub_patterns": "pubsub_patterns", |
| 278 | "pubsubshard_channels": "pubsubshard_channels", // Added in Redis 7.0.3 |
| 279 | "latest_fork_usec": "latest_fork_usec", |
| 280 | "tracking_total_keys": "tracking_total_keys", |
| 281 | "tracking_total_items": "tracking_total_items", |
| 282 | "tracking_total_prefixes": "tracking_total_prefixes", |
| 283 | "instantaneous_eventloop_cycles_per_sec": "instantaneous_eventloop_cycles_per_sec", // Added in Redis 7.0 |
| 284 | "instantaneous_eventloop_duration_usec": "instantaneous_eventloop_duration_usec", // Added in Redis 7.0 |
| 285 | |
| 286 | // # Replication |
| 287 | "connected_slaves": "connected_slaves", |
| 288 | "repl_backlog_size": "replication_backlog_bytes", |
| 289 | "repl_backlog_active": "repl_backlog_is_active", |
| 290 | "repl_backlog_first_byte_offset": "repl_backlog_first_byte_offset", |
| 291 | "repl_backlog_histlen": "repl_backlog_history_bytes", |
| 292 | "master_repl_offset": "master_repl_offset", |
| 293 | "second_repl_offset": "second_repl_offset", |
| 294 | "slave_expires_tracked_keys": "slave_expires_tracked_keys", |
| 295 | "slave_priority": "slave_priority", |
| 296 | "sync_full": "replica_resyncs_full", |
| 297 | "sync_partial_ok": "replica_partial_resync_accepted", |
| 298 | "sync_partial_err": "replica_partial_resync_denied", |
| 299 | |
| 300 | // # Cluster |
| 301 | "cluster_stats_messages_sent": "cluster_messages_sent_total", |
| 302 | "cluster_stats_messages_received": "cluster_messages_received_total", |
| 303 | |
| 304 | // # Tile38 |
| 305 | // based on https://tile38.com/commands/server/ |
| 306 | "tile38_aof_size": "tile38_aof_size_bytes", |
| 307 | "tile38_avg_point_size": "tile38_avg_item_size_bytes", |
| 308 | "tile38_sys_cpus": "tile38_cpus_total", |
| 309 | "tile38_heap_released_bytes": "tile38_heap_released_bytes", |
| 310 | "tile38_heap_alloc_bytes": "tile38_heap_size_bytes", |
| 311 | "tile38_http_transport": "tile38_http_transport", |
| 312 | "tile38_in_memory_size": "tile38_in_memory_size_bytes", |
| 313 | "tile38_max_heap_size": "tile38_max_heap_size_bytes", |
| 314 | "tile38_alloc_bytes": "tile38_mem_alloc_bytes", |
| 315 | "tile38_num_collections": "tile38_num_collections_total", |
| 316 | "tile38_num_hooks": "tile38_num_hooks_total", |
| 317 | "tile38_num_objects": "tile38_num_objects_total", |
| 318 | "tile38_num_points": "tile38_num_points_total", |
| 319 | "tile38_pointer_size": "tile38_pointer_size_bytes", |
| 320 | "tile38_read_only": "tile38_read_only", |
| 321 | "tile38_go_threads": "tile38_threads_total", |
| 322 | "tile38_go_goroutines": "tile38_go_goroutines_total", |
| 323 | "tile38_last_gc_time_seconds": "tile38_last_gc_time_seconds", |
| 324 | "tile38_next_gc_bytes": "tile38_next_gc_bytes", |
| 325 | |
| 326 | // addtl. KeyDB metrics |
| 327 | "server_threads": "server_threads_total", |
| 328 | "long_lock_waits": "long_lock_waits_total", |
| 329 | "current_client_thread": "current_client_thread", |
| 330 | |
| 331 | // Redis Modules metrics, RediSearch module |
| 332 | "search_number_of_indexes": "search_number_of_indexes", |
| 333 | "search_used_memory_indexes": "search_used_memory_indexes_bytes", |
| 334 | "search_dialect_1": "search_dialect_1", |
| 335 | "search_dialect_2": "search_dialect_2", |
| 336 | "search_dialect_3": "search_dialect_3", |
| 337 | "search_dialect_4": "search_dialect_4", |
| 338 | // Legacy redis-stack v7.4 metrics |
| 339 | "search_global_idle": "search_global_idle", |
| 340 | "search_global_total": "search_global_total", |
| 341 | "search_bytes_collected": "search_collected_bytes", |
| 342 | // RediSearch module v8.0 |
| 343 | "search_number_of_active_indexes": "search_number_of_active_indexes", |
| 344 | "search_number_of_active_indexes_running_queries": "search_number_of_active_indexes_running_queries", |
| 345 | "search_number_of_active_indexes_indexing": "search_number_of_active_indexes_indexing", |
| 346 | "search_total_active_write_threads": "search_total_active_write_threads", |
| 347 | "search_total_num_docs_in_indexes": "search_total_num_docs_in_indexes", |
| 348 | "search_smallest_memory_index": "search_smallest_memory_index_bytes", |
| 349 | "search_largest_memory_index": "search_largest_memory_index_bytes", |
| 350 | "search_used_memory_vector_index": "search_used_memory_vector_index_bytes", |
| 351 | "search_global_idle_user": "search_global_idle_user", // search_gc metrics were split into user and internal |
| 352 | "search_global_idle_internal": "search_global_idle_internal", // in PR: https://github.com/RediSearch/RediSearch/pull/5616 |
| 353 | "search_global_total_user": "search_global_total_user", |
| 354 | "search_global_total_internal": "search_global_total_internal", |
| 355 | "search_gc_bytes_collected": "search_gc_collected_bytes", // search_bytes_collected was renamed in https://github.com/RediSearch/RediSearch/pull/5616 |
| 356 | "search_gc_total_docs_not_collected": "search_gc_total_docs_not_collected", |
| 357 | "search_gc_marked_deleted_vectors": "search_gc_marked_deleted_vectors", |
| 358 | "search_errors_indexing_failures": "search_errors_indexing_failures", |
| 359 | // Valkey v8 metrics |
| 360 | "bf_bloom_total_memory_bytes": "bf_bloom_total_memory_bytes", |
| 361 | "bf_bloom_num_objects": "bf_bloom_num_objects", |
| 362 | "bf_bloom_num_filters_across_objects": "bf_bloom_num_filters_across_objects", |
| 363 | "bf_bloom_num_items_across_objects": "bf_bloom_num_items_across_objects", |
| 364 | "bf_bloom_capacity_across_objects": "bf_bloom_capacity_across_objects", |
| 365 | "json_total_memory_bytes": "json_total_memory_bytes", |
| 366 | "json_num_documents": "json_num_documents", |
| 367 | "search_used_memory_bytes": "search_used_memory_bytes", |
| 368 | "search_number_of_attributes": "search_number_of_attributes", |
| 369 | "search_total_indexed_documents": "search_total_indexed_documents", |
| 370 | "search_query_queue_size": "search_query_queue_size", |
| 371 | "search_writer_queue_size": "search_writer_queue_size", |
| 372 | "search_string_interning_store_size": "search_string_interning_store_size", |
| 373 | "search_vector_externing_hash_extern_errors": "search_vector_externing_hash_extern_errors", |
| 374 | "search_vector_externing_num_lru_entries": "search_vector_externing_num_lru_entries", |
| 375 | }, |
| 376 | |
| 377 | metricMapCounters: map[string]string{ |
| 378 | "total_connections_received": "connections_received_total", |
| 379 | "total_commands_processed": "commands_processed_total", |
| 380 | |
| 381 | "rejected_connections": "rejected_connections_total", |
| 382 | "total_net_input_bytes": "net_input_bytes_total", |
| 383 | "total_net_output_bytes": "net_output_bytes_total", |
| 384 | |
| 385 | "total_net_repl_input_bytes": "net_repl_input_bytes_total", |
| 386 | "total_net_repl_output_bytes": "net_repl_output_bytes_total", |
| 387 | |
| 388 | "expired_subkeys": "expired_subkeys_total", |
| 389 | "expired_keys": "expired_keys_total", |
| 390 | "expired_time_cap_reached_count": "expired_time_cap_reached_total", |
| 391 | "expire_cycle_cpu_milliseconds": "expire_cycle_cpu_time_ms_total", |
| 392 | "evicted_keys": "evicted_keys_total", |
| 393 | "evicted_clients": "evicted_clients_total", // Added in Redis 7.0 |
| 394 | "evicted_scripts": "evicted_scripts_total", // Added in Redis 7.4 |
| 395 | "total_eviction_exceeded_time": "eviction_exceeded_time_ms_total", |
| 396 | "keyspace_hits": "keyspace_hits_total", |
| 397 | "keyspace_misses": "keyspace_misses_total", |
| 398 | |
| 399 | "eventloop_cycles": "eventloop_cycles_total", // Added in Redis 7.0 |
| 400 | "eventloop_duration_sum": "eventloop_duration_sum_usec_total", // Added in Redis 7.0 |
| 401 | "eventloop_duration_cmd_sum": "eventloop_duration_cmd_sum_usec_total", // Added in Redis 7.0 |
| 402 | |
| 403 | "used_cpu_sys": "cpu_sys_seconds_total", |
| 404 | "used_cpu_user": "cpu_user_seconds_total", |
| 405 | "used_cpu_sys_children": "cpu_sys_children_seconds_total", |
| 406 | "used_cpu_user_children": "cpu_user_children_seconds_total", |
| 407 | "used_cpu_sys_main_thread": "cpu_sys_main_thread_seconds_total", |
| 408 | "used_cpu_user_main_thread": "cpu_user_main_thread_seconds_total", |
| 409 | |
| 410 | "unexpected_error_replies": "unexpected_error_replies", |
| 411 | "total_error_replies": "total_error_replies", |
| 412 | "dump_payload_sanitizations": "dump_payload_sanitizations", |
| 413 | "total_reads_processed": "total_reads_processed", |
| 414 | "total_writes_processed": "total_writes_processed", |
| 415 | "io_threaded_reads_processed": "io_threaded_reads_processed", |
| 416 | "io_threaded_writes_processed": "io_threaded_writes_processed", |
| 417 | "client_query_buffer_limit_disconnections": "client_query_buffer_limit_disconnections_total", |
| 418 | "client_output_buffer_limit_disconnections": "client_output_buffer_limit_disconnections_total", |
| 419 | "reply_buffer_shrinks": "reply_buffer_shrinks_total", |
| 420 | "reply_buffer_expands": "reply_buffer_expands_total", |
| 421 | "acl_access_denied_auth": "acl_access_denied_auth_total", |
| 422 | "acl_access_denied_cmd": "acl_access_denied_cmd_total", |
| 423 | "acl_access_denied_key": "acl_access_denied_key_total", |
| 424 | "acl_access_denied_channel": "acl_access_denied_channel_total", |
| 425 | |
| 426 | // addtl. KeyDB metrics |
| 427 | "cached_keys": "cached_keys_total", |
| 428 | "storage_provider_read_hits": "storage_provider_read_hits", |
| 429 | "storage_provider_read_misses": "storage_provider_read_misses", |
| 430 | |
| 431 | // Redis Modules metrics, RediSearch module |
| 432 | "search_total_indexing_time": "search_indexing_time_ms_total", |
| 433 | // Legacy redis-stack v7.4 metrics |
| 434 | "search_total_cycles": "search_cycles_total", |
| 435 | "search_total_ms_run": "search_run_ms_total", |
| 436 | // RediSearch module v8.0 |
| 437 | "search_gc_total_cycles": "search_gc_cycles_total", // search_gc metrics were renamed |
| 438 | "search_gc_total_ms_run": "search_gc_run_ms_total", // in PR: https://github.com/RediSearch/RediSearch/pull/5616 |
| 439 | "search_total_queries_processed": "search_queries_processed_total", |
| 440 | "search_total_query_commands": "search_query_commands_total", |
| 441 | "search_total_query_execution_time_ms": "search_query_execution_time_ms_total", |
| 442 | "search_total_active_queries": "search_active_queries_total", |
| 443 | // Valkey v8 metrics |
| 444 | "bf_bloom_defrag_hits": "bf_bloom_defrag_hits_total", |
| 445 | "bf_bloom_defrag_misses": "bf_bloom_defrag_misses_total", |
| 446 | "search_worker_pool_suspend_cnt": "search_worker_pool_suspend_count", |
| 447 | "search_writer_resumed_cnt": "search_writer_resumed_count", |
| 448 | "search_reader_resumed_cnt": "search_reader_resumed_count", |
| 449 | "search_writer_suspension_expired_cnt": "search_writer_suspension_expired_count", |
| 450 | "search_rdb_load_success_cnt": "search_rdb_load_success_count", |
| 451 | "search_rdb_load_failure_cnt": "search_rdb_load_failure_count", |
| 452 | "search_rdb_save_success_cnt": "search_rdb_save_success_count", |
| 453 | "search_rdb_save_failure_cnt": "search_rdb_save_failure_count", |
| 454 | "search_successful_requests_count": "search_successful_requests_count", |
| 455 | "search_failure_requests_count": "search_failure_requests_count", |
| 456 | "search_hybrid_requests_count": "search_hybrid_requests_count", |
| 457 | "search_inline_filtering_requests_count": "search_inline_filtering_requests_count", |
| 458 | "search_hnsw_add_exceptions_count": "search_hnsw_add_exceptions_count", |
| 459 | "search_hnsw_remove_exceptions_count": "search_hnsw_remove_exceptions_count", |
| 460 | "search_hnsw_modify_exceptions_count": "search_hnsw_modify_exceptions_count", |
| 461 | "search_hnsw_search_exceptions_count": "search_hnsw_search_exceptions_count", |
| 462 | "search_hnsw_create_exceptions_count": "search_hnsw_create_exceptions_count", |
| 463 | "search_vector_externing_entry_count": "search_vector_externing_entry_count", |
| 464 | "search_vector_externing_generated_value_cnt": "search_vector_externing_generated_value_count", |
| 465 | "search_vector_externing_lru_promote_cnt": "search_vector_externing_lru_promote_count", |
| 466 | "search_vector_externing_deferred_entry_cnt": "search_vector_externing_deferred_entry_count", |
| 467 | }, |
| 468 | } |
| 469 | |
| 470 | if e.options.ConfigCommandName == "" { |
| 471 | e.options.ConfigCommandName = "CONFIG" |
| 472 | } |
| 473 | |
| 474 | if keys, err := parseKeyArg(opts.CheckKeys); err != nil { |
| 475 | return nil, fmt.Errorf("couldn't parse check-keys: %s", err) |
| 476 | } else { |
| 477 | log.Debugf("keys: %#v", keys) |
| 478 | } |
| 479 | |
| 480 | if singleKeys, err := parseKeyArg(opts.CheckSingleKeys); err != nil { |
| 481 | return nil, fmt.Errorf("couldn't parse check-single-keys: %s", err) |
| 482 | } else { |
| 483 | log.Debugf("singleKeys: %#v", singleKeys) |
| 484 | } |
| 485 | |
| 486 | if streams, err := parseKeyArg(opts.CheckStreams); err != nil { |
| 487 | return nil, fmt.Errorf("couldn't parse check-streams: %s", err) |
| 488 | } else { |
| 489 | log.Debugf("streams: %#v", streams) |
| 490 | } |
| 491 | |
| 492 | if singleStreams, err := parseKeyArg(opts.CheckSingleStreams); err != nil { |
| 493 | return nil, fmt.Errorf("couldn't parse check-single-streams: %s", err) |
| 494 | } else { |
| 495 | log.Debugf("singleStreams: %#v", singleStreams) |
| 496 | } |
| 497 | |
| 498 | if countKeys, err := parseKeyArg(opts.CountKeys); err != nil { |
| 499 | return nil, fmt.Errorf("couldn't parse count-keys: %s", err) |
| 500 | } else { |
| 501 | log.Debugf("countKeys: %#v", countKeys) |
| 502 | } |
| 503 | |
| 504 | if opts.InclSystemMetrics { |
| 505 | e.metricMapGauges["total_system_memory"] = "total_system_memory_bytes" |
| 506 | } |
| 507 | |
| 508 | e.metricDescriptions = map[string]*prometheus.Desc{} |
| 509 | |
| 510 | for k, desc := range map[string]struct { |
| 511 | txt string |
| 512 | lbls []string |
| 513 | }{ |
| 514 | "commands_duration_seconds_total": {txt: `Total amount of time in seconds spent per command`, lbls: []string{"cmd"}}, |
| 515 | "commands_failed_calls_total": {txt: `Total number of errors prior command execution per command`, lbls: []string{"cmd"}}, |
| 516 | "commands_latencies_usec": {txt: `A histogram of latencies per command`, lbls: []string{"cmd"}}, |
| 517 | "commands_rejected_calls_total": {txt: `Total number of errors within command execution per command`, lbls: []string{"cmd"}}, |
| 518 | "commands_total": {txt: `Total number of calls per command`, lbls: []string{"cmd"}}, |
| 519 | "config_client_output_buffer_limit_bytes": {txt: `The configured buffer limits per class`, lbls: []string{"class", "limit"}}, |
| 520 | "config_client_output_buffer_limit_overcome_seconds": {txt: `How long for buffer limits per class to be exceeded before replicas are dropped`, lbls: []string{"class", "limit"}}, |
| 521 | "config_key_value": {txt: `Config key and value`, lbls: []string{"key", "value"}}, |
| 522 | "config_value": {txt: `Config key and value as metric`, lbls: []string{"key"}}, |
| 523 | "connected_slave_lag_seconds": {txt: "Lag of connected slave", lbls: []string{"slave_ip", "slave_port", "slave_state"}}, |
| 524 | "connected_slave_offset_bytes": {txt: "Offset of connected slave", lbls: []string{"slave_ip", "slave_port", "slave_state"}}, |
| 525 | "db_avg_ttl_seconds": {txt: "Avg TTL in seconds", lbls: []string{"db"}}, |
| 526 | "db_keys": {txt: "Total number of keys by DB", lbls: []string{"db"}}, |
| 527 | "db_keys_cached": {txt: "Total number of cached keys by DB", lbls: []string{"db"}}, |
| 528 | "db_keys_expiring": {txt: "Total number of expiring keys by DB", lbls: []string{"db"}}, |
| 529 | "errors_total": {txt: `Total number of errors per error type`, lbls: []string{"err"}}, |
| 530 | "exporter_last_scrape_error": {txt: "The last scrape error status.", lbls: []string{"err"}}, |
| 531 | "key_group_count": {txt: `Count of keys in key group`, lbls: []string{"db", "key_group"}}, |
| 532 | "key_group_memory_usage_bytes": {txt: `Total memory usage of key group in bytes`, lbls: []string{"db", "key_group"}}, |
| 533 | "key_memory_usage_bytes": {txt: `The memory usage of "key" in bytes`, lbls: []string{"db", "key"}}, |
| 534 | "key_size": {txt: `The length or size of "key"`, lbls: []string{"db", "key"}}, |
| 535 | "key_value": {txt: `The value of "key"`, lbls: []string{"db", "key"}}, |
| 536 | "key_value_as_string": {txt: `The value of "key" as a string`, lbls: []string{"db", "key", "val"}}, |
| 537 | "keys_count": {txt: `Count of keys`, lbls: []string{"db", "key"}}, |
| 538 | "last_key_groups_scrape_duration_milliseconds": {txt: `Duration of the last key group metrics scrape in milliseconds`}, |
| 539 | "last_slow_execution_duration_seconds": {txt: `The amount of time needed for last slow execution, in seconds`}, |
| 540 | "latency_percentiles_usec": {txt: `A summary of latency percentile distribution per command`, lbls: []string{"cmd"}}, |
| 541 | "latency_spike_duration_seconds": {txt: `Length of the last latency spike in seconds`, lbls: []string{"event_name"}}, |
| 542 | "latency_spike_last": {txt: `When the latency spike last occurred`, lbls: []string{"event_name"}}, |
| 543 | "master_last_io_seconds_ago": {txt: "Master last io seconds ago", lbls: []string{"master_host", "master_port"}}, |
| 544 | "master_link_up": {txt: "Master link status on Redis slave", lbls: []string{"master_host", "master_port"}}, |
| 545 | "master_sync_in_progress": {txt: "Master sync in progress", lbls: []string{"master_host", "master_port"}}, |
| 546 | "module_info": {txt: "Information about loaded Redis module", lbls: []string{"name", "ver", "api", "filters", "usedby", "using"}}, |
| 547 | "number_of_distinct_key_groups": {txt: `Number of distinct key groups`, lbls: []string{"db"}}, |
| 548 | "rdb_current_size_bytes": {txt: "Current RDB file size in bytes"}, |
| 549 | "script_result": {txt: "Result of the collect script evaluation", lbls: []string{"filename"}}, |
| 550 | "script_values": {txt: "Values returned by the collect script", lbls: []string{"key", "filename"}}, |
| 551 | "search_index_num_docs": {txt: "Number of documents in search index", lbls: []string{"index_name"}}, |
| 552 | "search_index_max_doc_id": {txt: "Maximum document ID in search index", lbls: []string{"index_name"}}, |
| 553 | "search_index_num_terms": {txt: "Number of distinct terms in search index", lbls: []string{"index_name"}}, |
| 554 | "search_index_num_records": {txt: "Total number of records in search index", lbls: []string{"index_name"}}, |
| 555 | "search_index_inverted_size_bytes": {txt: "Memory used by the inverted index", lbls: []string{"index_name"}}, |
| 556 | "search_index_total_inverted_index_blocks": {txt: "Total number of blocks in the inverted index", lbls: []string{"index_name"}}, |
| 557 | "search_index_vector_index_size_bytes": {txt: "Memory used by the vector index, stores vectors associated with each document", lbls: []string{"index_name"}}, |
| 558 | "search_index_offset_vectors_size_bytes": {txt: "Memory used by the offset vectors, store positional information for terms in documents", lbls: []string{"index_name"}}, |
| 559 | "search_index_doc_table_size_bytes": {txt: "Memory used by the document table, contains metadata about each document in the index", lbls: []string{"index_name"}}, |
| 560 | "search_index_sortable_values_size_bytes": {txt: "Memory used by sortable values, used for sorting purposes", lbls: []string{"index_name"}}, |
| 561 | "search_index_key_table_size_bytes": {txt: "Memory used by the key table, stores mapping between document IDs and keys", lbls: []string{"index_name"}}, |
| 562 | "search_index_tag_overhead_size_bytes": {txt: "Size of the TAG index structures used for optimising performance", lbls: []string{"index_name"}}, |
| 563 | "search_index_text_overhead_size_bytes": {txt: "Size of the TEXT index structures used for optimising performance", lbls: []string{"index_name"}}, |
| 564 | "search_index_total_index_memory_size_bytes": {txt: "Total memory consumed by all indexes in the DB", lbls: []string{"index_name"}}, |
| 565 | "search_index_geoshapes_size_bytes": {txt: "Memory used by GEO-related fields", lbls: []string{"index_name"}}, |
| 566 | "search_index_avg_per_doc_records": {txt: "Average number of records (including deletions) per document", lbls: []string{"index_name"}}, |
| 567 | "search_index_avg_per_record_bytes": {txt: "Average size of each record in bytes", lbls: []string{"index_name"}}, |
| 568 | "search_index_avg_per_term_offsets": {txt: "Average number of offsets (position information) per term", lbls: []string{"index_name"}}, |
| 569 | "search_index_avg_per_record_offset_bits": {txt: "Average number of bits used for offsets per record", lbls: []string{"index_name"}}, |
| 570 | "search_index_indexing": {txt: "Indicates whether the index is currently being generated", lbls: []string{"index_name"}}, |
| 571 | "search_index_percent_indexed": {txt: "Percentage of the index that has been successfully generated (0-1)", lbls: []string{"index_name"}}, |
| 572 | "search_index_hash_indexing_failures": {txt: "Number of failures encountered during indexing", lbls: []string{"index_name"}}, |
| 573 | "search_index_number_of_uses_total": {txt: "Number of times the index has been used", lbls: []string{"index_name"}}, |
| 574 | "search_index_cleaning": {txt: "Index deletion flag. A value of 1 indicates index deletion is in progress", lbls: []string{"index_name"}}, |
| 575 | "sentinel_master_ckquorum_status": {txt: "Master ckquorum status", lbls: []string{"master_name", "message"}}, |
| 576 | "sentinel_peer_info": {txt: "Other Sentinel peers discovered via SENTINEL SENTINELS (one scrape from one Sentinel)", lbls: []string{"master_name", "master_address", "name", "ip", "port", "runid", "flags"}}, |
| 577 | "sentinel_master_ok_sentinels": {txt: "The number of okay sentinels monitoring this master", lbls: []string{"master_name", "master_address"}}, |
| 578 | "sentinel_master_ok_slaves": {txt: "The number of okay slaves of the master", lbls: []string{"master_name", "master_address"}}, |
| 579 | "sentinel_master_sentinels": {txt: "The number of sentinels monitoring this master", lbls: []string{"master_name", "master_address"}}, |
| 580 | "sentinel_master_setting_ckquorum": {txt: "Show the current ckquorum config for each master", lbls: []string{"master_name", "master_address"}}, |
| 581 | "sentinel_master_setting_down_after_milliseconds": {txt: "Show the current down-after-milliseconds config for each master", lbls: []string{"master_name", "master_address"}}, |
| 582 | "sentinel_master_setting_failover_timeout": {txt: "Show the current failover-timeout config for each master", lbls: []string{"master_name", "master_address"}}, |
| 583 | "sentinel_master_setting_parallel_syncs": {txt: "Show the current parallel-syncs config for each master", lbls: []string{"master_name", "master_address"}}, |
| 584 | "sentinel_master_config_epoch": {txt: "The configuration epoch of the master (increments on each failover)", lbls: []string{"master_name", "master_address"}}, |
| 585 | "sentinel_master_last_ok_ping_reply_seconds": {txt: "Elapsed time in seconds since the last successful ping reply from the master", lbls: []string{"master_name", "master_address"}}, |
| 586 | "sentinel_master_slaves": {txt: "The number of slaves of the master", lbls: []string{"master_name", "master_address"}}, |
| 587 | "sentinel_master_status": {txt: "Master status on Sentinel", lbls: []string{"master_name", "master_address", "master_status"}}, |
| 588 | "sentinel_masters": {txt: "The number of masters this sentinel is watching"}, |
| 589 | "sentinel_running_scripts": {txt: "Number of scripts in execution right now"}, |
| 590 | "sentinel_scripts_queue_length": {txt: "Queue of user scripts to execute"}, |
| 591 | "sentinel_simulate_failure_flags": {txt: "Failures simulations"}, |
| 592 | "sentinel_tilt": {txt: "Sentinel is in TILT mode"}, |
| 593 | "sentinel_config_key_value": {txt: `Sentinel global config key and value`, lbls: []string{"key", "value"}}, |
| 594 | "sentinel_config_value": {txt: `Sentinel global config key and value as metric`, lbls: []string{"key"}}, |
| 595 | "slave_info": {txt: "Information about the Redis slave", lbls: []string{"master_host", "master_port", "read_only"}}, |
| 596 | "slave_repl_offset": {txt: "Slave replication offset", lbls: []string{"master_host", "master_port"}}, |
| 597 | "slowlog_last_id": {txt: `Last id of slowlog`}, |
| 598 | "slowlog_length": {txt: `Total slowlog`}, |
| 599 | "start_time_seconds": {txt: "Start time of the Redis instance since unix epoch in seconds."}, |
| 600 | "stream_first_entry_id": {txt: `The epoch timestamp (ms) of the first message in the stream`, lbls: []string{"db", "stream"}}, |
| 601 | "stream_group_consumer_idle_seconds": {txt: `Consumer idle time in seconds`, lbls: []string{"db", "stream", "group", "consumer"}}, |
| 602 | "stream_group_consumer_messages_pending": {txt: `Pending number of messages for this specific consumer`, lbls: []string{"db", "stream", "group", "consumer"}}, |
| 603 | "stream_group_consumers": {txt: `Consumers count of stream group`, lbls: []string{"db", "stream", "group"}}, |
| 604 | "stream_group_entries_read": {txt: `Total number of entries read from the stream group`, lbls: []string{"db", "stream", "group"}}, |
| 605 | "stream_group_lag": {txt: `The number of messages waiting to be delivered to the stream group's consumers`, lbls: []string{"db", "stream", "group"}}, |
| 606 | "stream_group_last_delivered_id": {txt: `The epoch timestamp (ms) of the last delivered message`, lbls: []string{"db", "stream", "group"}}, |
| 607 | "stream_group_messages_pending": {txt: `Pending number of messages in that stream group`, lbls: []string{"db", "stream", "group"}}, |
| 608 | "stream_groups": {txt: `Groups count of stream`, lbls: []string{"db", "stream"}}, |
| 609 | "stream_last_entry_id": {txt: `The epoch timestamp (ms) of the last message in the stream`, lbls: []string{"db", "stream"}}, |
| 610 | "stream_last_generated_id": {txt: `The epoch timestamp (ms) of the latest message on the stream`, lbls: []string{"db", "stream"}}, |
| 611 | "stream_length": {txt: `The number of elements of the stream`, lbls: []string{"db", "stream"}}, |
| 612 | "stream_max_deleted_entry_id": {txt: `The epoch timestamp (ms) of last message was deleted from the stream`, lbls: []string{"db", "stream"}}, |
| 613 | "stream_radix_tree_keys": {txt: `Radix tree keys count"`, lbls: []string{"db", "stream"}}, |
| 614 | "stream_radix_tree_nodes": {txt: `Radix tree nodes count`, lbls: []string{"db", "stream"}}, |
| 615 | "up": {txt: "Information about the Redis instance"}, |
| 616 | } { |
| 617 | if e.options.AppendInstanceRoleLabel { |
| 618 | desc.lbls = append(desc.lbls, "instance_role") // append instance_role label to all metrics |
| 619 | } |
| 620 | e.metricDescriptions[k] = newMetricDescr(opts.Namespace, k, desc.txt, desc.lbls) |
| 621 | } |
| 622 | |
| 623 | if e.options.MetricsPath == "" { |
| 624 | e.options.MetricsPath = "/metrics" |
| 625 | } |
| 626 | |
| 627 | e.mux = http.NewServeMux() |
| 628 | |
| 629 | if e.options.Registry != nil { |
| 630 | e.options.Registry.MustRegister(e) |
| 631 | e.mux.Handle(e.options.MetricsPath, promhttp.HandlerFor( |
| 632 | e.options.Registry, promhttp.HandlerOpts{ErrorHandling: promhttp.ContinueOnError}, |
| 633 | )) |
| 634 | |
| 635 | if !e.options.RedisMetricsOnly { |
| 636 | buildInfoCollector := prometheus.NewGaugeVec(prometheus.GaugeOpts{ |
| 637 | Namespace: opts.Namespace, |
| 638 | Name: "exporter_build_info", |
| 639 | Help: "redis exporter build_info", |
| 640 | }, []string{"version", "commit_sha", "build_date", "golang_version"}) |
| 641 | buildInfoCollector.WithLabelValues(e.buildInfo.Version, e.buildInfo.CommitSha, e.buildInfo.Date, runtime.Version()).Set(1) |
| 642 | e.options.Registry.MustRegister(buildInfoCollector) |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | e.mux.HandleFunc("/", e.indexHandler) |
| 647 | if !e.options.DisableScrapeEndpoint { |
| 648 | e.mux.HandleFunc("/scrape", e.scrapeHandler) |
| 649 | } |
| 650 | e.mux.HandleFunc("/discover-cluster-nodes", e.discoverClusterNodesHandler) |
| 651 | e.mux.HandleFunc("/health", e.healthHandler) |
| 652 | e.mux.HandleFunc("/-/reload", e.reloadPwdFile) |
| 653 | |
| 654 | return e, nil |
| 655 | } |
| 656 | |
| 657 | // Describe outputs Redis metric descriptions. |
| 658 | func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { |
| 659 | for _, desc := range e.metricDescriptions { |
| 660 | ch <- desc |
| 661 | } |
| 662 | |
| 663 | for _, v := range e.metricMapGauges { |
| 664 | ch <- newMetricDescr(e.options.Namespace, v, v+" metric", nil) |
| 665 | } |
| 666 | |
| 667 | for _, v := range e.metricMapCounters { |
| 668 | ch <- newMetricDescr(e.options.Namespace, v, v+" metric", nil) |
| 669 | } |
| 670 | |
| 671 | ch <- e.totalScrapes.Desc() |
| 672 | ch <- e.scrapeDuration.Desc() |
| 673 | ch <- e.targetScrapeRequestErrors.Desc() |
| 674 | } |
| 675 | |
| 676 | // Collect fetches new metrics from the RedisHost and updates the appropriate metrics. |
| 677 | func (e *Exporter) Collect(ch chan<- prometheus.Metric) { |
| 678 | e.Lock() |
| 679 | defer e.Unlock() |
| 680 | e.totalScrapes.Inc() |
| 681 | |
| 682 | if e.redisAddr != "" { |
| 683 | startTime := time.Now() |
| 684 | var up float64 |
| 685 | if err := e.scrapeRedisHost(ch); err != nil { |
| 686 | e.registerConstMetricGauge(ch, "exporter_last_scrape_error", 1.0, fmt.Sprintf("%s", err)) |
| 687 | } else { |
| 688 | up = 1 |
| 689 | e.registerConstMetricGauge(ch, "exporter_last_scrape_error", 0, "") |
| 690 | } |
| 691 | |
| 692 | e.registerConstMetricGauge(ch, "up", up) |
| 693 | |
| 694 | took := time.Since(startTime).Seconds() |
| 695 | e.scrapeDuration.Observe(took) |
| 696 | e.registerConstMetricGauge(ch, "exporter_last_scrape_duration_seconds", took) |
| 697 | } |
| 698 | |
| 699 | ch <- e.totalScrapes |
| 700 | ch <- e.scrapeDuration |
| 701 | ch <- e.targetScrapeRequestErrors |
| 702 | } |
| 703 | |
| 704 | func (e *Exporter) extractConfigMetrics(ch chan<- prometheus.Metric, config map[string]string) (dbCount int, err error) { |
| 705 | for strKey, strVal := range config { |
| 706 | if strKey == "databases" { |
| 707 | if dbCount, err = strconv.Atoi(strVal); err != nil { |
| 708 | return 0, fmt.Errorf("invalid config value for key databases: %#v", strVal) |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | if e.options.InclConfigMetrics { |
| 713 | if redact := map[string]bool{ |
| 714 | "masterauth": true, |
| 715 | "requirepass": true, |
| 716 | "tls-key-file-pass": true, |
| 717 | "tls-client-key-file-pass": true, |
| 718 | }[strKey]; !redact || !e.options.RedactConfigMetrics { |
| 719 | e.registerConstMetricGauge(ch, "config_key_value", 1.0, strKey, strVal) |
| 720 | if val, err := strconv.ParseFloat(strVal, 64); err == nil { |
| 721 | e.registerConstMetricGauge(ch, "config_value", val, strKey) |
| 722 | } |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | if map[string]bool{ |
| 727 | "io-threads": true, |
| 728 | "maxclients": true, |
| 729 | "maxmemory": true, |
| 730 | "repl-backlog-size": true, |
| 731 | }[strKey] { |
| 732 | if val, err := strconv.ParseFloat(strVal, 64); err == nil { |
| 733 | strKey = strings.ReplaceAll(strKey, "-", "_") |
| 734 | e.registerConstMetricGauge(ch, fmt.Sprintf("config_%s", strKey), val) |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | if strKey == "client-output-buffer-limit" { |
| 739 | // client-output-buffer-limit "normal 0 0 0 slave 1610612736 1610612736 0 pubsub 33554432 8388608 60" |
| 740 | splitVal := strings.Split(strVal, " ") |
| 741 | for i := 0; i+3 < len(splitVal); i += 4 { |
| 742 | class := splitVal[i] |
| 743 | if val, err := strconv.ParseFloat(splitVal[i+1], 64); err == nil { |
| 744 | e.registerConstMetricGauge(ch, "config_client_output_buffer_limit_bytes", val, class, "hard") |
| 745 | } |
| 746 | if val, err := strconv.ParseFloat(splitVal[i+2], 64); err == nil { |
| 747 | e.registerConstMetricGauge(ch, "config_client_output_buffer_limit_bytes", val, class, "soft") |
| 748 | } |
| 749 | if val, err := strconv.ParseFloat(splitVal[i+3], 64); err == nil { |
| 750 | e.registerConstMetricGauge(ch, "config_client_output_buffer_limit_overcome_seconds", val, class, "soft") |
| 751 | } |
| 752 | } |
| 753 | } |
| 754 | } |
| 755 | return |
| 756 | } |
| 757 | |
| 758 | func (e *Exporter) scrapeRedisHost(ch chan<- prometheus.Metric) error { |
| 759 | defer log.Debugf("scrapeRedisHost() done") |
| 760 | |
| 761 | startTime := time.Now() |
| 762 | c, err := e.connectToRedis() |
| 763 | connectTookSeconds := time.Since(startTime).Seconds() |
| 764 | e.registerConstMetricGauge(ch, "exporter_last_scrape_connect_time_seconds", connectTookSeconds) |
| 765 | |
| 766 | if err != nil { |
| 767 | var redactedAddr string |
| 768 | if redisURL, err2 := url.Parse(e.redisAddr); err2 != nil { |
| 769 | log.Debugf("url.Parse( %s ) err: %s", e.redisAddr, err2) |
| 770 | redactedAddr = "<redacted>" |
| 771 | } else { |
| 772 | redactedAddr = redisURL.Redacted() |
| 773 | } |
| 774 | log.Errorf("Couldn't connect to redis instance (%s)", redactedAddr) |
| 775 | log.Debugf("connectToRedis( %s ) err: %s", e.redisAddr, err) |
| 776 | return err |
| 777 | } |
| 778 | defer c.Close() |
| 779 | |
| 780 | log.Debugf("connected to: %s", e.redisAddr) |
| 781 | log.Debugf("connecting took %f seconds", connectTookSeconds) |
| 782 | |
| 783 | if e.options.PingOnConnect { |
| 784 | startTime := time.Now() |
| 785 | |
| 786 | if _, err := doRedisCmd(c, "PING"); err != nil { |
| 787 | log.Errorf("Couldn't PING server, err: %s", err) |
| 788 | } else { |
| 789 | pingTookSeconds := time.Since(startTime).Seconds() |
| 790 | e.registerConstMetricGauge(ch, "exporter_last_scrape_ping_time_seconds", pingTookSeconds) |
| 791 | log.Debugf("PING took %f seconds", pingTookSeconds) |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | if e.options.SetClientName { |
| 796 | if _, err := doRedisCmd(c, "CLIENT", "SETNAME", "redis_exporter"); err != nil { |
| 797 | log.Errorf("Couldn't set client name, err: %s", err) |
| 798 | } |
| 799 | } |
| 800 | |
| 801 | infoAll, err := redis.String(doRedisCmd(c, "INFO", "ALL")) |
| 802 | if err != nil || infoAll == "" { |
| 803 | log.Debugf("Redis INFO ALL err: %s", err) |
| 804 | infoAll, err = redis.String(doRedisCmd(c, "INFO")) |
| 805 | if err != nil { |
| 806 | log.Errorf("Redis INFO err: %s", err) |
| 807 | return err |
| 808 | } |
| 809 | } |
| 810 | log.Debugf("Redis INFO ALL result: [%#v]", infoAll) |
| 811 | |
| 812 | if e.options.AppendInstanceRoleLabel { |
| 813 | e.instanceRole = getInstanceRoleFromInfo(infoAll) |
| 814 | } |
| 815 | |
| 816 | dbCount := 0 |
| 817 | if e.options.ConfigCommandName == "-" { |
| 818 | log.Debugf("Skipping extractConfigMetrics()") |
| 819 | } else { |
| 820 | if cfg, err := redis.StringMap(doRedisCmd(c, e.options.ConfigCommandName, "GET", "*")); err == nil { |
| 821 | dbCount, err = e.extractConfigMetrics(ch, cfg) |
| 822 | if err != nil { |
| 823 | log.Errorf("Redis extractConfigMetrics() err: %s", err) |
| 824 | return err |
| 825 | } |
| 826 | |
| 827 | if e.options.InclRdbFileSizeMetric { |
| 828 | e.extractRdbFileSizeMetric(ch, cfg) |
| 829 | } |
| 830 | } else { |
| 831 | log.Debugf("Redis CONFIG err: %s", err) |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | if strings.Contains(infoAll, "cluster_enabled:1") { |
| 836 | if clusterInfo, err := redis.String(doRedisCmd(c, "CLUSTER", "INFO")); err == nil { |
| 837 | e.extractClusterInfoMetrics(ch, clusterInfo) |
| 838 | |
| 839 | // in cluster mode Redis only supports one database, so no extra DB number padding needed |
| 840 | dbCount = 1 |
| 841 | } else { |
| 842 | log.Errorf("Redis CLUSTER INFO err: %s", err) |
| 843 | } |
| 844 | } else if dbCount == 0 { |
| 845 | // in non-cluster mode, if dbCount is zero, then "CONFIG" failed to retrieve a valid |
| 846 | // number of databases, and we use the Redis config default which is 16 |
| 847 | |
| 848 | dbCount = 16 |
| 849 | } |
| 850 | |
| 851 | log.Debugf("dbCount: %d", dbCount) |
| 852 | |
| 853 | role := e.extractInfoMetrics(ch, infoAll, dbCount) |
| 854 | |
| 855 | if !e.options.ExcludeLatencyHistogramMetrics { |
| 856 | e.extractLatencyMetrics(ch, infoAll, c) |
| 857 | } |
| 858 | |
| 859 | var keyConn redis.Conn |
| 860 | if e.options.IsCluster { |
| 861 | // |
| 862 | // in cluster mode we need to create a new, cluster-aware connection |
| 863 | // to properly handle cluster-redirects |
| 864 | // |
| 865 | k, keyConnErr := e.connectToRedisCluster() |
| 866 | if keyConnErr != nil { |
| 867 | log.Errorf("failed to get key operation connection: %s", keyConnErr) |
| 868 | } else { |
| 869 | // |
| 870 | // The "defer keyConn.Close()" ensures this temporary cluster connection gets |
| 871 | // cleaned up after key metrics extraction, while avoiding closing the original |
| 872 | // connection "c" which is still needed. |
| 873 | // |
| 874 | defer k.Close() |
| 875 | keyConn = k |
| 876 | } |
| 877 | } else { |
| 878 | // not in cluster mode - we can use our existing connection for retrieving keys and such |
| 879 | keyConn = c |
| 880 | } |
| 881 | |
| 882 | // skip these metrics for master if SkipCheckKeysForRoleMaster is set |
| 883 | // (can help with reducing workload on the master node) |
| 884 | log.Debugf("checkKeys metric collection for role: %s SkipCheckKeysForRoleMaster flag: %#v", role, e.options.SkipCheckKeysForRoleMaster) |
| 885 | if role == InstanceRoleSlave || !e.options.SkipCheckKeysForRoleMaster { |
| 886 | if keyConn != nil { |
| 887 | if err := e.extractCheckKeyMetrics(ch, keyConn); err != nil { |
| 888 | log.Errorf("extractCheckKeyMetrics() err: %s", err) |
| 889 | } |
| 890 | e.extractCountKeysMetrics(ch, keyConn) |
| 891 | e.extractStreamMetrics(ch, keyConn) |
| 892 | } |
| 893 | } else { |
| 894 | log.Infof("skipping checkKeys metrics, role: %s flag: %#v", role, e.options.SkipCheckKeysForRoleMaster) |
| 895 | } |
| 896 | |
| 897 | e.extractSlowLogMetrics(ch, c) |
| 898 | |
| 899 | if keyConn != nil { |
| 900 | e.extractKeyGroupMetrics(ch, keyConn, dbCount) |
| 901 | } |
| 902 | |
| 903 | if strings.Contains(infoAll, "# Sentinel") { |
| 904 | e.extractSentinelMetrics(ch, c) |
| 905 | |
| 906 | e.extractSentinelConfig(ch, c) |
| 907 | } |
| 908 | |
| 909 | if e.options.ExportClientList { |
| 910 | e.extractConnectedClientMetrics(ch, c) |
| 911 | } |
| 912 | |
| 913 | if e.options.IsTile38 { |
| 914 | e.extractTile38Metrics(ch, c) |
| 915 | } |
| 916 | |
| 917 | if e.options.InclModulesMetrics { |
| 918 | e.extractModulesMetrics(ch, c) |
| 919 | } |
| 920 | |
| 921 | if e.options.InclSearchIndexesMetrics { |
| 922 | e.extractSearchIndexesMetrics(ch, c) |
| 923 | } |
| 924 | |
| 925 | if len(e.options.LuaScript) > 0 { |
| 926 | for filename, script := range e.options.LuaScript { |
| 927 | if err := e.extractLuaScriptMetrics(ch, c, filename, script); err != nil { |
| 928 | return err |
| 929 | } |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | return nil |
| 934 | } |