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