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