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