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