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