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