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