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
58 typedef struct memcached_s memcached_t;
60 static _Bool memcached_have_instances = 0;
62 static void memcached_free(void *arg) {
63 memcached_t *st = arg;
68 shutdown(st->fd, SHUT_RDWR);
81 static int memcached_connect_unix(memcached_t *st) {
82 struct sockaddr_un serv_addr = {0};
85 serv_addr.sun_family = AF_UNIX;
86 sstrncpy(serv_addr.sun_path, st->socket, sizeof(serv_addr.sun_path));
88 /* create our socket descriptor */
89 fd = socket(AF_UNIX, SOCK_STREAM, 0);
92 ERROR("memcached plugin: memcached_connect_unix: socket(2) failed: %s",
93 sstrerror(errno, errbuf, sizeof(errbuf)));
97 /* connect to the memcached daemon */
98 int status = connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
100 shutdown(fd, SHUT_RDWR);
105 /* switch to non-blocking mode */
106 int flags = fcntl(fd, F_GETFL);
107 status = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
114 } /* int memcached_connect_unix */
116 static int memcached_connect_inet(memcached_t *st) {
117 struct addrinfo *ai_list;
121 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
122 .ai_flags = AI_ADDRCONFIG,
123 .ai_socktype = SOCK_STREAM};
125 status = getaddrinfo(st->connhost, st->connport, &ai_hints, &ai_list);
128 ERROR("memcached plugin: memcached_connect_inet: "
129 "getaddrinfo(%s,%s) failed: %s",
130 st->connhost, st->connport,
131 (status == EAI_SYSTEM) ? sstrerror(errno, errbuf, sizeof(errbuf))
132 : gai_strerror(status));
136 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
137 ai_ptr = ai_ptr->ai_next) {
138 /* create our socket descriptor */
139 fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
142 WARNING("memcached plugin: memcached_connect_inet: "
143 "socket(2) failed: %s",
144 sstrerror(errno, errbuf, sizeof(errbuf)));
148 /* switch socket to non-blocking mode */
149 int flags = fcntl(fd, F_GETFL);
150 status = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
157 /* connect to the memcached daemon */
158 status = (int)connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
159 if (status != 0 && errno != EINPROGRESS) {
160 shutdown(fd, SHUT_RDWR);
166 /* Wait until connection establishes */
167 struct pollfd pollfd = {
168 .fd = fd, .events = POLLOUT,
171 status = poll(&pollfd, 1, MEMCACHED_CONNECT_TIMEOUT);
172 while (status < 0 && errno == EINTR);
179 /* Check if all is good */
181 status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&socket_error,
182 &(socklen_t){sizeof(socket_error)});
183 if (status != 0 || socket_error != 0) {
188 /* A socket is opened and connection succeeded. We're done. */
192 freeaddrinfo(ai_list);
194 } /* int memcached_connect_inet */
196 static void memcached_connect(memcached_t *st) {
200 if (st->socket != NULL)
201 st->fd = memcached_connect_unix(st);
203 st->fd = memcached_connect_inet(st);
206 INFO("memcached plugin: Instance \"%s\": connection established.",
210 static int memcached_query_daemon(char *buffer, size_t buffer_size,
215 memcached_connect(st);
217 ERROR("memcached plugin: Instance \"%s\" could not connect to daemon.",
222 struct pollfd pollfd = {
223 .fd = st->fd, .events = POLLOUT,
227 status = poll(&pollfd, 1, MEMCACHED_IO_TIMEOUT);
228 while (status < 0 && errno == EINTR);
231 ERROR("memcached plugin: poll() failed for write() call.");
237 status = (int)swrite(st->fd, "stats\r\n", strlen("stats\r\n"));
240 ERROR("memcached plugin: Instance \"%s\": write(2) failed: %s", st->name,
241 sstrerror(errno, errbuf, sizeof(errbuf)));
242 shutdown(st->fd, SHUT_RDWR);
248 /* receive data from the memcached daemon */
249 memset(buffer, 0, buffer_size);
252 pollfd.events = POLLIN;
255 status = poll(&pollfd, 1, MEMCACHED_IO_TIMEOUT);
256 while (status < 0 && errno == EINTR);
259 ERROR("memcached plugin: Instance \"%s\": Timeout reading from socket",
267 status = (int)recv(st->fd, buffer + buffer_fill,
268 buffer_size - buffer_fill, /* flags = */ 0);
269 while (status < 0 && errno == EINTR);
271 char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
275 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
278 ERROR("memcached plugin: Instance \"%s\": Error reading from socket: %s",
279 st->name, sstrerror(errno, errbuf, sizeof(errbuf)));
280 shutdown(st->fd, SHUT_RDWR);
286 buffer_fill += (size_t)status;
287 if (buffer_fill > buffer_size) {
288 buffer_fill = buffer_size;
289 WARNING("memcached plugin: Instance \"%s\": Message was truncated.",
291 shutdown(st->fd, SHUT_RDWR);
297 /* If buffer ends in end_token, we have all the data. */
298 if (memcmp(buffer + buffer_fill - sizeof(end_token), end_token,
299 sizeof(end_token)) == 0)
304 if (buffer_fill == 0) {
305 WARNING("memcached plugin: Instance \"%s\": No data returned by memcached.",
311 } /* int memcached_query_daemon */
313 static void memcached_init_vl(value_list_t *vl, memcached_t const *st) {
314 sstrncpy(vl->plugin, "memcached", sizeof(vl->plugin));
315 if (st->host != NULL)
316 sstrncpy(vl->host, st->host, sizeof(vl->host));
317 if (st->name != NULL)
318 sstrncpy(vl->plugin_instance, st->name, sizeof(vl->plugin_instance));
321 static void submit_derive(const char *type, const char *type_inst,
322 derive_t value, memcached_t *st) {
323 value_list_t vl = VALUE_LIST_INIT;
325 memcached_init_vl(&vl, st);
326 vl.values = &(value_t){.derive = value};
328 sstrncpy(vl.type, type, sizeof(vl.type));
329 if (type_inst != NULL)
330 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
332 plugin_dispatch_values(&vl);
335 static void submit_derive2(const char *type, const char *type_inst,
336 derive_t value0, derive_t value1, memcached_t *st) {
337 value_list_t vl = VALUE_LIST_INIT;
339 {.derive = value0}, {.derive = value1},
342 memcached_init_vl(&vl, st);
344 vl.values_len = STATIC_ARRAY_SIZE(values);
345 sstrncpy(vl.type, type, sizeof(vl.type));
346 if (type_inst != NULL)
347 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
349 plugin_dispatch_values(&vl);
352 static void submit_gauge(const char *type, const char *type_inst, gauge_t value,
354 value_list_t vl = VALUE_LIST_INIT;
356 memcached_init_vl(&vl, st);
357 vl.values = &(value_t){.gauge = value};
359 sstrncpy(vl.type, type, sizeof(vl.type));
360 if (type_inst != NULL)
361 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
363 plugin_dispatch_values(&vl);
366 static void submit_gauge2(const char *type, const char *type_inst,
367 gauge_t value0, gauge_t value1, memcached_t *st) {
368 value_list_t vl = VALUE_LIST_INIT;
370 {.gauge = value0}, {.gauge = value1},
373 memcached_init_vl(&vl, st);
375 vl.values_len = STATIC_ARRAY_SIZE(values);
376 sstrncpy(vl.type, type, sizeof(vl.type));
377 if (type_inst != NULL)
378 sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
380 plugin_dispatch_values(&vl);
383 static int memcached_read(user_data_t *user_data) {
391 gauge_t bytes_used = NAN;
392 gauge_t bytes_total = NAN;
395 gauge_t incr_hits = NAN;
397 gauge_t decr_hits = NAN;
399 derive_t rusage_user = 0;
400 derive_t rusage_syst = 0;
401 derive_t octets_rx = 0;
402 derive_t octets_tx = 0;
405 st = user_data->data;
407 /* get data from daemon */
408 if (memcached_query_daemon(buf, sizeof(buf), st) < 0) {
412 #define FIELD_IS(cnst) \
413 (((sizeof(cnst) - 1) == name_len) && (strcmp(cnst, fields[1]) == 0))
417 while ((line = strtok_r(ptr, "\n\r", &saveptr)) != NULL) {
422 fields_num = strsplit(line, fields, 3);
426 name_len = strlen(fields[1]);
431 * For an explanation on these fields please refer to
432 * <https://github.com/memcached/memcached/blob/master/doc/protocol.txt>
436 * CPU time consumed by the memcached process
438 if (FIELD_IS("rusage_user")) {
439 rusage_user = atoll(fields[2]);
440 } else if (FIELD_IS("rusage_system")) {
441 rusage_syst = atoll(fields[2]);
445 * Number of threads of this instance
447 else if (FIELD_IS("threads")) {
448 submit_gauge2("ps_count", NULL, NAN, atof(fields[2]), st);
452 * Number of items stored
454 else if (FIELD_IS("curr_items")) {
455 submit_gauge("memcached_items", "current", atof(fields[2]), st);
459 * Number of bytes used and available (total - used)
461 else if (FIELD_IS("bytes")) {
462 bytes_used = atof(fields[2]);
463 } else if (FIELD_IS("limit_maxbytes")) {
464 bytes_total = atof(fields[2]);
470 else if (FIELD_IS("curr_connections")) {
471 submit_gauge("memcached_connections", "current", atof(fields[2]), st);
472 } else if (FIELD_IS("listen_disabled_num")) {
473 submit_derive("connections", "listen_disabled", atof(fields[2]), st);
479 else if ((name_len > 4) && (strncmp(fields[1], "cmd_", 4) == 0)) {
480 const char *name = fields[1] + 4;
481 submit_derive("memcached_command", name, atoll(fields[2]), st);
482 if (strcmp(name, "get") == 0)
483 gets = atof(fields[2]);
487 * Increment/Decrement
489 else if (FIELD_IS("incr_misses")) {
490 derive_t incr_count = atoll(fields[2]);
491 submit_derive("memcached_ops", "incr_misses", incr_count, st);
493 } else if (FIELD_IS("incr_hits")) {
494 derive_t incr_count = atoll(fields[2]);
495 submit_derive("memcached_ops", "incr_hits", incr_count, st);
496 incr_hits = atof(fields[2]);
498 } else if (FIELD_IS("decr_misses")) {
499 derive_t decr_count = atoll(fields[2]);
500 submit_derive("memcached_ops", "decr_misses", decr_count, st);
502 } else if (FIELD_IS("decr_hits")) {
503 derive_t decr_count = atoll(fields[2]);
504 submit_derive("memcached_ops", "decr_hits", decr_count, st);
505 decr_hits = atof(fields[2]);
510 * Operations on the cache:
512 * - delete hits/misses
515 else if (FIELD_IS("get_hits")) {
516 submit_derive("memcached_ops", "hits", atoll(fields[2]), st);
517 hits = atof(fields[2]);
518 } else if (FIELD_IS("get_misses")) {
519 submit_derive("memcached_ops", "misses", atoll(fields[2]), st);
520 } else if (FIELD_IS("evictions")) {
521 submit_derive("memcached_ops", "evictions", atoll(fields[2]), st);
522 } else if (FIELD_IS("delete_hits")) {
523 submit_derive("memcached_ops", "delete_hits", atoll(fields[2]), st);
524 } else if (FIELD_IS("delete_misses")) {
525 submit_derive("memcached_ops", "delete_misses", atoll(fields[2]), st);
531 else if (FIELD_IS("bytes_read")) {
532 octets_rx = atoll(fields[2]);
533 } else if (FIELD_IS("bytes_written")) {
534 octets_tx = atoll(fields[2]);
536 } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
538 if (!isnan(bytes_used) && !isnan(bytes_total) && (bytes_used <= bytes_total))
539 submit_gauge2("df", "cache", bytes_used, bytes_total - bytes_used, st);
541 if ((rusage_user != 0) || (rusage_syst != 0))
542 submit_derive2("ps_cputime", NULL, rusage_user, rusage_syst, st);
544 if ((octets_rx != 0) || (octets_tx != 0))
545 submit_derive2("memcached_octets", NULL, octets_rx, octets_tx, st);
547 if (!isnan(gets) && !isnan(hits)) {
551 rate = 100.0 * hits / gets;
553 submit_gauge("percent", "hitratio", rate, st);
556 if (!isnan(incr_hits) && incr != 0) {
557 gauge_t incr_rate = 100.0 * incr_hits / incr;
558 submit_gauge("percent", "incr_hitratio", incr_rate, st);
559 submit_derive("memcached_ops", "incr", incr, st);
562 if (!isnan(decr_hits) && decr != 0) {
563 gauge_t decr_rate = 100.0 * decr_hits / decr;
564 submit_gauge("percent", "decr_hitratio", decr_rate, st);
565 submit_derive("memcached_ops", "decr", decr, st);
569 } /* int memcached_read */
571 static int memcached_set_defaults(memcached_t *st) {
572 /* If no <Address> used then:
573 * - Connect to the destination specified by <Host>, if present.
574 * If not, use the default address.
575 * - Use the default hostname (set st->host to NULL), if
576 * - Legacy mode is used (no configuration options at all), or
577 * - "Host" option is not provided, or
578 * - "Host" option is set to "localhost" or "127.0.0.1".
580 * If <Address> used then host may be set to "localhost" or "127.0.0.1"
583 if (st->connhost == NULL) {
585 st->connhost = strdup(st->host);
586 if (st->connhost == NULL)
589 if ((strcmp("127.0.0.1", st->host) == 0) ||
590 (strcmp("localhost", st->host) == 0))
593 st->connhost = strdup(MEMCACHED_DEF_HOST);
594 if (st->connhost == NULL)
599 if (st->connport == NULL) {
600 st->connport = strdup(MEMCACHED_DEF_PORT);
601 if (st->connport == NULL)
605 assert(st->connhost != NULL);
606 assert(st->connport != NULL);
609 } /* int memcached_set_defaults */
611 static int memcached_add_read_callback(memcached_t *st) {
612 char callback_name[3 * DATA_MAX_NAME_LEN];
614 if (memcached_set_defaults(st) != 0) {
619 snprintf(callback_name, sizeof(callback_name), "memcached/%s",
620 (st->name != NULL) ? st->name : "__legacy__");
622 return plugin_register_complex_read(
623 /* group = */ "memcached",
624 /* name = */ callback_name,
625 /* callback = */ memcached_read,
628 .data = st, .free_func = memcached_free,
630 } /* int memcached_add_read_callback */
632 /* Configuration handling functiions
634 * <Instance "instance_name">
641 static int config_add_instance(oconfig_item_t *ci) {
645 /* Disable automatic generation of default instance in the init callback. */
646 memcached_have_instances = 1;
648 st = calloc(1, sizeof(*st));
650 ERROR("memcached plugin: calloc failed.");
662 if (strcasecmp(ci->key, "Instance") == 0)
663 status = cf_util_get_string(ci, &st->name);
670 for (int i = 0; i < ci->children_num; i++) {
671 oconfig_item_t *child = ci->children + i;
673 if (strcasecmp("Socket", child->key) == 0)
674 status = cf_util_get_string(child, &st->socket);
675 else if (strcasecmp("Host", child->key) == 0)
676 status = cf_util_get_string(child, &st->host);
677 else if (strcasecmp("Address", child->key) == 0)
678 status = cf_util_get_string(child, &st->connhost);
679 else if (strcasecmp("Port", child->key) == 0)
680 status = cf_util_get_service(child, &st->connport);
682 WARNING("memcached plugin: Option `%s' not allowed here.", child->key);
695 return memcached_add_read_callback(st);
696 } /* int config_add_instance */
698 static int memcached_config(oconfig_item_t *ci) {
699 _Bool have_instance_block = 0;
701 for (int i = 0; i < ci->children_num; i++) {
702 oconfig_item_t *child = ci->children + i;
704 if (strcasecmp("Instance", child->key) == 0) {
705 config_add_instance(child);
706 have_instance_block = 1;
707 } else if (!have_instance_block) {
708 /* Non-instance option: Assume legacy configuration (without <Instance />
709 * blocks) and call config_add_instance() with the <Plugin /> block. */
710 return config_add_instance(ci);
712 WARNING("memcached plugin: The configuration option "
713 "\"%s\" is not allowed here. Did you "
714 "forget to add an <Instance /> block "
715 "around the configuration?",
717 } /* for (ci->children) */
720 } /* int memcached_config */
722 static int memcached_init(void) {
726 if (memcached_have_instances)
729 /* No instances were configured, lets start a default instance. */
730 st = calloc(1, sizeof(*st));
741 status = memcached_add_read_callback(st);
743 memcached_have_instances = 1;
746 } /* int memcached_init */
748 void module_register(void) {
749 plugin_register_complex_config("memcached", memcached_config);
750 plugin_register_init("memcached", memcached_init);