Fix compile time issues
[collectd.git] / src / ceph.c
1 /**
2  * collectd - src/ceph.c
3  * Copyright (C) 2011  New Dream Network
4  * Copyright (C) 2015  Florian octo Forster
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; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Colin McCabe <cmccabe at alumni.cmu.edu>
21  *   Dennis Zou <yunzou at cisco.com>
22  *   Dan Ryder <daryder at cisco.com>
23  *   Florian octo Forster <octo at collectd.org>
24  **/
25
26 #define _DEFAULT_SOURCE
27 #define _BSD_SOURCE
28
29 #include "collectd.h"
30
31 #include "plugin.h"
32 #include "utils/common/common.h"
33
34 #include <arpa/inet.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <yajl/yajl_parse.h>
38 #if HAVE_YAJL_YAJL_VERSION_H
39 #include <yajl/yajl_version.h>
40 #endif
41 #ifdef HAVE_SYS_CAPABILITY_H
42 #include <sys/capability.h>
43 #endif
44
45 #include <inttypes.h>
46 #include <limits.h>
47 #include <math.h>
48 #include <poll.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <strings.h>
54 #include <sys/time.h>
55 #include <sys/types.h>
56 #include <sys/un.h>
57 #include <unistd.h>
58
59 #define RETRY_AVGCOUNT -1
60
61 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
62 #define HAVE_YAJL_V2 1
63 #endif
64
65 #define RETRY_ON_EINTR(ret, expr)                                              \
66   while (1) {                                                                  \
67     ret = expr;                                                                \
68     if (ret >= 0)                                                              \
69       break;                                                                   \
70     ret = -errno;                                                              \
71     if (ret != -EINTR)                                                         \
72       break;                                                                   \
73   }
74
75 /** Timeout interval in seconds */
76 #define CEPH_TIMEOUT_INTERVAL 1
77
78 /** Maximum path length for a UNIX domain socket on this system */
79 #define UNIX_DOMAIN_SOCK_PATH_MAX (sizeof(((struct sockaddr_un *)0)->sun_path))
80
81 /** Yajl callback returns */
82 #define CEPH_CB_CONTINUE 1
83 #define CEPH_CB_ABORT 0
84
85 #if HAVE_YAJL_V2
86 typedef size_t yajl_len_t;
87 #else
88 typedef unsigned int yajl_len_t;
89 #endif
90
91 /** Number of types for ceph defined in types.db */
92 #define CEPH_DSET_TYPES_NUM 3
93 /** ceph types enum */
94 enum ceph_dset_type_d {
95   DSET_LATENCY = 0,
96   DSET_BYTES = 1,
97   DSET_RATE = 2,
98   DSET_TYPE_UNFOUND = 1000
99 };
100
101 /** Valid types for ceph defined in types.db */
102 static const char *const ceph_dset_types[CEPH_DSET_TYPES_NUM] = {
103     "ceph_latency", "ceph_bytes", "ceph_rate"};
104
105 /******* ceph_daemon *******/
106 struct ceph_daemon {
107   /** Version of the admin_socket interface */
108   uint32_t version;
109   /** daemon name **/
110   char name[DATA_MAX_NAME_LEN];
111
112   /** Path to the socket that we use to talk to the ceph daemon */
113   char asok_path[UNIX_DOMAIN_SOCK_PATH_MAX];
114
115   /** Number of counters */
116   int ds_num;
117   /** Track ds types */
118   uint32_t *ds_types;
119   /** Track ds names to match with types */
120   char **ds_names;
121
122   /**
123    * Keep track of last data for latency values so we can calculate rate
124    * since last poll.
125    */
126   struct last_data **last_poll_data;
127   /** index of last poll data */
128   int last_idx;
129 };
130
131 /******* JSON parsing *******/
132 typedef int (*node_handler_t)(void *, const char *, const char *);
133
134 /** Track state and handler while parsing JSON */
135 struct yajl_struct {
136   node_handler_t handler;
137   void *handler_arg;
138
139   char *key;
140   char *stack[YAJL_MAX_DEPTH];
141   size_t depth;
142 };
143 typedef struct yajl_struct yajl_struct;
144
145 enum perfcounter_type_d {
146   PERFCOUNTER_LATENCY = 0x4,
147   PERFCOUNTER_DERIVE = 0x8,
148 };
149
150 /** Give user option to use default (long run = since daemon started) avg */
151 static int long_run_latency_avg;
152
153 /**
154  * Give user option to use default type for special cases -
155  * filestore.journal_wr_bytes is currently only metric here. Ceph reports the
156  * type as a sum/count pair and will calculate it the same as a latency value.
157  * All other "bytes" metrics (excluding the used/capacity bytes for the OSD)
158  * use the DERIVE type. Unless user specifies to use given type, convert this
159  * metric to use DERIVE.
160  */
161 static int convert_special_metrics = 1;
162
163 /** Array of daemons to monitor */
164 static struct ceph_daemon **g_daemons;
165
166 /** Number of elements in g_daemons */
167 static size_t g_num_daemons;
168
169 /**
170  * A set of data that we build up in memory while parsing the JSON.
171  */
172 struct values_tmp {
173   /** ceph daemon we are processing data for*/
174   struct ceph_daemon *d;
175   /** track avgcount across counters for avgcount/sum latency pairs */
176   uint64_t avgcount;
177   /** current index of counters - used to get type of counter */
178   int index;
179   /**
180    * similar to index, but current index of latency type counters -
181    * used to get last poll data of counter
182    */
183   int latency_index;
184   /**
185    * values list - maintain across counters since
186    * host/plugin/plugin instance are always the same
187    */
188   value_list_t vlist;
189 };
190
191 /**
192  * A set of count/sum pairs to keep track of latency types and get difference
193  * between this poll data and last poll data.
194  */
195 struct last_data {
196   char ds_name[DATA_MAX_NAME_LEN];
197   double last_sum;
198   uint64_t last_count;
199 };
200
201 /******* network I/O *******/
202 enum cstate_t {
203   CSTATE_UNCONNECTED = 0,
204   CSTATE_WRITE_REQUEST,
205   CSTATE_READ_VERSION,
206   CSTATE_READ_AMT,
207   CSTATE_READ_JSON,
208 };
209
210 enum request_type_t {
211   ASOK_REQ_VERSION = 0,
212   ASOK_REQ_DATA = 1,
213   ASOK_REQ_SCHEMA = 2,
214   ASOK_REQ_NONE = 1000,
215 };
216
217 struct cconn {
218   /** The Ceph daemon that we're talking to */
219   struct ceph_daemon *d;
220
221   /** Request type */
222   uint32_t request_type;
223
224   /** The connection state */
225   enum cstate_t state;
226
227   /** The socket we use to talk to this daemon */
228   int asok;
229
230   /** The amount of data remaining to read / write. */
231   uint32_t amt;
232
233   /** Length of the JSON to read */
234   uint32_t json_len;
235
236   /** Buffer containing JSON data */
237   unsigned char *json;
238
239   /** Keep data important to yajl processing */
240   struct yajl_struct yajl;
241 };
242
243 static int ceph_cb_null(void *ctx) { return CEPH_CB_CONTINUE; }
244
245 static int ceph_cb_boolean(void *ctx, int bool_val) { return CEPH_CB_CONTINUE; }
246
247 #define BUFFER_ADD(dest, src)                                                  \
248   do {                                                                         \
249     size_t dest_size = sizeof(dest);                                           \
250     size_t dest_len = strlen(dest);                                            \
251     if (dest_size > dest_len) {                                                \
252       sstrncpy((dest) + dest_len, (src), dest_size - dest_len);                \
253     }                                                                          \
254     (dest)[dest_size - 1] = '\0';                                              \
255   } while (0)
256
257 static int ceph_cb_number(void *ctx, const char *number_val,
258                           yajl_len_t number_len) {
259   yajl_struct *state = (yajl_struct *)ctx;
260   char buffer[number_len + 1];
261   char key[2 * DATA_MAX_NAME_LEN] = {0};
262   int status;
263
264   memcpy(buffer, number_val, number_len);
265   buffer[sizeof(buffer) - 1] = '\0';
266
267   for (size_t i = 0; i < state->depth; i++) {
268     if (state->stack[i] == NULL)
269       continue;
270
271     if (strlen(key) != 0)
272       BUFFER_ADD(key, ".");
273     BUFFER_ADD(key, state->stack[i]);
274   }
275
276   /* Super-special case for filestore.journal_wr_bytes.avgcount: For
277    * some reason, Ceph schema encodes this as a count/sum pair while all
278    * other "Bytes" data (excluding used/capacity bytes for OSD space) uses
279    * a single "Derive" type. To spare further confusion, keep this KPI as
280    * the same type of other "Bytes". Instead of keeping an "average" or
281    * "rate", use the "sum" in the pair and assign that to the derive
282    * value. */
283   if (convert_special_metrics && (state->depth > 2) &&
284       state->stack[state->depth - 2] &&
285       (strcmp("filestore", state->stack[state->depth - 2]) == 0) &&
286       state->stack[state->depth - 1] &&
287       (strcmp("journal_wr_bytes", state->stack[state->depth - 1]) == 0) &&
288       (strcmp("avgcount", state->key) == 0)) {
289     DEBUG("ceph plugin: Skipping avgcount for filestore.JournalWrBytes");
290     return CEPH_CB_CONTINUE;
291   }
292
293   BUFFER_ADD(key, ".");
294   BUFFER_ADD(key, state->key);
295
296   status = state->handler(state->handler_arg, buffer, key);
297
298   if (status != 0) {
299     ERROR("ceph plugin: JSON handler failed with status %d.", status);
300     return CEPH_CB_ABORT;
301   }
302
303   return CEPH_CB_CONTINUE;
304 }
305
306 static int ceph_cb_string(void *ctx, const unsigned char *string_val,
307                           yajl_len_t string_len) {
308   return CEPH_CB_CONTINUE;
309 }
310
311 static int ceph_cb_start_map(void *ctx) {
312   yajl_struct *state = (yajl_struct *)ctx;
313
314   /* Push key to the stack */
315   if (state->depth == YAJL_MAX_DEPTH)
316     return CEPH_CB_ABORT;
317
318   state->stack[state->depth] = state->key;
319   state->depth++;
320   state->key = NULL;
321
322   return CEPH_CB_CONTINUE;
323 }
324
325 static int ceph_cb_end_map(void *ctx) {
326   yajl_struct *state = (yajl_struct *)ctx;
327
328   /* Pop key from the stack */
329   if (state->depth == 0)
330     return CEPH_CB_ABORT;
331
332   sfree(state->key);
333   state->depth--;
334   state->key = state->stack[state->depth];
335   state->stack[state->depth] = NULL;
336
337   return CEPH_CB_CONTINUE;
338 }
339
340 static int ceph_cb_map_key(void *ctx, const unsigned char *key,
341                            yajl_len_t string_len) {
342   yajl_struct *state = (yajl_struct *)ctx;
343   size_t sz = ((size_t)string_len) + 1;
344
345   sfree(state->key);
346   state->key = malloc(sz);
347   if (state->key == NULL) {
348     ERROR("ceph plugin: malloc failed.");
349     return CEPH_CB_ABORT;
350   }
351
352   memmove(state->key, key, sz - 1);
353   state->key[sz - 1] = '\0';
354
355   return CEPH_CB_CONTINUE;
356 }
357
358 static int ceph_cb_start_array(void *ctx) { return CEPH_CB_CONTINUE; }
359
360 static int ceph_cb_end_array(void *ctx) { return CEPH_CB_CONTINUE; }
361
362 static yajl_callbacks callbacks = {ceph_cb_null,
363                                    ceph_cb_boolean,
364                                    NULL,
365                                    NULL,
366                                    ceph_cb_number,
367                                    ceph_cb_string,
368                                    ceph_cb_start_map,
369                                    ceph_cb_map_key,
370                                    ceph_cb_end_map,
371                                    ceph_cb_start_array,
372                                    ceph_cb_end_array};
373
374 static void ceph_daemon_print(const struct ceph_daemon *d) {
375   DEBUG("ceph plugin: name=%s, asok_path=%s", d->name, d->asok_path);
376 }
377
378 static void ceph_daemons_print(void) {
379   for (size_t i = 0; i < g_num_daemons; ++i) {
380     ceph_daemon_print(g_daemons[i]);
381   }
382 }
383
384 static void ceph_daemon_free(struct ceph_daemon *d) {
385   for (int i = 0; i < d->last_idx; i++) {
386     sfree(d->last_poll_data[i]);
387   }
388   sfree(d->last_poll_data);
389   d->last_poll_data = NULL;
390   d->last_idx = 0;
391
392   for (int i = 0; i < d->ds_num; i++) {
393     sfree(d->ds_names[i]);
394   }
395   sfree(d->ds_types);
396   sfree(d->ds_names);
397   sfree(d);
398 }
399
400 /* compact_ds_name removed the special characters ":", "_", "-" and "+" from the
401  * input string. Characters following these special characters are capitalized.
402  * Trailing "+" and "-" characters are replaces with the strings "Plus" and
403  * "Minus". */
404 static int compact_ds_name(char *buffer, size_t buffer_size, char const *src) {
405   char *src_copy;
406   size_t src_len;
407   char *ptr = buffer;
408   size_t ptr_size = buffer_size;
409   bool append_plus = false;
410   bool append_minus = false;
411
412   if ((buffer == NULL) || (buffer_size <= strlen("Minus")) || (src == NULL))
413     return EINVAL;
414
415   src_copy = strdup(src);
416   src_len = strlen(src);
417
418   /* Remove trailing "+" and "-". */
419   if (src_copy[src_len - 1] == '+') {
420     append_plus = true;
421     src_len--;
422     src_copy[src_len] = 0;
423   } else if (src_copy[src_len - 1] == '-') {
424     append_minus = true;
425     src_len--;
426     src_copy[src_len] = 0;
427   }
428
429   /* Split at special chars, capitalize first character, append to buffer. */
430   char *dummy = src_copy;
431   char *token;
432   char *save_ptr = NULL;
433   while ((token = strtok_r(dummy, ":_-+", &save_ptr)) != NULL) {
434     size_t len;
435
436     dummy = NULL;
437
438     token[0] = toupper((int)token[0]);
439
440     assert(ptr_size > 1);
441
442     len = strlen(token);
443     if (len >= ptr_size)
444       len = ptr_size - 1;
445
446     assert(len > 0);
447     assert(len < ptr_size);
448
449     sstrncpy(ptr, token, len + 1);
450     ptr += len;
451     ptr_size -= len;
452
453     assert(*ptr == 0);
454     if (ptr_size <= 1)
455       break;
456   }
457
458   /* Append "Plus" or "Minus" if "+" or "-" has been stripped above. */
459   if (append_plus || append_minus) {
460     char const *append = "Plus";
461     if (append_minus)
462       append = "Minus";
463
464     size_t offset = buffer_size - (strlen(append) + 1);
465     if (offset > strlen(buffer))
466       offset = strlen(buffer);
467
468     sstrncpy(buffer + offset, append, buffer_size - offset);
469   }
470
471   sfree(src_copy);
472   return 0;
473 }
474
475 static bool has_suffix(char const *str, char const *suffix) {
476   size_t str_len = strlen(str);
477   size_t suffix_len = strlen(suffix);
478   size_t offset;
479
480   if (suffix_len > str_len)
481     return false;
482   offset = str_len - suffix_len;
483
484   if (strcmp(str + offset, suffix) == 0)
485     return true;
486
487   return false;
488 }
489
490 static void cut_suffix(char *buffer, size_t buffer_size, char const *str,
491                        char const *suffix) {
492
493   size_t str_len = strlen(str);
494   size_t suffix_len = strlen(suffix);
495
496   size_t offset = str_len - suffix_len + 1;
497
498   if (offset > buffer_size) {
499     offset = buffer_size;
500   }
501
502   sstrncpy(buffer, str, offset);
503 }
504
505 /* count_parts returns the number of elements a "foo.bar.baz" style key has. */
506 static size_t count_parts(char const *key) {
507   size_t parts_num = 0;
508
509   for (const char *ptr = key; ptr != NULL; ptr = strchr(ptr + 1, '.'))
510     parts_num++;
511
512   return parts_num;
513 }
514
515 /**
516  * Parse key to remove "type" if this is for schema and initiate compaction
517  */
518 static int parse_keys(char *buffer, size_t buffer_size, const char *key_str) {
519   char tmp[2 * buffer_size];
520   size_t tmp_size = sizeof(tmp);
521   const char *cut_suffixes[] = {".type", ".avgcount", ".sum", ".avgtime"};
522
523   if (buffer == NULL || buffer_size == 0 || key_str == NULL ||
524       strlen(key_str) == 0)
525     return EINVAL;
526
527   sstrncpy(tmp, key_str, tmp_size);
528
529   /* Strip suffix if it is ".type" or one of latency metric suffix. */
530   if (count_parts(key_str) > 2) {
531     for (size_t i = 0; i < STATIC_ARRAY_SIZE(cut_suffixes); i++) {
532       if (has_suffix(key_str, cut_suffixes[i])) {
533         cut_suffix(tmp, tmp_size, key_str, cut_suffixes[i]);
534         break;
535       }
536     }
537   }
538
539   return compact_ds_name(buffer, buffer_size, tmp);
540 }
541
542 /**
543  * while parsing ceph admin socket schema, save counter name and type for later
544  * data processing
545  */
546 static int ceph_daemon_add_ds_entry(struct ceph_daemon *d, const char *name,
547                                     int pc_type) {
548   uint32_t type;
549   char ds_name[DATA_MAX_NAME_LEN];
550
551   if (convert_special_metrics) {
552     /**
553      * Special case for filestore:JournalWrBytes. For some reason, Ceph
554      * schema encodes this as a count/sum pair while all other "Bytes" data
555      * (excluding used/capacity bytes for OSD space) uses a single "Derive"
556      * type. To spare further confusion, keep this KPI as the same type of
557      * other "Bytes". Instead of keeping an "average" or "rate", use the
558      * "sum" in the pair and assign that to the derive value.
559      */
560     if ((strcmp(name, "filestore.journal_wr_bytes.type") == 0)) {
561       pc_type = 10;
562     }
563   }
564
565   d->ds_names = realloc(d->ds_names, sizeof(char *) * (d->ds_num + 1));
566   if (!d->ds_names) {
567     return -ENOMEM;
568   }
569
570   d->ds_types = realloc(d->ds_types, sizeof(uint32_t) * (d->ds_num + 1));
571   if (!d->ds_types) {
572     return -ENOMEM;
573   }
574
575   d->ds_names[d->ds_num] = malloc(DATA_MAX_NAME_LEN);
576   if (!d->ds_names[d->ds_num]) {
577     return -ENOMEM;
578   }
579
580   type = (pc_type & PERFCOUNTER_DERIVE)
581              ? DSET_RATE
582              : ((pc_type & PERFCOUNTER_LATENCY) ? DSET_LATENCY : DSET_BYTES);
583   d->ds_types[d->ds_num] = type;
584
585   if (parse_keys(ds_name, sizeof(ds_name), name)) {
586     return 1;
587   }
588
589   sstrncpy(d->ds_names[d->ds_num], ds_name, DATA_MAX_NAME_LEN - 1);
590   d->ds_num = (d->ds_num + 1);
591
592   return 0;
593 }
594
595 /******* ceph_config *******/
596 static int cc_handle_str(struct oconfig_item_s *item, char *dest,
597                          int dest_len) {
598   const char *val;
599   if (item->values_num != 1) {
600     return -ENOTSUP;
601   }
602   if (item->values[0].type != OCONFIG_TYPE_STRING) {
603     return -ENOTSUP;
604   }
605   val = item->values[0].value.string;
606   if (snprintf(dest, dest_len, "%s", val) > (dest_len - 1)) {
607     ERROR("ceph plugin: configuration parameter '%s' is too long.\n",
608           item->key);
609     return -ENAMETOOLONG;
610   }
611   return 0;
612 }
613
614 static int cc_handle_bool(struct oconfig_item_s *item, int *dest) {
615   if (item->values_num != 1) {
616     return -ENOTSUP;
617   }
618
619   if (item->values[0].type != OCONFIG_TYPE_BOOLEAN) {
620     return -ENOTSUP;
621   }
622
623   *dest = (item->values[0].value.boolean) ? 1 : 0;
624   return 0;
625 }
626
627 static int cc_add_daemon_config(oconfig_item_t *ci) {
628   int ret;
629   struct ceph_daemon *nd, cd = {0};
630   struct ceph_daemon **tmp;
631
632   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
633     WARNING("ceph plugin: `Daemon' blocks need exactly one string "
634             "argument.");
635     return -1;
636   }
637
638   ret = cc_handle_str(ci, cd.name, DATA_MAX_NAME_LEN);
639   if (ret) {
640     return ret;
641   }
642
643   for (int i = 0; i < ci->children_num; i++) {
644     oconfig_item_t *child = ci->children + i;
645
646     if (strcasecmp("SocketPath", child->key) == 0) {
647       ret = cc_handle_str(child, cd.asok_path, sizeof(cd.asok_path));
648       if (ret) {
649         return ret;
650       }
651     } else {
652       WARNING("ceph plugin: ignoring unknown option %s", child->key);
653     }
654   }
655   if (cd.name[0] == '\0') {
656     ERROR("ceph plugin: you must configure a daemon name.\n");
657     return -EINVAL;
658   } else if (cd.asok_path[0] == '\0') {
659     ERROR("ceph plugin(name=%s): you must configure an administrative "
660           "socket path.\n",
661           cd.name);
662     return -EINVAL;
663   } else if (!((cd.asok_path[0] == '/') ||
664                (cd.asok_path[0] == '.' && cd.asok_path[1] == '/'))) {
665     ERROR("ceph plugin(name=%s): administrative socket paths must begin "
666           "with '/' or './' Can't parse: '%s'\n",
667           cd.name, cd.asok_path);
668     return -EINVAL;
669   }
670
671   tmp = realloc(g_daemons, (g_num_daemons + 1) * sizeof(*g_daemons));
672   if (tmp == NULL) {
673     /* The positive return value here indicates that this is a
674      * runtime error, not a configuration error.  */
675     return ENOMEM;
676   }
677   g_daemons = tmp;
678
679   nd = malloc(sizeof(*nd));
680   if (!nd) {
681     return ENOMEM;
682   }
683   memcpy(nd, &cd, sizeof(*nd));
684   g_daemons[g_num_daemons] = nd;
685   g_num_daemons++;
686   return 0;
687 }
688
689 static int ceph_config(oconfig_item_t *ci) {
690   int ret;
691
692   for (int i = 0; i < ci->children_num; ++i) {
693     oconfig_item_t *child = ci->children + i;
694     if (strcasecmp("Daemon", child->key) == 0) {
695       ret = cc_add_daemon_config(child);
696       if (ret == ENOMEM) {
697         ERROR("ceph plugin: Couldn't allocate memory");
698         return ret;
699       } else if (ret) {
700         // process other daemons and ignore this one
701         continue;
702       }
703     } else if (strcasecmp("LongRunAvgLatency", child->key) == 0) {
704       ret = cc_handle_bool(child, &long_run_latency_avg);
705       if (ret) {
706         return ret;
707       }
708     } else if (strcasecmp("ConvertSpecialMetricTypes", child->key) == 0) {
709       ret = cc_handle_bool(child, &convert_special_metrics);
710       if (ret) {
711         return ret;
712       }
713     } else {
714       WARNING("ceph plugin: ignoring unknown option %s", child->key);
715     }
716   }
717   return 0;
718 }
719
720 /**
721  * Parse JSON and get error message if present
722  */
723 static int traverse_json(const unsigned char *json, uint32_t json_len,
724                          yajl_handle hand) {
725   yajl_status status = yajl_parse(hand, json, json_len);
726   unsigned char *msg;
727
728   switch (status) {
729   case yajl_status_error:
730     msg = yajl_get_error(hand, /* verbose = */ 1,
731                          /* jsonText = */ (unsigned char *)json,
732                          (unsigned int)json_len);
733     ERROR("ceph plugin: yajl_parse failed: %s", msg);
734     yajl_free_error(hand, msg);
735     return 1;
736   case yajl_status_client_canceled:
737     return 1;
738   default:
739     return 0;
740   }
741 }
742
743 /**
744  * Add entry for each counter while parsing schema
745  */
746 static int node_handler_define_schema(void *arg, const char *val,
747                                       const char *key) {
748   struct ceph_daemon *d = (struct ceph_daemon *)arg;
749   int pc_type;
750   pc_type = atoi(val);
751   return ceph_daemon_add_ds_entry(d, key, pc_type);
752 }
753
754 /**
755  * Latency counter does not yet have an entry in last poll data - add it.
756  */
757 static int add_last(struct ceph_daemon *d, const char *ds_n, double cur_sum,
758                     uint64_t cur_count) {
759   d->last_poll_data[d->last_idx] =
760       malloc(sizeof(*d->last_poll_data[d->last_idx]));
761   if (!d->last_poll_data[d->last_idx]) {
762     return -ENOMEM;
763   }
764   sstrncpy(d->last_poll_data[d->last_idx]->ds_name, ds_n,
765            sizeof(d->last_poll_data[d->last_idx]->ds_name));
766   d->last_poll_data[d->last_idx]->last_sum = cur_sum;
767   d->last_poll_data[d->last_idx]->last_count = cur_count;
768   d->last_idx = (d->last_idx + 1);
769   return 0;
770 }
771
772 /**
773  * Update latency counter or add new entry if it doesn't exist
774  */
775 static int update_last(struct ceph_daemon *d, const char *ds_n, int index,
776                        double cur_sum, uint64_t cur_count) {
777   if ((d->last_idx > index) &&
778       (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0)) {
779     d->last_poll_data[index]->last_sum = cur_sum;
780     d->last_poll_data[index]->last_count = cur_count;
781     return 0;
782   }
783
784   if (!d->last_poll_data) {
785     d->last_poll_data = malloc(sizeof(*d->last_poll_data));
786     if (!d->last_poll_data) {
787       return -ENOMEM;
788     }
789   } else {
790     struct last_data **tmp_last = realloc(
791         d->last_poll_data, ((d->last_idx + 1) * sizeof(struct last_data *)));
792     if (!tmp_last) {
793       return -ENOMEM;
794     }
795     d->last_poll_data = tmp_last;
796   }
797   return add_last(d, ds_n, cur_sum, cur_count);
798 }
799
800 /**
801  * If using index guess failed (shouldn't happen, but possible if counters
802  * get rearranged), resort to searching for counter name
803  */
804 static int backup_search_for_last_avg(struct ceph_daemon *d, const char *ds_n) {
805   for (int i = 0; i < d->last_idx; i++) {
806     if (strcmp(d->last_poll_data[i]->ds_name, ds_n) == 0) {
807       return i;
808     }
809   }
810   return -1;
811 }
812
813 /**
814  * Calculate average b/t current data and last poll data
815  * if last poll data exists
816  */
817 static double get_last_avg(struct ceph_daemon *d, const char *ds_n, int index,
818                            double cur_sum, uint64_t cur_count) {
819   double result = -1.1, sum_delt = 0.0;
820   uint64_t count_delt = 0;
821   int tmp_index = 0;
822   if (d->last_idx > index) {
823     if (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0) {
824       tmp_index = index;
825     }
826     // test previous index
827     else if ((index > 0) &&
828              (strcmp(d->last_poll_data[index - 1]->ds_name, ds_n) == 0)) {
829       tmp_index = (index - 1);
830     } else {
831       tmp_index = backup_search_for_last_avg(d, ds_n);
832     }
833
834     if ((tmp_index > -1) &&
835         (cur_count > d->last_poll_data[tmp_index]->last_count)) {
836       sum_delt = (cur_sum - d->last_poll_data[tmp_index]->last_sum);
837       count_delt = (cur_count - d->last_poll_data[tmp_index]->last_count);
838       result = (sum_delt / count_delt);
839     }
840   }
841
842   if (result == -1.1) {
843     result = NAN;
844   }
845   if (update_last(d, ds_n, tmp_index, cur_sum, cur_count) == -ENOMEM) {
846     return -ENOMEM;
847   }
848   return result;
849 }
850
851 /**
852  * If using index guess failed, resort to searching for counter name
853  */
854 static uint32_t backup_search_for_type(struct ceph_daemon *d, char *ds_name) {
855   for (int i = 0; i < d->ds_num; i++) {
856     if (strcmp(d->ds_names[i], ds_name) == 0) {
857       return d->ds_types[i];
858     }
859   }
860   return DSET_TYPE_UNFOUND;
861 }
862
863 /**
864  * Process counter data and dispatch values
865  */
866 static int node_handler_fetch_data(void *arg, const char *val,
867                                    const char *key) {
868   value_t uv;
869   double tmp_d;
870   uint64_t tmp_u;
871   struct values_tmp *vtmp = (struct values_tmp *)arg;
872   uint32_t type = DSET_TYPE_UNFOUND;
873   int index = vtmp->index;
874
875   char ds_name[DATA_MAX_NAME_LEN];
876
877   if (parse_keys(ds_name, sizeof(ds_name), key)) {
878     return 1;
879   }
880
881   if (index >= vtmp->d->ds_num) {
882     // don't overflow bounds of array
883     index = (vtmp->d->ds_num - 1);
884   }
885
886   /**
887    * counters should remain in same order we parsed schema... we maintain the
888    * index variable to keep track of current point in list of counters. first
889    * use index to guess point in array for retrieving type. if that doesn't
890    * work, use the old way to get the counter type
891    */
892   if (strcmp(ds_name, vtmp->d->ds_names[index]) == 0) {
893     // found match
894     type = vtmp->d->ds_types[index];
895   } else if ((index > 0) &&
896              (strcmp(ds_name, vtmp->d->ds_names[index - 1]) == 0)) {
897     // try previous key
898     type = vtmp->d->ds_types[index - 1];
899   }
900
901   if (type == DSET_TYPE_UNFOUND) {
902     // couldn't find right type by guessing, check the old way
903     type = backup_search_for_type(vtmp->d, ds_name);
904   }
905
906   switch (type) {
907   case DSET_LATENCY:
908     if (has_suffix(key, ".avgcount")) {
909       sscanf(val, "%" PRIu64, &vtmp->avgcount);
910       // return after saving avgcount - don't dispatch value
911       // until latency calculation
912       return 0;
913     } else if (has_suffix(key, ".sum")) {
914       if (vtmp->avgcount == 0) {
915         vtmp->avgcount = 1;
916       }
917       // user wants latency values as long run avg
918       // skip this step
919       if (long_run_latency_avg) {
920         return 0;
921       }
922       double sum, result;
923       sscanf(val, "%lf", &sum);
924       result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum,
925                             vtmp->avgcount);
926       if (result == -ENOMEM) {
927         return -ENOMEM;
928       }
929       uv.gauge = result;
930       vtmp->latency_index = (vtmp->latency_index + 1);
931     } else if (has_suffix(key, ".avgtime")) {
932
933       /* The "avgtime" metric reports ("sum" / "avgcount"), i.e. the average
934        * time per request since the start of the Ceph daemon. Report this only
935        * when the user has configured "long running average". Otherwise, use the
936        * rate of "sum" and "avgcount" to calculate the current latency.
937        */
938
939       if (!long_run_latency_avg) {
940         return 0;
941       }
942       double result;
943       sscanf(val, "%lf", &result);
944       uv.gauge = result;
945       vtmp->latency_index = (vtmp->latency_index + 1);
946     } else {
947       WARNING("ceph plugin: ignoring unknown latency metric: %s", key);
948       return 0;
949     }
950     break;
951   case DSET_BYTES:
952     sscanf(val, "%lf", &tmp_d);
953     uv.gauge = tmp_d;
954     break;
955   case DSET_RATE:
956     sscanf(val, "%" PRIu64, &tmp_u);
957     uv.derive = tmp_u;
958     break;
959   case DSET_TYPE_UNFOUND:
960   default:
961     ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);
962     return -1;
963   }
964
965   sstrncpy(vtmp->vlist.type, ceph_dset_types[type], sizeof(vtmp->vlist.type));
966   sstrncpy(vtmp->vlist.type_instance, ds_name,
967            sizeof(vtmp->vlist.type_instance));
968   vtmp->vlist.values = &uv;
969   vtmp->vlist.values_len = 1;
970
971   vtmp->index = (vtmp->index + 1);
972   plugin_dispatch_values(&vtmp->vlist);
973
974   return 0;
975 }
976
977 static int cconn_connect(struct cconn *io) {
978   struct sockaddr_un address = {0};
979   int flags, fd, err;
980   if (io->state != CSTATE_UNCONNECTED) {
981     ERROR("ceph plugin: cconn_connect: io->state != CSTATE_UNCONNECTED");
982     return -EDOM;
983   }
984   fd = socket(PF_UNIX, SOCK_STREAM, 0);
985   if (fd < 0) {
986     err = -errno;
987     ERROR("ceph plugin: cconn_connect: socket(PF_UNIX, SOCK_STREAM, 0) "
988           "failed: error %d",
989           err);
990     return err;
991   }
992   address.sun_family = AF_UNIX;
993   ssnprintf(address.sun_path, sizeof(address.sun_path), "%s", io->d->asok_path);
994   RETRY_ON_EINTR(err, connect(fd, (struct sockaddr *)&address,
995                               sizeof(struct sockaddr_un)));
996   if (err < 0) {
997     ERROR("ceph plugin: cconn_connect: connect(%d) failed: error %d", fd, err);
998     close(fd);
999     return err;
1000   }
1001
1002   flags = fcntl(fd, F_GETFL, 0);
1003   if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
1004     err = -errno;
1005     ERROR("ceph plugin: cconn_connect: fcntl(%d, O_NONBLOCK) error %d", fd,
1006           err);
1007     close(fd);
1008     return err;
1009   }
1010   io->asok = fd;
1011   io->state = CSTATE_WRITE_REQUEST;
1012   io->amt = 0;
1013   io->json_len = 0;
1014   io->json = NULL;
1015   return 0;
1016 }
1017
1018 static void cconn_close(struct cconn *io) {
1019   io->state = CSTATE_UNCONNECTED;
1020   if (io->asok != -1) {
1021     int res;
1022     RETRY_ON_EINTR(res, close(io->asok));
1023   }
1024   io->asok = -1;
1025   io->amt = 0;
1026   io->json_len = 0;
1027   sfree(io->json);
1028   io->json = NULL;
1029 }
1030
1031 /* Process incoming JSON counter data */
1032 static int cconn_process_data(struct cconn *io, yajl_struct *yajl,
1033                               yajl_handle hand) {
1034   int ret;
1035   struct values_tmp *vtmp = calloc(1, sizeof(*vtmp));
1036   if (!vtmp) {
1037     return -ENOMEM;
1038   }
1039
1040   vtmp->vlist = (value_list_t)VALUE_LIST_INIT;
1041   sstrncpy(vtmp->vlist.plugin, "ceph", sizeof(vtmp->vlist.plugin));
1042   sstrncpy(vtmp->vlist.plugin_instance, io->d->name,
1043            sizeof(vtmp->vlist.plugin_instance));
1044
1045   vtmp->d = io->d;
1046   vtmp->latency_index = 0;
1047   vtmp->index = 0;
1048   yajl->handler_arg = vtmp;
1049   ret = traverse_json(io->json, io->json_len, hand);
1050   sfree(vtmp);
1051   return ret;
1052 }
1053
1054 /**
1055  * Initiate JSON parsing and print error if one occurs
1056  */
1057 static int cconn_process_json(struct cconn *io) {
1058   if ((io->request_type != ASOK_REQ_DATA) &&
1059       (io->request_type != ASOK_REQ_SCHEMA)) {
1060     return -EDOM;
1061   }
1062
1063   int result = 1;
1064   yajl_handle hand;
1065   yajl_status status;
1066
1067   hand = yajl_alloc(&callbacks,
1068 #if HAVE_YAJL_V2
1069                     /* alloc funcs = */ NULL,
1070 #else
1071                     /* alloc funcs = */ NULL, NULL,
1072 #endif
1073                     /* context = */ (void *)(&io->yajl));
1074
1075   if (!hand) {
1076     ERROR("ceph plugin: yajl_alloc failed.");
1077     return ENOMEM;
1078   }
1079
1080   io->yajl.depth = 0;
1081
1082   switch (io->request_type) {
1083   case ASOK_REQ_DATA:
1084     io->yajl.handler = node_handler_fetch_data;
1085     result = cconn_process_data(io, &io->yajl, hand);
1086     break;
1087   case ASOK_REQ_SCHEMA:
1088     // init daemon specific variables
1089     io->d->ds_num = 0;
1090     io->d->last_idx = 0;
1091     io->d->last_poll_data = NULL;
1092     io->yajl.handler = node_handler_define_schema;
1093     io->yajl.handler_arg = io->d;
1094     result = traverse_json(io->json, io->json_len, hand);
1095     break;
1096   }
1097
1098   if (result) {
1099     goto done;
1100   }
1101
1102 #if HAVE_YAJL_V2
1103   status = yajl_complete_parse(hand);
1104 #else
1105   status = yajl_parse_complete(hand);
1106 #endif
1107
1108   if (status != yajl_status_ok) {
1109     unsigned char *errmsg =
1110         yajl_get_error(hand, /* verbose = */ 0,
1111                        /* jsonText = */ NULL, /* jsonTextLen = */ 0);
1112     ERROR("ceph plugin: yajl_parse_complete failed: %s", (char *)errmsg);
1113     yajl_free_error(hand, errmsg);
1114     yajl_free(hand);
1115     return 1;
1116   }
1117
1118 done:
1119   yajl_free(hand);
1120   return result;
1121 }
1122
1123 static int cconn_validate_revents(struct cconn *io, int revents) {
1124   if (revents & POLLERR) {
1125     ERROR("ceph plugin: cconn_validate_revents(name=%s): got POLLERR",
1126           io->d->name);
1127     return -EIO;
1128   }
1129   switch (io->state) {
1130   case CSTATE_WRITE_REQUEST:
1131     return (revents & POLLOUT) ? 0 : -EINVAL;
1132   case CSTATE_READ_VERSION:
1133   case CSTATE_READ_AMT:
1134   case CSTATE_READ_JSON:
1135     return (revents & POLLIN) ? 0 : -EINVAL;
1136   default:
1137     ERROR("ceph plugin: cconn_validate_revents(name=%s) got to "
1138           "illegal state on line %d",
1139           io->d->name, __LINE__);
1140     return -EDOM;
1141   }
1142 }
1143
1144 /** Handle a network event for a connection */
1145 static ssize_t cconn_handle_event(struct cconn *io) {
1146   ssize_t ret;
1147   switch (io->state) {
1148   case CSTATE_UNCONNECTED:
1149     ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1150           "state on line %d",
1151           io->d->name, __LINE__);
1152
1153     return -EDOM;
1154   case CSTATE_WRITE_REQUEST: {
1155     char cmd[32];
1156     ssnprintf(cmd, sizeof(cmd), "%s%d%s", "{ \"prefix\": \"", io->request_type,
1157               "\" }\n");
1158     size_t cmd_len = strlen(cmd);
1159     RETRY_ON_EINTR(
1160         ret, write(io->asok, ((char *)&cmd) + io->amt, cmd_len - io->amt));
1161     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,amt=%d,ret=%zd)",
1162           io->d->name, io->state, io->amt, ret);
1163     if (ret < 0) {
1164       return ret;
1165     }
1166     io->amt += ret;
1167     if (io->amt >= cmd_len) {
1168       io->amt = 0;
1169       switch (io->request_type) {
1170       case ASOK_REQ_VERSION:
1171         io->state = CSTATE_READ_VERSION;
1172         break;
1173       default:
1174         io->state = CSTATE_READ_AMT;
1175         break;
1176       }
1177     }
1178     return 0;
1179   }
1180   case CSTATE_READ_VERSION: {
1181     RETRY_ON_EINTR(ret, read(io->asok, ((char *)(&io->d->version)) + io->amt,
1182                              sizeof(io->d->version) - io->amt));
1183     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%zd)",
1184           io->d->name, io->state, ret);
1185     if (ret < 0) {
1186       return ret;
1187     }
1188     io->amt += ret;
1189     if (io->amt >= sizeof(io->d->version)) {
1190       io->d->version = ntohl(io->d->version);
1191       if (io->d->version != 1) {
1192         ERROR("ceph plugin: cconn_handle_event(name=%s) not "
1193               "expecting version %d!",
1194               io->d->name, io->d->version);
1195         return -ENOTSUP;
1196       }
1197       DEBUG("ceph plugin: cconn_handle_event(name=%s): identified as "
1198             "version %d",
1199             io->d->name, io->d->version);
1200       io->amt = 0;
1201       cconn_close(io);
1202       io->request_type = ASOK_REQ_SCHEMA;
1203     }
1204     return 0;
1205   }
1206   case CSTATE_READ_AMT: {
1207     RETRY_ON_EINTR(ret, read(io->asok, ((char *)(&io->json_len)) + io->amt,
1208                              sizeof(io->json_len) - io->amt));
1209     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%zd)",
1210           io->d->name, io->state, ret);
1211     if (ret < 0) {
1212       return ret;
1213     }
1214     io->amt += ret;
1215     if (io->amt >= sizeof(io->json_len)) {
1216       io->json_len = ntohl(io->json_len);
1217       io->amt = 0;
1218       io->state = CSTATE_READ_JSON;
1219       io->json = calloc(1, io->json_len + 1);
1220       if (!io->json) {
1221         ERROR("ceph plugin: error callocing io->json");
1222         return -ENOMEM;
1223       }
1224     }
1225     return 0;
1226   }
1227   case CSTATE_READ_JSON: {
1228     RETRY_ON_EINTR(ret,
1229                    read(io->asok, io->json + io->amt, io->json_len - io->amt));
1230     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%zd)",
1231           io->d->name, io->state, ret);
1232     if (ret < 0) {
1233       return ret;
1234     }
1235     io->amt += ret;
1236     if (io->amt >= io->json_len) {
1237       ret = cconn_process_json(io);
1238       if (ret) {
1239         return ret;
1240       }
1241       cconn_close(io);
1242       io->request_type = ASOK_REQ_NONE;
1243     }
1244     return 0;
1245   }
1246   default:
1247     ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1248           "state on line %d",
1249           io->d->name, __LINE__);
1250     return -EDOM;
1251   }
1252 }
1253
1254 static int cconn_prepare(struct cconn *io, struct pollfd *fds) {
1255   int ret;
1256   if (io->request_type == ASOK_REQ_NONE) {
1257     /* The request has already been serviced. */
1258     return 0;
1259   } else if ((io->request_type == ASOK_REQ_DATA) && (io->d->ds_num == 0)) {
1260     /* If there are no counters to report on, don't bother
1261      * connecting */
1262     return 0;
1263   }
1264
1265   switch (io->state) {
1266   case CSTATE_UNCONNECTED:
1267     ret = cconn_connect(io);
1268     if (ret > 0) {
1269       return -ret;
1270     } else if (ret < 0) {
1271       return ret;
1272     }
1273     fds->fd = io->asok;
1274     fds->events = POLLOUT;
1275     return 1;
1276   case CSTATE_WRITE_REQUEST:
1277     fds->fd = io->asok;
1278     fds->events = POLLOUT;
1279     return 1;
1280   case CSTATE_READ_VERSION:
1281   case CSTATE_READ_AMT:
1282   case CSTATE_READ_JSON:
1283     fds->fd = io->asok;
1284     fds->events = POLLIN;
1285     return 1;
1286   default:
1287     ERROR("ceph plugin: cconn_prepare(name=%s) got to illegal state "
1288           "on line %d",
1289           io->d->name, __LINE__);
1290     return -EDOM;
1291   }
1292 }
1293
1294 /** Returns the difference between two struct timevals in milliseconds.
1295  * On overflow, we return max/min int.
1296  */
1297 static int milli_diff(const struct timeval *t1, const struct timeval *t2) {
1298   int64_t ret;
1299   long sec_diff = t1->tv_sec - t2->tv_sec;
1300   long usec_diff = t1->tv_usec - t2->tv_usec;
1301   ret = usec_diff / 1000;
1302   ret += (sec_diff * 1000);
1303   return (ret > INT_MAX) ? INT_MAX : ((ret < INT_MIN) ? INT_MIN : (int)ret);
1304 }
1305
1306 /** This handles the actual network I/O to talk to the Ceph daemons.
1307  */
1308 static ssize_t cconn_main_loop(uint32_t request_type) {
1309   int some_unreachable = 0;
1310   ssize_t ret;
1311   struct timeval end_tv;
1312   struct cconn io_array[g_num_daemons];
1313
1314   DEBUG("ceph plugin: entering cconn_main_loop(request_type = %" PRIu32 ")",
1315         request_type);
1316
1317   if (g_num_daemons < 1) {
1318     ERROR("ceph plugin: No daemons configured. See the \"Daemon\" config "
1319           "option.");
1320     return ENOENT;
1321   }
1322
1323   /* create cconn array */
1324   for (size_t i = 0; i < g_num_daemons; i++) {
1325     io_array[i] = (struct cconn){
1326         .d = g_daemons[i],
1327         .request_type = request_type,
1328         .state = CSTATE_UNCONNECTED,
1329     };
1330   }
1331
1332   /** Calculate the time at which we should give up */
1333   gettimeofday(&end_tv, NULL);
1334   end_tv.tv_sec += CEPH_TIMEOUT_INTERVAL;
1335
1336   while (1) {
1337     int nfds, diff;
1338     struct timeval tv;
1339     struct cconn *polled_io_array[g_num_daemons];
1340     struct pollfd fds[g_num_daemons];
1341     memset(fds, 0, sizeof(fds));
1342     nfds = 0;
1343     for (size_t i = 0; i < g_num_daemons; ++i) {
1344       struct cconn *io = io_array + i;
1345       ret = cconn_prepare(io, fds + nfds);
1346       if (ret < 0) {
1347         WARNING("ceph plugin: cconn_prepare(name=%s,i=%" PRIsz ",st=%d)=%zd",
1348                 io->d->name, i, io->state, ret);
1349         cconn_close(io);
1350         io->request_type = ASOK_REQ_NONE;
1351         some_unreachable = 1;
1352       } else if (ret == 1) {
1353         polled_io_array[nfds++] = io_array + i;
1354       }
1355     }
1356     if (nfds == 0) {
1357       /* finished */
1358       ret = 0;
1359       goto done;
1360     }
1361     gettimeofday(&tv, NULL);
1362     diff = milli_diff(&end_tv, &tv);
1363     if (diff <= 0) {
1364       /* Timed out */
1365       ret = -ETIMEDOUT;
1366       WARNING("ceph plugin: cconn_main_loop: timed out.");
1367       goto done;
1368     }
1369     RETRY_ON_EINTR(ret, poll(fds, nfds, diff));
1370     if (ret < 0) {
1371       ERROR("ceph plugin: poll(2) error: %zd", ret);
1372       goto done;
1373     }
1374     for (int i = 0; i < nfds; ++i) {
1375       struct cconn *io = polled_io_array[i];
1376       int revents = fds[i].revents;
1377       if (revents == 0) {
1378         /* do nothing */
1379         continue;
1380       } else if (cconn_validate_revents(io, revents)) {
1381         WARNING("ceph plugin: cconn(name=%s,i=%d,st=%d): "
1382                 "revents validation error: "
1383                 "revents=0x%08x",
1384                 io->d->name, i, io->state, revents);
1385         cconn_close(io);
1386         io->request_type = ASOK_REQ_NONE;
1387         some_unreachable = 1;
1388       } else {
1389         ret = cconn_handle_event(io);
1390         if (ret) {
1391           WARNING("ceph plugin: cconn_handle_event(name=%s,"
1392                   "i=%d,st=%d): error %zd",
1393                   io->d->name, i, io->state, ret);
1394           cconn_close(io);
1395           io->request_type = ASOK_REQ_NONE;
1396           some_unreachable = 1;
1397         }
1398       }
1399     }
1400   }
1401 done:
1402   for (size_t i = 0; i < g_num_daemons; ++i) {
1403     cconn_close(io_array + i);
1404   }
1405   if (some_unreachable) {
1406     DEBUG("ceph plugin: cconn_main_loop: some Ceph daemons were unreachable.");
1407   } else {
1408     DEBUG("ceph plugin: cconn_main_loop: reached all Ceph daemons :)");
1409   }
1410   return ret;
1411 }
1412
1413 static int ceph_read(void) { return (int)cconn_main_loop(ASOK_REQ_DATA); }
1414
1415 /******* lifecycle *******/
1416 static int ceph_init(void) {
1417 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_DAC_OVERRIDE)
1418   if (check_capability(CAP_DAC_OVERRIDE) != 0) {
1419     if (getuid() == 0)
1420       WARNING("ceph plugin: Running collectd as root, but the "
1421               "CAP_DAC_OVERRIDE capability is missing. The plugin's read "
1422               "function will probably fail. Is your init system dropping "
1423               "capabilities?");
1424     else
1425       WARNING(
1426           "ceph plugin: collectd doesn't have the CAP_DAC_OVERRIDE "
1427           "capability. If you don't want to run collectd as root, try running "
1428           "\"setcap cap_dac_override=ep\" on the collectd binary.");
1429   }
1430 #endif
1431
1432   ceph_daemons_print();
1433
1434   if (g_num_daemons < 1) {
1435     ERROR("ceph plugin: No daemons configured. See the \"Daemon\" config "
1436           "option.");
1437     return ENOENT;
1438   }
1439
1440   return (int)cconn_main_loop(ASOK_REQ_VERSION);
1441 }
1442
1443 static int ceph_shutdown(void) {
1444   for (size_t i = 0; i < g_num_daemons; ++i) {
1445     ceph_daemon_free(g_daemons[i]);
1446   }
1447   sfree(g_daemons);
1448   g_daemons = NULL;
1449   g_num_daemons = 0;
1450   DEBUG("ceph plugin: finished ceph_shutdown");
1451   return 0;
1452 }
1453
1454 void module_register(void) {
1455   plugin_register_complex_config("ceph", ceph_config);
1456   plugin_register_init("ceph", ceph_init);
1457   plugin_register_read("ceph", ceph_read);
1458   plugin_register_shutdown("ceph", ceph_shutdown);
1459 }