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