2 * collectd - src/ceph.c
3 * Copyright (C) 2011 New Dream Network
4 * Copyright (C) 2015 Florian octo Forster
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.
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.
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
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>
26 #define _DEFAULT_SOURCE
34 #include <arpa/inet.h>
37 #include <yajl/yajl_parse.h>
38 #if HAVE_YAJL_YAJL_VERSION_H
39 #include <yajl/yajl_version.h>
50 #include <sys/types.h>
56 #define RETRY_AVGCOUNT -1
58 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
59 # define HAVE_YAJL_V2 1
62 #define RETRY_ON_EINTR(ret, expr) \
72 /** Timeout interval in seconds */
73 #define CEPH_TIMEOUT_INTERVAL 1
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))
78 /** Yajl callback returns */
79 #define CEPH_CB_CONTINUE 1
80 #define CEPH_CB_ABORT 0
83 typedef size_t yajl_len_t;
85 typedef unsigned int yajl_len_t;
88 /** Number of types for ceph defined in types.db */
89 #define CEPH_DSET_TYPES_NUM 3
90 /** ceph types enum */
96 DSET_TYPE_UNFOUND = 1000
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"};
103 /******* ceph_daemon *******/
106 /** Version of the admin_socket interface */
109 char name[DATA_MAX_NAME_LEN];
111 /** Path to the socket that we use to talk to the ceph daemon */
112 char asok_path[UNIX_DOMAIN_SOCK_PATH_MAX];
114 /** Number of counters */
116 /** Track ds types */
118 /** Track ds names to match with types */
122 * Keep track of last data for latency values so we can calculate rate
125 struct last_data **last_poll_data;
126 /** index of last poll data */
130 /******* JSON parsing *******/
131 typedef int (*node_handler_t)(void *, const char*, const char*);
133 /** Track state and handler while parsing JSON */
136 node_handler_t handler;
140 char *stack[YAJL_MAX_DEPTH];
143 typedef struct yajl_struct yajl_struct;
145 enum perfcounter_type_d
147 PERFCOUNTER_LATENCY = 0x4, PERFCOUNTER_DERIVE = 0x8,
150 /** Give user option to use default (long run = since daemon started) avg */
151 static int long_run_latency_avg = 0;
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.
161 static int convert_special_metrics = 1;
163 /** Array of daemons to monitor */
164 static struct ceph_daemon **g_daemons = NULL;
166 /** Number of elements in g_daemons */
167 static int g_num_daemons = 0;
170 * A set of data that we build up in memory while parsing the JSON.
174 /** ceph daemon we are processing data for*/
175 struct ceph_daemon *d;
176 /** track avgcount across counters for avgcount/sum latency pairs */
178 /** current index of counters - used to get type of counter */
180 /** do we already have an avgcount for latency pair */
183 * similar to index, but current index of latency type counters -
184 * used to get last poll data of counter
188 * values list - maintain across counters since
189 * host/plugin/plugin instance are always the same
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.
200 char ds_name[DATA_MAX_NAME_LEN];
205 /******* network I/O *******/
208 CSTATE_UNCONNECTED = 0,
209 CSTATE_WRITE_REQUEST,
217 ASOK_REQ_VERSION = 0,
220 ASOK_REQ_NONE = 1000,
225 /** The Ceph daemon that we're talking to */
226 struct ceph_daemon *d;
229 uint32_t request_type;
231 /** The connection state */
234 /** The socket we use to talk to this daemon */
237 /** The amount of data remaining to read / write. */
240 /** Length of the JSON to read */
243 /** Buffer containing JSON data */
246 /** Keep data important to yajl processing */
247 struct yajl_struct yajl;
250 static int ceph_cb_null(void *ctx)
252 return CEPH_CB_CONTINUE;
255 static int ceph_cb_boolean(void *ctx, int bool_val)
257 return CEPH_CB_CONTINUE;
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'; \
267 ceph_cb_number(void *ctx, const char *number_val, yajl_len_t number_len)
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;
276 memcpy(buffer, number_val, number_len);
277 buffer[sizeof(buffer) - 1] = '\0';
279 for (size_t i = 0; i < state->depth; i++)
281 if (state->stack[i] == NULL)
284 if (strlen (key) != 0)
285 BUFFER_ADD (key, ".");
286 BUFFER_ADD (key, state->stack[i]);
289 /* Special case for latency metrics. */
290 if ((strcmp ("avgcount", state->key) == 0)
291 || (strcmp ("sum", state->key) == 0))
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
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))
307 DEBUG("ceph plugin: Skipping avgcount for filestore.JournalWrBytes");
308 return CEPH_CB_CONTINUE;
311 else /* not a latency type */
313 BUFFER_ADD (key, ".");
314 BUFFER_ADD (key, state->key);
317 status = state->handler(state->handler_arg, buffer, key);
318 if((status == RETRY_AVGCOUNT) && latency_type)
320 /* Add previously skipped part of the key, either "avgcount" or "sum",
322 BUFFER_ADD (key, ".");
323 BUFFER_ADD (key, state->key);
325 status = state->handler(state->handler_arg, buffer, key);
330 ERROR("ceph plugin: JSON handler failed with status %d.", status);
331 return CEPH_CB_ABORT;
334 return CEPH_CB_CONTINUE;
337 static int ceph_cb_string(void *ctx, const unsigned char *string_val,
338 yajl_len_t string_len)
340 return CEPH_CB_CONTINUE;
343 static int ceph_cb_start_map(void *ctx)
345 yajl_struct *state = (yajl_struct*) ctx;
347 /* Push key to the stack */
348 if (state->depth == YAJL_MAX_DEPTH)
349 return CEPH_CB_ABORT;
351 state->stack[state->depth] = state->key;
355 return CEPH_CB_CONTINUE;
358 static int ceph_cb_end_map(void *ctx)
360 yajl_struct *state = (yajl_struct*) ctx;
362 /* Pop key from the stack */
363 if (state->depth == 0)
364 return CEPH_CB_ABORT;
368 state->key = state->stack[state->depth];
369 state->stack[state->depth] = NULL;
371 return CEPH_CB_CONTINUE;
375 ceph_cb_map_key(void *ctx, const unsigned char *key, yajl_len_t string_len)
377 yajl_struct *state = (yajl_struct*) ctx;
378 size_t sz = ((size_t) string_len) + 1;
381 state->key = malloc (sz);
382 if (state->key == NULL)
384 ERROR ("ceph plugin: malloc failed.");
385 return CEPH_CB_ABORT;
388 memmove (state->key, key, sz - 1);
389 state->key[sz - 1] = 0;
391 return CEPH_CB_CONTINUE;
394 static int ceph_cb_start_array(void *ctx)
396 return CEPH_CB_CONTINUE;
399 static int ceph_cb_end_array(void *ctx)
401 return CEPH_CB_CONTINUE;
404 static yajl_callbacks callbacks = {
418 static void ceph_daemon_print(const struct ceph_daemon *d)
420 DEBUG("ceph plugin: name=%s, asok_path=%s", d->name, d->asok_path);
423 static void ceph_daemons_print(void)
425 for(int i = 0; i < g_num_daemons; ++i)
427 ceph_daemon_print(g_daemons[i]);
431 static void ceph_daemon_free(struct ceph_daemon *d)
433 for(int i = 0; i < d->last_idx; i++)
435 sfree(d->last_poll_data[i]);
437 sfree(d->last_poll_data);
438 d->last_poll_data = NULL;
441 for(int i = 0; i < d->ds_num; i++)
443 sfree(d->ds_names[i]);
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
454 static int compact_ds_name (char *buffer, size_t buffer_size, char const *src)
459 size_t ptr_size = buffer_size;
460 _Bool append_plus = 0;
461 _Bool append_minus = 0;
463 if ((buffer == NULL) || (buffer_size <= strlen ("Minus")) || (src == NULL))
466 src_copy = strdup (src);
467 src_len = strlen(src);
469 /* Remove trailing "+" and "-". */
470 if (src_copy[src_len - 1] == '+')
474 src_copy[src_len] = 0;
476 else if (src_copy[src_len - 1] == '-')
480 src_copy[src_len] = 0;
483 /* Split at special chars, capitalize first character, append to buffer. */
484 char *dummy = src_copy;
486 char *save_ptr = NULL;
487 while ((token = strtok_r (dummy, ":_-+", &save_ptr)) != NULL)
493 token[0] = toupper ((int) token[0]);
495 assert (ptr_size > 1);
497 len = strlen (token);
502 assert (len < ptr_size);
504 sstrncpy (ptr, token, len + 1);
513 /* Append "Plus" or "Minus" if "+" or "-" has been stripped above. */
514 if (append_plus || append_minus)
516 char const *append = "Plus";
520 size_t offset = buffer_size - (strlen (append) + 1);
521 if (offset > strlen (buffer))
522 offset = strlen (buffer);
524 sstrncpy (buffer + offset, append, buffer_size - offset);
531 static _Bool has_suffix (char const *str, char const *suffix)
533 size_t str_len = strlen (str);
534 size_t suffix_len = strlen (suffix);
537 if (suffix_len > str_len)
539 offset = str_len - suffix_len;
541 if (strcmp (str + offset, suffix) == 0)
547 /* count_parts returns the number of elements a "foo.bar.baz" style key has. */
548 static size_t count_parts (char const *key)
550 size_t parts_num = 0;
552 for (const char *ptr = key; ptr != NULL; ptr = strchr (ptr + 1, '.'))
559 * Parse key to remove "type" if this is for schema and initiate compaction
561 static int parse_keys (char *buffer, size_t buffer_size, const char *key_str)
563 char tmp[2 * buffer_size];
565 if (buffer == NULL || buffer_size == 0 || key_str == NULL || strlen (key_str) == 0)
568 if ((count_parts (key_str) > 2) && has_suffix (key_str, ".type"))
570 /* strip ".type" suffix iff the key has more than two parts. */
571 size_t sz = strlen (key_str) - strlen (".type") + 1;
573 if (sz > sizeof (tmp))
575 sstrncpy (tmp, key_str, sz);
579 sstrncpy (tmp, key_str, sizeof (tmp));
582 return compact_ds_name (buffer, buffer_size, tmp);
586 * while parsing ceph admin socket schema, save counter name and type for later
589 static int ceph_daemon_add_ds_entry(struct ceph_daemon *d, const char *name,
593 char ds_name[DATA_MAX_NAME_LEN];
595 if(convert_special_metrics)
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.
605 if((strcmp(name,"filestore.journal_wr_bytes.type") == 0))
611 d->ds_names = realloc(d->ds_names, sizeof(char *) * (d->ds_num + 1));
617 d->ds_types = realloc(d->ds_types, sizeof(uint32_t) * (d->ds_num + 1));
623 d->ds_names[d->ds_num] = malloc(DATA_MAX_NAME_LEN);
624 if(!d->ds_names[d->ds_num])
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;
633 if (parse_keys(ds_name, sizeof (ds_name), name))
638 sstrncpy(d->ds_names[d->ds_num], ds_name, DATA_MAX_NAME_LEN -1);
639 d->ds_num = (d->ds_num + 1);
644 /******* ceph_config *******/
645 static int cc_handle_str(struct oconfig_item_s *item, char *dest, int dest_len)
648 if(item->values_num != 1)
652 if(item->values[0].type != OCONFIG_TYPE_STRING)
656 val = item->values[0].value.string;
657 if(snprintf(dest, dest_len, "%s", val) > (dest_len - 1))
659 ERROR("ceph plugin: configuration parameter '%s' is too long.\n",
661 return -ENAMETOOLONG;
666 static int cc_handle_bool(struct oconfig_item_s *item, int *dest)
668 if(item->values_num != 1)
673 if(item->values[0].type != OCONFIG_TYPE_BOOLEAN)
678 *dest = (item->values[0].value.boolean) ? 1 : 0;
682 static int cc_add_daemon_config(oconfig_item_t *ci)
685 struct ceph_daemon *nd, cd = { 0 };
686 struct ceph_daemon **tmp;
688 if((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
690 WARNING("ceph plugin: `Daemon' blocks need exactly one string "
695 ret = cc_handle_str(ci, cd.name, DATA_MAX_NAME_LEN);
701 for(int i=0; i < ci->children_num; i++)
703 oconfig_item_t *child = ci->children + i;
705 if(strcasecmp("SocketPath", child->key) == 0)
707 ret = cc_handle_str(child, cd.asok_path, sizeof(cd.asok_path));
715 WARNING("ceph plugin: ignoring unknown option %s", child->key);
718 if(cd.name[0] == '\0')
720 ERROR("ceph plugin: you must configure a daemon name.\n");
723 else if(cd.asok_path[0] == '\0')
725 ERROR("ceph plugin(name=%s): you must configure an administrative "
726 "socket path.\n", cd.name);
729 else if(!((cd.asok_path[0] == '/') ||
730 (cd.asok_path[0] == '.' && cd.asok_path[1] == '/')))
732 ERROR("ceph plugin(name=%s): administrative socket paths must begin "
733 "with '/' or './' Can't parse: '%s'\n", cd.name, cd.asok_path);
737 tmp = realloc(g_daemons, (g_num_daemons+1) * sizeof(*g_daemons));
740 /* The positive return value here indicates that this is a
741 * runtime error, not a configuration error. */
746 nd = malloc(sizeof (*nd));
751 memcpy(nd, &cd, sizeof(*nd));
752 g_daemons[g_num_daemons++] = nd;
756 static int ceph_config(oconfig_item_t *ci)
760 for(int i = 0; i < ci->children_num; ++i)
762 oconfig_item_t *child = ci->children + i;
763 if(strcasecmp("Daemon", child->key) == 0)
765 ret = cc_add_daemon_config(child);
768 ERROR("ceph plugin: Couldn't allocate memory");
773 //process other daemons and ignore this one
777 else if(strcasecmp("LongRunAvgLatency", child->key) == 0)
779 ret = cc_handle_bool(child, &long_run_latency_avg);
785 else if(strcasecmp("ConvertSpecialMetricTypes", child->key) == 0)
787 ret = cc_handle_bool(child, &convert_special_metrics);
795 WARNING("ceph plugin: ignoring unknown option %s", child->key);
802 * Parse JSON and get error message if present
805 traverse_json(const unsigned char *json, uint32_t json_len, yajl_handle hand)
807 yajl_status status = yajl_parse(hand, json, json_len);
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);
819 case yajl_status_client_canceled:
827 * Add entry for each counter while parsing schema
830 node_handler_define_schema(void *arg, const char *val, const char *key)
832 struct ceph_daemon *d = (struct ceph_daemon *) arg;
835 return ceph_daemon_add_ds_entry(d, key, pc_type);
839 * Latency counter does not yet have an entry in last poll data - add it.
841 static int add_last(struct ceph_daemon *d, const char *ds_n, double cur_sum,
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])
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);
858 * Update latency counter or add new entry if it doesn't exist
860 static int update_last(struct ceph_daemon *d, const char *ds_n, int index,
861 double cur_sum, uint64_t cur_count)
863 if((d->last_idx > index) && (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0))
865 d->last_poll_data[index]->last_sum = cur_sum;
866 d->last_poll_data[index]->last_count = cur_count;
870 if(!d->last_poll_data)
872 d->last_poll_data = malloc(sizeof (*d->last_poll_data));
873 if(!d->last_poll_data)
880 struct last_data **tmp_last = realloc(d->last_poll_data,
881 ((d->last_idx+1) * sizeof(struct last_data *)));
886 d->last_poll_data = tmp_last;
888 return add_last(d, ds_n, cur_sum, cur_count);
892 * If using index guess failed (shouldn't happen, but possible if counters
893 * get rearranged), resort to searching for counter name
895 static int backup_search_for_last_avg(struct ceph_daemon *d, const char *ds_n)
897 for(int i = 0; i < d->last_idx; i++)
899 if(strcmp(d->last_poll_data[i]->ds_name, ds_n) == 0)
908 * Calculate average b/t current data and last poll data
909 * if last poll data exists
911 static double get_last_avg(struct ceph_daemon *d, const char *ds_n, int index,
912 double cur_sum, uint64_t cur_count)
914 double result = -1.1, sum_delt = 0.0;
915 uint64_t count_delt = 0;
917 if(d->last_idx > index)
919 if(strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0)
923 //test previous index
924 else if((index > 0) && (strcmp(d->last_poll_data[index-1]->ds_name, ds_n) == 0))
926 tmp_index = (index - 1);
930 tmp_index = backup_search_for_last_avg(d, ds_n);
933 if((tmp_index > -1) && (cur_count > d->last_poll_data[tmp_index]->last_count))
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);
945 if(update_last(d, ds_n, tmp_index, cur_sum, cur_count) == -ENOMEM)
953 * If using index guess failed, resort to searching for counter name
955 static uint32_t backup_search_for_type(struct ceph_daemon *d, char *ds_name)
957 for(int i = 0; i < d->ds_num; i++)
959 if(strcmp(d->ds_names[i], ds_name) == 0)
961 return d->ds_types[i];
964 return DSET_TYPE_UNFOUND;
968 * Process counter data and dispatch values
970 static int node_handler_fetch_data(void *arg, const char *val, const char *key)
975 struct values_tmp *vtmp = (struct values_tmp*) arg;
976 uint32_t type = DSET_TYPE_UNFOUND;
977 int index = vtmp->index;
979 char ds_name[DATA_MAX_NAME_LEN];
981 if (parse_keys (ds_name, sizeof (ds_name), key))
986 if(index >= vtmp->d->ds_num)
988 //don't overflow bounds of array
989 index = (vtmp->d->ds_num - 1);
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
998 if(strcmp(ds_name, vtmp->d->ds_names[index]) == 0)
1001 type = vtmp->d->ds_types[index];
1003 else if((index > 0) && (strcmp(ds_name, vtmp->d->ds_names[index-1]) == 0))
1006 type = vtmp->d->ds_types[index-1];
1009 if(type == DSET_TYPE_UNFOUND)
1011 //couldn't find right type by guessing, check the old way
1012 type = backup_search_for_type(vtmp->d, ds_name);
1018 if(vtmp->avgcount_exists == -1)
1020 sscanf(val, "%" PRIu64, &vtmp->avgcount);
1021 vtmp->avgcount_exists = 0;
1022 //return after saving avgcount - don't dispatch value
1023 //until latency calculation
1029 sscanf(val, "%lf", &sum);
1031 if(vtmp->avgcount == 0)
1036 /** User wants latency values as long run avg */
1037 if(long_run_latency_avg)
1039 result = (sum / vtmp->avgcount);
1043 result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum, vtmp->avgcount);
1044 if(result == -ENOMEM)
1051 vtmp->avgcount_exists = -1;
1052 vtmp->latency_index = (vtmp->latency_index + 1);
1056 sscanf(val, "%lf", &tmp_d);
1060 sscanf(val, "%" PRIu64, &tmp_u);
1063 case DSET_TYPE_UNFOUND:
1065 ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);
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;
1074 vtmp->index = (vtmp->index + 1);
1075 plugin_dispatch_values(&vtmp->vlist);
1080 static int cconn_connect(struct cconn *io)
1082 struct sockaddr_un address = { 0 };
1084 if(io->state != CSTATE_UNCONNECTED)
1086 ERROR("ceph plugin: cconn_connect: io->state != CSTATE_UNCONNECTED");
1089 fd = socket(PF_UNIX, SOCK_STREAM, 0);
1093 ERROR("ceph plugin: cconn_connect: socket(PF_UNIX, SOCK_STREAM, 0) "
1094 "failed: error %d", err);
1097 address.sun_family = AF_UNIX;
1098 snprintf(address.sun_path, sizeof(address.sun_path), "%s",
1101 connect(fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)));
1104 ERROR("ceph plugin: cconn_connect: connect(%d) failed: error %d",
1110 flags = fcntl(fd, F_GETFL, 0);
1111 if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0)
1114 ERROR("ceph plugin: cconn_connect: fcntl(%d, O_NONBLOCK) error %d",
1120 io->state = CSTATE_WRITE_REQUEST;
1127 static void cconn_close(struct cconn *io)
1129 io->state = CSTATE_UNCONNECTED;
1133 RETRY_ON_EINTR(res, close(io->asok));
1142 /* Process incoming JSON counter data */
1144 cconn_process_data(struct cconn *io, yajl_struct *yajl, yajl_handle hand)
1147 struct values_tmp *vtmp = calloc(1, sizeof(struct values_tmp) * 1);
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));
1159 vtmp->avgcount_exists = -1;
1160 vtmp->latency_index = 0;
1162 yajl->handler_arg = vtmp;
1163 ret = traverse_json(io->json, io->json_len, hand);
1169 * Initiate JSON parsing and print error if one occurs
1171 static int cconn_process_json(struct cconn *io)
1173 if((io->request_type != ASOK_REQ_DATA) &&
1174 (io->request_type != ASOK_REQ_SCHEMA))
1183 hand = yajl_alloc(&callbacks,
1185 /* alloc funcs = */ NULL,
1187 /* alloc funcs = */ NULL, NULL,
1189 /* context = */ (void *)(&io->yajl));
1193 ERROR ("ceph plugin: yajl_alloc failed.");
1199 switch(io->request_type)
1202 io->yajl.handler = node_handler_fetch_data;
1203 result = cconn_process_data(io, &io->yajl, hand);
1205 case ASOK_REQ_SCHEMA:
1206 //init daemon specific variables
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);
1222 status = yajl_complete_parse(hand);
1224 status = yajl_parse_complete(hand);
1227 if (status != yajl_status_ok)
1229 unsigned char *errmsg = yajl_get_error (hand, /* verbose = */ 0,
1230 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
1231 ERROR ("ceph plugin: yajl_parse_complete failed: %s",
1233 yajl_free_error (hand, errmsg);
1243 static int cconn_validate_revents(struct cconn *io, int revents)
1245 if(revents & POLLERR)
1247 ERROR("ceph plugin: cconn_validate_revents(name=%s): got POLLERR",
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;
1260 ERROR("ceph plugin: cconn_validate_revents(name=%s) got to "
1261 "illegal state on line %d", io->d->name, __LINE__);
1266 /** Handle a network event for a connection */
1267 static int cconn_handle_event(struct cconn *io)
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__);
1277 case CSTATE_WRITE_REQUEST:
1280 snprintf(cmd, sizeof(cmd), "%s%d%s", "{ \"prefix\": \"",
1281 io->request_type, "\" }\n");
1282 size_t cmd_len = strlen(cmd);
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);
1292 if(io->amt >= cmd_len)
1295 switch (io->request_type)
1297 case ASOK_REQ_VERSION:
1298 io->state = CSTATE_READ_VERSION;
1301 io->state = CSTATE_READ_AMT;
1307 case CSTATE_READ_VERSION:
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);
1319 if(io->amt >= sizeof(io->d->version))
1321 io->d->version = ntohl(io->d->version);
1322 if(io->d->version != 1)
1324 ERROR("ceph plugin: cconn_handle_event(name=%s) not "
1325 "expecting version %d!", io->d->name, io->d->version);
1328 DEBUG("ceph plugin: cconn_handle_event(name=%s): identified as "
1329 "version %d", io->d->name, io->d->version);
1332 io->request_type = ASOK_REQ_SCHEMA;
1336 case CSTATE_READ_AMT:
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);
1348 if(io->amt >= sizeof(io->json_len))
1350 io->json_len = ntohl(io->json_len);
1352 io->state = CSTATE_READ_JSON;
1353 io->json = calloc(1, io->json_len + 1);
1356 ERROR("ceph plugin: error callocing io->json");
1362 case CSTATE_READ_JSON:
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);
1373 if(io->amt >= io->json_len)
1375 ret = cconn_process_json(io);
1381 io->request_type = ASOK_REQ_NONE;
1386 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1387 "state on line %d", io->d->name, __LINE__);
1392 static int cconn_prepare(struct cconn *io, struct pollfd* fds)
1395 if(io->request_type == ASOK_REQ_NONE)
1397 /* The request has already been serviced. */
1400 else if((io->request_type == ASOK_REQ_DATA) && (io->d->ds_num == 0))
1402 /* If there are no counters to report on, don't bother
1409 case CSTATE_UNCONNECTED:
1410 ret = cconn_connect(io);
1420 fds->events = POLLOUT;
1422 case CSTATE_WRITE_REQUEST:
1424 fds->events = POLLOUT;
1426 case CSTATE_READ_VERSION:
1427 case CSTATE_READ_AMT:
1428 case CSTATE_READ_JSON:
1430 fds->events = POLLIN;
1433 ERROR("ceph plugin: cconn_prepare(name=%s) got to illegal state "
1434 "on line %d", io->d->name, __LINE__);
1439 /** Returns the difference between two struct timevals in milliseconds.
1440 * On overflow, we return max/min int.
1442 static int milli_diff(const struct timeval *t1, const struct timeval *t2)
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);
1452 /** This handles the actual network I/O to talk to the Ceph daemons.
1454 static int cconn_main_loop(uint32_t request_type)
1456 int ret, some_unreachable = 0;
1457 struct timeval end_tv;
1458 struct cconn io_array[g_num_daemons];
1460 DEBUG("ceph plugin: entering cconn_main_loop(request_type = %d)", request_type);
1462 /* create cconn array */
1463 memset(io_array, 0, sizeof(io_array));
1464 for(int i = 0; i < g_num_daemons; ++i)
1466 io_array[i].d = g_daemons[i];
1467 io_array[i].request_type = request_type;
1468 io_array[i].state = CSTATE_UNCONNECTED;
1471 /** Calculate the time at which we should give up */
1472 gettimeofday(&end_tv, NULL);
1473 end_tv.tv_sec += CEPH_TIMEOUT_INTERVAL;
1479 struct cconn *polled_io_array[g_num_daemons];
1480 struct pollfd fds[g_num_daemons];
1481 memset(fds, 0, sizeof(fds));
1483 for(int i = 0; i < g_num_daemons; ++i)
1485 struct cconn *io = io_array + i;
1486 ret = cconn_prepare(io, fds + nfds);
1489 WARNING("ceph plugin: cconn_prepare(name=%s,i=%d,st=%d)=%d",
1490 io->d->name, i, io->state, ret);
1492 io->request_type = ASOK_REQ_NONE;
1493 some_unreachable = 1;
1497 polled_io_array[nfds++] = io_array + i;
1506 gettimeofday(&tv, NULL);
1507 diff = milli_diff(&end_tv, &tv);
1512 WARNING("ceph plugin: cconn_main_loop: timed out.");
1515 RETRY_ON_EINTR(ret, poll(fds, nfds, diff));
1518 ERROR("ceph plugin: poll(2) error: %d", ret);
1521 for(int i = 0; i < nfds; ++i)
1523 struct cconn *io = polled_io_array[i];
1524 int revents = fds[i].revents;
1529 else if(cconn_validate_revents(io, revents))
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);
1535 io->request_type = ASOK_REQ_NONE;
1536 some_unreachable = 1;
1540 ret = cconn_handle_event(io);
1543 WARNING("ceph plugin: cconn_handle_event(name=%s,"
1544 "i=%d,st=%d): error %d", io->d->name, i, io->state, ret);
1546 io->request_type = ASOK_REQ_NONE;
1547 some_unreachable = 1;
1552 done: for(int i = 0; i < g_num_daemons; ++i)
1554 cconn_close(io_array + i);
1556 if(some_unreachable)
1558 DEBUG("ceph plugin: cconn_main_loop: some Ceph daemons were unreachable.");
1562 DEBUG("ceph plugin: cconn_main_loop: reached all Ceph daemons :)");
1567 static int ceph_read(void)
1569 return cconn_main_loop(ASOK_REQ_DATA);
1572 /******* lifecycle *******/
1573 static int ceph_init(void)
1576 ceph_daemons_print();
1578 ret = cconn_main_loop(ASOK_REQ_VERSION);
1580 return (ret) ? ret : 0;
1583 static int ceph_shutdown(void)
1585 for(int i = 0; i < g_num_daemons; ++i)
1587 ceph_daemon_free(g_daemons[i]);
1592 DEBUG("ceph plugin: finished ceph_shutdown");
1596 void module_register(void)
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);
1603 /* vim: set sw=4 sts=4 et : */