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