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