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 }
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 return (fd);
88 } /* int memcached_connect_unix */
90 static int memcached_connect_inet (memcached_t *st)
91 {
92 char *host;
93 char *port;
95 struct addrinfo ai_hints;
96 struct addrinfo *ai_list, *ai_ptr;
97 int status;
98 int fd = -1;
100 memset (&ai_hints, 0, sizeof (ai_hints));
101 ai_hints.ai_flags = 0;
102 #ifdef AI_ADDRCONFIG
103 ai_hints.ai_flags |= AI_ADDRCONFIG;
104 #endif
105 ai_hints.ai_family = AF_UNSPEC;
106 ai_hints.ai_socktype = SOCK_STREAM;
107 ai_hints.ai_protocol = 0;
109 host = (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST;
110 port = (st->port != NULL) ? st->port : MEMCACHED_DEF_PORT;
112 ai_list = NULL;
113 status = getaddrinfo (host, port, &ai_hints, &ai_list);
114 if (status != 0)
115 {
116 char errbuf[1024];
117 ERROR ("memcached plugin: memcached_connect_inet: "
118 "getaddrinfo(%s,%s) failed: %s",
119 host, port,
120 (status == EAI_SYSTEM)
121 ? sstrerror (errno, errbuf, sizeof (errbuf))
122 : gai_strerror (status));
123 return (-1);
124 }
126 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
127 {
128 /* create our socket descriptor */
129 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
130 if (fd < 0)
131 {
132 char errbuf[1024];
133 WARNING ("memcached plugin: memcached_connect_inet: "
134 "socket(2) failed: %s",
135 sstrerror (errno, errbuf, sizeof (errbuf)));
136 continue;
137 }
139 /* connect to the memcached daemon */
140 status = (int) connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
141 if (status != 0)
142 {
143 shutdown (fd, SHUT_RDWR);
144 close (fd);
145 fd = -1;
146 continue;
147 }
149 /* A socket could be opened and connecting succeeded. We're done. */
150 break;
151 }
153 freeaddrinfo (ai_list);
154 return (fd);
155 } /* int memcached_connect_inet */
157 static int memcached_connect (memcached_t *st)
158 {
159 if (st->socket != NULL)
160 return (memcached_connect_unix (st));
161 else
162 return (memcached_connect_inet (st));
163 }
165 static int memcached_query_daemon (char *buffer, size_t buffer_size, memcached_t *st)
166 {
167 int fd = -1;
168 int status;
169 size_t buffer_fill;
171 fd = memcached_connect (st);
172 if (fd < 0) {
173 ERROR ("memcached plugin: Instance \"%s\" could not connect to daemon.",
174 st->name);
175 return -1;
176 }
178 status = (int) swrite (fd, "stats\r\n", strlen ("stats\r\n"));
179 if (status != 0)
180 {
181 char errbuf[1024];
182 ERROR ("memcached plugin: write(2) failed: %s",
183 sstrerror (errno, errbuf, sizeof (errbuf)));
184 shutdown(fd, SHUT_RDWR);
185 close (fd);
186 return (-1);
187 }
189 /* receive data from the memcached daemon */
190 memset (buffer, 0, buffer_size);
192 buffer_fill = 0;
193 while ((status = (int) recv (fd, buffer + buffer_fill,
194 buffer_size - buffer_fill, /* flags = */ 0)) != 0)
195 {
196 char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
197 if (status < 0)
198 {
199 char errbuf[1024];
201 if ((errno == EAGAIN) || (errno == EINTR))
202 continue;
204 ERROR ("memcached: Error reading from socket: %s",
205 sstrerror (errno, errbuf, sizeof (errbuf)));
206 shutdown(fd, SHUT_RDWR);
207 close (fd);
208 return (-1);
209 }
211 buffer_fill += (size_t) status;
212 if (buffer_fill > buffer_size)
213 {
214 buffer_fill = buffer_size;
215 WARNING ("memcached plugin: Message was truncated.");
216 break;
217 }
219 /* If buffer ends in end_token, we have all the data. */
220 if (memcmp (buffer + buffer_fill - sizeof (end_token),
221 end_token, sizeof (end_token)) == 0)
222 break;
223 } /* while (recv) */
225 status = 0;
226 if (buffer_fill == 0)
227 {
228 WARNING ("memcached plugin: No data returned by memcached.");
229 status = -1;
230 }
232 shutdown(fd, SHUT_RDWR);
233 close(fd);
234 return (status);
235 } /* int memcached_query_daemon */
237 static void memcached_init_vl (value_list_t *vl, memcached_t const *st)
238 {
239 sstrncpy (vl->plugin, "memcached", sizeof (vl->plugin));
240 if (strcmp (st->name, "__legacy__") == 0) /* legacy mode */
241 {
242 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
243 }
244 else
245 {
246 if (st->socket != NULL)
247 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
248 else
249 sstrncpy (vl->host,
250 (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST,
251 sizeof (vl->host));
252 sstrncpy (vl->plugin_instance, st->name, sizeof (vl->plugin_instance));
253 }
254 }
256 static void submit_derive (const char *type, const char *type_inst,
257 derive_t value, memcached_t *st)
258 {
259 value_t values[1];
260 value_list_t vl = VALUE_LIST_INIT;
261 memcached_init_vl (&vl, st);
263 values[0].derive = value;
265 vl.values = values;
266 vl.values_len = 1;
267 sstrncpy (vl.type, type, sizeof (vl.type));
268 if (type_inst != NULL)
269 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
271 plugin_dispatch_values (&vl);
272 }
274 static void submit_derive2 (const char *type, const char *type_inst,
275 derive_t value0, derive_t value1, memcached_t *st)
276 {
277 value_t values[2];
278 value_list_t vl = VALUE_LIST_INIT;
279 memcached_init_vl (&vl, st);
281 values[0].derive = value0;
282 values[1].derive = value1;
284 vl.values = values;
285 vl.values_len = 2;
286 sstrncpy (vl.type, type, sizeof (vl.type));
287 if (type_inst != NULL)
288 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
290 plugin_dispatch_values (&vl);
291 }
293 static void submit_gauge (const char *type, const char *type_inst,
294 gauge_t value, memcached_t *st)
295 {
296 value_t values[1];
297 value_list_t vl = VALUE_LIST_INIT;
298 memcached_init_vl (&vl, st);
300 values[0].gauge = value;
302 vl.values = values;
303 vl.values_len = 1;
304 sstrncpy (vl.type, type, sizeof (vl.type));
305 if (type_inst != NULL)
306 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
308 plugin_dispatch_values (&vl);
309 }
311 static void submit_gauge2 (const char *type, const char *type_inst,
312 gauge_t value0, gauge_t value1, memcached_t *st)
313 {
314 value_t values[2];
315 value_list_t vl = VALUE_LIST_INIT;
316 memcached_init_vl (&vl, st);
318 values[0].gauge = value0;
319 values[1].gauge = value1;
321 vl.values = values;
322 vl.values_len = 2;
323 sstrncpy (vl.type, type, sizeof (vl.type));
324 if (type_inst != NULL)
325 sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
327 plugin_dispatch_values (&vl);
328 }
330 static int memcached_read (user_data_t *user_data)
331 {
332 char buf[4096];
333 char *fields[3];
334 char *ptr;
335 char *line;
336 char *saveptr;
337 int fields_num;
339 gauge_t bytes_used = NAN;
340 gauge_t bytes_total = NAN;
341 gauge_t hits = NAN;
342 gauge_t gets = NAN;
343 gauge_t incr_hits = NAN;
344 derive_t incr = 0;
345 gauge_t decr_hits = NAN;
346 derive_t decr = 0;
347 derive_t rusage_user = 0;
348 derive_t rusage_syst = 0;
349 derive_t octets_rx = 0;
350 derive_t octets_tx = 0;
352 memcached_t *st;
353 st = user_data->data;
355 /* get data from daemon */
356 if (memcached_query_daemon (buf, sizeof (buf), st) < 0) {
357 return -1;
358 }
360 #define FIELD_IS(cnst) \
361 (((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))
363 ptr = buf;
364 saveptr = NULL;
365 while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
366 {
367 int name_len;
369 ptr = NULL;
371 fields_num = strsplit(line, fields, 3);
372 if (fields_num != 3)
373 continue;
375 name_len = strlen(fields[1]);
376 if (name_len == 0)
377 continue;
379 /*
380 * For an explanation on these fields please refer to
381 * <http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt>
382 */
384 /*
385 * CPU time consumed by the memcached process
386 */
387 if (FIELD_IS ("rusage_user"))
388 {
389 rusage_user = atoll (fields[2]);
390 }
391 else if (FIELD_IS ("rusage_system"))
392 {
393 rusage_syst = atoll(fields[2]);
394 }
396 /*
397 * Number of threads of this instance
398 */
399 else if (FIELD_IS ("threads"))
400 {
401 submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]), st);
402 }
404 /*
405 * Number of items stored
406 */
407 else if (FIELD_IS ("curr_items"))
408 {
409 submit_gauge ("memcached_items", "current", atof (fields[2]), st);
410 }
412 /*
413 * Number of bytes used and available (total - used)
414 */
415 else if (FIELD_IS ("bytes"))
416 {
417 bytes_used = atof (fields[2]);
418 }
419 else if (FIELD_IS ("limit_maxbytes"))
420 {
421 bytes_total = atof(fields[2]);
422 }
424 /*
425 * Connections
426 */
427 else if (FIELD_IS ("curr_connections"))
428 {
429 submit_gauge ("memcached_connections", "current", atof (fields[2]), st);
430 }
432 /*
433 * Commands
434 */
435 else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
436 {
437 const char *name = fields[1] + 4;
438 submit_derive ("memcached_command", name, atoll (fields[2]), st);
439 if (strcmp (name, "get") == 0)
440 gets = atof (fields[2]);
441 }
443 /*
444 * Increment/Decrement
445 */
446 else if (FIELD_IS("incr_misses"))
447 {
448 derive_t incr_count = atoll (fields[2]);
449 submit_derive ("memcached_ops", "incr_misses", incr_count, st);
450 incr += incr_count;
451 }
452 else if (FIELD_IS ("incr_hits"))
453 {
454 derive_t incr_count = atoll (fields[2]);
455 submit_derive ("memcached_ops", "incr_hits", incr_count, st);
456 incr_hits = atof (fields[2]);
457 incr += incr_count;
458 }
459 else if (FIELD_IS ("decr_misses"))
460 {
461 derive_t decr_count = atoll (fields[2]);
462 submit_derive ("memcached_ops", "decr_misses", decr_count, st);
463 decr += decr_count;
464 }
465 else if (FIELD_IS ("decr_hits"))
466 {
467 derive_t decr_count = atoll (fields[2]);
468 submit_derive ("memcached_ops", "decr_hits", decr_count, st);
469 decr_hits = atof (fields[2]);
470 decr += decr_count;
471 }
473 /*
474 * Operations on the cache, i. e. cache hits, cache misses and evictions of items
475 */
476 else if (FIELD_IS ("get_hits"))
477 {
478 submit_derive ("memcached_ops", "hits", atoll (fields[2]), st);
479 hits = atof (fields[2]);
480 }
481 else if (FIELD_IS ("get_misses"))
482 {
483 submit_derive ("memcached_ops", "misses", atoll (fields[2]), st);
484 }
485 else if (FIELD_IS ("evictions"))
486 {
487 submit_derive ("memcached_ops", "evictions", atoll (fields[2]), st);
488 }
490 /*
491 * Network traffic
492 */
493 else if (FIELD_IS ("bytes_read"))
494 {
495 octets_rx = atoll (fields[2]);
496 }
497 else if (FIELD_IS ("bytes_written"))
498 {
499 octets_tx = atoll (fields[2]);
500 }
501 } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
503 if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
504 submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used, st);
506 if ((rusage_user != 0) || (rusage_syst != 0))
507 submit_derive2 ("ps_cputime", NULL, rusage_user, rusage_syst, st);
509 if ((octets_rx != 0) || (octets_tx != 0))
510 submit_derive2 ("memcached_octets", NULL, octets_rx, octets_tx, st);
512 if (!isnan (gets) && !isnan (hits))
513 {
514 gauge_t rate = NAN;
516 if (gets != 0.0)
517 rate = 100.0 * hits / gets;
519 submit_gauge ("percent", "hitratio", rate, st);
520 }
522 if (!isnan (incr_hits) && incr != 0)
523 {
524 gauge_t incr_rate = 100.0 * incr_hits / incr;
525 submit_gauge ("percent", "incr_hitratio", incr_rate, st);
526 submit_derive ("memcached_ops", "incr", incr, st);
527 }
529 if (!isnan (decr_hits) && decr != 0)
530 {
531 gauge_t decr_rate = 100.0 * decr_hits / decr;
532 submit_gauge ("percent", "decr_hitratio", decr_rate, st);
533 submit_derive ("memcached_ops", "decr", decr, st);
534 }
536 return 0;
537 } /* int memcached_read */
539 static int memcached_add_read_callback (memcached_t *st)
540 {
541 user_data_t ud;
542 char callback_name[3*DATA_MAX_NAME_LEN];
543 int status;
545 memset (&ud, 0, sizeof (ud));
546 ud.data = st;
547 ud.free_func = (void *) memcached_free;
549 assert (st->name != NULL);
550 ssnprintf (callback_name, sizeof (callback_name), "memcached/%s", st->name);
552 status = plugin_register_complex_read (/* group = */ "memcached",
553 /* name = */ callback_name,
554 /* callback = */ memcached_read,
555 /* interval = */ NULL,
556 /* user_data = */ &ud);
557 return (status);
558 } /* int memcached_add_read_callback */
560 /* Configuration handling functiions
561 * <Plugin memcached>
562 * <Instance "instance_name">
563 * Host foo.zomg.com
564 * Port "1234"
565 * </Instance>
566 * </Plugin>
567 */
568 static int config_add_instance(oconfig_item_t *ci)
569 {
570 memcached_t *st;
571 int i;
572 int status = 0;
574 /* Disable automatic generation of default instance in the init callback. */
575 memcached_have_instances = 1;
577 st = malloc (sizeof (*st));
578 if (st == NULL)
579 {
580 ERROR ("memcached plugin: malloc failed.");
581 return (-1);
582 }
584 memset (st, 0, sizeof (*st));
585 st->name = NULL;
586 st->socket = NULL;
587 st->host = NULL;
588 st->port = NULL;
590 if (strcasecmp (ci->key, "Plugin") == 0) /* default instance */
591 st->name = sstrdup ("__legacy__");
592 else /* <Instance /> block */
593 status = cf_util_get_string (ci, &st->name);
594 if (status != 0)
595 {
596 sfree (st);
597 return (status);
598 }
599 assert (st->name != NULL);
601 for (i = 0; i < ci->children_num; i++)
602 {
603 oconfig_item_t *child = ci->children + i;
605 if (strcasecmp ("Socket", child->key) == 0)
606 status = cf_util_get_string (child, &st->socket);
607 else if (strcasecmp ("Host", child->key) == 0)
608 status = cf_util_get_string (child, &st->host);
609 else if (strcasecmp ("Port", child->key) == 0)
610 status = cf_util_get_service (child, &st->port);
611 else
612 {
613 WARNING ("memcached plugin: Option `%s' not allowed here.",
614 child->key);
615 status = -1;
616 }
618 if (status != 0)
619 break;
620 }
622 if (status == 0)
623 status = memcached_add_read_callback (st);
625 if (status != 0)
626 {
627 memcached_free(st);
628 return (-1);
629 }
631 return (0);
632 }
634 static int memcached_config (oconfig_item_t *ci)
635 {
636 int status = 0;
637 _Bool have_instance_block = 0;
638 int i;
640 for (i = 0; i < ci->children_num; i++)
641 {
642 oconfig_item_t *child = ci->children + i;
644 if (strcasecmp ("Instance", child->key) == 0)
645 {
646 config_add_instance (child);
647 have_instance_block = 1;
648 }
649 else if (!have_instance_block)
650 {
651 /* Non-instance option: Assume legacy configuration (without <Instance />
652 * blocks) and call config_add_instance() with the <Plugin /> block. */
653 return (config_add_instance (ci));
654 }
655 else
656 WARNING ("memcached plugin: The configuration option "
657 "\"%s\" is not allowed here. Did you "
658 "forget to add an <Instance /> block "
659 "around the configuration?",
660 child->key);
661 } /* for (ci->children) */
663 return (status);
664 }
666 static int memcached_init (void)
667 {
668 memcached_t *st;
669 int status;
671 if (memcached_have_instances)
672 return (0);
674 /* No instances were configured, lets start a default instance. */
675 st = malloc (sizeof (*st));
676 if (st == NULL)
677 return (ENOMEM);
678 memset (st, 0, sizeof (*st));
679 st->name = sstrdup ("__legacy__");
680 st->socket = NULL;
681 st->host = NULL;
682 st->port = NULL;
684 status = memcached_add_read_callback (st);
685 if (status == 0)
686 memcached_have_instances = 1;
687 else
688 memcached_free (st);
690 return (status);
691 } /* int memcached_init */
693 void module_register (void)
694 {
695 plugin_register_complex_config ("memcached", memcached_config);
696 plugin_register_init ("memcached", memcached_init);
697 }