ceph plugin: Make cut_suffix void, change var names
[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 "common.h"
32 #include "plugin.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 = 0;
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 = NULL;
165
166 /** Number of elements in g_daemons */
167 static size_t g_num_daemons = 0;
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       (strcmp("filestore", state->stack[state->depth - 2]) == 0) &&
285       (strcmp("journal_wr_bytes", state->stack[state->depth - 1]) == 0) &&
286       (strcmp("avgcount", state->key) == 0)) {
287     DEBUG("ceph plugin: Skipping avgcount for filestore.JournalWrBytes");
288     return CEPH_CB_CONTINUE;
289   }
290
291   BUFFER_ADD(key, ".");
292   BUFFER_ADD(key, state->key);
293
294   status = state->handler(state->handler_arg, buffer, key);
295
296   if (status != 0) {
297     ERROR("ceph plugin: JSON handler failed with status %d.", status);
298     return CEPH_CB_ABORT;
299   }
300
301   return CEPH_CB_CONTINUE;
302 }
303
304 static int ceph_cb_string(void *ctx, const unsigned char *string_val,
305                           yajl_len_t string_len) {
306   return CEPH_CB_CONTINUE;
307 }
308
309 static int ceph_cb_start_map(void *ctx) {
310   yajl_struct *state = (yajl_struct *)ctx;
311
312   /* Push key to the stack */
313   if (state->depth == YAJL_MAX_DEPTH)
314     return CEPH_CB_ABORT;
315
316   state->stack[state->depth] = state->key;
317   state->depth++;
318   state->key = NULL;
319
320   return CEPH_CB_CONTINUE;
321 }
322
323 static int ceph_cb_end_map(void *ctx) {
324   yajl_struct *state = (yajl_struct *)ctx;
325
326   /* Pop key from the stack */
327   if (state->depth == 0)
328     return CEPH_CB_ABORT;
329
330   sfree(state->key);
331   state->depth--;
332   state->key = state->stack[state->depth];
333   state->stack[state->depth] = NULL;
334
335   return CEPH_CB_CONTINUE;
336 }
337
338 static int ceph_cb_map_key(void *ctx, const unsigned char *key,
339                            yajl_len_t string_len) {
340   yajl_struct *state = (yajl_struct *)ctx;
341   size_t sz = ((size_t)string_len) + 1;
342
343   sfree(state->key);
344   state->key = malloc(sz);
345   if (state->key == NULL) {
346     ERROR("ceph plugin: malloc failed.");
347     return CEPH_CB_ABORT;
348   }
349
350   memmove(state->key, key, sz - 1);
351   state->key[sz - 1] = 0;
352
353   return CEPH_CB_CONTINUE;
354 }
355
356 static int ceph_cb_start_array(void *ctx) { return CEPH_CB_CONTINUE; }
357
358 static int ceph_cb_end_array(void *ctx) { return CEPH_CB_CONTINUE; }
359
360 static yajl_callbacks callbacks = {ceph_cb_null,
361                                    ceph_cb_boolean,
362                                    NULL,
363                                    NULL,
364                                    ceph_cb_number,
365                                    ceph_cb_string,
366                                    ceph_cb_start_map,
367                                    ceph_cb_map_key,
368                                    ceph_cb_end_map,
369                                    ceph_cb_start_array,
370                                    ceph_cb_end_array};
371
372 static void ceph_daemon_print(const struct ceph_daemon *d) {
373   DEBUG("ceph plugin: name=%s, asok_path=%s", d->name, d->asok_path);
374 }
375
376 static void ceph_daemons_print(void) {
377   for (size_t i = 0; i < g_num_daemons; ++i) {
378     ceph_daemon_print(g_daemons[i]);
379   }
380 }
381
382 static void ceph_daemon_free(struct ceph_daemon *d) {
383   for (int i = 0; i < d->last_idx; i++) {
384     sfree(d->last_poll_data[i]);
385   }
386   sfree(d->last_poll_data);
387   d->last_poll_data = NULL;
388   d->last_idx = 0;
389
390   for (int i = 0; i < d->ds_num; i++) {
391     sfree(d->ds_names[i]);
392   }
393   sfree(d->ds_types);
394   sfree(d->ds_names);
395   sfree(d);
396 }
397
398 /* compact_ds_name removed the special characters ":", "_", "-" and "+" from the
399  * intput string. Characters following these special characters are capitalized.
400  * Trailing "+" and "-" characters are replaces with the strings "Plus" and
401  * "Minus". */
402 static int compact_ds_name(char *buffer, size_t buffer_size, char const *src) {
403   char *src_copy;
404   size_t src_len;
405   char *ptr = buffer;
406   size_t ptr_size = buffer_size;
407   _Bool append_plus = 0;
408   _Bool append_minus = 0;
409
410   if ((buffer == NULL) || (buffer_size <= strlen("Minus")) || (src == NULL))
411     return EINVAL;
412
413   src_copy = strdup(src);
414   src_len = strlen(src);
415
416   /* Remove trailing "+" and "-". */
417   if (src_copy[src_len - 1] == '+') {
418     append_plus = 1;
419     src_len--;
420     src_copy[src_len] = 0;
421   } else if (src_copy[src_len - 1] == '-') {
422     append_minus = 1;
423     src_len--;
424     src_copy[src_len] = 0;
425   }
426
427   /* Split at special chars, capitalize first character, append to buffer. */
428   char *dummy = src_copy;
429   char *token;
430   char *save_ptr = NULL;
431   while ((token = strtok_r(dummy, ":_-+", &save_ptr)) != NULL) {
432     size_t len;
433
434     dummy = NULL;
435
436     token[0] = toupper((int)token[0]);
437
438     assert(ptr_size > 1);
439
440     len = strlen(token);
441     if (len >= ptr_size)
442       len = ptr_size - 1;
443
444     assert(len > 0);
445     assert(len < ptr_size);
446
447     sstrncpy(ptr, token, len + 1);
448     ptr += len;
449     ptr_size -= len;
450
451     assert(*ptr == 0);
452     if (ptr_size <= 1)
453       break;
454   }
455
456   /* Append "Plus" or "Minus" if "+" or "-" has been stripped above. */
457   if (append_plus || append_minus) {
458     char const *append = "Plus";
459     if (append_minus)
460       append = "Minus";
461
462     size_t offset = buffer_size - (strlen(append) + 1);
463     if (offset > strlen(buffer))
464       offset = strlen(buffer);
465
466     sstrncpy(buffer + offset, append, buffer_size - offset);
467   }
468
469   sfree(src_copy);
470   return 0;
471 }
472
473 static _Bool has_suffix(char const *str, char const *suffix) {
474   size_t str_len = strlen(str);
475   size_t suffix_len = strlen(suffix);
476   size_t offset;
477
478   if (suffix_len > str_len)
479     return 0;
480   offset = str_len - suffix_len;
481
482   if (strcmp(str + offset, suffix) == 0)
483     return 1;
484
485   return 0;
486 }
487
488 static void cut_suffix(char *buffer, size_t buffer_size, char const *str,
489                       char const *suffix) {
490
491   size_t str_len = strlen(str);
492   size_t suffix_len = strlen(suffix);
493
494   size_t offset = str_len - suffix_len + 1;
495
496   if (offset > buffer_size) {
497     offset = buffer_size;
498   }
499
500   sstrncpy(buffer, str, offset);
501 }
502
503 /* count_parts returns the number of elements a "foo.bar.baz" style key has. */
504 static size_t count_parts(char const *key) {
505   size_t parts_num = 0;
506
507   for (const char *ptr = key; ptr != NULL; ptr = strchr(ptr + 1, '.'))
508     parts_num++;
509
510   return parts_num;
511 }
512
513 /**
514  * Parse key to remove "type" if this is for schema and initiate compaction
515  */
516 static int parse_keys(char *buffer, size_t buffer_size, const char *key_str) {
517   char tmp[2 * buffer_size];
518   size_t tmp_size = sizeof(tmp);
519
520   if (buffer == NULL || buffer_size == 0 || key_str == NULL ||
521       strlen(key_str) == 0)
522     return EINVAL;
523   /* Strip suffix if it is ".type" or one of latency metric suffix. */
524   if (count_parts(key_str) > 2) {
525     if (has_suffix(key_str, ".type")) {
526       cut_suffix(tmp, tmp_size, key_str, ".type");
527     } else if (has_suffix(key_str, ".avgcount")) {
528       cut_suffix(tmp, tmp_size, key_str, ".avgcount");
529     } else if (has_suffix(key_str, ".sum")) {
530       cut_suffix(tmp, tmp_size, key_str, ".sum");
531     } else if (has_suffix(key_str, ".avgtime")) {
532       cut_suffix(tmp, tmp_size, key_str, ".avgtime");
533     } else {
534       sstrncpy(tmp, key_str, sizeof(tmp));
535     }
536   } else {
537     sstrncpy(tmp, key_str, sizeof(tmp));
538   }
539
540   return compact_ds_name(buffer, buffer_size, tmp);
541 }
542
543 /**
544  * while parsing ceph admin socket schema, save counter name and type for later
545  * data processing
546  */
547 static int ceph_daemon_add_ds_entry(struct ceph_daemon *d, const char *name,
548                                     int pc_type) {
549   uint32_t type;
550   char ds_name[DATA_MAX_NAME_LEN];
551
552   if (convert_special_metrics) {
553     /**
554      * Special case for filestore:JournalWrBytes. For some reason, Ceph
555      * schema encodes this as a count/sum pair while all other "Bytes" data
556      * (excluding used/capacity bytes for OSD space) uses a single "Derive"
557      * type. To spare further confusion, keep this KPI as the same type of
558      * other "Bytes". Instead of keeping an "average" or "rate", use the
559      * "sum" in the pair and assign that to the derive value.
560      */
561     if ((strcmp(name, "filestore.journal_wr_bytes.type") == 0)) {
562       pc_type = 10;
563     }
564   }
565
566   d->ds_names = realloc(d->ds_names, sizeof(char *) * (d->ds_num + 1));
567   if (!d->ds_names) {
568     return -ENOMEM;
569   }
570
571   d->ds_types = realloc(d->ds_types, sizeof(uint32_t) * (d->ds_num + 1));
572   if (!d->ds_types) {
573     return -ENOMEM;
574   }
575
576   d->ds_names[d->ds_num] = malloc(DATA_MAX_NAME_LEN);
577   if (!d->ds_names[d->ds_num]) {
578     return -ENOMEM;
579   }
580
581   type = (pc_type & PERFCOUNTER_DERIVE)
582              ? DSET_RATE
583              : ((pc_type & PERFCOUNTER_LATENCY) ? DSET_LATENCY : DSET_BYTES);
584   d->ds_types[d->ds_num] = type;
585
586   if (parse_keys(ds_name, sizeof(ds_name), name)) {
587     return 1;
588   }
589
590   sstrncpy(d->ds_names[d->ds_num], ds_name, DATA_MAX_NAME_LEN - 1);
591   d->ds_num = (d->ds_num + 1);
592
593   return 0;
594 }
595
596 /******* ceph_config *******/
597 static int cc_handle_str(struct oconfig_item_s *item, char *dest,
598                          int dest_len) {
599   const char *val;
600   if (item->values_num != 1) {
601     return -ENOTSUP;
602   }
603   if (item->values[0].type != OCONFIG_TYPE_STRING) {
604     return -ENOTSUP;
605   }
606   val = item->values[0].value.string;
607   if (snprintf(dest, dest_len, "%s", val) > (dest_len - 1)) {
608     ERROR("ceph plugin: configuration parameter '%s' is too long.\n",
609           item->key);
610     return -ENAMETOOLONG;
611   }
612   return 0;
613 }
614
615 static int cc_handle_bool(struct oconfig_item_s *item, int *dest) {
616   if (item->values_num != 1) {
617     return -ENOTSUP;
618   }
619
620   if (item->values[0].type != OCONFIG_TYPE_BOOLEAN) {
621     return -ENOTSUP;
622   }
623
624   *dest = (item->values[0].value.boolean) ? 1 : 0;
625   return 0;
626 }
627
628 static int cc_add_daemon_config(oconfig_item_t *ci) {
629   int ret;
630   struct ceph_daemon *nd, cd = {0};
631   struct ceph_daemon **tmp;
632
633   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
634     WARNING("ceph plugin: `Daemon' blocks need exactly one string "
635             "argument.");
636     return -1;
637   }
638
639   ret = cc_handle_str(ci, cd.name, DATA_MAX_NAME_LEN);
640   if (ret) {
641     return ret;
642   }
643
644   for (int i = 0; i < ci->children_num; i++) {
645     oconfig_item_t *child = ci->children + i;
646
647     if (strcasecmp("SocketPath", child->key) == 0) {
648       ret = cc_handle_str(child, cd.asok_path, sizeof(cd.asok_path));
649       if (ret) {
650         return ret;
651       }
652     } else {
653       WARNING("ceph plugin: ignoring unknown option %s", child->key);
654     }
655   }
656   if (cd.name[0] == '\0') {
657     ERROR("ceph plugin: you must configure a daemon name.\n");
658     return -EINVAL;
659   } else if (cd.asok_path[0] == '\0') {
660     ERROR("ceph plugin(name=%s): you must configure an administrative "
661           "socket path.\n",
662           cd.name);
663     return -EINVAL;
664   } else if (!((cd.asok_path[0] == '/') ||
665                (cd.asok_path[0] == '.' && cd.asok_path[1] == '/'))) {
666     ERROR("ceph plugin(name=%s): administrative socket paths must begin "
667           "with '/' or './' Can't parse: '%s'\n",
668           cd.name, cd.asok_path);
669     return -EINVAL;
670   }
671
672   tmp = realloc(g_daemons, (g_num_daemons + 1) * sizeof(*g_daemons));
673   if (tmp == NULL) {
674     /* The positive return value here indicates that this is a
675      * runtime error, not a configuration error.  */
676     return ENOMEM;
677   }
678   g_daemons = tmp;
679
680   nd = malloc(sizeof(*nd));
681   if (!nd) {
682     return ENOMEM;
683   }
684   memcpy(nd, &cd, sizeof(*nd));
685   g_daemons[g_num_daemons] = nd;
686   g_num_daemons++;
687   return 0;
688 }
689
690 static int ceph_config(oconfig_item_t *ci) {
691   int ret;
692
693   for (int i = 0; i < ci->children_num; ++i) {
694     oconfig_item_t *child = ci->children + i;
695     if (strcasecmp("Daemon", child->key) == 0) {
696       ret = cc_add_daemon_config(child);
697       if (ret == ENOMEM) {
698         ERROR("ceph plugin: Couldn't allocate memory");
699         return ret;
700       } else if (ret) {
701         // process other daemons and ignore this one
702         continue;
703       }
704     } else if (strcasecmp("LongRunAvgLatency", child->key) == 0) {
705       ret = cc_handle_bool(child, &long_run_latency_avg);
706       if (ret) {
707         return ret;
708       }
709     } else if (strcasecmp("ConvertSpecialMetricTypes", child->key) == 0) {
710       ret = cc_handle_bool(child, &convert_special_metrics);
711       if (ret) {
712         return ret;
713       }
714     } else {
715       WARNING("ceph plugin: ignoring unknown option %s", child->key);
716     }
717   }
718   return 0;
719 }
720
721 /**
722  * Parse JSON and get error message if present
723  */
724 static int traverse_json(const unsigned char *json, uint32_t json_len,
725                          yajl_handle hand) {
726   yajl_status status = yajl_parse(hand, json, json_len);
727   unsigned char *msg;
728
729   switch (status) {
730   case yajl_status_error:
731     msg = yajl_get_error(hand, /* verbose = */ 1,
732                          /* jsonText = */ (unsigned char *)json,
733                          (unsigned int)json_len);
734     ERROR("ceph plugin: yajl_parse failed: %s", msg);
735     yajl_free_error(hand, msg);
736     return 1;
737   case yajl_status_client_canceled:
738     return 1;
739   default:
740     return 0;
741   }
742 }
743
744 /**
745  * Add entry for each counter while parsing schema
746  */
747 static int node_handler_define_schema(void *arg, const char *val,
748                                       const char *key) {
749   struct ceph_daemon *d = (struct ceph_daemon *)arg;
750   int pc_type;
751   pc_type = atoi(val);
752   return ceph_daemon_add_ds_entry(d, key, pc_type);
753 }
754
755 /**
756  * Latency counter does not yet have an entry in last poll data - add it.
757  */
758 static int add_last(struct ceph_daemon *d, const char *ds_n, double cur_sum,
759                     uint64_t cur_count) {
760   d->last_poll_data[d->last_idx] =
761       malloc(sizeof(*d->last_poll_data[d->last_idx]));
762   if (!d->last_poll_data[d->last_idx]) {
763     return -ENOMEM;
764   }
765   sstrncpy(d->last_poll_data[d->last_idx]->ds_name, ds_n,
766            sizeof(d->last_poll_data[d->last_idx]->ds_name));
767   d->last_poll_data[d->last_idx]->last_sum = cur_sum;
768   d->last_poll_data[d->last_idx]->last_count = cur_count;
769   d->last_idx = (d->last_idx + 1);
770   return 0;
771 }
772
773 /**
774  * Update latency counter or add new entry if it doesn't exist
775  */
776 static int update_last(struct ceph_daemon *d, const char *ds_n, int index,
777                        double cur_sum, uint64_t cur_count) {
778   if ((d->last_idx > index) &&
779       (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0)) {
780     d->last_poll_data[index]->last_sum = cur_sum;
781     d->last_poll_data[index]->last_count = cur_count;
782     return 0;
783   }
784
785   if (!d->last_poll_data) {
786     d->last_poll_data = malloc(sizeof(*d->last_poll_data));
787     if (!d->last_poll_data) {
788       return -ENOMEM;
789     }
790   } else {
791     struct last_data **tmp_last = realloc(
792         d->last_poll_data, ((d->last_idx + 1) * sizeof(struct last_data *)));
793     if (!tmp_last) {
794       return -ENOMEM;
795     }
796     d->last_poll_data = tmp_last;
797   }
798   return add_last(d, ds_n, cur_sum, cur_count);
799 }
800
801 /**
802  * If using index guess failed (shouldn't happen, but possible if counters
803  * get rearranged), resort to searching for counter name
804  */
805 static int backup_search_for_last_avg(struct ceph_daemon *d, const char *ds_n) {
806   for (int i = 0; i < d->last_idx; i++) {
807     if (strcmp(d->last_poll_data[i]->ds_name, ds_n) == 0) {
808       return i;
809     }
810   }
811   return -1;
812 }
813
814 /**
815  * Calculate average b/t current data and last poll data
816  * if last poll data exists
817  */
818 static double get_last_avg(struct ceph_daemon *d, const char *ds_n, int index,
819                            double cur_sum, uint64_t cur_count) {
820   double result = -1.1, sum_delt = 0.0;
821   uint64_t count_delt = 0;
822   int tmp_index = 0;
823   if (d->last_idx > index) {
824     if (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0) {
825       tmp_index = index;
826     }
827     // test previous index
828     else if ((index > 0) &&
829              (strcmp(d->last_poll_data[index - 1]->ds_name, ds_n) == 0)) {
830       tmp_index = (index - 1);
831     } else {
832       tmp_index = backup_search_for_last_avg(d, ds_n);
833     }
834
835     if ((tmp_index > -1) &&
836         (cur_count > d->last_poll_data[tmp_index]->last_count)) {
837       sum_delt = (cur_sum - d->last_poll_data[tmp_index]->last_sum);
838       count_delt = (cur_count - d->last_poll_data[tmp_index]->last_count);
839       result = (sum_delt / count_delt);
840     }
841   }
842
843   if (result == -1.1) {
844     result = NAN;
845   }
846   if (update_last(d, ds_n, tmp_index, cur_sum, cur_count) == -ENOMEM) {
847     return -ENOMEM;
848   }
849   return result;
850 }
851
852 /**
853  * If using index guess failed, resort to searching for counter name
854  */
855 static uint32_t backup_search_for_type(struct ceph_daemon *d, char *ds_name) {
856   for (int i = 0; i < d->ds_num; i++) {
857     if (strcmp(d->ds_names[i], ds_name) == 0) {
858       return d->ds_types[i];
859     }
860   }
861   return DSET_TYPE_UNFOUND;
862 }
863
864 /**
865  * Process counter data and dispatch values
866  */
867 static int node_handler_fetch_data(void *arg, const char *val,
868                                    const char *key) {
869   value_t uv;
870   double tmp_d;
871   uint64_t tmp_u;
872   struct values_tmp *vtmp = (struct values_tmp *)arg;
873   uint32_t type = DSET_TYPE_UNFOUND;
874   int index = vtmp->index;
875
876   char ds_name[DATA_MAX_NAME_LEN];
877
878   if (parse_keys(ds_name, sizeof(ds_name), key)) {
879     return 1;
880   }
881
882   if (index >= vtmp->d->ds_num) {
883     // don't overflow bounds of array
884     index = (vtmp->d->ds_num - 1);
885   }
886
887   /**
888    * counters should remain in same order we parsed schema... we maintain the
889    * index variable to keep track of current point in list of counters. first
890    * use index to guess point in array for retrieving type. if that doesn't
891    * work, use the old way to get the counter type
892    */
893   if (strcmp(ds_name, vtmp->d->ds_names[index]) == 0) {
894     // found match
895     type = vtmp->d->ds_types[index];
896   } else if ((index > 0) &&
897              (strcmp(ds_name, vtmp->d->ds_names[index - 1]) == 0)) {
898     // try previous key
899     type = vtmp->d->ds_types[index - 1];
900   }
901
902   if (type == DSET_TYPE_UNFOUND) {
903     // couldn't find right type by guessing, check the old way
904     type = backup_search_for_type(vtmp->d, ds_name);
905   }
906
907   switch (type) {
908   case DSET_LATENCY:
909     if (has_suffix(key, ".avgcount")) {
910       sscanf(val, "%" PRIu64, &vtmp->avgcount);
911       // return after saving avgcount - don't dispatch value
912       // until latency calculation
913       return 0;
914     } else if (has_suffix(key, ".sum")) {
915       if (vtmp->avgcount == 0) {
916         vtmp->avgcount = 1;
917       }
918       // user wants latency values as long run avg
919       // skip this step
920       if (long_run_latency_avg) {
921         return 0;
922       }
923       double sum, result;
924       sscanf(val, "%lf", &sum);
925       result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum,
926                             vtmp->avgcount);
927       if (result == -ENOMEM) {
928         return -ENOMEM;
929       }
930       uv.gauge = result;
931       vtmp->latency_index = (vtmp->latency_index + 1);
932     } else if (has_suffix(key, ".avgtime")) {
933       // skip this step if no need in long run latency
934       if (!long_run_latency_avg) {
935         return 0;
936       }
937       double result;
938       sscanf(val, "%lf", &result);
939       uv.gauge = result;
940       vtmp->latency_index = (vtmp->latency_index + 1);
941     } else {
942       WARNING("ceph plugin: ignoring unknown latency metric: %s", key);
943       return 0;
944     }
945     break;
946   case DSET_BYTES:
947     sscanf(val, "%lf", &tmp_d);
948     uv.gauge = tmp_d;
949     break;
950   case DSET_RATE:
951     sscanf(val, "%" PRIu64, &tmp_u);
952     uv.derive = tmp_u;
953     break;
954   case DSET_TYPE_UNFOUND:
955   default:
956     ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);
957     return -1;
958   }
959
960   sstrncpy(vtmp->vlist.type, ceph_dset_types[type], sizeof(vtmp->vlist.type));
961   sstrncpy(vtmp->vlist.type_instance, ds_name,
962            sizeof(vtmp->vlist.type_instance));
963   vtmp->vlist.values = &uv;
964   vtmp->vlist.values_len = 1;
965
966   vtmp->index = (vtmp->index + 1);
967   plugin_dispatch_values(&vtmp->vlist);
968
969   return 0;
970 }
971
972 static int cconn_connect(struct cconn *io) {
973   struct sockaddr_un address = {0};
974   int flags, fd, err;
975   if (io->state != CSTATE_UNCONNECTED) {
976     ERROR("ceph plugin: cconn_connect: io->state != CSTATE_UNCONNECTED");
977     return -EDOM;
978   }
979   fd = socket(PF_UNIX, SOCK_STREAM, 0);
980   if (fd < 0) {
981     err = -errno;
982     ERROR("ceph plugin: cconn_connect: socket(PF_UNIX, SOCK_STREAM, 0) "
983           "failed: error %d",
984           err);
985     return err;
986   }
987   address.sun_family = AF_UNIX;
988   snprintf(address.sun_path, sizeof(address.sun_path), "%s", io->d->asok_path);
989   RETRY_ON_EINTR(err, connect(fd, (struct sockaddr *)&address,
990                               sizeof(struct sockaddr_un)));
991   if (err < 0) {
992     ERROR("ceph plugin: cconn_connect: connect(%d) failed: error %d", fd, err);
993     close(fd);
994     return err;
995   }
996
997   flags = fcntl(fd, F_GETFL, 0);
998   if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
999     err = -errno;
1000     ERROR("ceph plugin: cconn_connect: fcntl(%d, O_NONBLOCK) error %d", fd,
1001           err);
1002     close(fd);
1003     return err;
1004   }
1005   io->asok = fd;
1006   io->state = CSTATE_WRITE_REQUEST;
1007   io->amt = 0;
1008   io->json_len = 0;
1009   io->json = NULL;
1010   return 0;
1011 }
1012
1013 static void cconn_close(struct cconn *io) {
1014   io->state = CSTATE_UNCONNECTED;
1015   if (io->asok != -1) {
1016     int res;
1017     RETRY_ON_EINTR(res, close(io->asok));
1018   }
1019   io->asok = -1;
1020   io->amt = 0;
1021   io->json_len = 0;
1022   sfree(io->json);
1023   io->json = NULL;
1024 }
1025
1026 /* Process incoming JSON counter data */
1027 static int cconn_process_data(struct cconn *io, yajl_struct *yajl,
1028                               yajl_handle hand) {
1029   int ret;
1030   struct values_tmp *vtmp = calloc(1, sizeof(struct values_tmp) * 1);
1031   if (!vtmp) {
1032     return -ENOMEM;
1033   }
1034
1035   vtmp->vlist = (value_list_t)VALUE_LIST_INIT;
1036   sstrncpy(vtmp->vlist.plugin, "ceph", sizeof(vtmp->vlist.plugin));
1037   sstrncpy(vtmp->vlist.plugin_instance, io->d->name,
1038            sizeof(vtmp->vlist.plugin_instance));
1039
1040   vtmp->d = io->d;
1041   vtmp->latency_index = 0;
1042   vtmp->index = 0;
1043   yajl->handler_arg = vtmp;
1044   ret = traverse_json(io->json, io->json_len, hand);
1045   sfree(vtmp);
1046   return ret;
1047 }
1048
1049 /**
1050  * Initiate JSON parsing and print error if one occurs
1051  */
1052 static int cconn_process_json(struct cconn *io) {
1053   if ((io->request_type != ASOK_REQ_DATA) &&
1054       (io->request_type != ASOK_REQ_SCHEMA)) {
1055     return -EDOM;
1056   }
1057
1058   int result = 1;
1059   yajl_handle hand;
1060   yajl_status status;
1061
1062   hand = yajl_alloc(&callbacks,
1063 #if HAVE_YAJL_V2
1064                     /* alloc funcs = */ NULL,
1065 #else
1066                     /* alloc funcs = */ NULL, NULL,
1067 #endif
1068                     /* context = */ (void *)(&io->yajl));
1069
1070   if (!hand) {
1071     ERROR("ceph plugin: yajl_alloc failed.");
1072     return ENOMEM;
1073   }
1074
1075   io->yajl.depth = 0;
1076
1077   switch (io->request_type) {
1078   case ASOK_REQ_DATA:
1079     io->yajl.handler = node_handler_fetch_data;
1080     result = cconn_process_data(io, &io->yajl, hand);
1081     break;
1082   case ASOK_REQ_SCHEMA:
1083     // init daemon specific variables
1084     io->d->ds_num = 0;
1085     io->d->last_idx = 0;
1086     io->d->last_poll_data = NULL;
1087     io->yajl.handler = node_handler_define_schema;
1088     io->yajl.handler_arg = io->d;
1089     result = traverse_json(io->json, io->json_len, hand);
1090     break;
1091   }
1092
1093   if (result) {
1094     goto done;
1095   }
1096
1097 #if HAVE_YAJL_V2
1098   status = yajl_complete_parse(hand);
1099 #else
1100   status = yajl_parse_complete(hand);
1101 #endif
1102
1103   if (status != yajl_status_ok) {
1104     unsigned char *errmsg =
1105         yajl_get_error(hand, /* verbose = */ 0,
1106                        /* jsonText = */ NULL, /* jsonTextLen = */ 0);
1107     ERROR("ceph plugin: yajl_parse_complete failed: %s", (char *)errmsg);
1108     yajl_free_error(hand, errmsg);
1109     yajl_free(hand);
1110     return 1;
1111   }
1112
1113 done:
1114   yajl_free(hand);
1115   return result;
1116 }
1117
1118 static int cconn_validate_revents(struct cconn *io, int revents) {
1119   if (revents & POLLERR) {
1120     ERROR("ceph plugin: cconn_validate_revents(name=%s): got POLLERR",
1121           io->d->name);
1122     return -EIO;
1123   }
1124   switch (io->state) {
1125   case CSTATE_WRITE_REQUEST:
1126     return (revents & POLLOUT) ? 0 : -EINVAL;
1127   case CSTATE_READ_VERSION:
1128   case CSTATE_READ_AMT:
1129   case CSTATE_READ_JSON:
1130     return (revents & POLLIN) ? 0 : -EINVAL;
1131   default:
1132     ERROR("ceph plugin: cconn_validate_revents(name=%s) got to "
1133           "illegal state on line %d",
1134           io->d->name, __LINE__);
1135     return -EDOM;
1136   }
1137 }
1138
1139 /** Handle a network event for a connection */
1140 static int cconn_handle_event(struct cconn *io) {
1141   int ret;
1142   switch (io->state) {
1143   case CSTATE_UNCONNECTED:
1144     ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1145           "state on line %d",
1146           io->d->name, __LINE__);
1147
1148     return -EDOM;
1149   case CSTATE_WRITE_REQUEST: {
1150     char cmd[32];
1151     snprintf(cmd, sizeof(cmd), "%s%d%s", "{ \"prefix\": \"", io->request_type,
1152              "\" }\n");
1153     size_t cmd_len = strlen(cmd);
1154     RETRY_ON_EINTR(
1155         ret, write(io->asok, ((char *)&cmd) + io->amt, cmd_len - io->amt));
1156     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,amt=%d,ret=%d)",
1157           io->d->name, io->state, io->amt, ret);
1158     if (ret < 0) {
1159       return ret;
1160     }
1161     io->amt += ret;
1162     if (io->amt >= cmd_len) {
1163       io->amt = 0;
1164       switch (io->request_type) {
1165       case ASOK_REQ_VERSION:
1166         io->state = CSTATE_READ_VERSION;
1167         break;
1168       default:
1169         io->state = CSTATE_READ_AMT;
1170         break;
1171       }
1172     }
1173     return 0;
1174   }
1175   case CSTATE_READ_VERSION: {
1176     RETRY_ON_EINTR(ret, read(io->asok, ((char *)(&io->d->version)) + io->amt,
1177                              sizeof(io->d->version) - io->amt));
1178     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1179           io->d->name, io->state, ret);
1180     if (ret < 0) {
1181       return ret;
1182     }
1183     io->amt += ret;
1184     if (io->amt >= sizeof(io->d->version)) {
1185       io->d->version = ntohl(io->d->version);
1186       if (io->d->version != 1) {
1187         ERROR("ceph plugin: cconn_handle_event(name=%s) not "
1188               "expecting version %d!",
1189               io->d->name, io->d->version);
1190         return -ENOTSUP;
1191       }
1192       DEBUG("ceph plugin: cconn_handle_event(name=%s): identified as "
1193             "version %d",
1194             io->d->name, io->d->version);
1195       io->amt = 0;
1196       cconn_close(io);
1197       io->request_type = ASOK_REQ_SCHEMA;
1198     }
1199     return 0;
1200   }
1201   case CSTATE_READ_AMT: {
1202     RETRY_ON_EINTR(ret, read(io->asok, ((char *)(&io->json_len)) + io->amt,
1203                              sizeof(io->json_len) - io->amt));
1204     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1205           io->d->name, io->state, ret);
1206     if (ret < 0) {
1207       return ret;
1208     }
1209     io->amt += ret;
1210     if (io->amt >= sizeof(io->json_len)) {
1211       io->json_len = ntohl(io->json_len);
1212       io->amt = 0;
1213       io->state = CSTATE_READ_JSON;
1214       io->json = calloc(1, io->json_len + 1);
1215       if (!io->json) {
1216         ERROR("ceph plugin: error callocing io->json");
1217         return -ENOMEM;
1218       }
1219     }
1220     return 0;
1221   }
1222   case CSTATE_READ_JSON: {
1223     RETRY_ON_EINTR(ret,
1224                    read(io->asok, io->json + io->amt, io->json_len - io->amt));
1225     DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1226           io->d->name, io->state, ret);
1227     if (ret < 0) {
1228       return ret;
1229     }
1230     io->amt += ret;
1231     if (io->amt >= io->json_len) {
1232       ret = cconn_process_json(io);
1233       if (ret) {
1234         return ret;
1235       }
1236       cconn_close(io);
1237       io->request_type = ASOK_REQ_NONE;
1238     }
1239     return 0;
1240   }
1241   default:
1242     ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1243           "state on line %d",
1244           io->d->name, __LINE__);
1245     return -EDOM;
1246   }
1247 }
1248
1249 static int cconn_prepare(struct cconn *io, struct pollfd *fds) {
1250   int ret;
1251   if (io->request_type == ASOK_REQ_NONE) {
1252     /* The request has already been serviced. */
1253     return 0;
1254   } else if ((io->request_type == ASOK_REQ_DATA) && (io->d->ds_num == 0)) {
1255     /* If there are no counters to report on, don't bother
1256      * connecting */
1257     return 0;
1258   }
1259
1260   switch (io->state) {
1261   case CSTATE_UNCONNECTED:
1262     ret = cconn_connect(io);
1263     if (ret > 0) {
1264       return -ret;
1265     } else if (ret < 0) {
1266       return ret;
1267     }
1268     fds->fd = io->asok;
1269     fds->events = POLLOUT;
1270     return 1;
1271   case CSTATE_WRITE_REQUEST:
1272     fds->fd = io->asok;
1273     fds->events = POLLOUT;
1274     return 1;
1275   case CSTATE_READ_VERSION:
1276   case CSTATE_READ_AMT:
1277   case CSTATE_READ_JSON:
1278     fds->fd = io->asok;
1279     fds->events = POLLIN;
1280     return 1;
1281   default:
1282     ERROR("ceph plugin: cconn_prepare(name=%s) got to illegal state "
1283           "on line %d",
1284           io->d->name, __LINE__);
1285     return -EDOM;
1286   }
1287 }
1288
1289 /** Returns the difference between two struct timevals in milliseconds.
1290  * On overflow, we return max/min int.
1291  */
1292 static int milli_diff(const struct timeval *t1, const struct timeval *t2) {
1293   int64_t ret;
1294   int sec_diff = t1->tv_sec - t2->tv_sec;
1295   int usec_diff = t1->tv_usec - t2->tv_usec;
1296   ret = usec_diff / 1000;
1297   ret += (sec_diff * 1000);
1298   return (ret > INT_MAX) ? INT_MAX : ((ret < INT_MIN) ? INT_MIN : (int)ret);
1299 }
1300
1301 /** This handles the actual network I/O to talk to the Ceph daemons.
1302  */
1303 static int cconn_main_loop(uint32_t request_type) {
1304   int ret, some_unreachable = 0;
1305   struct timeval end_tv;
1306   struct cconn io_array[g_num_daemons];
1307
1308   DEBUG("ceph plugin: entering cconn_main_loop(request_type = %" PRIu32 ")",
1309         request_type);
1310
1311   if (g_num_daemons < 1) {
1312     ERROR("ceph plugin: No daemons configured. See the \"Daemon\" config "
1313           "option.");
1314     return ENOENT;
1315   }
1316
1317   /* create cconn array */
1318   for (size_t i = 0; i < g_num_daemons; i++) {
1319     io_array[i] = (struct cconn){
1320         .d = g_daemons[i],
1321         .request_type = request_type,
1322         .state = CSTATE_UNCONNECTED,
1323     };
1324   }
1325
1326   /** Calculate the time at which we should give up */
1327   gettimeofday(&end_tv, NULL);
1328   end_tv.tv_sec += CEPH_TIMEOUT_INTERVAL;
1329
1330   while (1) {
1331     int nfds, diff;
1332     struct timeval tv;
1333     struct cconn *polled_io_array[g_num_daemons];
1334     struct pollfd fds[g_num_daemons];
1335     memset(fds, 0, sizeof(fds));
1336     nfds = 0;
1337     for (size_t i = 0; i < g_num_daemons; ++i) {
1338       struct cconn *io = io_array + i;
1339       ret = cconn_prepare(io, fds + nfds);
1340       if (ret < 0) {
1341         WARNING("ceph plugin: cconn_prepare(name=%s,i=%zu,st=%d)=%d",
1342                 io->d->name, i, io->state, ret);
1343         cconn_close(io);
1344         io->request_type = ASOK_REQ_NONE;
1345         some_unreachable = 1;
1346       } else if (ret == 1) {
1347         polled_io_array[nfds++] = io_array + i;
1348       }
1349     }
1350     if (nfds == 0) {
1351       /* finished */
1352       ret = 0;
1353       goto done;
1354     }
1355     gettimeofday(&tv, NULL);
1356     diff = milli_diff(&end_tv, &tv);
1357     if (diff <= 0) {
1358       /* Timed out */
1359       ret = -ETIMEDOUT;
1360       WARNING("ceph plugin: cconn_main_loop: timed out.");
1361       goto done;
1362     }
1363     RETRY_ON_EINTR(ret, poll(fds, nfds, diff));
1364     if (ret < 0) {
1365       ERROR("ceph plugin: poll(2) error: %d", ret);
1366       goto done;
1367     }
1368     for (int i = 0; i < nfds; ++i) {
1369       struct cconn *io = polled_io_array[i];
1370       int revents = fds[i].revents;
1371       if (revents == 0) {
1372         /* do nothing */
1373         continue;
1374       } else if (cconn_validate_revents(io, revents)) {
1375         WARNING("ceph plugin: cconn(name=%s,i=%d,st=%d): "
1376                 "revents validation error: "
1377                 "revents=0x%08x",
1378                 io->d->name, i, io->state, revents);
1379         cconn_close(io);
1380         io->request_type = ASOK_REQ_NONE;
1381         some_unreachable = 1;
1382       } else {
1383         ret = cconn_handle_event(io);
1384         if (ret) {
1385           WARNING("ceph plugin: cconn_handle_event(name=%s,"
1386                   "i=%d,st=%d): error %d",
1387                   io->d->name, i, io->state, ret);
1388           cconn_close(io);
1389           io->request_type = ASOK_REQ_NONE;
1390           some_unreachable = 1;
1391         }
1392       }
1393     }
1394   }
1395 done:
1396   for (size_t i = 0; i < g_num_daemons; ++i) {
1397     cconn_close(io_array + i);
1398   }
1399   if (some_unreachable) {
1400     DEBUG("ceph plugin: cconn_main_loop: some Ceph daemons were unreachable.");
1401   } else {
1402     DEBUG("ceph plugin: cconn_main_loop: reached all Ceph daemons :)");
1403   }
1404   return ret;
1405 }
1406
1407 static int ceph_read(void) { return cconn_main_loop(ASOK_REQ_DATA); }
1408
1409 /******* lifecycle *******/
1410 static int ceph_init(void) {
1411 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_DAC_OVERRIDE)
1412   if (check_capability(CAP_DAC_OVERRIDE) != 0) {
1413     if (getuid() == 0)
1414       WARNING("ceph plugin: Running collectd as root, but the "
1415               "CAP_DAC_OVERRIDE capability is missing. The plugin's read "
1416               "function will probably fail. Is your init system dropping "
1417               "capabilities?");
1418     else
1419       WARNING(
1420           "ceph plugin: collectd doesn't have the CAP_DAC_OVERRIDE "
1421           "capability. If you don't want to run collectd as root, try running "
1422           "\"setcap cap_dac_override=ep\" on the collectd binary.");
1423   }
1424 #endif
1425
1426   ceph_daemons_print();
1427
1428   if (g_num_daemons < 1) {
1429     ERROR("ceph plugin: No daemons configured. See the \"Daemon\" config "
1430           "option.");
1431     return ENOENT;
1432   }
1433
1434   return cconn_main_loop(ASOK_REQ_VERSION);
1435 }
1436
1437 static int ceph_shutdown(void) {
1438   for (size_t i = 0; i < g_num_daemons; ++i) {
1439     ceph_daemon_free(g_daemons[i]);
1440   }
1441   sfree(g_daemons);
1442   g_daemons = NULL;
1443   g_num_daemons = 0;
1444   DEBUG("ceph plugin: finished ceph_shutdown");
1445   return 0;
1446 }
1447
1448 void module_register(void) {
1449   plugin_register_complex_config("ceph", ceph_config);
1450   plugin_register_init("ceph", ceph_init);
1451   plugin_register_read("ceph", ceph_read);
1452   plugin_register_shutdown("ceph", ceph_shutdown);
1453 }