2 * collectd - src/memcached.c, based on src/hddtemp.c
3 * Copyright (C) 2007 Antony Dovgal
4 * Copyright (C) 2007-2012 Florian Forster
5 * Copyright (C) 2009 Doug MacEachern
6 * Copyright (C) 2009 Franck Lombardi
7 * Copyright (C) 2012 Nicolas Szalay
8 * Copyright (C) 2017 Pavel Rochnyak
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the
12 * Free Software Foundation; either version 2 of the License, or (at your
13 * option) any later version.
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 * Antony Dovgal <tony at daylessday dot org>
26 * Florian octo Forster <octo at collectd.org>
27 * Doug MacEachern <dougm at hyperic.com>
30 * Pavel Rochnyak <pavel2000 ngs.ru>
39 #include <netinet/in.h>
40 #include <netinet/tcp.h>
45 #define MEMCACHED_DEF_HOST "127.0.0.1"
46 #define MEMCACHED_DEF_PORT "11211"
47 #define MEMCACHED_CONNECT_TIMEOUT 10000
48 #define MEMCACHED_IO_TIMEOUT 5000
59 typedef struct prev_s prev_t;
70 typedef struct memcached_s memcached_t;
72 static _Bool memcached_have_instances = 0;
74 static void memcached_free(void *arg) {
75 memcached_t *st = arg;
80 shutdown(st->fd, SHUT_RDWR);
93 static int memcached_connect_unix(memcached_t *st) {
94 struct sockaddr_un serv_addr = {0};
96 serv_addr.sun_family = AF_UNIX;
97 sstrncpy(serv_addr.sun_path, st->socket, sizeof(serv_addr.sun_path));
99 /* create our socket descriptor */
100 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
102 ERROR("memcached plugin: memcached_connect_unix: socket(2) failed: %s",
107 /* connect to the memcached daemon */
108 int status = connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
110 shutdown(fd, SHUT_RDWR);
115 /* switch to non-blocking mode */
116 int flags = fcntl(fd, F_GETFL);
117 status = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
124 } /* int memcached_connect_unix */
126 static int memcached_connect_inet(memcached_t *st) {
127 struct addrinfo *ai_list;
130 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
131 .ai_flags = AI_ADDRCONFIG,
132 .ai_socktype = SOCK_STREAM};
134 int status = getaddrinfo(st->connhost, st->connport, &ai_hints, &ai_list);
136 ERROR("memcached plugin: memcached_connect_inet: "
137 "getaddrinfo(%s,%s) failed: %s",
138 st->connhost, st->connport,
139 (status == EAI_SYSTEM) ? STRERRNO : gai_strerror(status));
143 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
144 ai_ptr = ai_ptr->ai_next) {
145 /* create our socket descriptor */
146 fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
148 WARNING("memcached plugin: memcached_connect_inet: "
149 "socket(2) failed: %s",
154 /* switch socket to non-blocking mode */
155 int flags = fcntl(fd, F_GETFL);
156 status = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
163 /* connect to the memcached daemon */
164 status = (int)connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
165 if (status != 0 && errno != EINPROGRESS) {
166 shutdown(fd, SHUT_RDWR);
172 /* Wait until connection establishes */
173 struct pollfd pollfd = {
174 .fd = fd, .events = POLLOUT,
177 status = poll(&pollfd, 1, MEMCACHED_CONNECT_TIMEOUT);
178 while (status < 0 && errno == EINTR);
185 /* Check if all is good */
187 status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&socket_error,
188 &(socklen_t){sizeof(socket_error)});
189 if (status != 0 || socket_error != 0) {
194 /* A socket is opened and connection succeeded. We're done. */
198 freeaddrinfo(ai_list);
200 } /* int memcached_connect_inet */
202 static void memcached_connect(memcached_t *st) {
206 if (st->socket != NULL)
207 st->fd = memcached_connect_unix(st);
209 st->fd = memcached_connect_inet(st);
212 INFO("memcached plugin: Instance \"%s\": connection established.",
216 static int memcached_query_daemon(char *buffer, size_t buffer_size,
221 memcached_connect(st);
223 ERROR("memcached plugin: Instance \"%s\" could not connect to daemon.",
228 struct pollfd pollfd = {
229 .fd = st->fd, .events = POLLOUT,
233 status = poll(&pollfd, 1, MEMCACHED_IO_TIMEOUT);
234 while (status < 0 && errno == EINTR);
237 ERROR("memcached plugin: poll() failed for write() call.");
243 status = (int)swrite(st->fd, "stats\r\n", strlen("stats\r\n"));
245 ERROR("memcached plugin: Instance \"%s\": write(2) failed: %s", st->name,
247 shutdown(st->fd, SHUT_RDWR);
253 /* receive data from the memcached daemon */
254 memset(buffer, 0, buffer_size);
257 pollfd.events = POLLIN;
260 status = poll(&pollfd, 1, MEMCACHED_IO_TIMEOUT);
261 while (status < 0 && errno == EINTR);
264 ERROR("memcached plugin: Instance \"%s\": Timeout reading from socket",
272 status = (int)recv(st->fd, buffer + buffer_fill,
273 buffer_size - buffer_fill, /* flags = */ 0);
274 while (status < 0 && errno == EINTR);
276 char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
279 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
282 ERROR("memcached plugin: Instance \"%s\": Error reading from socket: %s",
284 shutdown(st->fd, SHUT_RDWR);
288 } else if (status == 0) {
289 ERROR("memcached plugin: Instance \"%s\": Connection closed by peer",
296 buffer_fill += (size_t)status;
297 if (buffer_fill > buffer_size) {
298 buffer_fill = buffer_size;
299 WARNING("memcached plugin: Instance \"%s\": Message was truncated.",
301 shutdown(st->fd, SHUT_RDWR);
307 /* If buffer ends in end_token, we have all the data. */
308 if (memcmp(buffer + buffer_fill - sizeof(end_token), end_token,
309 sizeof(end_token)) == 0)
314 if (buffer_fill == 0) {
315 WARNING("memcached plugin: Instance \"%s\": No data returned by memcached.",
321 } /* int memcached_query_daemon */
323 static void memcached_init_vl(value_list_t *vl, memcached_t const *st) {
324 sstrncpy(vl->plugin, "memcached", sizeof(vl->plugin));
325 if (st->host != NULL)
326 sstrncpy(vl->host, st->host, sizeof(vl->host));
327 if (st->name != NULL)
328 sstrncpy(vl->plugin_instance, st->name, sizeof(vl->plugin_instance));
331 static void submit_derive(const char *type, const char *type_inst,
332 derive_t value, memcached_t *st) {
333 value_list_t vl = VALUE_LIST_INIT;
335 memcached_init_vl(&vl, st);
336 vl.values = &(value_t){.derive = value};
338 sstrncpy(vl.type, type, sizeof(vl.type));
339 if (type_inst != NULL)
340 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
342 plugin_dispatch_values(&vl);
345 static void submit_derive2(const char *type, const char *type_inst,
346 derive_t value0, derive_t value1, memcached_t *st) {
347 value_list_t vl = VALUE_LIST_INIT;
349 {.derive = value0}, {.derive = value1},
352 memcached_init_vl(&vl, st);
354 vl.values_len = STATIC_ARRAY_SIZE(values);
355 sstrncpy(vl.type, type, sizeof(vl.type));
356 if (type_inst != NULL)
357 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
359 plugin_dispatch_values(&vl);
362 static void submit_gauge(const char *type, const char *type_inst, gauge_t value,
364 value_list_t vl = VALUE_LIST_INIT;
366 memcached_init_vl(&vl, st);
367 vl.values = &(value_t){.gauge = value};
369 sstrncpy(vl.type, type, sizeof(vl.type));
370 if (type_inst != NULL)
371 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
373 plugin_dispatch_values(&vl);
376 static void submit_gauge2(const char *type, const char *type_inst,
377 gauge_t value0, gauge_t value1, memcached_t *st) {
378 value_list_t vl = VALUE_LIST_INIT;
380 {.gauge = value0}, {.gauge = value1},
383 memcached_init_vl(&vl, st);
385 vl.values_len = STATIC_ARRAY_SIZE(values);
386 sstrncpy(vl.type, type, sizeof(vl.type));
387 if (type_inst != NULL)
388 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
390 plugin_dispatch_values(&vl);
393 static gauge_t calculate_ratio_percent(derive_t part, derive_t total,
395 derive_t *prev_total) {
396 if ((*prev_part == 0) || (*prev_total == 0) || (part < *prev_part) ||
397 (total < *prev_total)) {
403 derive_t num = part - *prev_part;
404 derive_t denom = total - *prev_total;
415 return 100.0 * (gauge_t)num / (gauge_t)denom;
418 static gauge_t calculate_ratio_percent2(derive_t part1, derive_t part2,
419 derive_t *prev1, derive_t *prev2) {
420 if ((*prev1 == 0) || (*prev2 == 0) || (part1 < *prev1) || (part2 < *prev2)) {
426 derive_t num = part1 - *prev1;
427 derive_t denom = part2 - *prev2 + num;
438 return 100.0 * (gauge_t)num / (gauge_t)denom;
441 static int memcached_read(user_data_t *user_data) {
446 derive_t bytes_used = 0;
447 derive_t bytes_total = 0;
448 derive_t get_hits = 0;
449 derive_t cmd_get = 0;
450 derive_t incr_hits = 0;
451 derive_t incr_misses = 0;
452 derive_t decr_hits = 0;
453 derive_t decr_misses = 0;
454 derive_t rusage_user = 0;
455 derive_t rusage_syst = 0;
456 derive_t octets_rx = 0;
457 derive_t octets_tx = 0;
459 memcached_t *st = user_data->data;
460 prev_t *prev = &st->prev;
462 /* get data from daemon */
463 if (memcached_query_daemon(buf, sizeof(buf), st) < 0) {
467 #define FIELD_IS(cnst) \
468 (((sizeof(cnst) - 1) == name_len) && (strcmp(cnst, fields[1]) == 0))
471 char *saveptr = NULL;
472 while ((line = strtok_r(ptr, "\n\r", &saveptr)) != NULL) {
475 if (strsplit(line, fields, 3) != 3)
478 int name_len = strlen(fields[1]);
483 * For an explanation on these fields please refer to
484 * <https://github.com/memcached/memcached/blob/master/doc/protocol.txt>
488 * CPU time consumed by the memcached process
490 if (FIELD_IS("rusage_user")) {
491 /* Convert to useconds */
492 rusage_user = atof(fields[2]) * 1000000;
493 } else if (FIELD_IS("rusage_system")) {
494 rusage_syst = atof(fields[2]) * 1000000;
498 * Number of threads of this instance
500 else if (FIELD_IS("threads")) {
501 submit_gauge2("ps_count", NULL, NAN, atof(fields[2]), st);
505 * Number of items stored
507 else if (FIELD_IS("curr_items")) {
508 submit_gauge("memcached_items", "current", atof(fields[2]), st);
512 * Number of bytes used and available (total - used)
514 else if (FIELD_IS("bytes")) {
515 bytes_used = atoll(fields[2]);
516 } else if (FIELD_IS("limit_maxbytes")) {
517 bytes_total = atoll(fields[2]);
523 else if (FIELD_IS("curr_connections")) {
524 submit_gauge("memcached_connections", "current", atof(fields[2]), st);
525 } else if (FIELD_IS("listen_disabled_num")) {
526 submit_derive("total_events", "listen_disabled", atoll(fields[2]), st);
529 * Total number of connections opened since the server started running
530 * Report this as connection rate.
532 else if (FIELD_IS("total_connections")) {
533 submit_derive("connections", "opened", atoll(fields[2]), st);
539 else if ((name_len > 4) && (strncmp(fields[1], "cmd_", 4) == 0)) {
540 const char *name = fields[1] + 4;
541 submit_derive("memcached_command", name, atoll(fields[2]), st);
542 if (strcmp(name, "get") == 0)
543 cmd_get = atoll(fields[2]);
547 * Increment/Decrement
549 else if (FIELD_IS("incr_misses")) {
550 incr_misses = atoll(fields[2]);
551 submit_derive("memcached_ops", "incr_misses", incr_misses, st);
552 } else if (FIELD_IS("incr_hits")) {
553 incr_hits = atoll(fields[2]);
554 submit_derive("memcached_ops", "incr_hits", incr_hits, st);
555 } else if (FIELD_IS("decr_misses")) {
556 decr_misses = atoll(fields[2]);
557 submit_derive("memcached_ops", "decr_misses", decr_misses, st);
558 } else if (FIELD_IS("decr_hits")) {
559 decr_hits = atoll(fields[2]);
560 submit_derive("memcached_ops", "decr_hits", decr_hits, st);
564 * Operations on the cache:
566 * - delete hits/misses
569 else if (FIELD_IS("get_hits")) {
570 get_hits = atoll(fields[2]);
571 submit_derive("memcached_ops", "hits", get_hits, st);
572 } else if (FIELD_IS("get_misses")) {
573 submit_derive("memcached_ops", "misses", atoll(fields[2]), st);
574 } else if (FIELD_IS("evictions")) {
575 submit_derive("memcached_ops", "evictions", atoll(fields[2]), st);
576 } else if (FIELD_IS("delete_hits")) {
577 submit_derive("memcached_ops", "delete_hits", atoll(fields[2]), st);
578 } else if (FIELD_IS("delete_misses")) {
579 submit_derive("memcached_ops", "delete_misses", atoll(fields[2]), st);
585 else if (FIELD_IS("bytes_read")) {
586 octets_rx = atoll(fields[2]);
587 } else if (FIELD_IS("bytes_written")) {
588 octets_tx = atoll(fields[2]);
590 } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
592 if ((bytes_total > 0) && (bytes_used <= bytes_total))
593 submit_gauge2("df", "cache", bytes_used, bytes_total - bytes_used, st);
595 if ((rusage_user != 0) || (rusage_syst != 0))
596 submit_derive2("ps_cputime", NULL, rusage_user, rusage_syst, st);
598 if ((octets_rx != 0) || (octets_tx != 0))
599 submit_derive2("memcached_octets", NULL, octets_rx, octets_tx, st);
601 if ((cmd_get != 0) && (get_hits != 0)) {
603 calculate_ratio_percent(get_hits, cmd_get, &prev->hits, &prev->gets);
604 submit_gauge("percent", "hitratio", ratio, st);
607 if ((incr_hits != 0) && (incr_misses != 0)) {
608 gauge_t ratio = calculate_ratio_percent2(
609 incr_hits, incr_misses, &prev->incr_hits, &prev->incr_misses);
610 submit_gauge("percent", "incr_hitratio", ratio, st);
611 submit_derive("memcached_ops", "incr", incr_hits + incr_misses, st);
614 if ((decr_hits != 0) && (decr_misses != 0)) {
615 gauge_t ratio = calculate_ratio_percent2(
616 decr_hits, decr_misses, &prev->decr_hits, &prev->decr_misses);
617 submit_gauge("percent", "decr_hitratio", ratio, st);
618 submit_derive("memcached_ops", "decr", decr_hits + decr_misses, st);
622 } /* int memcached_read */
624 static int memcached_set_defaults(memcached_t *st) {
625 /* If no <Address> used then:
626 * - Connect to the destination specified by <Host>, if present.
627 * If not, use the default address.
628 * - Use the default hostname (set st->host to NULL), if
629 * - Legacy mode is used (no configuration options at all), or
630 * - "Host" option is not provided, or
631 * - "Host" option is set to "localhost" or "127.0.0.1".
633 * If <Address> used then host may be set to "localhost" or "127.0.0.1"
636 if (st->connhost == NULL) {
638 st->connhost = strdup(st->host);
639 if (st->connhost == NULL)
642 if ((strcmp("127.0.0.1", st->host) == 0) ||
643 (strcmp("localhost", st->host) == 0))
646 st->connhost = strdup(MEMCACHED_DEF_HOST);
647 if (st->connhost == NULL)
652 if (st->connport == NULL) {
653 st->connport = strdup(MEMCACHED_DEF_PORT);
654 if (st->connport == NULL)
658 assert(st->connhost != NULL);
659 assert(st->connport != NULL);
663 st->prev.incr_hits = 0;
664 st->prev.incr_misses = 0;
665 st->prev.decr_hits = 0;
666 st->prev.decr_misses = 0;
669 } /* int memcached_set_defaults */
671 static int memcached_add_read_callback(memcached_t *st) {
672 char callback_name[3 * DATA_MAX_NAME_LEN];
674 if (memcached_set_defaults(st) != 0) {
679 snprintf(callback_name, sizeof(callback_name), "memcached/%s",
680 (st->name != NULL) ? st->name : "__legacy__");
682 return plugin_register_complex_read(
683 /* group = */ "memcached",
684 /* name = */ callback_name,
685 /* callback = */ memcached_read,
688 .data = st, .free_func = memcached_free,
690 } /* int memcached_add_read_callback */
692 /* Configuration handling functiions
694 * <Instance "instance_name">
701 static int config_add_instance(oconfig_item_t *ci) {
704 /* Disable automatic generation of default instance in the init callback. */
705 memcached_have_instances = 1;
707 memcached_t *st = calloc(1, sizeof(*st));
709 ERROR("memcached plugin: calloc failed.");
721 if (strcasecmp(ci->key, "Instance") == 0)
722 status = cf_util_get_string(ci, &st->name);
729 for (int i = 0; i < ci->children_num; i++) {
730 oconfig_item_t *child = ci->children + i;
732 if (strcasecmp("Socket", child->key) == 0)
733 status = cf_util_get_string(child, &st->socket);
734 else if (strcasecmp("Host", child->key) == 0)
735 status = cf_util_get_string(child, &st->host);
736 else if (strcasecmp("Address", child->key) == 0)
737 status = cf_util_get_string(child, &st->connhost);
738 else if (strcasecmp("Port", child->key) == 0)
739 status = cf_util_get_service(child, &st->connport);
741 WARNING("memcached plugin: Option `%s' not allowed here.", child->key);
754 return memcached_add_read_callback(st);
755 } /* int config_add_instance */
757 static int memcached_config(oconfig_item_t *ci) {
758 _Bool have_instance_block = 0;
760 for (int i = 0; i < ci->children_num; i++) {
761 oconfig_item_t *child = ci->children + i;
763 if (strcasecmp("Instance", child->key) == 0) {
764 config_add_instance(child);
765 have_instance_block = 1;
766 } else if (!have_instance_block) {
767 /* Non-instance option: Assume legacy configuration (without <Instance />
768 * blocks) and call config_add_instance() with the <Plugin /> block. */
769 return config_add_instance(ci);
771 WARNING("memcached plugin: The configuration option "
772 "\"%s\" is not allowed here. Did you "
773 "forget to add an <Instance /> block "
774 "around the configuration?",
776 } /* for (ci->children) */
779 } /* int memcached_config */
781 static int memcached_init(void) {
783 if (memcached_have_instances)
786 /* No instances were configured, lets start a default instance. */
787 memcached_t *st = calloc(1, sizeof(*st));
798 int status = memcached_add_read_callback(st);
800 memcached_have_instances = 1;
803 } /* int memcached_init */
805 void module_register(void) {
806 plugin_register_complex_config("memcached", memcached_config);
807 plugin_register_init("memcached", memcached_init);