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