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/socket.h>
38 #include <sys/un.h>
39 #include <netinet/in.h>
40 #include <netinet/tcp.h>
42 #define MEMCACHED_DEF_HOST "127.0.0.1"
43 #define MEMCACHED_DEF_PORT "11211"
45 struct memcached_s
46 {
47 char *name;
48 char *socket;
49 char *host;
50 char *port;
51 };
52 typedef struct memcached_s memcached_t;
54 static _Bool memcached_have_instances = 0;
56 static void memcached_free (memcached_t *st)
57 {
58 if (st == NULL)
59 return;
61 sfree (st->name);
62 sfree (st->socket);
63 sfree (st->host);
64 sfree (st->port);
65 sfree (st);
66 }
68 static int memcached_connect_unix (memcached_t *st)
69 {
70 struct sockaddr_un serv_addr;
71 int fd;
73 memset (&serv_addr, 0, sizeof (serv_addr));
74 serv_addr.sun_family = AF_UNIX;
75 sstrncpy (serv_addr.sun_path, st->socket,
76 sizeof (serv_addr.sun_path));
78 /* create our socket descriptor */
79 fd = socket (AF_UNIX, SOCK_STREAM, 0);
80 if (fd < 0)
81 {
82 char errbuf[1024];
83 ERROR ("memcached plugin: memcached_connect_unix: socket(2) failed: %s",
84 sstrerror (errno, errbuf, sizeof (errbuf)));
85 return (-1);
86 }
88 /* connect to the memcached daemon */
89 int status = connect (fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
90 if (status != 0)
91 {
92 shutdown (fd, SHUT_RDWR);
93 close (fd);
94 fd = -1;
95 }
97 return (fd);
98 } /* int memcached_connect_unix */
100 static int memcached_connect_inet (memcached_t *st)
101 {
102 char *host;
103 char *port;
105 struct addrinfo ai_hints;
106 struct addrinfo *ai_list, *ai_ptr;
107 int status;
108 int fd = -1;
110 memset (&ai_hints, 0, sizeof (ai_hints));
111 ai_hints.ai_flags = 0;
112 #ifdef AI_ADDRCONFIG
113 ai_hints.ai_flags |= AI_ADDRCONFIG;
114 #endif
115 ai_hints.ai_family = AF_UNSPEC;
116 ai_hints.ai_socktype = SOCK_STREAM;
117 ai_hints.ai_protocol = 0;
119 host = (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST;
120 port = (st->port != NULL) ? st->port : MEMCACHED_DEF_PORT;
122 ai_list = NULL;
123 status = getaddrinfo (host, port, &ai_hints, &ai_list);
124 if (status != 0)
125 {
126 char errbuf[1024];
127 ERROR ("memcached plugin: memcached_connect_inet: "
128 "getaddrinfo(%s,%s) failed: %s",
129 host, port,
130 (status == EAI_SYSTEM)
131 ? sstrerror (errno, errbuf, sizeof (errbuf))
132 : gai_strerror (status));
133 return (-1);
134 }
136 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
137 {
138 /* create our socket descriptor */
139 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
140 if (fd < 0)
141 {
142 char errbuf[1024];
143 WARNING ("memcached plugin: memcached_connect_inet: "
144 "socket(2) failed: %s",
145 sstrerror (errno, errbuf, sizeof (errbuf)));
146 continue;
147 }
149 /* connect to the memcached daemon */
150 status = (int) connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
151 if (status != 0)
152 {
153 shutdown (fd, SHUT_RDWR);
154 close (fd);
155 fd = -1;
156 continue;
157 }
159 /* A socket could be opened and connecting succeeded. We're done. */
160 break;
161 }
163 freeaddrinfo (ai_list);
164 return (fd);
165 } /* int memcached_connect_inet */
167 static int memcached_connect (memcached_t *st)
168 {
169 if (st->socket != NULL)
170 return (memcached_connect_unix (st));
171 else
172 return (memcached_connect_inet (st));
173 }
175 static int memcached_query_daemon (char *buffer, size_t buffer_size, memcached_t *st)
176 {
177 int fd = -1;
178 int status;
179 size_t buffer_fill;
181 fd = memcached_connect (st);
182 if (fd < 0) {
183 ERROR ("memcached plugin: Instance \"%s\" could not connect to daemon.",
184 st->name);
185 return -1;
186 }
188 status = (int) swrite (fd, "stats\r\n", strlen ("stats\r\n"));
189 if (status != 0)
190 {
191 char errbuf[1024];
192 ERROR ("memcached plugin: write(2) failed: %s",
193 sstrerror (errno, errbuf, sizeof (errbuf)));
194 shutdown(fd, SHUT_RDWR);
195 close (fd);
196 return (-1);
197 }
199 /* receive data from the memcached daemon */
200 memset (buffer, 0, buffer_size);
202 buffer_fill = 0;
203 while ((status = (int) recv (fd, buffer + buffer_fill,
204 buffer_size - buffer_fill, /* flags = */ 0)) != 0)
205 {
206 char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
207 if (status < 0)
208 {
209 char errbuf[1024];
211 if ((errno == EAGAIN) || (errno == EINTR))
212 continue;
214 ERROR ("memcached: Error reading from socket: %s",
215 sstrerror (errno, errbuf, sizeof (errbuf)));
216 shutdown(fd, SHUT_RDWR);
217 close (fd);
218 return (-1);
219 }
221 buffer_fill += (size_t) status;
222 if (buffer_fill > buffer_size)
223 {
224 buffer_fill = buffer_size;
225 WARNING ("memcached plugin: Message was truncated.");
226 break;
227 }
229 /* If buffer ends in end_token, we have all the data. */
230 if (memcmp (buffer + buffer_fill - sizeof (end_token),
231 end_token, sizeof (end_token)) == 0)
232 break;
233 } /* while (recv) */
235 status = 0;
236 if (buffer_fill == 0)
237 {
238 WARNING ("memcached plugin: No data returned by memcached.");
239 status = -1;
240 }
242 shutdown(fd, SHUT_RDWR);
243 close(fd);
244 return (status);
245 } /* int memcached_query_daemon */
247 static void memcached_init_vl (value_list_t *vl, memcached_t const *st)
248 {
249 sstrncpy (vl->plugin, "memcached", sizeof (vl->plugin));
250 if (strcmp (st->name, "__legacy__") == 0) /* legacy mode */
251 {
252 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
253 }
254 else
255 {
256 if (st->socket != NULL)
257 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
258 else
259 sstrncpy (vl->host,
260 (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST,
261 sizeof (vl->host));
262 sstrncpy (vl->plugin_instance, st->name, sizeof (vl->plugin_instance));
263 }
264 }
266 static void submit_derive (const char *type, const char *type_inst,
267 derive_t value, memcached_t *st)
268 {
269 value_t values[1];
270 value_list_t vl = VALUE_LIST_INIT;
271 memcached_init_vl (&vl, st);
273 values[0].derive = value;
275 vl.values = values;
276 vl.values_len = 1;
277 sstrncpy (vl.type, type, sizeof (vl.type));
278 if (type_inst != NULL)
279 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
281 plugin_dispatch_values (&vl);
282 }
284 static void submit_derive2 (const char *type, const char *type_inst,
285 derive_t value0, derive_t value1, memcached_t *st)
286 {
287 value_t values[2];
288 value_list_t vl = VALUE_LIST_INIT;
289 memcached_init_vl (&vl, st);
291 values[0].derive = value0;
292 values[1].derive = value1;
294 vl.values = values;
295 vl.values_len = 2;
296 sstrncpy (vl.type, type, sizeof (vl.type));
297 if (type_inst != NULL)
298 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
300 plugin_dispatch_values (&vl);
301 }
303 static void submit_gauge (const char *type, const char *type_inst,
304 gauge_t value, memcached_t *st)
305 {
306 value_t values[1];
307 value_list_t vl = VALUE_LIST_INIT;
308 memcached_init_vl (&vl, st);
310 values[0].gauge = value;
312 vl.values = values;
313 vl.values_len = 1;
314 sstrncpy (vl.type, type, sizeof (vl.type));
315 if (type_inst != NULL)
316 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
318 plugin_dispatch_values (&vl);
319 }
321 static void submit_gauge2 (const char *type, const char *type_inst,
322 gauge_t value0, gauge_t value1, memcached_t *st)
323 {
324 value_t values[2];
325 value_list_t vl = VALUE_LIST_INIT;
326 memcached_init_vl (&vl, st);
328 values[0].gauge = value0;
329 values[1].gauge = value1;
331 vl.values = values;
332 vl.values_len = 2;
333 sstrncpy (vl.type, type, sizeof (vl.type));
334 if (type_inst != NULL)
335 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
337 plugin_dispatch_values (&vl);
338 }
340 static int memcached_read (user_data_t *user_data)
341 {
342 char buf[4096];
343 char *fields[3];
344 char *ptr;
345 char *line;
346 char *saveptr;
347 int fields_num;
349 gauge_t bytes_used = NAN;
350 gauge_t bytes_total = NAN;
351 gauge_t hits = NAN;
352 gauge_t gets = NAN;
353 gauge_t incr_hits = NAN;
354 derive_t incr = 0;
355 gauge_t decr_hits = NAN;
356 derive_t decr = 0;
357 derive_t rusage_user = 0;
358 derive_t rusage_syst = 0;
359 derive_t octets_rx = 0;
360 derive_t octets_tx = 0;
362 memcached_t *st;
363 st = user_data->data;
365 /* get data from daemon */
366 if (memcached_query_daemon (buf, sizeof (buf), st) < 0) {
367 return -1;
368 }
370 #define FIELD_IS(cnst) \
371 (((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))
373 ptr = buf;
374 saveptr = NULL;
375 while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
376 {
377 int name_len;
379 ptr = NULL;
381 fields_num = strsplit(line, fields, 3);
382 if (fields_num != 3)
383 continue;
385 name_len = strlen(fields[1]);
386 if (name_len == 0)
387 continue;
389 /*
390 * For an explanation on these fields please refer to
391 * <http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt>
392 */
394 /*
395 * CPU time consumed by the memcached process
396 */
397 if (FIELD_IS ("rusage_user"))
398 {
399 rusage_user = atoll (fields[2]);
400 }
401 else if (FIELD_IS ("rusage_system"))
402 {
403 rusage_syst = atoll(fields[2]);
404 }
406 /*
407 * Number of threads of this instance
408 */
409 else if (FIELD_IS ("threads"))
410 {
411 submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]), st);
412 }
414 /*
415 * Number of items stored
416 */
417 else if (FIELD_IS ("curr_items"))
418 {
419 submit_gauge ("memcached_items", "current", atof (fields[2]), st);
420 }
422 /*
423 * Number of bytes used and available (total - used)
424 */
425 else if (FIELD_IS ("bytes"))
426 {
427 bytes_used = atof (fields[2]);
428 }
429 else if (FIELD_IS ("limit_maxbytes"))
430 {
431 bytes_total = atof(fields[2]);
432 }
434 /*
435 * Connections
436 */
437 else if (FIELD_IS ("curr_connections"))
438 {
439 submit_gauge ("memcached_connections", "current", atof (fields[2]), st);
440 }
442 /*
443 * Commands
444 */
445 else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
446 {
447 const char *name = fields[1] + 4;
448 submit_derive ("memcached_command", name, atoll (fields[2]), st);
449 if (strcmp (name, "get") == 0)
450 gets = atof (fields[2]);
451 }
453 /*
454 * Increment/Decrement
455 */
456 else if (FIELD_IS("incr_misses"))
457 {
458 derive_t incr_count = atoll (fields[2]);
459 submit_derive ("memcached_ops", "incr_misses", incr_count, st);
460 incr += incr_count;
461 }
462 else if (FIELD_IS ("incr_hits"))
463 {
464 derive_t incr_count = atoll (fields[2]);
465 submit_derive ("memcached_ops", "incr_hits", incr_count, st);
466 incr_hits = atof (fields[2]);
467 incr += incr_count;
468 }
469 else if (FIELD_IS ("decr_misses"))
470 {
471 derive_t decr_count = atoll (fields[2]);
472 submit_derive ("memcached_ops", "decr_misses", decr_count, st);
473 decr += decr_count;
474 }
475 else if (FIELD_IS ("decr_hits"))
476 {
477 derive_t decr_count = atoll (fields[2]);
478 submit_derive ("memcached_ops", "decr_hits", decr_count, st);
479 decr_hits = atof (fields[2]);
480 decr += decr_count;
481 }
483 /*
484 * Operations on the cache, i. e. cache hits, cache misses and evictions of items
485 */
486 else if (FIELD_IS ("get_hits"))
487 {
488 submit_derive ("memcached_ops", "hits", atoll (fields[2]), st);
489 hits = atof (fields[2]);
490 }
491 else if (FIELD_IS ("get_misses"))
492 {
493 submit_derive ("memcached_ops", "misses", atoll (fields[2]), st);
494 }
495 else if (FIELD_IS ("evictions"))
496 {
497 submit_derive ("memcached_ops", "evictions", atoll (fields[2]), st);
498 }
500 /*
501 * Network traffic
502 */
503 else if (FIELD_IS ("bytes_read"))
504 {
505 octets_rx = atoll (fields[2]);
506 }
507 else if (FIELD_IS ("bytes_written"))
508 {
509 octets_tx = atoll (fields[2]);
510 }
511 } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
513 if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
514 submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used, st);
516 if ((rusage_user != 0) || (rusage_syst != 0))
517 submit_derive2 ("ps_cputime", NULL, rusage_user, rusage_syst, st);
519 if ((octets_rx != 0) || (octets_tx != 0))
520 submit_derive2 ("memcached_octets", NULL, octets_rx, octets_tx, st);
522 if (!isnan (gets) && !isnan (hits))
523 {
524 gauge_t rate = NAN;
526 if (gets != 0.0)
527 rate = 100.0 * hits / gets;
529 submit_gauge ("percent", "hitratio", rate, st);
530 }
532 if (!isnan (incr_hits) && incr != 0)
533 {
534 gauge_t incr_rate = 100.0 * incr_hits / incr;
535 submit_gauge ("percent", "incr_hitratio", incr_rate, st);
536 submit_derive ("memcached_ops", "incr", incr, st);
537 }
539 if (!isnan (decr_hits) && decr != 0)
540 {
541 gauge_t decr_rate = 100.0 * decr_hits / decr;
542 submit_gauge ("percent", "decr_hitratio", decr_rate, st);
543 submit_derive ("memcached_ops", "decr", decr, st);
544 }
546 return 0;
547 } /* int memcached_read */
549 static int memcached_add_read_callback (memcached_t *st)
550 {
551 user_data_t ud;
552 char callback_name[3*DATA_MAX_NAME_LEN];
553 int status;
555 memset (&ud, 0, sizeof (ud));
556 ud.data = st;
557 ud.free_func = (void *) memcached_free;
559 assert (st->name != NULL);
560 ssnprintf (callback_name, sizeof (callback_name), "memcached/%s", st->name);
562 status = plugin_register_complex_read (/* group = */ "memcached",
563 /* name = */ callback_name,
564 /* callback = */ memcached_read,
565 /* interval = */ NULL,
566 /* user_data = */ &ud);
567 return (status);
568 } /* int memcached_add_read_callback */
570 /* Configuration handling functiions
571 * <Plugin memcached>
572 * <Instance "instance_name">
573 * Host foo.zomg.com
574 * Port "1234"
575 * </Instance>
576 * </Plugin>
577 */
578 static int config_add_instance(oconfig_item_t *ci)
579 {
580 memcached_t *st;
581 int i;
582 int status = 0;
584 /* Disable automatic generation of default instance in the init callback. */
585 memcached_have_instances = 1;
587 st = malloc (sizeof (*st));
588 if (st == NULL)
589 {
590 ERROR ("memcached plugin: malloc failed.");
591 return (-1);
592 }
594 memset (st, 0, sizeof (*st));
595 st->name = NULL;
596 st->socket = NULL;
597 st->host = NULL;
598 st->port = NULL;
600 if (strcasecmp (ci->key, "Plugin") == 0) /* default instance */
601 st->name = sstrdup ("__legacy__");
602 else /* <Instance /> block */
603 status = cf_util_get_string (ci, &st->name);
604 if (status != 0)
605 {
606 sfree (st);
607 return (status);
608 }
609 assert (st->name != NULL);
611 for (i = 0; i < ci->children_num; i++)
612 {
613 oconfig_item_t *child = ci->children + i;
615 if (strcasecmp ("Socket", child->key) == 0)
616 status = cf_util_get_string (child, &st->socket);
617 else if (strcasecmp ("Host", child->key) == 0)
618 status = cf_util_get_string (child, &st->host);
619 else if (strcasecmp ("Port", child->key) == 0)
620 status = cf_util_get_service (child, &st->port);
621 else
622 {
623 WARNING ("memcached plugin: Option `%s' not allowed here.",
624 child->key);
625 status = -1;
626 }
628 if (status != 0)
629 break;
630 }
632 if (status == 0)
633 status = memcached_add_read_callback (st);
635 if (status != 0)
636 {
637 memcached_free(st);
638 return (-1);
639 }
641 return (0);
642 }
644 static int memcached_config (oconfig_item_t *ci)
645 {
646 int status = 0;
647 _Bool have_instance_block = 0;
648 int i;
650 for (i = 0; i < ci->children_num; i++)
651 {
652 oconfig_item_t *child = ci->children + i;
654 if (strcasecmp ("Instance", child->key) == 0)
655 {
656 config_add_instance (child);
657 have_instance_block = 1;
658 }
659 else if (!have_instance_block)
660 {
661 /* Non-instance option: Assume legacy configuration (without <Instance />
662 * blocks) and call config_add_instance() with the <Plugin /> block. */
663 return (config_add_instance (ci));
664 }
665 else
666 WARNING ("memcached plugin: The configuration option "
667 "\"%s\" is not allowed here. Did you "
668 "forget to add an <Instance /> block "
669 "around the configuration?",
670 child->key);
671 } /* for (ci->children) */
673 return (status);
674 }
676 static int memcached_init (void)
677 {
678 memcached_t *st;
679 int status;
681 if (memcached_have_instances)
682 return (0);
684 /* No instances were configured, lets start a default instance. */
685 st = malloc (sizeof (*st));
686 if (st == NULL)
687 return (ENOMEM);
688 memset (st, 0, sizeof (*st));
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 }