2 * collectd - src/redis.c, based on src/memcached.c
3 * Copyright (C) 2010 Andrés J. Díaz <ajdiaz@connectical.com>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * Andrés J. Díaz <ajdiaz@connectical.com>
28 #include <hiredis/hiredis.h>
31 #define REDIS_DEF_HOST "localhost"
32 #define REDIS_DEF_PASSWD ""
33 #define REDIS_DEF_PORT 6379
34 #define REDIS_DEF_TIMEOUT_SEC 2
35 #define REDIS_DEF_DB_COUNT 256
36 #define MAX_REDIS_VAL_SIZE 256
37 #define MAX_REDIS_QUERY 2048
39 /* Redis plugin configuration example:
52 typedef struct redis_query_s redis_query_t;
53 struct redis_query_s {
54 char query[MAX_REDIS_QUERY];
55 char type[DATA_MAX_NAME_LEN];
56 char instance[DATA_MAX_NAME_LEN];
63 derive_t keyspace_hits;
64 derive_t keyspace_misses;
66 typedef struct prev_s prev_t;
69 typedef struct redis_node_s redis_node_t;
75 struct timeval timeout;
76 bool report_command_stats;
77 bool report_cpu_usage;
78 redisContext *redisContext;
79 redis_query_t *queries;
85 static bool redis_have_instances;
86 static int redis_read(user_data_t *user_data);
88 static void redis_node_free(void *arg) {
89 redis_node_t *rn = arg;
93 redis_query_t *rq = rn->queries;
95 redis_query_t *next = rq->next;
100 redisFree(rn->redisContext);
105 } /* void redis_node_free */
107 static int redis_node_add(redis_node_t *rn) /* {{{ */
109 DEBUG("redis plugin: Adding node \"%s\".", rn->name);
111 /* Disable automatic generation of default instance in the init callback. */
112 redis_have_instances = true;
114 char cb_name[sizeof("redis/") + DATA_MAX_NAME_LEN];
115 snprintf(cb_name, sizeof(cb_name), "redis/%s", rn->name);
117 return plugin_register_complex_read(
118 /* group = */ "redis",
119 /* name = */ cb_name,
120 /* callback = */ redis_read,
123 .data = rn, .free_func = redis_node_free,
127 static redis_query_t *redis_config_query(oconfig_item_t *ci) /* {{{ */
132 rq = calloc(1, sizeof(*rq));
134 ERROR("redis plugin: calloc failed adding redis_query.");
137 status = cf_util_get_string_buffer(ci, rq->query, sizeof(rq->query));
142 * Default to a gauge type.
144 (void)strncpy(rq->type, "gauge", sizeof(rq->type));
145 (void)sstrncpy(rq->instance, rq->query, sizeof(rq->instance));
146 replace_special(rq->instance, sizeof(rq->instance));
150 for (int i = 0; i < ci->children_num; i++) {
151 oconfig_item_t *option = ci->children + i;
153 if (strcasecmp("Type", option->key) == 0) {
154 status = cf_util_get_string_buffer(option, rq->type, sizeof(rq->type));
155 } else if (strcasecmp("Instance", option->key) == 0) {
157 cf_util_get_string_buffer(option, rq->instance, sizeof(rq->instance));
158 } else if (strcasecmp("Database", option->key) == 0) {
159 status = cf_util_get_int(option, &rq->database);
160 if (rq->database < 0) {
161 WARNING("redis plugin: The \"Database\" option must be positive "
166 WARNING("redis plugin: unknown configuration option: %s", option->key);
178 static int redis_config_node(oconfig_item_t *ci) /* {{{ */
180 redis_node_t *rn = calloc(1, sizeof(*rn));
182 ERROR("redis plugin: calloc failed adding node.");
186 rn->port = REDIS_DEF_PORT;
187 rn->timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC;
188 rn->report_cpu_usage = true;
190 rn->host = strdup(REDIS_DEF_HOST);
191 if (rn->host == NULL) {
192 ERROR("redis plugin: strdup failed adding node.");
197 int status = cf_util_get_string(ci, &rn->name);
204 for (int i = 0; i < ci->children_num; i++) {
205 oconfig_item_t *option = ci->children + i;
207 if (strcasecmp("Host", option->key) == 0)
208 status = cf_util_get_string(option, &rn->host);
209 else if (strcasecmp("Port", option->key) == 0) {
210 status = cf_util_get_port_number(option);
215 } else if (strcasecmp("Query", option->key) == 0) {
216 redis_query_t *rq = redis_config_query(option);
220 rq->next = rn->queries;
223 } else if (strcasecmp("Timeout", option->key) == 0) {
225 status = cf_util_get_int(option, &timeout);
227 rn->timeout.tv_usec = timeout * 1000;
228 rn->timeout.tv_sec = rn->timeout.tv_usec / 1000000L;
229 rn->timeout.tv_usec %= 1000000L;
231 } else if (strcasecmp("Password", option->key) == 0)
232 status = cf_util_get_string(option, &rn->passwd);
233 else if (strcasecmp("ReportCommandStats", option->key) == 0)
234 status = cf_util_get_boolean(option, &rn->report_command_stats);
235 else if (strcasecmp("ReportCpuUsage", option->key) == 0)
236 status = cf_util_get_boolean(option, &rn->report_cpu_usage);
238 WARNING("redis plugin: Option `%s' not allowed inside a `Node' "
239 "block. I'll ignore this option.",
251 return redis_node_add(rn);
252 } /* }}} int redis_config_node */
254 static int redis_config(oconfig_item_t *ci) /* {{{ */
256 for (int i = 0; i < ci->children_num; i++) {
257 oconfig_item_t *option = ci->children + i;
259 if (strcasecmp("Node", option->key) == 0)
260 redis_config_node(option);
262 WARNING("redis plugin: Option `%s' not allowed in redis"
263 " configuration. It will be ignored.",
270 __attribute__((nonnull(2))) static void
271 redis_submit(const char *plugin_instance, const char *type,
272 const char *type_instance, value_t value) /* {{{ */
274 value_list_t vl = VALUE_LIST_INIT;
278 sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
279 if (plugin_instance != NULL)
280 sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
281 sstrncpy(vl.type, type, sizeof(vl.type));
282 if (type_instance != NULL)
283 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
285 plugin_dispatch_values(&vl);
288 __attribute__((nonnull(2))) static void
289 redis_submit2(const char *plugin_instance, const char *type,
290 const char *type_instance, value_t value0,
291 value_t value1) /* {{{ */
293 value_list_t vl = VALUE_LIST_INIT;
294 value_t values[] = {value0, value1};
297 vl.values_len = STATIC_ARRAY_SIZE(values);
299 sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
300 sstrncpy(vl.type, type, sizeof(vl.type));
302 if (plugin_instance != NULL)
303 sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
305 if (type_instance != NULL)
306 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
308 plugin_dispatch_values(&vl);
311 static int redis_init(void) /* {{{ */
313 if (redis_have_instances)
316 redis_node_t *rn = calloc(1, sizeof(*rn));
320 rn->port = REDIS_DEF_PORT;
321 rn->timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC;
323 rn->name = strdup("default");
324 rn->host = strdup(REDIS_DEF_HOST);
326 if (rn->name == NULL || rn->host == NULL) {
333 return redis_node_add(rn);
334 } /* }}} int redis_init */
336 static void *c_redisCommand(redis_node_t *rn, const char *format, ...) {
337 redisContext *c = rn->redisContext;
343 va_start(ap, format);
344 void *reply = redisvCommand(c, format, ap);
348 ERROR("redis plugin: Connection error: %s", c->errstr);
349 redisFree(rn->redisContext);
350 rn->redisContext = NULL;
354 } /* void c_redisCommand */
356 static int redis_get_info_value(char const *info_line, char const *field_name,
357 int ds_type, value_t *val) {
358 char *str = strstr(info_line, field_name);
359 static char buf[MAX_REDIS_VAL_SIZE];
363 str += strlen(field_name) + 1; /* also skip the ':' */
364 for (i = 0; (*str && (isdigit((unsigned char)*str) || *str == '.'));
369 if (parse_value(buf, val, ds_type) == -1) {
370 WARNING("redis plugin: Unable to parse field `%s'.", field_name);
377 } /* int redis_get_info_value */
379 static int redis_handle_info(char *node, char const *info_line,
380 char const *type, char const *type_instance,
381 char const *field_name, int ds_type) /* {{{ */
384 if (redis_get_info_value(info_line, field_name, ds_type, &val) != 0)
387 redis_submit(node, type, type_instance, val);
389 } /* }}} int redis_handle_info */
391 static int redis_handle_query(redis_node_t *rn, redis_query_t *rq) /* {{{ */
394 const data_set_t *ds;
397 ds = plugin_get_ds(rq->type);
399 ERROR("redis plugin: DS type `%s' not defined.", rq->type);
403 if (ds->ds_num != 1) {
404 ERROR("redis plugin: DS type `%s' has too many datasources. This is not "
405 "supported currently.",
410 if ((rr = c_redisCommand(rn, "SELECT %d", rq->database)) == NULL) {
411 WARNING("redis plugin: unable to switch to database `%d' on node `%s'.",
412 rq->database, rn->name);
416 if ((rr = c_redisCommand(rn, rq->query)) == NULL) {
417 WARNING("redis plugin: unable to carry out query `%s'.", rq->query);
422 case REDIS_REPLY_INTEGER:
423 switch (ds->ds[0].type) {
424 case DS_TYPE_COUNTER:
425 val.counter = (counter_t)rr->integer;
428 val.gauge = (gauge_t)rr->integer;
431 val.gauge = (derive_t)rr->integer;
433 case DS_TYPE_ABSOLUTE:
434 val.gauge = (absolute_t)rr->integer;
438 case REDIS_REPLY_STRING:
439 if (parse_value(rr->str, &val, ds->ds[0].type) == -1) {
440 WARNING("redis plugin: Query `%s': Unable to parse value.", rq->query);
445 case REDIS_REPLY_ERROR:
446 WARNING("redis plugin: Query `%s' failed: %s.", rq->query, rr->str);
449 case REDIS_REPLY_ARRAY:
450 WARNING("redis plugin: Query `%s' should return string or integer. Arrays "
451 "are not supported.",
456 WARNING("redis plugin: Query `%s': Cannot coerce redis type (%i).",
457 rq->query, rr->type);
462 redis_submit(rn->name, rq->type,
463 (strlen(rq->instance) > 0) ? rq->instance : NULL, val);
466 } /* }}} int redis_handle_query */
468 static int redis_db_stats(const char *node, char const *info_line) /* {{{ */
470 /* redis_db_stats parses and dispatches Redis database statistics,
471 * currently the number of keys for each database.
472 * info_line needs to have the following format:
473 * db0:keys=4,expires=0,avg_ttl=0
476 for (int db = 0; db < REDIS_DEF_DB_COUNT; db++) {
477 static char buf[MAX_REDIS_VAL_SIZE];
478 static char field_name[12];
479 static char db_id[4];
484 snprintf(field_name, sizeof(field_name), "db%d:keys=", db);
486 str = strstr(info_line, field_name);
490 str += strlen(field_name);
491 for (i = 0; (*str && isdigit((int)*str)); i++, str++)
495 if (parse_value(buf, &val, DS_TYPE_GAUGE) != 0) {
496 WARNING("redis plugin: Unable to parse field `%s'.", field_name);
500 snprintf(db_id, sizeof(db_id), "%d", db);
501 redis_submit(node, "records", db_id, val);
505 } /* }}} int redis_db_stats */
507 static void redis_cpu_usage(const char *node, char const *info_line) {
512 if (redis_get_info_value(info_line, "used_cpu_user", DS_TYPE_GAUGE,
516 if (redis_get_info_value(info_line, "used_cpu_sys", DS_TYPE_GAUGE,
520 redis_submit2(node, "ps_cputime", "daemon",
521 (value_t){.derive = rusage_user.gauge * 1000000},
522 (value_t){.derive = rusage_syst.gauge * 1000000});
530 if (redis_get_info_value(info_line, "used_cpu_user_children", DS_TYPE_GAUGE,
534 if (redis_get_info_value(info_line, "used_cpu_sys_children", DS_TYPE_GAUGE,
538 redis_submit2(node, "ps_cputime", "children",
539 (value_t){.derive = rusage_user.gauge * 1000000},
540 (value_t){.derive = rusage_syst.gauge * 1000000});
543 } /* void redis_cpu_usage */
545 static gauge_t calculate_ratio_percent(derive_t part1, derive_t part2,
546 derive_t *prev1, derive_t *prev2) {
547 if ((*prev1 == 0) || (*prev2 == 0) || (part1 < *prev1) || (part2 < *prev2)) {
553 derive_t num = part1 - *prev1;
554 derive_t denom = part2 - *prev2 + num;
565 return 100.0 * (gauge_t)num / (gauge_t)denom;
566 } /* gauge_t calculate_ratio_percent */
568 static void redis_keyspace_usage(redis_node_t *rn, char const *info_line) {
569 value_t hits, misses;
571 if (redis_get_info_value(info_line, "keyspace_hits", DS_TYPE_DERIVE, &hits) !=
575 if (redis_get_info_value(info_line, "keyspace_misses", DS_TYPE_DERIVE,
579 redis_submit(rn->name, "cache_result", "hits", hits);
580 redis_submit(rn->name, "cache_result", "misses", misses);
582 prev_t *prev = &rn->prev;
583 gauge_t ratio = calculate_ratio_percent(
584 hits.derive, misses.derive, &prev->keyspace_hits, &prev->keyspace_misses);
585 redis_submit(rn->name, "percent", "hitratio", (value_t){.gauge = ratio});
587 } /* void redis_keyspace_usage */
589 static void redis_check_connection(redis_node_t *rn) {
590 if (rn->redisContext)
593 redisContext *rh = redisConnectWithTimeout(rn->host, rn->port, rn->timeout);
596 ERROR("redis plugin: can't allocate redis context");
600 ERROR("redis plugin: unable to connect to node `%s' (%s:%d): %s.", rn->name,
601 rn->host, rn->port, rh->errstr);
606 rn->redisContext = rh;
611 DEBUG("redis plugin: authenticating node `%s' passwd(%s).", rn->name,
614 if ((rr = c_redisCommand(rn, "AUTH %s", rn->passwd)) == NULL) {
615 WARNING("redis plugin: unable to authenticate on node `%s'.", rn->name);
619 if (rr->type != REDIS_REPLY_STATUS) {
620 WARNING("redis plugin: invalid authentication on node `%s'.", rn->name);
622 redisFree(rn->redisContext);
623 rn->redisContext = NULL;
630 } /* void redis_check_connection */
632 static void redis_read_server_info(redis_node_t *rn) {
635 if ((rr = c_redisCommand(rn, "INFO")) == NULL) {
636 WARNING("redis plugin: unable to get INFO from node `%s'.", rn->name);
640 redis_handle_info(rn->name, rr->str, "uptime", NULL, "uptime_in_seconds",
642 redis_handle_info(rn->name, rr->str, "current_connections", "clients",
643 "connected_clients", DS_TYPE_GAUGE);
644 redis_handle_info(rn->name, rr->str, "blocked_clients", NULL,
645 "blocked_clients", DS_TYPE_GAUGE);
646 redis_handle_info(rn->name, rr->str, "memory", NULL, "used_memory",
648 redis_handle_info(rn->name, rr->str, "memory_lua", NULL, "used_memory_lua",
650 /* changes_since_last_save: Deprecated in redis version 2.6 and above */
651 redis_handle_info(rn->name, rr->str, "volatile_changes", NULL,
652 "changes_since_last_save", DS_TYPE_GAUGE);
653 redis_handle_info(rn->name, rr->str, "total_connections", NULL,
654 "total_connections_received", DS_TYPE_DERIVE);
655 redis_handle_info(rn->name, rr->str, "total_operations", NULL,
656 "total_commands_processed", DS_TYPE_DERIVE);
657 redis_handle_info(rn->name, rr->str, "expired_keys", NULL, "expired_keys",
659 redis_handle_info(rn->name, rr->str, "evicted_keys", NULL, "evicted_keys",
661 redis_handle_info(rn->name, rr->str, "pubsub", "channels", "pubsub_channels",
663 redis_handle_info(rn->name, rr->str, "pubsub", "patterns", "pubsub_patterns",
665 redis_handle_info(rn->name, rr->str, "current_connections", "slaves",
666 "connected_slaves", DS_TYPE_GAUGE);
667 redis_handle_info(rn->name, rr->str, "total_bytes", "input",
668 "total_net_input_bytes", DS_TYPE_DERIVE);
669 redis_handle_info(rn->name, rr->str, "total_bytes", "output",
670 "total_net_output_bytes", DS_TYPE_DERIVE);
672 redis_keyspace_usage(rn, rr->str);
674 redis_db_stats(rn->name, rr->str);
676 if (rn->report_cpu_usage)
677 redis_cpu_usage(rn->name, rr->str);
680 } /* void redis_read_server_info */
682 static void redis_read_command_stats(redis_node_t *rn) {
685 if ((rr = c_redisCommand(rn, "INFO commandstats")) == NULL) {
686 WARNING("redis plugin: node `%s': unable to get `INFO commandstats'.",
691 if (rr->type != REDIS_REPLY_STRING) {
692 WARNING("redis plugin: node `%s' `INFO commandstats' returned unsupported "
702 char *saveptr = NULL;
703 while ((line = strtok_r(ptr, "\n\r", &saveptr)) != NULL) {
710 if (strstr(line, "cmdstat_") != line) {
711 ERROR("redis plugin: not found 'cmdstat_' prefix in line '%s'", line);
715 char *values = strstr(line, ":");
716 if (values == NULL) {
717 ERROR("redis plugin: not found ':' separator in line '%s'", line);
721 /* Null-terminate command token */
723 command = line + strlen("cmdstat_");
727 /* cmdstat_publish:calls=20795774,usec=111039258,usec_per_call=5.34 */
729 char *saveptr_field = NULL;
730 while ((field = strtok_r(values, "=", &saveptr_field)) != NULL) {
734 /* only these are supported */
735 if (strcmp(field, "calls") == 0)
737 else if (strcmp(field, "usec") == 0)
738 type = "redis_command_cputime";
742 if ((field = strtok_r(NULL, ",", &saveptr_field)) == NULL)
747 derive_t value = strtoll(field, &endptr, 0);
749 if ((endptr == field) || (errno != 0))
752 redis_submit(rn->name, type, command, (value_t){.derive = value});
756 } /* void redis_read_command_stats */
758 static int redis_read(user_data_t *user_data) /* {{{ */
760 redis_node_t *rn = user_data->data;
762 DEBUG("redis plugin: querying info from node `%s' (%s:%d).", rn->name,
765 redis_check_connection(rn);
767 if (!rn->redisContext) /* no connection */
770 redis_read_server_info(rn);
772 if (!rn->redisContext) /* connection lost */
775 if (rn->report_command_stats) {
776 redis_read_command_stats(rn);
778 if (!rn->redisContext) /* connection lost */
782 for (redis_query_t *rq = rn->queries; rq != NULL; rq = rq->next) {
783 redis_handle_query(rn, rq);
784 if (!rn->redisContext) /* connection lost */
792 void module_register(void) /* {{{ */
794 plugin_register_complex_config("redis", redis_config);
795 plugin_register_init("redis", redis_init);