memcached plugin: Fix a possible file descriptor leak.
[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) 2005,2006  Vincent StehlĂ©
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Antony Dovgal <tony at daylessday dot org>
22  *   Vincent StehlĂ© <vincent.stehle at free.fr>
23  *   Florian octo Forster <octo at verplant.org>
24  **/
25
26 #include "collectd.h"
27 #include "common.h"
28 #include "plugin.h"
29 #include "configfile.h"
30
31 # include <poll.h>
32 # include <netdb.h>
33 # include <sys/socket.h>
34 # include <netinet/in.h>
35 # include <netinet/tcp.h>
36
37 #define MEMCACHED_DEF_HOST "127.0.0.1"
38 #define MEMCACHED_DEF_PORT "11211"
39
40 #define MEMCACHED_RETRY_COUNT 100
41
42 static const char *config_keys[] =
43 {
44         "Host",
45         "Port"
46 };
47 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
48
49 static char *memcached_host = NULL;
50 static char memcached_port[16];
51
52 static int memcached_query_daemon (char *buffer, int buffer_size) /* {{{ */
53 {
54         int fd;
55         ssize_t status;
56         int buffer_fill;
57
58         const char *host;
59         const char *port;
60
61         struct addrinfo  ai_hints;
62         struct addrinfo *ai_list, *ai_ptr;
63         int              ai_return, i = 0;
64
65         memset (&ai_hints, '\0', sizeof (ai_hints));
66         ai_hints.ai_flags    = 0;
67 #ifdef AI_ADDRCONFIG
68 /*      ai_hints.ai_flags   |= AI_ADDRCONFIG; */
69 #endif
70         ai_hints.ai_family   = AF_INET;
71         ai_hints.ai_socktype = SOCK_STREAM;
72         ai_hints.ai_protocol = 0;
73
74         host = memcached_host;
75         if (host == NULL) {
76                 host = MEMCACHED_DEF_HOST;
77         }
78
79         port = memcached_port;
80         if (strlen (port) == 0) {
81                 port = MEMCACHED_DEF_PORT;
82         }
83
84         if ((ai_return = getaddrinfo (host, port, NULL, &ai_list)) != 0) {
85                 char errbuf[1024];
86                 ERROR ("memcached: getaddrinfo (%s, %s): %s",
87                                 host, port,
88                                 (ai_return == EAI_SYSTEM)
89                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
90                                 : gai_strerror (ai_return));
91                 return -1;
92         }
93
94         fd = -1;
95         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
96                 /* create our socket descriptor */
97                 if ((fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol)) < 0) {
98                         char errbuf[1024];
99                         ERROR ("memcached: socket: %s", sstrerror (errno, errbuf, sizeof (errbuf)));
100                         continue;
101                 }
102
103                 /* connect to the memcached daemon */
104                 if (connect (fd, (struct sockaddr *) ai_ptr->ai_addr, ai_ptr->ai_addrlen)) {
105                         shutdown(fd, SHUT_RDWR);
106                         close(fd);
107                         fd = -1;
108                         continue;
109                 }
110
111                 /* A socket could be opened and connecting succeeded. We're
112                  * done. */
113                 break;
114         }
115
116         freeaddrinfo (ai_list);
117
118         if (fd < 0) {
119                 ERROR ("memcached: Could not connect to daemon.");
120                 return -1;
121         }
122
123         if (send(fd, "stats\r\n", sizeof("stats\r\n") - 1, MSG_DONTWAIT) != (sizeof("stats\r\n") - 1)) {
124                 ERROR ("memcached: Could not send command to the memcached daemon.");
125                 return -1;
126         }
127
128         {
129                 struct pollfd p;
130                 int timeout;
131                 int status;
132
133                 memset (&p, 0, sizeof (p));
134                 p.fd = fd;
135                 p.events = POLLIN | POLLERR | POLLHUP;
136                 p.revents = 0;
137
138                 status = poll (&p, /* nfds = */ 1, /* timeout = */ interval_g);
139                 if (status <= 0)
140                 {
141                         if (status == 0)
142                         {
143                                 ERROR ("memcached: poll(2) timed out after %i seconds.", interval_g);
144                         }
145                         else
146                         {
147                                 char errbuf[1024];
148                                 ERROR ("memcached: poll(2) failed: %s",
149                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
150                         }
151                         shutdown (fd, SHUT_RDWR);
152                         close (fd);
153                         return (-1);
154                 }
155         }
156
157         /* receive data from the memcached daemon */
158         memset (buffer, '\0', buffer_size);
159
160         buffer_fill = 0;
161         while ((status = recv (fd, buffer + buffer_fill, buffer_size - buffer_fill, MSG_DONTWAIT)) != 0) {
162                 if (i > MEMCACHED_RETRY_COUNT) {
163                         ERROR("recv() timed out");
164                         break;
165                 }
166                 i++;
167
168                 if (status == -1) {
169                         char errbuf[1024];
170
171                         if (errno == EAGAIN) {
172                                 continue;
173                         }
174
175                         ERROR ("memcached: Error reading from socket: %s",
176                                         sstrerror (errno, errbuf, sizeof (errbuf)));
177                         shutdown(fd, SHUT_RDWR);
178                         close (fd);
179                         return -1;
180                 }
181                 buffer_fill += status;
182
183                 if (buffer_fill > 3 && buffer[buffer_fill-5] == 'E' && buffer[buffer_fill-4] == 'N' && buffer[buffer_fill-3] == 'D') {
184                         /* we got all the data */
185                         break;
186                 }
187         }
188
189         if (buffer_fill >= buffer_size) {
190                 buffer[buffer_size - 1] = '\0';
191                 WARNING ("memcached: Message from memcached has been truncated.");
192         } else if (buffer_fill == 0) {
193                 WARNING ("memcached: Peer has unexpectedly shut down the socket. "
194                                 "Buffer: `%s'", buffer);
195                 shutdown(fd, SHUT_RDWR);
196                 close(fd);
197                 return -1;
198         }
199
200         shutdown(fd, SHUT_RDWR);
201         close(fd);
202         return 0;
203 }
204 /* }}} */
205
206 static int memcached_config (const char *key, const char *value) /* {{{ */
207 {
208         if (strcasecmp (key, "Host") == 0) {
209                 if (memcached_host != NULL) {
210                         free (memcached_host);
211                 }
212                 memcached_host = strdup (value);
213         } else if (strcasecmp (key, "Port") == 0) {
214                 int port = (int) (atof (value));
215                 if ((port > 0) && (port <= 65535)) {
216                         snprintf (memcached_port, sizeof (memcached_port), "%i", port);
217                 } else {
218                         strncpy (memcached_port, value, sizeof (memcached_port));
219                 }
220                 memcached_port[sizeof (memcached_port) - 1] = '\0';
221         } else {
222                 return -1;
223         }
224
225         return 0;
226 }
227 /* }}} */
228
229 static void submit_counter (const char *type, const char *type_inst,
230                 counter_t value) /* {{{ */
231 {
232         value_t values[1];
233         value_list_t vl = VALUE_LIST_INIT;
234
235         values[0].counter = value;
236
237         vl.values = values;
238         vl.values_len = 1;
239         vl.time = time (NULL);
240         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
241         sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
242         if (type_inst != NULL)
243         {
244                 strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
245                 vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
246         }
247
248         plugin_dispatch_values (type, &vl);
249 } /* void memcached_submit_cmd */
250 /* }}} */
251
252 static void submit_counter2 (const char *type, const char *type_inst,
253                 counter_t value0, counter_t value1) /* {{{ */
254 {
255         value_t values[2];
256         value_list_t vl = VALUE_LIST_INIT;
257
258         values[0].counter = value0;
259         values[1].counter = value1;
260
261         vl.values = values;
262         vl.values_len = 2;
263         vl.time = time (NULL);
264         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
265         sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
266         if (type_inst != NULL)
267         {
268                 strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
269                 vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
270         }
271
272         plugin_dispatch_values (type, &vl);
273 } /* void memcached_submit_cmd */
274 /* }}} */
275
276 static void submit_gauge (const char *type, const char *type_inst,
277                 gauge_t value) /* {{{ */
278 {
279         value_t values[1];
280         value_list_t vl = VALUE_LIST_INIT;
281
282         values[0].gauge = value;
283
284         vl.values = values;
285         vl.values_len = 1;
286         vl.time = time (NULL);
287         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
288         sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
289         if (type_inst != NULL)
290         {
291                 strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
292                 vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
293         }
294
295         plugin_dispatch_values (type, &vl);
296 }
297 /* }}} */
298
299 static void submit_gauge2 (const char *type, const char *type_inst,
300                 gauge_t value0, gauge_t value1) /* {{{ */
301 {
302         value_t values[2];
303         value_list_t vl = VALUE_LIST_INIT;
304
305         values[0].gauge = value0;
306         values[1].gauge = value1;
307
308         vl.values = values;
309         vl.values_len = 2;
310         vl.time = time (NULL);
311         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
312         sstrncpy (vl.plugin, "memcached", sizeof (vl.plugin));
313         if (type_inst != NULL)
314         {
315                 strncpy (vl.type_instance, type_inst, sizeof (vl.type_instance));
316                 vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
317         }
318
319         plugin_dispatch_values (type, &vl);
320 }
321 /* }}} */
322
323 static int memcached_read (void) /* {{{ */
324 {
325         char buf[1024];
326         char *fields[3];
327         char *ptr;
328         char *line;
329         char *saveptr;
330         int fields_num;
331
332         gauge_t bytes_used = NAN;
333         gauge_t bytes_total = NAN;
334         counter_t rusage_user = 0;
335         counter_t rusage_syst = 0;
336         counter_t octets_rx = 0;
337         counter_t octets_tx = 0;
338
339         /* get data from daemon */
340         if (memcached_query_daemon (buf, sizeof (buf)) < 0) {
341                 return -1;
342         }
343
344 #define FIELD_IS(cnst) \
345         (((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))
346
347     ptr = buf;
348     saveptr = NULL;
349     while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
350         {
351                 int name_len;
352
353         ptr = NULL;
354
355                 fields_num = strsplit(line, fields, 3);
356                 if (fields_num != 3)
357                         continue;
358
359                 name_len = strlen(fields[1]);
360                 if (name_len == 0)
361                         continue;
362
363                 /*
364                  * For an explanation on these fields please refer to
365                  * <http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt>
366                  */
367
368                 /*
369                  * CPU time consumed by the memcached process
370                  */
371                 if (FIELD_IS ("rusage_user"))
372                 {
373                         rusage_user = atoll (fields[2]);
374                 }
375                 else if (FIELD_IS ("rusage_system"))
376                 {
377                         rusage_syst = atoll(fields[2]);
378                 }
379         
380                 /*
381                  * Number of threads of this instance
382                  */
383                 else if (FIELD_IS ("threads"))
384                 {
385                         submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]));
386                 }
387
388                 /*
389                  * Number of items stored
390                  */
391                 else if (FIELD_IS ("curr_items"))
392                 {
393                         submit_gauge ("memcached_items", "current", atof (fields[2]));
394                 }
395 /*              
396                 else if (FIELD_IS ("total_items"))
397                 {
398                         total_items = atoll(fields[2]);
399                 }
400  */
401
402                 /*
403                  * Number of bytes used and available (total - used)
404                  */
405                 else if (FIELD_IS ("bytes"))
406                 {
407                         bytes_used = atof (fields[2]);
408                 }
409                 else if (FIELD_IS ("limit_maxbytes"))
410                 {
411                         bytes_total = atof(fields[2]);
412                 }
413
414                 /*
415                  * Connections
416                  */
417                 else if (FIELD_IS ("curr_connections"))
418                 {
419                         submit_gauge ("memcached_connections", "current", atof (fields[2]));
420                 }
421 /*
422                 else if (FIELD_IS("total_connections"))
423                 {
424                         total_connections = atoll(fields[2]);
425                 }
426 */
427
428 /*
429  * ``Number of connection structures allocated by the server''
430                 else if (FIELD_IS ("connection_structures"))
431                 {
432                         connection_structures = atof(fields[2]);
433                 }
434  */
435
436                 /*
437                  * Commands
438                  */
439                 else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
440                 {
441                         const char *name = fields[1] + 4;
442                         submit_counter ("memcached_command", name, atoll (fields[2]));
443                 }
444
445                 /*
446                  * Operations on the cache, i. e. cache hits, cache misses and evictions of items
447                  */
448                 else if (FIELD_IS ("get_hits"))
449                 {
450                         submit_counter ("memcached_ops", "hits", atoll (fields[2]));
451                 }
452                 else if (FIELD_IS ("get_misses"))
453                 {
454                         submit_counter ("memcached_ops", "misses", atoll (fields[2]));
455                 }
456                 else if (FIELD_IS ("evictions"))
457                 {
458                         submit_counter ("memcached_ops", "evictions", atoll (fields[2]));
459                 }
460
461                 /*
462                  * Network traffic
463                  */
464                 else if (FIELD_IS ("bytes_read"))
465                 {
466                         octets_rx = atoll (fields[2]);
467                 }
468                 else if (FIELD_IS ("bytes_written"))
469                 {
470                         octets_tx = atoll (fields[2]);
471                 }
472         } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
473
474         if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
475                 submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used);
476         
477         if ((rusage_user != 0) || (rusage_syst != 0))
478                 submit_counter2 ("ps_cputime", NULL, rusage_user, rusage_syst);
479
480         if ((octets_rx != 0) || (octets_tx != 0))
481                 submit_counter2 ("memcached_octets", NULL, octets_rx, octets_tx);
482         
483         return 0;
484 }
485 /* }}} */
486
487 void module_register (void) /* {{{ */
488 {
489         plugin_register_config ("memcached", memcached_config, config_keys, config_keys_num);
490         plugin_register_read ("memcached", memcached_read);
491 }
492 /* }}} */
493
494 /*
495  * Local variables:
496  * tab-width: 4
497  * c-basic-offset: 4
498  * End:
499  * vim600: sw=4 ts=4 fdm=marker
500  * vim<600: sw=4 ts=4
501  */
502