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