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