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