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