oconfig: fix oconfig_free to free all elements
[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/socket.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 (memcached_t *st)
57 {
58   if (st == NULL)
59     return;
60
61   sfree (st->name);
62   sfree (st->socket);
63   sfree (st->host);
64   sfree (st->port);
65 }
66
67 static int memcached_connect_unix (memcached_t *st)
68 {
69   struct sockaddr_un serv_addr;
70   int fd;
71
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));
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   char *host;
102   char *port;
103
104   struct addrinfo  ai_hints;
105   struct addrinfo *ai_list, *ai_ptr;
106   int status;
107   int fd = -1;
108
109   memset (&ai_hints, 0, sizeof (ai_hints));
110   ai_hints.ai_flags    = 0;
111 #ifdef AI_ADDRCONFIG
112   ai_hints.ai_flags   |= AI_ADDRCONFIG;
113 #endif
114   ai_hints.ai_family   = AF_UNSPEC;
115   ai_hints.ai_socktype = SOCK_STREAM;
116   ai_hints.ai_protocol = 0;
117
118   host = (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST;
119   port = (st->port != NULL) ? st->port : MEMCACHED_DEF_PORT;
120
121   ai_list = NULL;
122   status = getaddrinfo (host, port, &ai_hints, &ai_list);
123   if (status != 0)
124   {
125     char errbuf[1024];
126     ERROR ("memcached plugin: memcached_connect_inet: "
127         "getaddrinfo(%s,%s) failed: %s",
128         host, port,
129         (status == EAI_SYSTEM)
130         ? sstrerror (errno, errbuf, sizeof (errbuf))
131         : gai_strerror (status));
132     return (-1);
133   }
134
135   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
136   {
137     /* create our socket descriptor */
138     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
139     if (fd < 0)
140     {
141       char errbuf[1024];
142       WARNING ("memcached plugin: memcached_connect_inet: "
143           "socket(2) failed: %s",
144           sstrerror (errno, errbuf, sizeof (errbuf)));
145       continue;
146     }
147
148     /* connect to the memcached daemon */
149     status = (int) connect (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
150     if (status != 0)
151     {
152       shutdown (fd, SHUT_RDWR);
153       close (fd);
154       fd = -1;
155       continue;
156     }
157
158     /* A socket could be opened and connecting succeeded. We're done. */
159     break;
160   }
161
162   freeaddrinfo (ai_list);
163   return (fd);
164 } /* int memcached_connect_inet */
165
166 static int memcached_connect (memcached_t *st)
167 {
168   if (st->socket != NULL)
169     return (memcached_connect_unix (st));
170   else
171     return (memcached_connect_inet (st));
172 }
173
174 static int memcached_query_daemon (char *buffer, size_t buffer_size, memcached_t *st)
175 {
176   int fd = -1;
177   int status;
178   size_t buffer_fill;
179
180   fd = memcached_connect (st);
181   if (fd < 0) {
182     ERROR ("memcached plugin: Instance \"%s\" could not connect to daemon.",
183         st->name);
184     return -1;
185   }
186
187   status = (int) swrite (fd, "stats\r\n", strlen ("stats\r\n"));
188   if (status != 0)
189   {
190     char errbuf[1024];
191     ERROR ("memcached plugin: write(2) failed: %s",
192         sstrerror (errno, errbuf, sizeof (errbuf)));
193     shutdown(fd, SHUT_RDWR);
194     close (fd);
195     return (-1);
196   }
197
198   /* receive data from the memcached daemon */
199   memset (buffer, 0, buffer_size);
200
201   buffer_fill = 0;
202   while ((status = (int) recv (fd, buffer + buffer_fill,
203           buffer_size - buffer_fill, /* flags = */ 0)) != 0)
204   {
205     char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
206     if (status < 0)
207     {
208       char errbuf[1024];
209
210       if ((errno == EAGAIN) || (errno == EINTR))
211           continue;
212
213       ERROR ("memcached: Error reading from socket: %s",
214           sstrerror (errno, errbuf, sizeof (errbuf)));
215       shutdown(fd, SHUT_RDWR);
216       close (fd);
217       return (-1);
218     }
219
220     buffer_fill += (size_t) status;
221     if (buffer_fill > buffer_size)
222     {
223       buffer_fill = buffer_size;
224       WARNING ("memcached plugin: Message was truncated.");
225       break;
226     }
227
228     /* If buffer ends in end_token, we have all the data. */
229     if (memcmp (buffer + buffer_fill - sizeof (end_token),
230           end_token, sizeof (end_token)) == 0)
231       break;
232   } /* while (recv) */
233
234   status = 0;
235   if (buffer_fill == 0)
236   {
237     WARNING ("memcached plugin: No data returned by memcached.");
238     status = -1;
239   }
240
241   shutdown(fd, SHUT_RDWR);
242   close(fd);
243   return (status);
244 } /* int memcached_query_daemon */
245
246 static void memcached_init_vl (value_list_t *vl, memcached_t const *st)
247 {
248   sstrncpy (vl->plugin, "memcached", sizeof (vl->plugin));
249   if (strcmp (st->name, "__legacy__") == 0) /* legacy mode */
250   {
251     sstrncpy (vl->host, hostname_g, sizeof (vl->host));
252   }
253   else
254   {
255     if (st->socket != NULL)
256       sstrncpy (vl->host, hostname_g, sizeof (vl->host));
257     else
258       sstrncpy (vl->host,
259           (st->host != NULL) ? st->host : MEMCACHED_DEF_HOST,
260           sizeof (vl->host));
261     sstrncpy (vl->plugin_instance, st->name, sizeof (vl->plugin_instance));
262   }
263 }
264
265 static void submit_derive (const char *type, const char *type_inst,
266     derive_t value, memcached_t *st)
267 {
268   value_t values[1];
269   value_list_t vl = VALUE_LIST_INIT;
270   memcached_init_vl (&vl, st);
271
272   values[0].derive = value;
273
274   vl.values = values;
275   vl.values_len = 1;
276   sstrncpy (vl.type, type, sizeof (vl.type));
277   if (type_inst != NULL)
278     sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
279
280   plugin_dispatch_values (&vl);
281 }
282
283 static void submit_derive2 (const char *type, const char *type_inst,
284     derive_t value0, derive_t value1, memcached_t *st)
285 {
286   value_t values[2];
287   value_list_t vl = VALUE_LIST_INIT;
288   memcached_init_vl (&vl, st);
289
290   values[0].derive = value0;
291   values[1].derive = value1;
292
293   vl.values = values;
294   vl.values_len = 2;
295   sstrncpy (vl.type, type, sizeof (vl.type));
296   if (type_inst != NULL)
297     sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
298
299   plugin_dispatch_values (&vl);
300 }
301
302 static void submit_gauge (const char *type, const char *type_inst,
303     gauge_t value, memcached_t *st)
304 {
305   value_t values[1];
306   value_list_t vl = VALUE_LIST_INIT;
307   memcached_init_vl (&vl, st);
308
309   values[0].gauge = value;
310
311   vl.values = values;
312   vl.values_len = 1;
313   sstrncpy (vl.type, type, sizeof (vl.type));
314   if (type_inst != NULL)
315     sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
316
317   plugin_dispatch_values (&vl);
318 }
319
320 static void submit_gauge2 (const char *type, const char *type_inst,
321     gauge_t value0, gauge_t value1, memcached_t *st)
322 {
323   value_t values[2];
324   value_list_t vl = VALUE_LIST_INIT;
325   memcached_init_vl (&vl, st);
326
327   values[0].gauge = value0;
328   values[1].gauge = value1;
329
330   vl.values = values;
331   vl.values_len = 2;
332   sstrncpy (vl.type, type, sizeof (vl.type));
333   if (type_inst != NULL)
334     sstrncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
335
336   plugin_dispatch_values (&vl);
337 }
338
339 static int memcached_read (user_data_t *user_data)
340 {
341   char buf[4096];
342   char *fields[3];
343   char *ptr;
344   char *line;
345   char *saveptr;
346   int fields_num;
347
348   gauge_t bytes_used = NAN;
349   gauge_t bytes_total = NAN;
350   gauge_t hits = NAN;
351   gauge_t gets = NAN;
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      * <http://code.sixapart.com/svn/memcached/trunk/server/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
437     /*
438      * Commands
439      */
440     else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
441     {
442       const char *name = fields[1] + 4;
443       submit_derive ("memcached_command", name, atoll (fields[2]), st);
444       if (strcmp (name, "get") == 0)
445         gets = atof (fields[2]);
446     }
447
448     /*
449      * Operations on the cache, i. e. cache hits, cache misses and evictions of items
450      */
451     else if (FIELD_IS ("get_hits"))
452     {
453       submit_derive ("memcached_ops", "hits", atoll (fields[2]), st);
454       hits = atof (fields[2]);
455     }
456     else if (FIELD_IS ("get_misses"))
457     {
458       submit_derive ("memcached_ops", "misses", atoll (fields[2]), st);
459     }
460     else if (FIELD_IS ("evictions"))
461     {
462       submit_derive ("memcached_ops", "evictions", atoll (fields[2]), st);
463     }
464
465     /*
466      * Network traffic
467      */
468     else if (FIELD_IS ("bytes_read"))
469     {
470       octets_rx = atoll (fields[2]);
471     }
472     else if (FIELD_IS ("bytes_written"))
473     {
474       octets_tx = atoll (fields[2]);
475     }
476   } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
477
478   if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
479     submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used, st);
480
481   if ((rusage_user != 0) || (rusage_syst != 0))
482     submit_derive2 ("ps_cputime", NULL, rusage_user, rusage_syst, st);
483
484   if ((octets_rx != 0) || (octets_tx != 0))
485     submit_derive2 ("memcached_octets", NULL, octets_rx, octets_tx, st);
486
487   if (!isnan (gets) && !isnan (hits))
488   {
489     gauge_t rate = NAN;
490
491     if (gets != 0.0)
492       rate = 100.0 * hits / gets;
493
494     submit_gauge ("percent", "hitratio", rate, st);
495   }
496
497   return 0;
498 } /* int memcached_read */
499
500 static int memcached_add_read_callback (memcached_t *st)
501 {
502   user_data_t ud;
503   char callback_name[3*DATA_MAX_NAME_LEN];
504   int status;
505
506   memset (&ud, 0, sizeof (ud));
507   ud.data = st;
508   ud.free_func = (void *) memcached_free;
509
510   assert (st->name != NULL);
511   ssnprintf (callback_name, sizeof (callback_name), "memcached/%s", st->name);
512
513   status = plugin_register_complex_read (/* group = */ "memcached",
514       /* name      = */ callback_name,
515       /* callback  = */ memcached_read,
516       /* interval  = */ NULL,
517       /* user_data = */ &ud);
518   return (status);
519 } /* int memcached_add_read_callback */
520
521 /* Configuration handling functiions
522  * <Plugin memcached>
523  *   <Instance "instance_name">
524  *     Host foo.zomg.com
525  *     Port "1234"
526  *   </Instance>
527  * </Plugin>
528  */
529 static int config_add_instance(oconfig_item_t *ci)
530 {
531   memcached_t *st;
532   int i;
533   int status = 0;
534
535   /* Disable automatic generation of default instance in the init callback. */
536   memcached_have_instances = 1;
537
538   st = malloc (sizeof (*st));
539   if (st == NULL)
540   {
541     ERROR ("memcached plugin: malloc failed.");
542     return (-1);
543   }
544
545   memset (st, 0, sizeof (*st));
546   st->name = NULL;
547   st->socket = NULL;
548   st->host = NULL;
549   st->port = NULL;
550
551   if (strcasecmp (ci->key, "Plugin") == 0) /* default instance */
552     st->name = sstrdup ("__legacy__");
553   else /* <Instance /> block */
554     status = cf_util_get_string (ci, &st->name);
555   if (status != 0)
556   {
557     sfree (st);
558     return (status);
559   }
560   assert (st->name != NULL);
561
562   for (i = 0; i < ci->children_num; i++)
563   {
564     oconfig_item_t *child = ci->children + i;
565
566     if (strcasecmp ("Socket", child->key) == 0)
567       status = cf_util_get_string (child, &st->socket);
568     else if (strcasecmp ("Host", child->key) == 0)
569       status = cf_util_get_string (child, &st->host);
570     else if (strcasecmp ("Port", child->key) == 0)
571       status = cf_util_get_service (child, &st->port);
572     else
573     {
574       WARNING ("memcached plugin: Option `%s' not allowed here.",
575           child->key);
576       status = -1;
577     }
578
579     if (status != 0)
580       break;
581   }
582
583   if (status == 0)
584     status = memcached_add_read_callback (st);
585
586   if (status != 0)
587   {
588     memcached_free(st);
589     return (-1);
590   }
591
592   return (0);
593 }
594
595 static int memcached_config (oconfig_item_t *ci)
596 {
597   int status = 0;
598   _Bool have_instance_block = 0;
599   int i;
600
601   for (i = 0; i < ci->children_num; i++)
602   {
603     oconfig_item_t *child = ci->children + i;
604
605     if (strcasecmp ("Instance", child->key) == 0)
606     {
607       config_add_instance (child);
608       have_instance_block = 1;
609     }
610     else if (!have_instance_block)
611     {
612       /* Non-instance option: Assume legacy configuration (without <Instance />
613        * blocks) and call config_add_instance() with the <Plugin /> block. */
614       return (config_add_instance (ci));
615     }
616     else
617       WARNING ("memcached plugin: The configuration option "
618           "\"%s\" is not allowed here. Did you "
619           "forget to add an <Instance /> block "
620           "around the configuration?",
621           child->key);
622   } /* for (ci->children) */
623
624   return (status);
625 }
626
627 static int memcached_init (void)
628 {
629   memcached_t *st;
630   int status;
631
632   if (memcached_have_instances)
633     return (0);
634
635   /* No instances were configured, lets start a default instance. */
636   st = malloc (sizeof (*st));
637   if (st == NULL)
638     return (ENOMEM);
639   memset (st, 0, sizeof (*st));
640   st->name = sstrdup ("__legacy__");
641   st->socket = NULL;
642   st->host = NULL;
643   st->port = NULL;
644
645   status = memcached_add_read_callback (st);
646   if (status == 0)
647     memcached_have_instances = 1;
648   else
649     memcached_free (st);
650
651   return (status);
652 } /* int memcached_init */
653
654 void module_register (void)
655 {
656   plugin_register_complex_config ("memcached", memcached_config);
657   plugin_register_init ("memcached", memcached_init);
658 }