1 /**
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 *
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; either version 2 of the License, or (at your
12 * option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 *
23 * Authors:
24 * Antony Dovgal <tony at daylessday dot org>
25 * Florian octo Forster <octo at collectd.org>
26 * Doug MacEachern <dougm at hyperic.com>
27 * Franck Lombardi
28 * Nicolas Szalay
29 **/
31 #include "collectd.h"
32 #include "common.h"
33 #include "plugin.h"
34 #include "configfile.h"
36 #include <netdb.h>
37 #include <sys/un.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
41 #define MEMCACHED_DEF_HOST "127.0.0.1"
42 #define MEMCACHED_DEF_PORT "11211"
44 struct memcached_s
45 {
46 char *name;
47 char *socket;
48 char *host;
49 char *port;
50 };
51 typedef struct memcached_s memcached_t;
53 static _Bool memcached_have_instances = 0;
55 static void memcached_free (memcached_t *st)
56 {
57 if (st == NULL)
58 return;
60 sfree (st->name);
61 sfree (st->socket);
62 sfree (st->host);
63 sfree (st->port);
64 sfree (st);
65 }
67 static int memcached_connect_unix (memcached_t *st)
68 {
69 struct sockaddr_un serv_addr;
70 int fd;
72 memset (&serv_addr, 0, sizeof (serv_addr));
73 serv_addr.sun_family = AF_UNIX;
74 sstrncpy (serv_addr.sun_path, st->socket,
75 sizeof (serv_addr.sun_path));
77 /* create our socket descriptor */
78 fd = socket (AF_UNIX, SOCK_STREAM, 0);
79 if (fd < 0)
80 {
81 char errbuf[1024];
82 ERROR ("memcached plugin: memcached_connect_unix: socket(2) failed: %s",
83 sstrerror (errno, errbuf, sizeof (errbuf)));
84 return (-1);
85 }
87 /* connect to the memcached daemon */
88 int status = connect (fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
89 if (status != 0)
90 {
91 shutdown (fd, SHUT_RDWR);
92 close (fd);
93 fd = -1;
94 }
96 return (fd);
97 } /* int memcached_connect_unix */
99 static int memcached_connect_inet (memcached_t *st)
100 {
101 const char *host;
102 const char *port;
104 struct addrinfo ai_hints;
105 struct addrinfo *ai_list, *ai_ptr;
106 int status;
107 int fd = -1;
109 memset (&ai_hints, 0, sizeof (ai_hints));
110 ai_hints.ai_flags = 0;
111 #ifdef AI_ADDRCONFIG
112 ai_hints.ai_flags |= AI_ADDRCONFIG;
113 #endif
114 ai_hints.ai_family = AF_UNSPEC;
115 ai_hints.ai_socktype = SOCK_STREAM;
116 ai_hints.ai_protocol = 0;
118 host = (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST;
119 port = (st->port != NULL) ? st->port : MEMCACHED_DEF_PORT;
121 ai_list = NULL;
122 status = getaddrinfo (host, port, &ai_hints, &ai_list);
123 if (status != 0)
124 {
125 char errbuf[1024];
126 ERROR ("memcached plugin: memcached_connect_inet: "
127 "getaddrinfo(%s,%s) failed: %s",
128 host, port,
129 (status == EAI_SYSTEM)
130 ? sstrerror (errno, errbuf, sizeof (errbuf))
131 : gai_strerror (status));
132 return (-1);
133 }
135 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
136 {
137 /* create our socket descriptor */
138 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
139 if (fd < 0)
140 {
141 char errbuf[1024];
142 WARNING ("memcached plugin: memcached_connect_inet: "
143 "socket(2) failed: %s",
144 sstrerror (errno, errbuf, sizeof (errbuf)));
145 continue;
146 }
148 /* connect to the memcached daemon */
149 status = (int) connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
150 if (status != 0)
151 {
152 shutdown (fd, SHUT_RDWR);
153 close (fd);
154 fd = -1;
155 continue;
156 }
158 /* A socket could be opened and connecting succeeded. We're done. */
159 break;
160 }
162 freeaddrinfo (ai_list);
163 return (fd);
164 } /* int memcached_connect_inet */
166 static int memcached_connect (memcached_t *st)
167 {
168 if (st->socket != NULL)
169 return (memcached_connect_unix (st));
170 else
171 return (memcached_connect_inet (st));
172 }
174 static int memcached_query_daemon (char *buffer, size_t buffer_size, memcached_t *st)
175 {
176 int fd, status;
177 size_t buffer_fill;
179 fd = memcached_connect (st);
180 if (fd < 0) {
181 ERROR ("memcached plugin: Instance \"%s\" could not connect to daemon.",
182 st->name);
183 return -1;
184 }
186 status = (int) swrite (fd, "stats\r\n", strlen ("stats\r\n"));
187 if (status != 0)
188 {
189 char errbuf[1024];
190 ERROR ("memcached plugin: write(2) failed: %s",
191 sstrerror (errno, errbuf, sizeof (errbuf)));
192 shutdown(fd, SHUT_RDWR);
193 close (fd);
194 return (-1);
195 }
197 /* receive data from the memcached daemon */
198 memset (buffer, 0, buffer_size);
200 buffer_fill = 0;
201 while ((status = (int) recv (fd, buffer + buffer_fill,
202 buffer_size - buffer_fill, /* flags = */ 0)) != 0)
203 {
204 char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
205 if (status < 0)
206 {
207 char errbuf[1024];
209 if ((errno == EAGAIN) || (errno == EINTR))
210 continue;
212 ERROR ("memcached: Error reading from socket: %s",
213 sstrerror (errno, errbuf, sizeof (errbuf)));
214 shutdown(fd, SHUT_RDWR);
215 close (fd);
216 return (-1);
217 }
219 buffer_fill += (size_t) status;
220 if (buffer_fill > buffer_size)
221 {
222 buffer_fill = buffer_size;
223 WARNING ("memcached plugin: Message was truncated.");
224 break;
225 }
227 /* If buffer ends in end_token, we have all the data. */
228 if (memcmp (buffer + buffer_fill - sizeof (end_token),
229 end_token, sizeof (end_token)) == 0)
230 break;
231 } /* while (recv) */
233 status = 0;
234 if (buffer_fill == 0)
235 {
236 WARNING ("memcached plugin: No data returned by memcached.");
237 status = -1;
238 }
240 shutdown(fd, SHUT_RDWR);
241 close(fd);
242 return (status);
243 } /* int memcached_query_daemon */
245 static void memcached_init_vl (value_list_t *vl, memcached_t const *st)
246 {
247 sstrncpy (vl->plugin, "memcached", sizeof (vl->plugin));
248 if (strcmp (st->name, "__legacy__") == 0) /* legacy mode */
249 {
250 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
251 }
252 else
253 {
254 if (st->socket != NULL)
255 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
256 else
257 sstrncpy (vl->host,
258 (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST,
259 sizeof (vl->host));
260 sstrncpy (vl->plugin_instance, st->name, sizeof (vl->plugin_instance));
261 }
262 }
264 static void submit_derive (const char *type, const char *type_inst,
265 derive_t value, memcached_t *st)
266 {
267 value_t values[1];
268 value_list_t vl = VALUE_LIST_INIT;
269 memcached_init_vl (&vl, st);
271 values[0].derive = value;
273 vl.values = values;
274 vl.values_len = 1;
275 sstrncpy (vl.type, type, sizeof (vl.type));
276 if (type_inst != NULL)
277 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
279 plugin_dispatch_values (&vl);
280 }
282 static void submit_derive2 (const char *type, const char *type_inst,
283 derive_t value0, derive_t value1, memcached_t *st)
284 {
285 value_t values[2];
286 value_list_t vl = VALUE_LIST_INIT;
287 memcached_init_vl (&vl, st);
289 values[0].derive = value0;
290 values[1].derive = value1;
292 vl.values = values;
293 vl.values_len = 2;
294 sstrncpy (vl.type, type, sizeof (vl.type));
295 if (type_inst != NULL)
296 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
298 plugin_dispatch_values (&vl);
299 }
301 static void submit_gauge (const char *type, const char *type_inst,
302 gauge_t value, memcached_t *st)
303 {
304 value_t values[1];
305 value_list_t vl = VALUE_LIST_INIT;
306 memcached_init_vl (&vl, st);
308 values[0].gauge = value;
310 vl.values = values;
311 vl.values_len = 1;
312 sstrncpy (vl.type, type, sizeof (vl.type));
313 if (type_inst != NULL)
314 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
316 plugin_dispatch_values (&vl);
317 }
319 static void submit_gauge2 (const char *type, const char *type_inst,
320 gauge_t value0, gauge_t value1, memcached_t *st)
321 {
322 value_t values[2];
323 value_list_t vl = VALUE_LIST_INIT;
324 memcached_init_vl (&vl, st);
326 values[0].gauge = value0;
327 values[1].gauge = value1;
329 vl.values = values;
330 vl.values_len = 2;
331 sstrncpy (vl.type, type, sizeof (vl.type));
332 if (type_inst != NULL)
333 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
335 plugin_dispatch_values (&vl);
336 }
338 static int memcached_read (user_data_t *user_data)
339 {
340 char buf[4096];
341 char *fields[3];
342 char *ptr;
343 char *line;
344 char *saveptr;
345 int fields_num;
347 gauge_t bytes_used = NAN;
348 gauge_t bytes_total = NAN;
349 gauge_t hits = NAN;
350 gauge_t gets = NAN;
351 gauge_t incr_hits = NAN;
352 derive_t incr = 0;
353 gauge_t decr_hits = NAN;
354 derive_t decr = 0;
355 derive_t rusage_user = 0;
356 derive_t rusage_syst = 0;
357 derive_t octets_rx = 0;
358 derive_t octets_tx = 0;
360 memcached_t *st;
361 st = user_data->data;
363 /* get data from daemon */
364 if (memcached_query_daemon (buf, sizeof (buf), st) < 0) {
365 return -1;
366 }
368 #define FIELD_IS(cnst) \
369 (((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))
371 ptr = buf;
372 saveptr = NULL;
373 while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
374 {
375 int name_len;
377 ptr = NULL;
379 fields_num = strsplit(line, fields, 3);
380 if (fields_num != 3)
381 continue;
383 name_len = strlen(fields[1]);
384 if (name_len == 0)
385 continue;
387 /*
388 * For an explanation on these fields please refer to
389 * <https://github.com/memcached/memcached/blob/master/doc/protocol.txt>
390 */
392 /*
393 * CPU time consumed by the memcached process
394 */
395 if (FIELD_IS ("rusage_user"))
396 {
397 rusage_user = atoll (fields[2]);
398 }
399 else if (FIELD_IS ("rusage_system"))
400 {
401 rusage_syst = atoll(fields[2]);
402 }
404 /*
405 * Number of threads of this instance
406 */
407 else if (FIELD_IS ("threads"))
408 {
409 submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]), st);
410 }
412 /*
413 * Number of items stored
414 */
415 else if (FIELD_IS ("curr_items"))
416 {
417 submit_gauge ("memcached_items", "current", atof (fields[2]), st);
418 }
420 /*
421 * Number of bytes used and available (total - used)
422 */
423 else if (FIELD_IS ("bytes"))
424 {
425 bytes_used = atof (fields[2]);
426 }
427 else if (FIELD_IS ("limit_maxbytes"))
428 {
429 bytes_total = atof(fields[2]);
430 }
432 /*
433 * Connections
434 */
435 else if (FIELD_IS ("curr_connections"))
436 {
437 submit_gauge ("memcached_connections", "current", atof (fields[2]), st);
438 }
439 else if (FIELD_IS ("listen_disabled_num"))
440 {
441 submit_derive ("connections", "listen_disabled", atof (fields[2]), st);
442 }
444 /*
445 * Commands
446 */
447 else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
448 {
449 const char *name = fields[1] + 4;
450 submit_derive ("memcached_command", name, atoll (fields[2]), st);
451 if (strcmp (name, "get") == 0)
452 gets = atof (fields[2]);
453 }
455 /*
456 * Increment/Decrement
457 */
458 else if (FIELD_IS("incr_misses"))
459 {
460 derive_t incr_count = atoll (fields[2]);
461 submit_derive ("memcached_ops", "incr_misses", incr_count, st);
462 incr += incr_count;
463 }
464 else if (FIELD_IS ("incr_hits"))
465 {
466 derive_t incr_count = atoll (fields[2]);
467 submit_derive ("memcached_ops", "incr_hits", incr_count, st);
468 incr_hits = atof (fields[2]);
469 incr += incr_count;
470 }
471 else if (FIELD_IS ("decr_misses"))
472 {
473 derive_t decr_count = atoll (fields[2]);
474 submit_derive ("memcached_ops", "decr_misses", decr_count, st);
475 decr += decr_count;
476 }
477 else if (FIELD_IS ("decr_hits"))
478 {
479 derive_t decr_count = atoll (fields[2]);
480 submit_derive ("memcached_ops", "decr_hits", decr_count, st);
481 decr_hits = atof (fields[2]);
482 decr += decr_count;
483 }
485 /*
486 * Operations on the cache, i. e. cache hits, cache misses and evictions of items
487 */
488 else if (FIELD_IS ("get_hits"))
489 {
490 submit_derive ("memcached_ops", "hits", atoll (fields[2]), st);
491 hits = atof (fields[2]);
492 }
493 else if (FIELD_IS ("get_misses"))
494 {
495 submit_derive ("memcached_ops", "misses", atoll (fields[2]), st);
496 }
497 else if (FIELD_IS ("evictions"))
498 {
499 submit_derive ("memcached_ops", "evictions", atoll (fields[2]), st);
500 }
502 /*
503 * Network traffic
504 */
505 else if (FIELD_IS ("bytes_read"))
506 {
507 octets_rx = atoll (fields[2]);
508 }
509 else if (FIELD_IS ("bytes_written"))
510 {
511 octets_tx = atoll (fields[2]);
512 }
513 } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
515 if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
516 submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used, st);
518 if ((rusage_user != 0) || (rusage_syst != 0))
519 submit_derive2 ("ps_cputime", NULL, rusage_user, rusage_syst, st);
521 if ((octets_rx != 0) || (octets_tx != 0))
522 submit_derive2 ("memcached_octets", NULL, octets_rx, octets_tx, st);
524 if (!isnan (gets) && !isnan (hits))
525 {
526 gauge_t rate = NAN;
528 if (gets != 0.0)
529 rate = 100.0 * hits / gets;
531 submit_gauge ("percent", "hitratio", rate, st);
532 }
534 if (!isnan (incr_hits) && incr != 0)
535 {
536 gauge_t incr_rate = 100.0 * incr_hits / incr;
537 submit_gauge ("percent", "incr_hitratio", incr_rate, st);
538 submit_derive ("memcached_ops", "incr", incr, st);
539 }
541 if (!isnan (decr_hits) && decr != 0)
542 {
543 gauge_t decr_rate = 100.0 * decr_hits / decr;
544 submit_gauge ("percent", "decr_hitratio", decr_rate, st);
545 submit_derive ("memcached_ops", "decr", decr, st);
546 }
548 return 0;
549 } /* int memcached_read */
551 static int memcached_add_read_callback (memcached_t *st)
552 {
553 user_data_t ud;
554 char callback_name[3*DATA_MAX_NAME_LEN];
555 int status;
557 memset (&ud, 0, sizeof (ud));
558 ud.data = st;
559 ud.free_func = (void *) memcached_free;
561 assert (st->name != NULL);
562 ssnprintf (callback_name, sizeof (callback_name), "memcached/%s", st->name);
564 status = plugin_register_complex_read (/* group = */ "memcached",
565 /* name = */ callback_name,
566 /* callback = */ memcached_read,
567 /* interval = */ 0,
568 /* user_data = */ &ud);
569 return (status);
570 } /* int memcached_add_read_callback */
572 /* Configuration handling functiions
573 * <Plugin memcached>
574 * <Instance "instance_name">
575 * Host foo.zomg.com
576 * Port "1234"
577 * </Instance>
578 * </Plugin>
579 */
580 static int config_add_instance(oconfig_item_t *ci)
581 {
582 memcached_t *st;
583 int i;
584 int status = 0;
586 /* Disable automatic generation of default instance in the init callback. */
587 memcached_have_instances = 1;
589 st = calloc (1, sizeof (*st));
590 if (st == NULL)
591 {
592 ERROR ("memcached plugin: calloc failed.");
593 return (-1);
594 }
596 st->name = NULL;
597 st->socket = NULL;
598 st->host = NULL;
599 st->port = NULL;
601 if (strcasecmp (ci->key, "Plugin") == 0) /* default instance */
602 st->name = sstrdup ("__legacy__");
603 else /* <Instance /> block */
604 status = cf_util_get_string (ci, &st->name);
605 if (status != 0)
606 {
607 sfree (st);
608 return (status);
609 }
610 assert (st->name != NULL);
612 for (i = 0; i < ci->children_num; i++)
613 {
614 oconfig_item_t *child = ci->children + i;
616 if (strcasecmp ("Socket", child->key) == 0)
617 status = cf_util_get_string (child, &st->socket);
618 else if (strcasecmp ("Host", child->key) == 0)
619 status = cf_util_get_string (child, &st->host);
620 else if (strcasecmp ("Port", child->key) == 0)
621 status = cf_util_get_service (child, &st->port);
622 else
623 {
624 WARNING ("memcached plugin: Option `%s' not allowed here.",
625 child->key);
626 status = -1;
627 }
629 if (status != 0)
630 break;
631 }
633 if (status == 0)
634 status = memcached_add_read_callback (st);
636 if (status != 0)
637 {
638 memcached_free(st);
639 return (-1);
640 }
642 return (0);
643 }
645 static int memcached_config (oconfig_item_t *ci)
646 {
647 int status = 0;
648 _Bool have_instance_block = 0;
649 int i;
651 for (i = 0; i < ci->children_num; i++)
652 {
653 oconfig_item_t *child = ci->children + i;
655 if (strcasecmp ("Instance", child->key) == 0)
656 {
657 config_add_instance (child);
658 have_instance_block = 1;
659 }
660 else if (!have_instance_block)
661 {
662 /* Non-instance option: Assume legacy configuration (without <Instance />
663 * blocks) and call config_add_instance() with the <Plugin /> block. */
664 return (config_add_instance (ci));
665 }
666 else
667 WARNING ("memcached plugin: The configuration option "
668 "\"%s\" is not allowed here. Did you "
669 "forget to add an <Instance /> block "
670 "around the configuration?",
671 child->key);
672 } /* for (ci->children) */
674 return (status);
675 }
677 static int memcached_init (void)
678 {
679 memcached_t *st;
680 int status;
682 if (memcached_have_instances)
683 return (0);
685 /* No instances were configured, lets start a default instance. */
686 st = calloc (1, sizeof (*st));
687 if (st == NULL)
688 return (ENOMEM);
689 st->name = sstrdup ("__legacy__");
690 st->socket = NULL;
691 st->host = NULL;
692 st->port = NULL;
694 status = memcached_add_read_callback (st);
695 if (status == 0)
696 memcached_have_instances = 1;
697 else
698 memcached_free (st);
700 return (status);
701 } /* int memcached_init */
703 void module_register (void)
704 {
705 plugin_register_complex_config ("memcached", memcached_config);
706 plugin_register_init ("memcached", memcached_init);
707 }