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