memcached: Fix hitratio reporting
[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  * Copyright (C) 2017       Pavel Rochnyak
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the
12  * Free Software Foundation; either version 2 of the License, or (at your
13  * option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23  *
24  * Authors:
25  *   Antony Dovgal <tony at daylessday dot org>
26  *   Florian octo Forster <octo at collectd.org>
27  *   Doug MacEachern <dougm at hyperic.com>
28  *   Franck Lombardi
29  *   Nicolas Szalay
30  *   Pavel Rochnyak <pavel2000 ngs.ru>
31  **/
32
33 #include "collectd.h"
34
35 #include "common.h"
36 #include "plugin.h"
37
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <netinet/tcp.h>
41 #include <sys/un.h>
42
43 #include <poll.h>
44
45 #define MEMCACHED_DEF_HOST "127.0.0.1"
46 #define MEMCACHED_DEF_PORT "11211"
47 #define MEMCACHED_CONNECT_TIMEOUT 10000
48 #define MEMCACHED_IO_TIMEOUT 5000
49
50 struct prev_s {
51   gauge_t hits;
52   gauge_t gets;
53   gauge_t incr_hits;
54   gauge_t incr_misses;
55   gauge_t decr_hits;
56   gauge_t decr_misses;
57 };
58
59 typedef struct prev_s prev_t;
60
61 struct memcached_s {
62   char *name;
63   char *host;
64   char *socket;
65   char *connhost;
66   char *connport;
67   int fd;
68   prev_t prev;
69 };
70 typedef struct memcached_s memcached_t;
71
72 static _Bool memcached_have_instances = 0;
73
74 static void memcached_free(void *arg) {
75   memcached_t *st = arg;
76   if (st == NULL)
77     return;
78
79   if (st->fd >= 0) {
80     shutdown(st->fd, SHUT_RDWR);
81     close(st->fd);
82     st->fd = -1;
83   }
84
85   sfree(st->name);
86   sfree(st->host);
87   sfree(st->socket);
88   sfree(st->connhost);
89   sfree(st->connport);
90   sfree(st);
91 }
92
93 static int memcached_connect_unix(memcached_t *st) {
94   struct sockaddr_un serv_addr = {0};
95   int fd;
96
97   serv_addr.sun_family = AF_UNIX;
98   sstrncpy(serv_addr.sun_path, st->socket, sizeof(serv_addr.sun_path));
99
100   /* create our socket descriptor */
101   fd = socket(AF_UNIX, SOCK_STREAM, 0);
102   if (fd < 0) {
103     char errbuf[1024];
104     ERROR("memcached plugin: memcached_connect_unix: socket(2) failed: %s",
105           sstrerror(errno, errbuf, sizeof(errbuf)));
106     return -1;
107   }
108
109   /* connect to the memcached daemon */
110   int status = connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
111   if (status != 0) {
112     shutdown(fd, SHUT_RDWR);
113     close(fd);
114     return -1;
115   }
116
117   /* switch to non-blocking mode */
118   int flags = fcntl(fd, F_GETFL);
119   status = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
120   if (status != 0) {
121     close(fd);
122     return -1;
123   }
124
125   return fd;
126 } /* int memcached_connect_unix */
127
128 static int memcached_connect_inet(memcached_t *st) {
129   struct addrinfo *ai_list;
130   int status;
131   int fd = -1;
132
133   struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
134                               .ai_flags = AI_ADDRCONFIG,
135                               .ai_socktype = SOCK_STREAM};
136
137   status = getaddrinfo(st->connhost, st->connport, &ai_hints, &ai_list);
138   if (status != 0) {
139     char errbuf[1024];
140     ERROR("memcached plugin: memcached_connect_inet: "
141           "getaddrinfo(%s,%s) failed: %s",
142           st->connhost, st->connport,
143           (status == EAI_SYSTEM) ? sstrerror(errno, errbuf, sizeof(errbuf))
144                                  : gai_strerror(status));
145     return -1;
146   }
147
148   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
149        ai_ptr = ai_ptr->ai_next) {
150     /* create our socket descriptor */
151     fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
152     if (fd < 0) {
153       char errbuf[1024];
154       WARNING("memcached plugin: memcached_connect_inet: "
155               "socket(2) failed: %s",
156               sstrerror(errno, errbuf, sizeof(errbuf)));
157       continue;
158     }
159
160     /* switch socket to non-blocking mode */
161     int flags = fcntl(fd, F_GETFL);
162     status = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
163     if (status != 0) {
164       close(fd);
165       fd = -1;
166       continue;
167     }
168
169     /* connect to the memcached daemon */
170     status = (int)connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
171     if (status != 0 && errno != EINPROGRESS) {
172       shutdown(fd, SHUT_RDWR);
173       close(fd);
174       fd = -1;
175       continue;
176     }
177
178     /* Wait until connection establishes */
179     struct pollfd pollfd = {
180         .fd = fd, .events = POLLOUT,
181     };
182     do
183       status = poll(&pollfd, 1, MEMCACHED_CONNECT_TIMEOUT);
184     while (status < 0 && errno == EINTR);
185     if (status <= 0) {
186       close(fd);
187       fd = -1;
188       continue;
189     }
190
191     /* Check if all is good */
192     int socket_error;
193     status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&socket_error,
194                         &(socklen_t){sizeof(socket_error)});
195     if (status != 0 || socket_error != 0) {
196       close(fd);
197       fd = -1;
198       continue;
199     }
200     /* A socket is opened and connection succeeded. We're done. */
201     break;
202   }
203
204   freeaddrinfo(ai_list);
205   return fd;
206 } /* int memcached_connect_inet */
207
208 static void memcached_connect(memcached_t *st) {
209   if (st->fd >= 0)
210     return;
211
212   if (st->socket != NULL)
213     st->fd = memcached_connect_unix(st);
214   else
215     st->fd = memcached_connect_inet(st);
216
217   if (st->fd >= 0)
218     INFO("memcached plugin: Instance \"%s\": connection established.",
219          st->name);
220 }
221
222 static int memcached_query_daemon(char *buffer, size_t buffer_size,
223                                   memcached_t *st) {
224   int status;
225   size_t buffer_fill;
226
227   memcached_connect(st);
228   if (st->fd < 0) {
229     ERROR("memcached plugin: Instance \"%s\" could not connect to daemon.",
230           st->name);
231     return -1;
232   }
233
234   struct pollfd pollfd = {
235       .fd = st->fd, .events = POLLOUT,
236   };
237
238   do
239     status = poll(&pollfd, 1, MEMCACHED_IO_TIMEOUT);
240   while (status < 0 && errno == EINTR);
241
242   if (status <= 0) {
243     ERROR("memcached plugin: poll() failed for write() call.");
244     close(st->fd);
245     st->fd = -1;
246     return -1;
247   }
248
249   status = (int)swrite(st->fd, "stats\r\n", strlen("stats\r\n"));
250   if (status != 0) {
251     char errbuf[1024];
252     ERROR("memcached plugin: Instance \"%s\": write(2) failed: %s", st->name,
253           sstrerror(errno, errbuf, sizeof(errbuf)));
254     shutdown(st->fd, SHUT_RDWR);
255     close(st->fd);
256     st->fd = -1;
257     return -1;
258   }
259
260   /* receive data from the memcached daemon */
261   memset(buffer, 0, buffer_size);
262
263   buffer_fill = 0;
264   pollfd.events = POLLIN;
265   while (1) {
266     do
267       status = poll(&pollfd, 1, MEMCACHED_IO_TIMEOUT);
268     while (status < 0 && errno == EINTR);
269
270     if (status <= 0) {
271       ERROR("memcached plugin: Instance \"%s\": Timeout reading from socket",
272             st->name);
273       close(st->fd);
274       st->fd = -1;
275       return -1;
276     }
277
278     do
279       status = (int)recv(st->fd, buffer + buffer_fill,
280                          buffer_size - buffer_fill, /* flags = */ 0);
281     while (status < 0 && errno == EINTR);
282
283     char const end_token[5] = {'E', 'N', 'D', '\r', '\n'};
284     if (status < 0) {
285       char errbuf[1024];
286
287       if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
288         continue;
289
290       ERROR("memcached plugin: Instance \"%s\": Error reading from socket: %s",
291             st->name, sstrerror(errno, errbuf, sizeof(errbuf)));
292       shutdown(st->fd, SHUT_RDWR);
293       close(st->fd);
294       st->fd = -1;
295       return -1;
296     }
297
298     buffer_fill += (size_t)status;
299     if (buffer_fill > buffer_size) {
300       buffer_fill = buffer_size;
301       WARNING("memcached plugin: Instance \"%s\": Message was truncated.",
302               st->name);
303       shutdown(st->fd, SHUT_RDWR);
304       close(st->fd);
305       st->fd = -1;
306       break;
307     }
308
309     /* If buffer ends in end_token, we have all the data. */
310     if (memcmp(buffer + buffer_fill - sizeof(end_token), end_token,
311                sizeof(end_token)) == 0)
312       break;
313   } /* while (recv) */
314
315   status = 0;
316   if (buffer_fill == 0) {
317     WARNING("memcached plugin: Instance \"%s\": No data returned by memcached.",
318             st->name);
319     status = -1;
320   }
321
322   return status;
323 } /* int memcached_query_daemon */
324
325 static void memcached_init_vl(value_list_t *vl, memcached_t const *st) {
326   sstrncpy(vl->plugin, "memcached", sizeof(vl->plugin));
327   if (st->host != NULL)
328     sstrncpy(vl->host, st->host, sizeof(vl->host));
329   if (st->name != NULL)
330     sstrncpy(vl->plugin_instance, st->name, sizeof(vl->plugin_instance));
331 }
332
333 static void submit_derive(const char *type, const char *type_inst,
334                           derive_t value, memcached_t *st) {
335   value_list_t vl = VALUE_LIST_INIT;
336
337   memcached_init_vl(&vl, st);
338   vl.values = &(value_t){.derive = value};
339   vl.values_len = 1;
340   sstrncpy(vl.type, type, sizeof(vl.type));
341   if (type_inst != NULL)
342     sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
343
344   plugin_dispatch_values(&vl);
345 }
346
347 static void submit_derive2(const char *type, const char *type_inst,
348                            derive_t value0, derive_t value1, memcached_t *st) {
349   value_list_t vl = VALUE_LIST_INIT;
350   value_t values[] = {
351       {.derive = value0}, {.derive = value1},
352   };
353
354   memcached_init_vl(&vl, st);
355   vl.values = values;
356   vl.values_len = STATIC_ARRAY_SIZE(values);
357   sstrncpy(vl.type, type, sizeof(vl.type));
358   if (type_inst != NULL)
359     sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
360
361   plugin_dispatch_values(&vl);
362 }
363
364 static void submit_gauge(const char *type, const char *type_inst, gauge_t value,
365                          memcached_t *st) {
366   value_list_t vl = VALUE_LIST_INIT;
367
368   memcached_init_vl(&vl, st);
369   vl.values = &(value_t){.gauge = value};
370   vl.values_len = 1;
371   sstrncpy(vl.type, type, sizeof(vl.type));
372   if (type_inst != NULL)
373     sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
374
375   plugin_dispatch_values(&vl);
376 }
377
378 static void submit_gauge2(const char *type, const char *type_inst,
379                           gauge_t value0, gauge_t value1, memcached_t *st) {
380   value_list_t vl = VALUE_LIST_INIT;
381   value_t values[] = {
382       {.gauge = value0}, {.gauge = value1},
383   };
384
385   memcached_init_vl(&vl, st);
386   vl.values = values;
387   vl.values_len = STATIC_ARRAY_SIZE(values);
388   sstrncpy(vl.type, type, sizeof(vl.type));
389   if (type_inst != NULL)
390     sstrncpy(vl.type_instance, type_inst, sizeof(vl.type_instance));
391
392   plugin_dispatch_values(&vl);
393 }
394
395 static gauge_t calculate_rate(gauge_t part, gauge_t total, gauge_t *prev_part,
396                               gauge_t *prev_total) {
397   if (isnan(*prev_part) || isnan(*prev_total) || (part < *prev_part) ||
398       (total < *prev_total)) {
399     *prev_part = part;
400     *prev_total = total;
401     return NAN;
402   }
403
404   gauge_t num = part - *prev_part;
405   gauge_t denom = total - *prev_total;
406
407   *prev_part = part;
408   *prev_total = total;
409
410   if (num == 0 || denom == 0)
411     return 0;
412
413   return 100.0 * num / denom;
414 }
415
416 static gauge_t calculate_rate2(gauge_t part1, gauge_t part2, gauge_t *prev1,
417                                gauge_t *prev2) {
418   if (isnan(*prev1) || isnan(*prev2) || (part1 < *prev1) || (part2 < *prev2)) {
419     *prev1 = part1;
420     *prev2 = part2;
421     return NAN;
422   }
423
424   gauge_t num = part1 - *prev1;
425   gauge_t denom = part2 - *prev2 + num;
426
427   *prev1 = part1;
428   *prev2 = part2;
429
430   if (num == 0 || denom == 0)
431     return 0;
432
433   return 100.0 * num / denom;
434 }
435
436 static int memcached_read(user_data_t *user_data) {
437   char buf[4096];
438   char *fields[3];
439   char *ptr;
440   char *line;
441   char *saveptr;
442   int fields_num;
443
444   gauge_t bytes_used = NAN;
445   gauge_t bytes_total = NAN;
446   gauge_t hits = NAN;
447   gauge_t gets = NAN;
448   gauge_t incr_hits = NAN;
449   gauge_t incr_misses = NAN;
450   gauge_t decr_hits = NAN;
451   gauge_t decr_misses = NAN;
452   derive_t rusage_user = 0;
453   derive_t rusage_syst = 0;
454   derive_t octets_rx = 0;
455   derive_t octets_tx = 0;
456
457   memcached_t *st;
458   st = user_data->data;
459   prev_t *prev = &st->prev;
460
461   /* get data from daemon */
462   if (memcached_query_daemon(buf, sizeof(buf), st) < 0) {
463     return -1;
464   }
465
466 #define FIELD_IS(cnst)                                                         \
467   (((sizeof(cnst) - 1) == name_len) && (strcmp(cnst, fields[1]) == 0))
468
469   ptr = buf;
470   saveptr = NULL;
471   while ((line = strtok_r(ptr, "\n\r", &saveptr)) != NULL) {
472     int name_len;
473
474     ptr = NULL;
475
476     fields_num = strsplit(line, fields, 3);
477     if (fields_num != 3)
478       continue;
479
480     name_len = strlen(fields[1]);
481     if (name_len == 0)
482       continue;
483
484     /*
485      * For an explanation on these fields please refer to
486      * <https://github.com/memcached/memcached/blob/master/doc/protocol.txt>
487      */
488
489     /*
490      * CPU time consumed by the memcached process
491      */
492     if (FIELD_IS("rusage_user")) {
493       /* Convert to useconds */
494       rusage_user = atof(fields[2]) * 1000000;
495     } else if (FIELD_IS("rusage_system")) {
496       rusage_syst = atof(fields[2]) * 1000000;
497     }
498
499     /*
500      * Number of threads of this instance
501      */
502     else if (FIELD_IS("threads")) {
503       submit_gauge2("ps_count", NULL, NAN, atof(fields[2]), st);
504     }
505
506     /*
507      * Number of items stored
508      */
509     else if (FIELD_IS("curr_items")) {
510       submit_gauge("memcached_items", "current", atof(fields[2]), st);
511     }
512
513     /*
514      * Number of bytes used and available (total - used)
515      */
516     else if (FIELD_IS("bytes")) {
517       bytes_used = atof(fields[2]);
518     } else if (FIELD_IS("limit_maxbytes")) {
519       bytes_total = atof(fields[2]);
520     }
521
522     /*
523      * Connections
524      */
525     else if (FIELD_IS("curr_connections")) {
526       submit_gauge("memcached_connections", "current", atof(fields[2]), st);
527     } else if (FIELD_IS("listen_disabled_num")) {
528       submit_derive("connections", "listen_disabled", atof(fields[2]), st);
529     }
530     /*
531      * Total number of connections opened since the server started running
532      * Report this as connection rate.
533      */
534     else if (FIELD_IS("total_connections")) {
535       submit_derive("connections", "opened", atof(fields[2]), st);
536     }
537
538     /*
539      * Commands
540      */
541     else if ((name_len > 4) && (strncmp(fields[1], "cmd_", 4) == 0)) {
542       const char *name = fields[1] + 4;
543       submit_derive("memcached_command", name, atoll(fields[2]), st);
544       if (strcmp(name, "get") == 0)
545         gets = atof(fields[2]);
546     }
547
548     /*
549      * Increment/Decrement
550      */
551     else if (FIELD_IS("incr_misses")) {
552       derive_t incr_count = atoll(fields[2]);
553       submit_derive("memcached_ops", "incr_misses", incr_count, st);
554       incr_misses = atof(fields[2]);
555     } else if (FIELD_IS("incr_hits")) {
556       derive_t incr_count = atoll(fields[2]);
557       submit_derive("memcached_ops", "incr_hits", incr_count, st);
558       incr_hits = atof(fields[2]);
559     } else if (FIELD_IS("decr_misses")) {
560       derive_t decr_count = atoll(fields[2]);
561       submit_derive("memcached_ops", "decr_misses", decr_count, st);
562       decr_misses = atof(fields[2]);
563     } else if (FIELD_IS("decr_hits")) {
564       derive_t decr_count = atoll(fields[2]);
565       submit_derive("memcached_ops", "decr_hits", decr_count, st);
566       decr_hits = atof(fields[2]);
567     }
568
569     /*
570      * Operations on the cache:
571      * - get hits/misses
572      * - delete hits/misses
573      * - evictions
574      */
575     else if (FIELD_IS("get_hits")) {
576       submit_derive("memcached_ops", "hits", atoll(fields[2]), st);
577       hits = atof(fields[2]);
578     } else if (FIELD_IS("get_misses")) {
579       submit_derive("memcached_ops", "misses", atoll(fields[2]), st);
580     } else if (FIELD_IS("evictions")) {
581       submit_derive("memcached_ops", "evictions", atoll(fields[2]), st);
582     } else if (FIELD_IS("delete_hits")) {
583       submit_derive("memcached_ops", "delete_hits", atoll(fields[2]), st);
584     } else if (FIELD_IS("delete_misses")) {
585       submit_derive("memcached_ops", "delete_misses", atoll(fields[2]), st);
586     }
587
588     /*
589      * Network traffic
590      */
591     else if (FIELD_IS("bytes_read")) {
592       octets_rx = atoll(fields[2]);
593     } else if (FIELD_IS("bytes_written")) {
594       octets_tx = atoll(fields[2]);
595     }
596   } /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */
597
598   if (!isnan(bytes_used) && !isnan(bytes_total) && (bytes_used <= bytes_total))
599     submit_gauge2("df", "cache", bytes_used, bytes_total - bytes_used, st);
600
601   if ((rusage_user != 0) || (rusage_syst != 0))
602     submit_derive2("ps_cputime", NULL, rusage_user, rusage_syst, st);
603
604   if ((octets_rx != 0) || (octets_tx != 0))
605     submit_derive2("memcached_octets", NULL, octets_rx, octets_tx, st);
606
607   if (!isnan(gets) && !isnan(hits)) {
608     gauge_t rate = calculate_rate(hits, gets, &prev->hits, &prev->gets);
609     submit_gauge("percent", "hitratio", rate, st);
610   }
611
612   if (!isnan(incr_hits) && !isnan(incr_misses) &&
613       (incr_hits + incr_misses > 0)) {
614     gauge_t rate = calculate_rate2(incr_hits, incr_misses, &prev->incr_hits,
615                                    &prev->incr_misses);
616     submit_gauge("percent", "incr_hitratio", rate, st);
617     submit_derive("memcached_ops", "incr", incr_hits + incr_misses, st);
618   }
619
620   if (!isnan(decr_hits) && !isnan(decr_misses) &&
621       (decr_hits + decr_misses > 0)) {
622     gauge_t rate = calculate_rate2(decr_hits, decr_misses, &prev->decr_hits,
623                                    &prev->decr_misses);
624     submit_gauge("percent", "decr_hitratio", rate, st);
625     submit_derive("memcached_ops", "decr", decr_hits + decr_misses, st);
626   }
627
628   return 0;
629 } /* int memcached_read */
630
631 static int memcached_set_defaults(memcached_t *st) {
632   /* If no <Address> used then:
633    * - Connect to the destination specified by <Host>, if present.
634    *   If not, use the default address.
635    * - Use the default hostname (set st->host to NULL), if
636    *    - Legacy mode is used (no configuration options at all), or
637    *    - "Host" option is not provided, or
638    *    - "Host" option is set to "localhost" or "127.0.0.1".
639    *
640    * If <Address> used then host may be set to "localhost" or "127.0.0.1"
641    * explicitly.
642    */
643   if (st->connhost == NULL) {
644     if (st->host) {
645       st->connhost = strdup(st->host);
646       if (st->connhost == NULL)
647         return ENOMEM;
648
649       if ((strcmp("127.0.0.1", st->host) == 0) ||
650           (strcmp("localhost", st->host) == 0))
651         sfree(st->host);
652     } else {
653       st->connhost = strdup(MEMCACHED_DEF_HOST);
654       if (st->connhost == NULL)
655         return ENOMEM;
656     }
657   }
658
659   if (st->connport == NULL) {
660     st->connport = strdup(MEMCACHED_DEF_PORT);
661     if (st->connport == NULL)
662       return ENOMEM;
663   }
664
665   assert(st->connhost != NULL);
666   assert(st->connport != NULL);
667   
668   st->prev.hits = NAN;
669   st->prev.gets = NAN;
670   st->prev.incr_hits = NAN;
671   st->prev.incr_misses = NAN;
672   st->prev.decr_hits = NAN;
673   st->prev.decr_misses = NAN;
674
675   return 0;
676 } /* int memcached_set_defaults */
677
678 static int memcached_add_read_callback(memcached_t *st) {
679   char callback_name[3 * DATA_MAX_NAME_LEN];
680
681   if (memcached_set_defaults(st) != 0) {
682     memcached_free(st);
683     return -1;
684   }
685
686   snprintf(callback_name, sizeof(callback_name), "memcached/%s",
687            (st->name != NULL) ? st->name : "__legacy__");
688
689   return plugin_register_complex_read(
690       /* group = */ "memcached",
691       /* name      = */ callback_name,
692       /* callback  = */ memcached_read,
693       /* interval  = */ 0,
694       &(user_data_t){
695           .data = st, .free_func = memcached_free,
696       });
697 } /* int memcached_add_read_callback */
698
699 /* Configuration handling functiions
700  * <Plugin memcached>
701  *   <Instance "instance_name">
702  *     Host foo.zomg.com
703  *     Address 1.2.3.4
704  *     Port "1234"
705  *   </Instance>
706  * </Plugin>
707  */
708 static int config_add_instance(oconfig_item_t *ci) {
709   memcached_t *st;
710   int status = 0;
711
712   /* Disable automatic generation of default instance in the init callback. */
713   memcached_have_instances = 1;
714
715   st = calloc(1, sizeof(*st));
716   if (st == NULL) {
717     ERROR("memcached plugin: calloc failed.");
718     return ENOMEM;
719   }
720
721   st->name = NULL;
722   st->host = NULL;
723   st->socket = NULL;
724   st->connhost = NULL;
725   st->connport = NULL;
726
727   st->fd = -1;
728
729   if (strcasecmp(ci->key, "Instance") == 0)
730     status = cf_util_get_string(ci, &st->name);
731
732   if (status != 0) {
733     sfree(st);
734     return status;
735   }
736
737   for (int i = 0; i < ci->children_num; i++) {
738     oconfig_item_t *child = ci->children + i;
739
740     if (strcasecmp("Socket", child->key) == 0)
741       status = cf_util_get_string(child, &st->socket);
742     else if (strcasecmp("Host", child->key) == 0)
743       status = cf_util_get_string(child, &st->host);
744     else if (strcasecmp("Address", child->key) == 0)
745       status = cf_util_get_string(child, &st->connhost);
746     else if (strcasecmp("Port", child->key) == 0)
747       status = cf_util_get_service(child, &st->connport);
748     else {
749       WARNING("memcached plugin: Option `%s' not allowed here.", child->key);
750       status = -1;
751     }
752
753     if (status != 0)
754       break;
755   }
756
757   if (status != 0) {
758     memcached_free(st);
759     return -1;
760   }
761
762   return memcached_add_read_callback(st);
763 } /* int config_add_instance */
764
765 static int memcached_config(oconfig_item_t *ci) {
766   _Bool have_instance_block = 0;
767
768   for (int i = 0; i < ci->children_num; i++) {
769     oconfig_item_t *child = ci->children + i;
770
771     if (strcasecmp("Instance", child->key) == 0) {
772       config_add_instance(child);
773       have_instance_block = 1;
774     } else if (!have_instance_block) {
775       /* Non-instance option: Assume legacy configuration (without <Instance />
776        * blocks) and call config_add_instance() with the <Plugin /> block. */
777       return config_add_instance(ci);
778     } else
779       WARNING("memcached plugin: The configuration option "
780               "\"%s\" is not allowed here. Did you "
781               "forget to add an <Instance /> block "
782               "around the configuration?",
783               child->key);
784   } /* for (ci->children) */
785
786   return 0;
787 } /* int memcached_config */
788
789 static int memcached_init(void) {
790   memcached_t *st;
791   int status;
792
793   if (memcached_have_instances)
794     return 0;
795
796   /* No instances were configured, lets start a default instance. */
797   st = calloc(1, sizeof(*st));
798   if (st == NULL)
799     return ENOMEM;
800   st->name = NULL;
801   st->host = NULL;
802   st->socket = NULL;
803   st->connhost = NULL;
804   st->connport = NULL;
805
806   st->fd = -1;
807
808   status = memcached_add_read_callback(st);
809   if (status == 0)
810     memcached_have_instances = 1;
811
812   return status;
813 } /* int memcached_init */
814
815 void module_register(void) {
816   plugin_register_complex_config("memcached", memcached_config);
817   plugin_register_init("memcached", memcached_init);
818 }