2 * collectd - src/ceph.c
3 * Copyright (C) 2011 New Dream Network
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Colin McCabe <cmccabe@alumni.cmu.edu>
20 * Dennis Zou <yunzou@cisco.com>
21 * Dan Ryder <daryder@cisco.com>
24 #define _DEFAULT_SOURCE
31 #include <arpa/inet.h>
34 #include <yajl/yajl_parse.h>
35 #if HAVE_YAJL_YAJL_VERSION_H
36 #include <yajl/yajl_version.h>
47 #include <sys/types.h>
53 #define RETRY_AVGCOUNT -1
55 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
56 # define HAVE_YAJL_V2 1
59 #define RETRY_ON_EINTR(ret, expr) \
69 /** Timeout interval in seconds */
70 #define CEPH_TIMEOUT_INTERVAL 1
72 /** Maximum path length for a UNIX domain socket on this system */
73 #define UNIX_DOMAIN_SOCK_PATH_MAX (sizeof(((struct sockaddr_un*)0)->sun_path))
75 /** Yajl callback returns */
76 #define CEPH_CB_CONTINUE 1
77 #define CEPH_CB_ABORT 0
80 typedef size_t yajl_len_t;
82 typedef unsigned int yajl_len_t;
85 /** Number of types for ceph defined in types.db */
86 #define CEPH_DSET_TYPES_NUM 3
87 /** ceph types enum */
93 DSET_TYPE_UNFOUND = 1000
96 /** Valid types for ceph defined in types.db */
97 const char * ceph_dset_types [CEPH_DSET_TYPES_NUM] =
98 {"ceph_latency", "ceph_bytes", "ceph_rate"};
100 /******* ceph_daemon *******/
103 /** Version of the admin_socket interface */
106 char name[DATA_MAX_NAME_LEN];
108 /** Path to the socket that we use to talk to the ceph daemon */
109 char asok_path[UNIX_DOMAIN_SOCK_PATH_MAX];
111 /** Number of counters */
113 /** Track ds types */
115 /** Track ds names to match with types */
119 * Keep track of last data for latency values so we can calculate rate
122 struct last_data **last_poll_data;
123 /** index of last poll data */
127 /******* JSON parsing *******/
128 typedef int (*node_handler_t)(void *, const char*, const char*);
130 /** Track state and handler while parsing JSON */
133 node_handler_t handler;
136 char key[DATA_MAX_NAME_LEN];
138 } state[YAJL_MAX_DEPTH];
141 typedef struct yajl_struct yajl_struct;
143 enum perfcounter_type_d
145 PERFCOUNTER_LATENCY = 0x4, PERFCOUNTER_DERIVE = 0x8,
148 /** Give user option to use default (long run = since daemon started) avg */
149 static int long_run_latency_avg = 0;
152 * Give user option to use default type for special cases -
153 * filestore.journal_wr_bytes is currently only metric here. Ceph reports the
154 * type as a sum/count pair and will calculate it the same as a latency value.
155 * All other "bytes" metrics (excluding the used/capacity bytes for the OSD)
156 * use the DERIVE type. Unless user specifies to use given type, convert this
157 * metric to use DERIVE.
159 static int convert_special_metrics = 1;
161 /** Array of daemons to monitor */
162 static struct ceph_daemon **g_daemons = NULL;
164 /** Number of elements in g_daemons */
165 static int g_num_daemons = 0;
168 * A set of data that we build up in memory while parsing the JSON.
172 /** ceph daemon we are processing data for*/
173 struct ceph_daemon *d;
174 /** track avgcount across counters for avgcount/sum latency pairs */
176 /** current index of counters - used to get type of counter */
178 /** do we already have an avgcount for latency pair */
181 * similar to index, but current index of latency type counters -
182 * used to get last poll data of counter
186 * values list - maintain across counters since
187 * host/plugin/plugin instance are always the same
193 * A set of count/sum pairs to keep track of latency types and get difference
194 * between this poll data and last poll data.
198 char ds_name[DATA_MAX_NAME_LEN];
203 /******* network I/O *******/
206 CSTATE_UNCONNECTED = 0,
207 CSTATE_WRITE_REQUEST,
215 ASOK_REQ_VERSION = 0,
218 ASOK_REQ_NONE = 1000,
223 /** The Ceph daemon that we're talking to */
224 struct ceph_daemon *d;
227 uint32_t request_type;
229 /** The connection state */
232 /** The socket we use to talk to this daemon */
235 /** The amount of data remaining to read / write. */
238 /** Length of the JSON to read */
241 /** Buffer containing JSON data */
244 /** Keep data important to yajl processing */
245 struct yajl_struct yajl;
248 static int ceph_cb_null(void *ctx)
250 return CEPH_CB_CONTINUE;
253 static int ceph_cb_boolean(void *ctx, int bool_val)
255 return CEPH_CB_CONTINUE;
259 ceph_cb_number(void *ctx, const char *number_val, yajl_len_t number_len)
261 yajl_struct *yajl = (yajl_struct*)ctx;
262 char buffer[number_len+1];
263 int i, latency_type = 0, result;
266 memcpy(buffer, number_val, number_len);
267 buffer[sizeof(buffer) - 1] = 0;
269 ssnprintf(key, yajl->state[0].key_len, "%s", yajl->state[0].key);
270 for(i = 1; i < yajl->depth; i++)
272 if((i == yajl->depth-1) && ((strcmp(yajl->state[i].key,"avgcount") == 0)
273 || (strcmp(yajl->state[i].key,"sum") == 0)))
275 if(convert_special_metrics)
278 * Special case for filestore:JournalWrBytes. For some reason,
279 * Ceph schema encodes this as a count/sum pair while all
280 * other "Bytes" data (excluding used/capacity bytes for OSD
281 * space) uses a single "Derive" type. To spare further
282 * confusion, keep this KPI as the same type of other "Bytes".
283 * Instead of keeping an "average" or "rate", use the "sum" in
284 * the pair and assign that to the derive value.
286 if((strcmp(yajl->state[i-1].key, "journal_wr_bytes") == 0) &&
287 (strcmp(yajl->state[i-2].key,"filestore") == 0) &&
288 (strcmp(yajl->state[i].key,"avgcount") == 0))
290 DEBUG("ceph plugin: Skipping avgcount for filestore.JournalWrBytes");
291 yajl->depth = (yajl->depth - 1);
292 return CEPH_CB_CONTINUE;
295 //probably a avgcount/sum pair. if not - we'll try full key later
299 strncat(key, ".", 1);
300 strncat(key, yajl->state[i].key, yajl->state[i].key_len+1);
303 result = yajl->handler(yajl->handler_arg, buffer, key);
305 if((result == RETRY_AVGCOUNT) && latency_type)
307 strncat(key, ".", 1);
308 strncat(key, yajl->state[yajl->depth-1].key,
309 yajl->state[yajl->depth-1].key_len+1);
310 result = yajl->handler(yajl->handler_arg, buffer, key);
313 if(result == -ENOMEM)
315 ERROR("ceph plugin: memory allocation failed");
316 return CEPH_CB_ABORT;
319 yajl->depth = (yajl->depth - 1);
320 return CEPH_CB_CONTINUE;
323 static int ceph_cb_string(void *ctx, const unsigned char *string_val,
324 yajl_len_t string_len)
326 return CEPH_CB_CONTINUE;
329 static int ceph_cb_start_map(void *ctx)
331 return CEPH_CB_CONTINUE;
335 ceph_cb_map_key(void *ctx, const unsigned char *key, yajl_len_t string_len)
337 yajl_struct *yajl = (yajl_struct*)ctx;
339 if((yajl->depth+1) >= YAJL_MAX_DEPTH)
341 ERROR("ceph plugin: depth exceeds max, aborting.");
342 return CEPH_CB_ABORT;
345 char buffer[string_len+1];
347 memcpy(buffer, key, string_len);
348 buffer[sizeof(buffer) - 1] = 0;
350 snprintf(yajl->state[yajl->depth].key, sizeof(buffer), "%s", buffer);
351 yajl->state[yajl->depth].key_len = sizeof(buffer);
352 yajl->depth = (yajl->depth + 1);
354 return CEPH_CB_CONTINUE;
357 static int ceph_cb_end_map(void *ctx)
359 yajl_struct *yajl = (yajl_struct*)ctx;
361 yajl->depth = (yajl->depth - 1);
362 return CEPH_CB_CONTINUE;
365 static int ceph_cb_start_array(void *ctx)
367 return CEPH_CB_CONTINUE;
370 static int ceph_cb_end_array(void *ctx)
372 return CEPH_CB_CONTINUE;
375 static yajl_callbacks callbacks = {
389 static void ceph_daemon_print(const struct ceph_daemon *d)
391 DEBUG("ceph plugin: name=%s, asok_path=%s", d->name, d->asok_path);
394 static void ceph_daemons_print(void)
397 for(i = 0; i < g_num_daemons; ++i)
399 ceph_daemon_print(g_daemons[i]);
403 static void ceph_daemon_free(struct ceph_daemon *d)
406 for(; i < d->last_idx; i++)
408 sfree(d->last_poll_data[i]);
410 sfree(d->last_poll_data);
411 d->last_poll_data = NULL;
413 for(i = 0; i < d->ds_num; i++)
415 sfree(d->ds_names[i]);
423 * Compact ds name by removing special characters and trimming length to
424 * DATA_MAX_NAME_LEN if necessary
426 static void compact_ds_name(char *source, char *dest)
429 char *save_ptr = NULL, *tmp_ptr = source;
432 char tmp[DATA_MAX_NAME_LEN];
433 size_t key_chars_remaining = (DATA_MAX_NAME_LEN-1);
436 memset(tmp, 0, sizeof(tmp));
437 if(source == NULL || dest == NULL || source[0] == '\0' || dest[0] != '\0')
441 size_t src_len = strlen(source);
442 snprintf(len_str, sizeof(len_str), "%zu", src_len);
443 unsigned char append_status = 0x0;
444 append_status |= (source[src_len - 1] == '-') ? 0x1 : 0x0;
445 append_status |= (source[src_len - 1] == '+') ? 0x2 : 0x0;
446 while ((keys[keys_num] = strtok_r(tmp_ptr, ":_-+", &save_ptr)) != NULL)
449 /** capitalize 1st char **/
450 keys[keys_num][0] = toupper(keys[keys_num][0]);
457 /** concatenate each part of source string **/
458 for(i = 0; i < keys_num; i++)
460 strncat(tmp, keys[i], key_chars_remaining);
461 key_chars_remaining -= strlen(keys[i]);
463 tmp[DATA_MAX_NAME_LEN - 1] = '\0';
464 /** to coordinate limitation of length of type_instance
465 * we will truncate ds_name
466 * when the its length is more than
469 if(strlen(tmp) > DATA_MAX_NAME_LEN - 1)
471 append_status |= 0x4;
472 /** we should reserve space for
477 if(append_status & 0x1)
479 /** we should reserve space for
484 if(append_status & 0x2)
486 /** we should reserve space for
491 snprintf(dest, DATA_MAX_NAME_LEN - reserved, "%s", tmp);
492 offset = strlen(dest);
493 switch (append_status)
496 memcpy(dest + offset, "Minus", 5);
499 memcpy(dest + offset, "Plus", 5);
502 memcpy(dest + offset, len_str, 2);
505 memcpy(dest + offset, "Minus", 5);
506 memcpy(dest + offset + 5, len_str, 2);
509 memcpy(dest + offset, "Plus", 4);
510 memcpy(dest + offset + 4, len_str, 2);
518 * Parse key to remove "type" if this is for schema and initiate compaction
520 static int parse_keys(const char *key_str, char *ds_name)
523 size_t ds_name_len = 0;
525 * allow up to 100 characters before compaction - compact_ds_name will not
526 * allow more than DATA_MAX_NAME_LEN chars
528 int max_str_len = 100;
529 char tmp_ds_name[max_str_len];
530 memset(tmp_ds_name, 0, sizeof(tmp_ds_name));
531 if(ds_name == NULL || key_str == NULL || key_str[0] == '\0' ||
536 if((ptr = strchr(key_str, '.')) == NULL
537 || (rptr = strrchr(key_str, '.')) == NULL)
539 memcpy(tmp_ds_name, key_str, max_str_len - 1);
543 ds_name_len = (rptr - ptr) > max_str_len ? max_str_len : (rptr - ptr);
544 if((ds_name_len == 0) || strncmp(rptr + 1, "type", 4))
545 { /** copy whole key **/
546 memcpy(tmp_ds_name, key_str, max_str_len - 1);
549 {/** more than two keys **/
550 memcpy(tmp_ds_name, key_str, ((rptr - key_str) > (max_str_len - 1) ?
551 (max_str_len - 1) : (rptr - key_str)));
554 compact: compact_ds_name(tmp_ds_name, ds_name);
559 * while parsing ceph admin socket schema, save counter name and type for later
562 static int ceph_daemon_add_ds_entry(struct ceph_daemon *d, const char *name,
566 char ds_name[DATA_MAX_NAME_LEN];
567 memset(ds_name, 0, sizeof(ds_name));
569 if(convert_special_metrics)
572 * Special case for filestore:JournalWrBytes. For some reason, Ceph
573 * schema encodes this as a count/sum pair while all other "Bytes" data
574 * (excluding used/capacity bytes for OSD space) uses a single "Derive"
575 * type. To spare further confusion, keep this KPI as the same type of
576 * other "Bytes". Instead of keeping an "average" or "rate", use the
577 * "sum" in the pair and assign that to the derive value.
579 if((strcmp(name,"filestore.journal_wr_bytes.type") == 0))
585 d->ds_names = realloc(d->ds_names, sizeof(char *) * (d->ds_num + 1));
591 d->ds_types = realloc(d->ds_types, sizeof(uint32_t) * (d->ds_num + 1));
597 d->ds_names[d->ds_num] = malloc(sizeof(char) * DATA_MAX_NAME_LEN);
598 if(!d->ds_names[d->ds_num])
603 type = (pc_type & PERFCOUNTER_DERIVE) ? DSET_RATE :
604 ((pc_type & PERFCOUNTER_LATENCY) ? DSET_LATENCY : DSET_BYTES);
605 d->ds_types[d->ds_num] = type;
607 if(parse_keys(name, ds_name))
612 sstrncpy(d->ds_names[d->ds_num], ds_name, DATA_MAX_NAME_LEN -1);
613 d->ds_num = (d->ds_num + 1);
618 /******* ceph_config *******/
619 static int cc_handle_str(struct oconfig_item_s *item, char *dest, int dest_len)
622 if(item->values_num != 1)
626 if(item->values[0].type != OCONFIG_TYPE_STRING)
630 val = item->values[0].value.string;
631 if(snprintf(dest, dest_len, "%s", val) > (dest_len - 1))
633 ERROR("ceph plugin: configuration parameter '%s' is too long.\n",
635 return -ENAMETOOLONG;
640 static int cc_handle_bool(struct oconfig_item_s *item, int *dest)
642 if(item->values_num != 1)
647 if(item->values[0].type != OCONFIG_TYPE_BOOLEAN)
652 *dest = (item->values[0].value.boolean) ? 1 : 0;
656 static int cc_add_daemon_config(oconfig_item_t *ci)
659 struct ceph_daemon *nd, cd;
660 struct ceph_daemon **tmp;
661 memset(&cd, 0, sizeof(struct ceph_daemon));
663 if((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
665 WARNING("ceph plugin: `Daemon' blocks need exactly one string "
670 ret = cc_handle_str(ci, cd.name, DATA_MAX_NAME_LEN);
676 for(i=0; i < ci->children_num; i++)
678 oconfig_item_t *child = ci->children + i;
680 if(strcasecmp("SocketPath", child->key) == 0)
682 ret = cc_handle_str(child, cd.asok_path, sizeof(cd.asok_path));
690 WARNING("ceph plugin: ignoring unknown option %s", child->key);
693 if(cd.name[0] == '\0')
695 ERROR("ceph plugin: you must configure a daemon name.\n");
698 else if(cd.asok_path[0] == '\0')
700 ERROR("ceph plugin(name=%s): you must configure an administrative "
701 "socket path.\n", cd.name);
704 else if(!((cd.asok_path[0] == '/') ||
705 (cd.asok_path[0] == '.' && cd.asok_path[1] == '/')))
707 ERROR("ceph plugin(name=%s): administrative socket paths must begin "
708 "with '/' or './' Can't parse: '%s'\n", cd.name, cd.asok_path);
712 tmp = realloc(g_daemons, (g_num_daemons+1) * sizeof(*g_daemons));
715 /* The positive return value here indicates that this is a
716 * runtime error, not a configuration error. */
721 nd = malloc(sizeof(*nd));
726 memcpy(nd, &cd, sizeof(*nd));
727 g_daemons[g_num_daemons++] = nd;
731 static int ceph_config(oconfig_item_t *ci)
735 for(i = 0; i < ci->children_num; ++i)
737 oconfig_item_t *child = ci->children + i;
738 if(strcasecmp("Daemon", child->key) == 0)
740 ret = cc_add_daemon_config(child);
743 ERROR("ceph plugin: Couldn't allocate memory");
748 //process other daemons and ignore this one
752 else if(strcasecmp("LongRunAvgLatency", child->key) == 0)
754 ret = cc_handle_bool(child, &long_run_latency_avg);
760 else if(strcasecmp("ConvertSpecialMetricTypes", child->key) == 0)
762 ret = cc_handle_bool(child, &convert_special_metrics);
770 WARNING("ceph plugin: ignoring unknown option %s", child->key);
777 * Parse JSON and get error message if present
780 traverse_json(const unsigned char *json, uint32_t json_len, yajl_handle hand)
782 yajl_status status = yajl_parse(hand, json, json_len);
787 case yajl_status_error:
788 msg = yajl_get_error(hand, /* verbose = */ 1,
789 /* jsonText = */ (unsigned char *) json,
790 (unsigned int) json_len);
791 ERROR ("ceph plugin: yajl_parse failed: %s", msg);
792 yajl_free_error(hand, msg);
794 case yajl_status_client_canceled:
802 * Add entry for each counter while parsing schema
805 node_handler_define_schema(void *arg, const char *val, const char *key)
807 struct ceph_daemon *d = (struct ceph_daemon *) arg;
810 return ceph_daemon_add_ds_entry(d, key, pc_type);
814 * Latency counter does not yet have an entry in last poll data - add it.
816 static int add_last(struct ceph_daemon *d, const char *ds_n, double cur_sum,
819 d->last_poll_data[d->last_idx] = malloc(1 * sizeof(struct last_data));
820 if(!d->last_poll_data[d->last_idx])
824 sstrncpy(d->last_poll_data[d->last_idx]->ds_name,ds_n,
825 sizeof(d->last_poll_data[d->last_idx]->ds_name));
826 d->last_poll_data[d->last_idx]->last_sum = cur_sum;
827 d->last_poll_data[d->last_idx]->last_count = cur_count;
828 d->last_idx = (d->last_idx + 1);
833 * Update latency counter or add new entry if it doesn't exist
835 static int update_last(struct ceph_daemon *d, const char *ds_n, int index,
836 double cur_sum, uint64_t cur_count)
838 if((d->last_idx > index) && (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0))
840 d->last_poll_data[index]->last_sum = cur_sum;
841 d->last_poll_data[index]->last_count = cur_count;
845 if(!d->last_poll_data)
847 d->last_poll_data = malloc(1 * sizeof(struct last_data *));
848 if(!d->last_poll_data)
855 struct last_data **tmp_last = realloc(d->last_poll_data,
856 ((d->last_idx+1) * sizeof(struct last_data *)));
861 d->last_poll_data = tmp_last;
863 return add_last(d, ds_n, cur_sum, cur_count);
867 * If using index guess failed (shouldn't happen, but possible if counters
868 * get rearranged), resort to searching for counter name
870 static int backup_search_for_last_avg(struct ceph_daemon *d, const char *ds_n)
873 for(; i < d->last_idx; i++)
875 if(strcmp(d->last_poll_data[i]->ds_name, ds_n) == 0)
884 * Calculate average b/t current data and last poll data
885 * if last poll data exists
887 static double get_last_avg(struct ceph_daemon *d, const char *ds_n, int index,
888 double cur_sum, uint64_t cur_count)
890 double result = -1.1, sum_delt = 0.0;
891 uint64_t count_delt = 0;
893 if(d->last_idx > index)
895 if(strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0)
899 //test previous index
900 else if((index > 0) && (strcmp(d->last_poll_data[index-1]->ds_name, ds_n) == 0))
902 tmp_index = (index - 1);
906 tmp_index = backup_search_for_last_avg(d, ds_n);
909 if((tmp_index > -1) && (cur_count > d->last_poll_data[tmp_index]->last_count))
911 sum_delt = (cur_sum - d->last_poll_data[tmp_index]->last_sum);
912 count_delt = (cur_count - d->last_poll_data[tmp_index]->last_count);
913 result = (sum_delt / count_delt);
921 if(update_last(d, ds_n, tmp_index, cur_sum, cur_count) == -ENOMEM)
929 * If using index guess failed, resort to searching for counter name
931 static uint32_t backup_search_for_type(struct ceph_daemon *d, char *ds_name)
934 for(; idx < d->ds_num; idx++)
936 if(strcmp(d->ds_names[idx], ds_name) == 0)
938 return d->ds_types[idx];
941 return DSET_TYPE_UNFOUND;
945 * Process counter data and dispatch values
947 static int node_handler_fetch_data(void *arg, const char *val, const char *key)
952 struct values_tmp *vtmp = (struct values_tmp*) arg;
953 uint32_t type = DSET_TYPE_UNFOUND;
954 int index = vtmp->index;
956 char ds_name[DATA_MAX_NAME_LEN];
957 memset(ds_name, 0, sizeof(ds_name));
959 if(parse_keys(key, ds_name))
964 if(index >= vtmp->d->ds_num)
966 //don't overflow bounds of array
967 index = (vtmp->d->ds_num - 1);
971 * counters should remain in same order we parsed schema... we maintain the
972 * index variable to keep track of current point in list of counters. first
973 * use index to guess point in array for retrieving type. if that doesn't
974 * work, use the old way to get the counter type
976 if(strcmp(ds_name, vtmp->d->ds_names[index]) == 0)
979 type = vtmp->d->ds_types[index];
981 else if((index > 0) && (strcmp(ds_name, vtmp->d->ds_names[index-1]) == 0))
984 type = vtmp->d->ds_types[index-1];
987 if(type == DSET_TYPE_UNFOUND)
989 //couldn't find right type by guessing, check the old way
990 type = backup_search_for_type(vtmp->d, ds_name);
996 if(vtmp->avgcount_exists == -1)
998 sscanf(val, "%" PRIu64, &vtmp->avgcount);
999 vtmp->avgcount_exists = 0;
1000 //return after saving avgcount - don't dispatch value
1001 //until latency calculation
1007 sscanf(val, "%lf", &sum);
1009 if(vtmp->avgcount == 0)
1014 /** User wants latency values as long run avg */
1015 if(long_run_latency_avg)
1017 result = (sum / vtmp->avgcount);
1021 result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum, vtmp->avgcount);
1022 if(result == -ENOMEM)
1029 vtmp->avgcount_exists = -1;
1030 vtmp->latency_index = (vtmp->latency_index + 1);
1034 sscanf(val, "%lf", &tmp_d);
1038 sscanf(val, "%" PRIu64, &tmp_u);
1041 case DSET_TYPE_UNFOUND:
1043 ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);
1047 sstrncpy(vtmp->vlist.type, ceph_dset_types[type], sizeof(vtmp->vlist.type));
1048 sstrncpy(vtmp->vlist.type_instance, ds_name, sizeof(vtmp->vlist.type_instance));
1049 vtmp->vlist.values = &uv;
1050 vtmp->vlist.values_len = 1;
1052 vtmp->index = (vtmp->index + 1);
1053 plugin_dispatch_values(&vtmp->vlist);
1058 static int cconn_connect(struct cconn *io)
1060 struct sockaddr_un address;
1062 if(io->state != CSTATE_UNCONNECTED)
1064 ERROR("ceph plugin: cconn_connect: io->state != CSTATE_UNCONNECTED");
1067 fd = socket(PF_UNIX, SOCK_STREAM, 0);
1071 ERROR("ceph plugin: cconn_connect: socket(PF_UNIX, SOCK_STREAM, 0) "
1072 "failed: error %d", err);
1075 memset(&address, 0, sizeof(struct sockaddr_un));
1076 address.sun_family = AF_UNIX;
1077 snprintf(address.sun_path, sizeof(address.sun_path), "%s",
1080 connect(fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)));
1083 ERROR("ceph plugin: cconn_connect: connect(%d) failed: error %d",
1089 flags = fcntl(fd, F_GETFL, 0);
1090 if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0)
1093 ERROR("ceph plugin: cconn_connect: fcntl(%d, O_NONBLOCK) error %d",
1099 io->state = CSTATE_WRITE_REQUEST;
1106 static void cconn_close(struct cconn *io)
1108 io->state = CSTATE_UNCONNECTED;
1112 RETRY_ON_EINTR(res, close(io->asok));
1121 /* Process incoming JSON counter data */
1123 cconn_process_data(struct cconn *io, yajl_struct *yajl, yajl_handle hand)
1126 struct values_tmp *vtmp = calloc(1, sizeof(struct values_tmp) * 1);
1132 vtmp->vlist = (value_list_t)VALUE_LIST_INIT;
1133 sstrncpy(vtmp->vlist.host, hostname_g, sizeof(vtmp->vlist.host));
1134 sstrncpy(vtmp->vlist.plugin, "ceph", sizeof(vtmp->vlist.plugin));
1135 sstrncpy(vtmp->vlist.plugin_instance, io->d->name, sizeof(vtmp->vlist.plugin_instance));
1138 vtmp->avgcount_exists = -1;
1139 vtmp->latency_index = 0;
1141 yajl->handler_arg = vtmp;
1142 ret = traverse_json(io->json, io->json_len, hand);
1148 * Initiate JSON parsing and print error if one occurs
1150 static int cconn_process_json(struct cconn *io)
1152 if((io->request_type != ASOK_REQ_DATA) &&
1153 (io->request_type != ASOK_REQ_SCHEMA))
1162 hand = yajl_alloc(&callbacks,
1164 /* alloc funcs = */ NULL,
1166 /* alloc funcs = */ NULL, NULL,
1168 /* context = */ (void *)(&io->yajl));
1172 ERROR ("ceph plugin: yajl_alloc failed.");
1178 switch(io->request_type)
1181 io->yajl.handler = node_handler_fetch_data;
1182 result = cconn_process_data(io, &io->yajl, hand);
1184 case ASOK_REQ_SCHEMA:
1185 //init daemon specific variables
1187 io->d->last_idx = 0;
1188 io->d->last_poll_data = NULL;
1189 io->yajl.handler = node_handler_define_schema;
1190 io->yajl.handler_arg = io->d;
1191 result = traverse_json(io->json, io->json_len, hand);
1201 status = yajl_complete_parse(hand);
1203 status = yajl_parse_complete(hand);
1206 if (status != yajl_status_ok)
1208 unsigned char *errmsg = yajl_get_error (hand, /* verbose = */ 0,
1209 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
1210 ERROR ("ceph plugin: yajl_parse_complete failed: %s",
1212 yajl_free_error (hand, errmsg);
1222 static int cconn_validate_revents(struct cconn *io, int revents)
1224 if(revents & POLLERR)
1226 ERROR("ceph plugin: cconn_validate_revents(name=%s): got POLLERR",
1232 case CSTATE_WRITE_REQUEST:
1233 return (revents & POLLOUT) ? 0 : -EINVAL;
1234 case CSTATE_READ_VERSION:
1235 case CSTATE_READ_AMT:
1236 case CSTATE_READ_JSON:
1237 return (revents & POLLIN) ? 0 : -EINVAL;
1239 ERROR("ceph plugin: cconn_validate_revents(name=%s) got to "
1240 "illegal state on line %d", io->d->name, __LINE__);
1245 /** Handle a network event for a connection */
1246 static int cconn_handle_event(struct cconn *io)
1251 case CSTATE_UNCONNECTED:
1252 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1253 "state on line %d", io->d->name, __LINE__);
1256 case CSTATE_WRITE_REQUEST:
1259 snprintf(cmd, sizeof(cmd), "%s%d%s", "{ \"prefix\": \"",
1260 io->request_type, "\" }\n");
1261 size_t cmd_len = strlen(cmd);
1263 write(io->asok, ((char*)&cmd) + io->amt, cmd_len - io->amt));
1264 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,amt=%d,ret=%d)",
1265 io->d->name, io->state, io->amt, ret);
1271 if(io->amt >= cmd_len)
1274 switch (io->request_type)
1276 case ASOK_REQ_VERSION:
1277 io->state = CSTATE_READ_VERSION;
1280 io->state = CSTATE_READ_AMT;
1286 case CSTATE_READ_VERSION:
1289 read(io->asok, ((char*)(&io->d->version)) + io->amt,
1290 sizeof(io->d->version) - io->amt));
1291 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1292 io->d->name, io->state, ret);
1298 if(io->amt >= sizeof(io->d->version))
1300 io->d->version = ntohl(io->d->version);
1301 if(io->d->version != 1)
1303 ERROR("ceph plugin: cconn_handle_event(name=%s) not "
1304 "expecting version %d!", io->d->name, io->d->version);
1307 DEBUG("ceph plugin: cconn_handle_event(name=%s): identified as "
1308 "version %d", io->d->name, io->d->version);
1311 io->request_type = ASOK_REQ_SCHEMA;
1315 case CSTATE_READ_AMT:
1318 read(io->asok, ((char*)(&io->json_len)) + io->amt,
1319 sizeof(io->json_len) - io->amt));
1320 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1321 io->d->name, io->state, ret);
1327 if(io->amt >= sizeof(io->json_len))
1329 io->json_len = ntohl(io->json_len);
1331 io->state = CSTATE_READ_JSON;
1332 io->json = calloc(1, io->json_len + 1);
1335 ERROR("ceph plugin: error callocing io->json");
1341 case CSTATE_READ_JSON:
1344 read(io->asok, io->json + io->amt, io->json_len - io->amt));
1345 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1346 io->d->name, io->state, ret);
1352 if(io->amt >= io->json_len)
1354 ret = cconn_process_json(io);
1360 io->request_type = ASOK_REQ_NONE;
1365 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1366 "state on line %d", io->d->name, __LINE__);
1371 static int cconn_prepare(struct cconn *io, struct pollfd* fds)
1374 if(io->request_type == ASOK_REQ_NONE)
1376 /* The request has already been serviced. */
1379 else if((io->request_type == ASOK_REQ_DATA) && (io->d->ds_num == 0))
1381 /* If there are no counters to report on, don't bother
1388 case CSTATE_UNCONNECTED:
1389 ret = cconn_connect(io);
1399 fds->events = POLLOUT;
1401 case CSTATE_WRITE_REQUEST:
1403 fds->events = POLLOUT;
1405 case CSTATE_READ_VERSION:
1406 case CSTATE_READ_AMT:
1407 case CSTATE_READ_JSON:
1409 fds->events = POLLIN;
1412 ERROR("ceph plugin: cconn_prepare(name=%s) got to illegal state "
1413 "on line %d", io->d->name, __LINE__);
1418 /** Returns the difference between two struct timevals in milliseconds.
1419 * On overflow, we return max/min int.
1421 static int milli_diff(const struct timeval *t1, const struct timeval *t2)
1424 int sec_diff = t1->tv_sec - t2->tv_sec;
1425 int usec_diff = t1->tv_usec - t2->tv_usec;
1426 ret = usec_diff / 1000;
1427 ret += (sec_diff * 1000);
1428 return (ret > INT_MAX) ? INT_MAX : ((ret < INT_MIN) ? INT_MIN : (int)ret);
1431 /** This handles the actual network I/O to talk to the Ceph daemons.
1433 static int cconn_main_loop(uint32_t request_type)
1435 int i, ret, some_unreachable = 0;
1436 struct timeval end_tv;
1437 struct cconn io_array[g_num_daemons];
1439 DEBUG("ceph plugin: entering cconn_main_loop(request_type = %d)", request_type);
1441 /* create cconn array */
1442 memset(io_array, 0, sizeof(io_array));
1443 for(i = 0; i < g_num_daemons; ++i)
1445 io_array[i].d = g_daemons[i];
1446 io_array[i].request_type = request_type;
1447 io_array[i].state = CSTATE_UNCONNECTED;
1450 /** Calculate the time at which we should give up */
1451 gettimeofday(&end_tv, NULL);
1452 end_tv.tv_sec += CEPH_TIMEOUT_INTERVAL;
1458 struct cconn *polled_io_array[g_num_daemons];
1459 struct pollfd fds[g_num_daemons];
1460 memset(fds, 0, sizeof(fds));
1462 for(i = 0; i < g_num_daemons; ++i)
1464 struct cconn *io = io_array + i;
1465 ret = cconn_prepare(io, fds + nfds);
1468 WARNING("ceph plugin: cconn_prepare(name=%s,i=%d,st=%d)=%d",
1469 io->d->name, i, io->state, ret);
1471 io->request_type = ASOK_REQ_NONE;
1472 some_unreachable = 1;
1476 polled_io_array[nfds++] = io_array + i;
1485 gettimeofday(&tv, NULL);
1486 diff = milli_diff(&end_tv, &tv);
1491 WARNING("ceph plugin: cconn_main_loop: timed out.");
1494 RETRY_ON_EINTR(ret, poll(fds, nfds, diff));
1497 ERROR("ceph plugin: poll(2) error: %d", ret);
1500 for(i = 0; i < nfds; ++i)
1502 struct cconn *io = polled_io_array[i];
1503 int revents = fds[i].revents;
1508 else if(cconn_validate_revents(io, revents))
1510 WARNING("ceph plugin: cconn(name=%s,i=%d,st=%d): "
1511 "revents validation error: "
1512 "revents=0x%08x", io->d->name, i, io->state, revents);
1514 io->request_type = ASOK_REQ_NONE;
1515 some_unreachable = 1;
1519 int ret = cconn_handle_event(io);
1522 WARNING("ceph plugin: cconn_handle_event(name=%s,"
1523 "i=%d,st=%d): error %d", io->d->name, i, io->state, ret);
1525 io->request_type = ASOK_REQ_NONE;
1526 some_unreachable = 1;
1531 done: for(i = 0; i < g_num_daemons; ++i)
1533 cconn_close(io_array + i);
1535 if(some_unreachable)
1537 DEBUG("ceph plugin: cconn_main_loop: some Ceph daemons were unreachable.");
1541 DEBUG("ceph plugin: cconn_main_loop: reached all Ceph daemons :)");
1546 static int ceph_read(void)
1548 return cconn_main_loop(ASOK_REQ_DATA);
1551 /******* lifecycle *******/
1552 static int ceph_init(void)
1555 ceph_daemons_print();
1557 ret = cconn_main_loop(ASOK_REQ_VERSION);
1559 return (ret) ? ret : 0;
1562 static int ceph_shutdown(void)
1565 for(i = 0; i < g_num_daemons; ++i)
1567 ceph_daemon_free(g_daemons[i]);
1572 DEBUG("ceph plugin: finished ceph_shutdown");
1576 void module_register(void)
1578 plugin_register_complex_config("ceph", ceph_config);
1579 plugin_register_init("ceph", ceph_init);
1580 plugin_register_read("ceph", ceph_read);
1581 plugin_register_shutdown("ceph", ceph_shutdown);