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