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
33 #include <arpa/inet.h>
36 #include <yajl/yajl_parse.h>
37 #if HAVE_YAJL_YAJL_VERSION_H
38 #include <yajl/yajl_version.h>
49 #include <sys/types.h>
55 #define RETRY_AVGCOUNT -1
57 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
58 # define HAVE_YAJL_V2 1
61 #define RETRY_ON_EINTR(ret, expr) \
71 /** Timeout interval in seconds */
72 #define CEPH_TIMEOUT_INTERVAL 1
74 /** Maximum path length for a UNIX domain socket on this system */
75 #define UNIX_DOMAIN_SOCK_PATH_MAX (sizeof(((struct sockaddr_un*)0)->sun_path))
77 /** Yajl callback returns */
78 #define CEPH_CB_CONTINUE 1
79 #define CEPH_CB_ABORT 0
82 typedef size_t yajl_len_t;
84 typedef unsigned int yajl_len_t;
87 /** Number of types for ceph defined in types.db */
88 #define CEPH_DSET_TYPES_NUM 3
89 /** ceph types enum */
95 DSET_TYPE_UNFOUND = 1000
98 /** Valid types for ceph defined in types.db */
99 static const char * const ceph_dset_types [CEPH_DSET_TYPES_NUM] =
100 {"ceph_latency", "ceph_bytes", "ceph_rate"};
102 /******* ceph_daemon *******/
105 /** Version of the admin_socket interface */
108 char name[DATA_MAX_NAME_LEN];
110 /** Path to the socket that we use to talk to the ceph daemon */
111 char asok_path[UNIX_DOMAIN_SOCK_PATH_MAX];
113 /** Number of counters */
115 /** Track ds types */
117 /** Track ds names to match with types */
121 * Keep track of last data for latency values so we can calculate rate
124 struct last_data **last_poll_data;
125 /** index of last poll data */
129 /******* JSON parsing *******/
130 typedef int (*node_handler_t)(void *, const char*, const char*);
132 /** Track state and handler while parsing JSON */
135 node_handler_t handler;
139 char *stack[YAJL_MAX_DEPTH];
142 typedef struct yajl_struct yajl_struct;
144 enum perfcounter_type_d
146 PERFCOUNTER_LATENCY = 0x4, PERFCOUNTER_DERIVE = 0x8,
149 /** Give user option to use default (long run = since daemon started) avg */
150 static int long_run_latency_avg = 0;
153 * Give user option to use default type for special cases -
154 * filestore.journal_wr_bytes is currently only metric here. Ceph reports the
155 * type as a sum/count pair and will calculate it the same as a latency value.
156 * All other "bytes" metrics (excluding the used/capacity bytes for the OSD)
157 * use the DERIVE type. Unless user specifies to use given type, convert this
158 * metric to use DERIVE.
160 static int convert_special_metrics = 1;
162 /** Array of daemons to monitor */
163 static struct ceph_daemon **g_daemons = NULL;
165 /** Number of elements in g_daemons */
166 static int g_num_daemons = 0;
169 * A set of data that we build up in memory while parsing the JSON.
173 /** ceph daemon we are processing data for*/
174 struct ceph_daemon *d;
175 /** track avgcount across counters for avgcount/sum latency pairs */
177 /** current index of counters - used to get type of counter */
179 /** do we already have an avgcount for latency pair */
182 * similar to index, but current index of latency type counters -
183 * used to get last poll data of counter
187 * values list - maintain across counters since
188 * host/plugin/plugin instance are always the same
194 * A set of count/sum pairs to keep track of latency types and get difference
195 * between this poll data and last poll data.
199 char ds_name[DATA_MAX_NAME_LEN];
204 /******* network I/O *******/
207 CSTATE_UNCONNECTED = 0,
208 CSTATE_WRITE_REQUEST,
216 ASOK_REQ_VERSION = 0,
219 ASOK_REQ_NONE = 1000,
224 /** The Ceph daemon that we're talking to */
225 struct ceph_daemon *d;
228 uint32_t request_type;
230 /** The connection state */
233 /** The socket we use to talk to this daemon */
236 /** The amount of data remaining to read / write. */
239 /** Length of the JSON to read */
242 /** Buffer containing JSON data */
245 /** Keep data important to yajl processing */
246 struct yajl_struct yajl;
249 static int ceph_cb_null(void *ctx)
251 return CEPH_CB_CONTINUE;
254 static int ceph_cb_boolean(void *ctx, int bool_val)
256 return CEPH_CB_CONTINUE;
259 #define BUFFER_ADD(dest, src) do { \
260 size_t dest_size = sizeof (dest); \
261 strncat ((dest), (src), dest_size - strlen (dest)); \
262 (dest)[dest_size - 1] = '\0'; \
266 ceph_cb_number(void *ctx, const char *number_val, yajl_len_t number_len)
268 yajl_struct *state = (yajl_struct*) ctx;
269 char buffer[number_len+1];
270 char key[2 * DATA_MAX_NAME_LEN];
271 _Bool latency_type = 0;
276 memcpy(buffer, number_val, number_len);
277 buffer[sizeof(buffer) - 1] = '\0';
279 for (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)
426 for(i = 0; i < g_num_daemons; ++i)
428 ceph_daemon_print(g_daemons[i]);
432 static void ceph_daemon_free(struct ceph_daemon *d)
435 for(; i < d->last_idx; i++)
437 sfree(d->last_poll_data[i]);
439 sfree(d->last_poll_data);
440 d->last_poll_data = NULL;
442 for(i = 0; i < d->ds_num; i++)
444 sfree(d->ds_names[i]);
451 /* compact_ds_name removed the special characters ":", "_", "-" and "+" from the
452 * intput string. Characters following these special characters are capitalized.
453 * Trailing "+" and "-" characters are replaces with the strings "Plus" and
455 static int compact_ds_name (char *buffer, size_t buffer_size, char const *src)
460 size_t ptr_size = buffer_size;
461 _Bool append_plus = 0;
462 _Bool append_minus = 0;
464 if ((buffer == NULL) || (buffer_size <= strlen ("Minus")) || (src == NULL))
467 src_copy = strdup (src);
468 src_len = strlen(src);
470 /* Remove trailing "+" and "-". */
471 if (src_copy[src_len - 1] == '+')
475 src_copy[src_len] = 0;
477 else if (src_copy[src_len - 1] == '-')
481 src_copy[src_len] = 0;
484 /* Split at special chars, capitalize first character, append to buffer. */
485 char *dummy = src_copy;
487 char *save_ptr = NULL;
488 while ((token = strtok_r (dummy, ":_-+", &save_ptr)) != NULL)
494 token[0] = toupper ((int) token[0]);
496 assert (ptr_size > 1);
498 len = strlen (token);
503 assert (len < ptr_size);
505 sstrncpy (ptr, token, len + 1);
514 /* Append "Plus" or "Minus" if "+" or "-" has been stripped above. */
515 if (append_plus || append_minus)
517 char const *append = "Plus";
521 size_t offset = buffer_size - (strlen (append) + 1);
522 if (offset > strlen (buffer))
523 offset = strlen (buffer);
525 sstrncpy (buffer + offset, append, buffer_size - offset);
532 static _Bool has_suffix (char const *str, char const *suffix)
534 size_t str_len = strlen (str);
535 size_t suffix_len = strlen (suffix);
538 if (suffix_len > str_len)
540 offset = str_len - suffix_len;
542 if (strcmp (str + offset, suffix) == 0)
548 /* count_parts returns the number of elements a "foo.bar.baz" style key has. */
549 static size_t count_parts (char const *key)
552 size_t parts_num = 0;
554 for (ptr = key; ptr != NULL; ptr = strchr (ptr + 1, '.'))
561 * Parse key to remove "type" if this is for schema and initiate compaction
563 static int parse_keys (char *buffer, size_t buffer_size, const char *key_str)
565 char tmp[2 * buffer_size];
567 if (buffer == NULL || buffer_size == 0 || key_str == NULL || strlen (key_str) == 0)
570 if ((count_parts (key_str) > 2) && has_suffix (key_str, ".type"))
572 /* strip ".type" suffix iff the key has more than two parts. */
573 size_t sz = strlen (key_str) - strlen (".type") + 1;
575 if (sz > sizeof (tmp))
577 sstrncpy (tmp, key_str, sz);
581 sstrncpy (tmp, key_str, sizeof (tmp));
584 return compact_ds_name (buffer, buffer_size, tmp);
588 * while parsing ceph admin socket schema, save counter name and type for later
591 static int ceph_daemon_add_ds_entry(struct ceph_daemon *d, const char *name,
595 char ds_name[DATA_MAX_NAME_LEN];
597 if(convert_special_metrics)
600 * Special case for filestore:JournalWrBytes. For some reason, Ceph
601 * schema encodes this as a count/sum pair while all other "Bytes" data
602 * (excluding used/capacity bytes for OSD space) uses a single "Derive"
603 * type. To spare further confusion, keep this KPI as the same type of
604 * other "Bytes". Instead of keeping an "average" or "rate", use the
605 * "sum" in the pair and assign that to the derive value.
607 if((strcmp(name,"filestore.journal_wr_bytes.type") == 0))
613 d->ds_names = realloc(d->ds_names, sizeof(char *) * (d->ds_num + 1));
619 d->ds_types = realloc(d->ds_types, sizeof(uint32_t) * (d->ds_num + 1));
625 d->ds_names[d->ds_num] = malloc(DATA_MAX_NAME_LEN);
626 if(!d->ds_names[d->ds_num])
631 type = (pc_type & PERFCOUNTER_DERIVE) ? DSET_RATE :
632 ((pc_type & PERFCOUNTER_LATENCY) ? DSET_LATENCY : DSET_BYTES);
633 d->ds_types[d->ds_num] = type;
635 if (parse_keys(ds_name, sizeof (ds_name), name))
640 sstrncpy(d->ds_names[d->ds_num], ds_name, DATA_MAX_NAME_LEN -1);
641 d->ds_num = (d->ds_num + 1);
646 /******* ceph_config *******/
647 static int cc_handle_str(struct oconfig_item_s *item, char *dest, int dest_len)
650 if(item->values_num != 1)
654 if(item->values[0].type != OCONFIG_TYPE_STRING)
658 val = item->values[0].value.string;
659 if(snprintf(dest, dest_len, "%s", val) > (dest_len - 1))
661 ERROR("ceph plugin: configuration parameter '%s' is too long.\n",
663 return -ENAMETOOLONG;
668 static int cc_handle_bool(struct oconfig_item_s *item, int *dest)
670 if(item->values_num != 1)
675 if(item->values[0].type != OCONFIG_TYPE_BOOLEAN)
680 *dest = (item->values[0].value.boolean) ? 1 : 0;
684 static int cc_add_daemon_config(oconfig_item_t *ci)
687 struct ceph_daemon *nd, cd = { 0 };
688 struct ceph_daemon **tmp;
690 if((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
692 WARNING("ceph plugin: `Daemon' blocks need exactly one string "
697 ret = cc_handle_str(ci, cd.name, DATA_MAX_NAME_LEN);
703 for(i=0; i < ci->children_num; i++)
705 oconfig_item_t *child = ci->children + i;
707 if(strcasecmp("SocketPath", child->key) == 0)
709 ret = cc_handle_str(child, cd.asok_path, sizeof(cd.asok_path));
717 WARNING("ceph plugin: ignoring unknown option %s", child->key);
720 if(cd.name[0] == '\0')
722 ERROR("ceph plugin: you must configure a daemon name.\n");
725 else if(cd.asok_path[0] == '\0')
727 ERROR("ceph plugin(name=%s): you must configure an administrative "
728 "socket path.\n", cd.name);
731 else if(!((cd.asok_path[0] == '/') ||
732 (cd.asok_path[0] == '.' && cd.asok_path[1] == '/')))
734 ERROR("ceph plugin(name=%s): administrative socket paths must begin "
735 "with '/' or './' Can't parse: '%s'\n", cd.name, cd.asok_path);
739 tmp = realloc(g_daemons, (g_num_daemons+1) * sizeof(*g_daemons));
742 /* The positive return value here indicates that this is a
743 * runtime error, not a configuration error. */
748 nd = malloc(sizeof (*nd));
753 memcpy(nd, &cd, sizeof(*nd));
754 g_daemons[g_num_daemons++] = nd;
758 static int ceph_config(oconfig_item_t *ci)
762 for(i = 0; i < ci->children_num; ++i)
764 oconfig_item_t *child = ci->children + i;
765 if(strcasecmp("Daemon", child->key) == 0)
767 ret = cc_add_daemon_config(child);
770 ERROR("ceph plugin: Couldn't allocate memory");
775 //process other daemons and ignore this one
779 else if(strcasecmp("LongRunAvgLatency", child->key) == 0)
781 ret = cc_handle_bool(child, &long_run_latency_avg);
787 else if(strcasecmp("ConvertSpecialMetricTypes", child->key) == 0)
789 ret = cc_handle_bool(child, &convert_special_metrics);
797 WARNING("ceph plugin: ignoring unknown option %s", child->key);
804 * Parse JSON and get error message if present
807 traverse_json(const unsigned char *json, uint32_t json_len, yajl_handle hand)
809 yajl_status status = yajl_parse(hand, json, json_len);
814 case yajl_status_error:
815 msg = yajl_get_error(hand, /* verbose = */ 1,
816 /* jsonText = */ (unsigned char *) json,
817 (unsigned int) json_len);
818 ERROR ("ceph plugin: yajl_parse failed: %s", msg);
819 yajl_free_error(hand, msg);
821 case yajl_status_client_canceled:
829 * Add entry for each counter while parsing schema
832 node_handler_define_schema(void *arg, const char *val, const char *key)
834 struct ceph_daemon *d = (struct ceph_daemon *) arg;
837 return ceph_daemon_add_ds_entry(d, key, pc_type);
841 * Latency counter does not yet have an entry in last poll data - add it.
843 static int add_last(struct ceph_daemon *d, const char *ds_n, double cur_sum,
846 d->last_poll_data[d->last_idx] = malloc(sizeof (*d->last_poll_data[d->last_idx]));
847 if(!d->last_poll_data[d->last_idx])
851 sstrncpy(d->last_poll_data[d->last_idx]->ds_name,ds_n,
852 sizeof(d->last_poll_data[d->last_idx]->ds_name));
853 d->last_poll_data[d->last_idx]->last_sum = cur_sum;
854 d->last_poll_data[d->last_idx]->last_count = cur_count;
855 d->last_idx = (d->last_idx + 1);
860 * Update latency counter or add new entry if it doesn't exist
862 static int update_last(struct ceph_daemon *d, const char *ds_n, int index,
863 double cur_sum, uint64_t cur_count)
865 if((d->last_idx > index) && (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0))
867 d->last_poll_data[index]->last_sum = cur_sum;
868 d->last_poll_data[index]->last_count = cur_count;
872 if(!d->last_poll_data)
874 d->last_poll_data = malloc(sizeof (*d->last_poll_data));
875 if(!d->last_poll_data)
882 struct last_data **tmp_last = realloc(d->last_poll_data,
883 ((d->last_idx+1) * sizeof(struct last_data *)));
888 d->last_poll_data = tmp_last;
890 return add_last(d, ds_n, cur_sum, cur_count);
894 * If using index guess failed (shouldn't happen, but possible if counters
895 * get rearranged), resort to searching for counter name
897 static int backup_search_for_last_avg(struct ceph_daemon *d, const char *ds_n)
900 for(; i < d->last_idx; i++)
902 if(strcmp(d->last_poll_data[i]->ds_name, ds_n) == 0)
911 * Calculate average b/t current data and last poll data
912 * if last poll data exists
914 static double get_last_avg(struct ceph_daemon *d, const char *ds_n, int index,
915 double cur_sum, uint64_t cur_count)
917 double result = -1.1, sum_delt = 0.0;
918 uint64_t count_delt = 0;
920 if(d->last_idx > index)
922 if(strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0)
926 //test previous index
927 else if((index > 0) && (strcmp(d->last_poll_data[index-1]->ds_name, ds_n) == 0))
929 tmp_index = (index - 1);
933 tmp_index = backup_search_for_last_avg(d, ds_n);
936 if((tmp_index > -1) && (cur_count > d->last_poll_data[tmp_index]->last_count))
938 sum_delt = (cur_sum - d->last_poll_data[tmp_index]->last_sum);
939 count_delt = (cur_count - d->last_poll_data[tmp_index]->last_count);
940 result = (sum_delt / count_delt);
948 if(update_last(d, ds_n, tmp_index, cur_sum, cur_count) == -ENOMEM)
956 * If using index guess failed, resort to searching for counter name
958 static uint32_t backup_search_for_type(struct ceph_daemon *d, char *ds_name)
961 for(; idx < d->ds_num; idx++)
963 if(strcmp(d->ds_names[idx], ds_name) == 0)
965 return d->ds_types[idx];
968 return DSET_TYPE_UNFOUND;
972 * Process counter data and dispatch values
974 static int node_handler_fetch_data(void *arg, const char *val, const char *key)
979 struct values_tmp *vtmp = (struct values_tmp*) arg;
980 uint32_t type = DSET_TYPE_UNFOUND;
981 int index = vtmp->index;
983 char ds_name[DATA_MAX_NAME_LEN];
985 if (parse_keys (ds_name, sizeof (ds_name), key))
990 if(index >= vtmp->d->ds_num)
992 //don't overflow bounds of array
993 index = (vtmp->d->ds_num - 1);
997 * counters should remain in same order we parsed schema... we maintain the
998 * index variable to keep track of current point in list of counters. first
999 * use index to guess point in array for retrieving type. if that doesn't
1000 * work, use the old way to get the counter type
1002 if(strcmp(ds_name, vtmp->d->ds_names[index]) == 0)
1005 type = vtmp->d->ds_types[index];
1007 else if((index > 0) && (strcmp(ds_name, vtmp->d->ds_names[index-1]) == 0))
1010 type = vtmp->d->ds_types[index-1];
1013 if(type == DSET_TYPE_UNFOUND)
1015 //couldn't find right type by guessing, check the old way
1016 type = backup_search_for_type(vtmp->d, ds_name);
1022 if(vtmp->avgcount_exists == -1)
1024 sscanf(val, "%" PRIu64, &vtmp->avgcount);
1025 vtmp->avgcount_exists = 0;
1026 //return after saving avgcount - don't dispatch value
1027 //until latency calculation
1033 sscanf(val, "%lf", &sum);
1035 if(vtmp->avgcount == 0)
1040 /** User wants latency values as long run avg */
1041 if(long_run_latency_avg)
1043 result = (sum / vtmp->avgcount);
1047 result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum, vtmp->avgcount);
1048 if(result == -ENOMEM)
1055 vtmp->avgcount_exists = -1;
1056 vtmp->latency_index = (vtmp->latency_index + 1);
1060 sscanf(val, "%lf", &tmp_d);
1064 sscanf(val, "%" PRIu64, &tmp_u);
1067 case DSET_TYPE_UNFOUND:
1069 ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);
1073 sstrncpy(vtmp->vlist.type, ceph_dset_types[type], sizeof(vtmp->vlist.type));
1074 sstrncpy(vtmp->vlist.type_instance, ds_name, sizeof(vtmp->vlist.type_instance));
1075 vtmp->vlist.values = &uv;
1076 vtmp->vlist.values_len = 1;
1078 vtmp->index = (vtmp->index + 1);
1079 plugin_dispatch_values(&vtmp->vlist);
1084 static int cconn_connect(struct cconn *io)
1086 struct sockaddr_un address = { 0 };
1088 if(io->state != CSTATE_UNCONNECTED)
1090 ERROR("ceph plugin: cconn_connect: io->state != CSTATE_UNCONNECTED");
1093 fd = socket(PF_UNIX, SOCK_STREAM, 0);
1097 ERROR("ceph plugin: cconn_connect: socket(PF_UNIX, SOCK_STREAM, 0) "
1098 "failed: error %d", err);
1101 address.sun_family = AF_UNIX;
1102 snprintf(address.sun_path, sizeof(address.sun_path), "%s",
1105 connect(fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)));
1108 ERROR("ceph plugin: cconn_connect: connect(%d) failed: error %d",
1114 flags = fcntl(fd, F_GETFL, 0);
1115 if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0)
1118 ERROR("ceph plugin: cconn_connect: fcntl(%d, O_NONBLOCK) error %d",
1124 io->state = CSTATE_WRITE_REQUEST;
1131 static void cconn_close(struct cconn *io)
1133 io->state = CSTATE_UNCONNECTED;
1137 RETRY_ON_EINTR(res, close(io->asok));
1146 /* Process incoming JSON counter data */
1148 cconn_process_data(struct cconn *io, yajl_struct *yajl, yajl_handle hand)
1151 struct values_tmp *vtmp = calloc(1, sizeof(struct values_tmp) * 1);
1157 vtmp->vlist = (value_list_t)VALUE_LIST_INIT;
1158 sstrncpy(vtmp->vlist.host, hostname_g, sizeof(vtmp->vlist.host));
1159 sstrncpy(vtmp->vlist.plugin, "ceph", sizeof(vtmp->vlist.plugin));
1160 sstrncpy(vtmp->vlist.plugin_instance, io->d->name, sizeof(vtmp->vlist.plugin_instance));
1163 vtmp->avgcount_exists = -1;
1164 vtmp->latency_index = 0;
1166 yajl->handler_arg = vtmp;
1167 ret = traverse_json(io->json, io->json_len, hand);
1173 * Initiate JSON parsing and print error if one occurs
1175 static int cconn_process_json(struct cconn *io)
1177 if((io->request_type != ASOK_REQ_DATA) &&
1178 (io->request_type != ASOK_REQ_SCHEMA))
1187 hand = yajl_alloc(&callbacks,
1189 /* alloc funcs = */ NULL,
1191 /* alloc funcs = */ NULL, NULL,
1193 /* context = */ (void *)(&io->yajl));
1197 ERROR ("ceph plugin: yajl_alloc failed.");
1203 switch(io->request_type)
1206 io->yajl.handler = node_handler_fetch_data;
1207 result = cconn_process_data(io, &io->yajl, hand);
1209 case ASOK_REQ_SCHEMA:
1210 //init daemon specific variables
1212 io->d->last_idx = 0;
1213 io->d->last_poll_data = NULL;
1214 io->yajl.handler = node_handler_define_schema;
1215 io->yajl.handler_arg = io->d;
1216 result = traverse_json(io->json, io->json_len, hand);
1226 status = yajl_complete_parse(hand);
1228 status = yajl_parse_complete(hand);
1231 if (status != yajl_status_ok)
1233 unsigned char *errmsg = yajl_get_error (hand, /* verbose = */ 0,
1234 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
1235 ERROR ("ceph plugin: yajl_parse_complete failed: %s",
1237 yajl_free_error (hand, errmsg);
1247 static int cconn_validate_revents(struct cconn *io, int revents)
1249 if(revents & POLLERR)
1251 ERROR("ceph plugin: cconn_validate_revents(name=%s): got POLLERR",
1257 case CSTATE_WRITE_REQUEST:
1258 return (revents & POLLOUT) ? 0 : -EINVAL;
1259 case CSTATE_READ_VERSION:
1260 case CSTATE_READ_AMT:
1261 case CSTATE_READ_JSON:
1262 return (revents & POLLIN) ? 0 : -EINVAL;
1264 ERROR("ceph plugin: cconn_validate_revents(name=%s) got to "
1265 "illegal state on line %d", io->d->name, __LINE__);
1270 /** Handle a network event for a connection */
1271 static int cconn_handle_event(struct cconn *io)
1276 case CSTATE_UNCONNECTED:
1277 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1278 "state on line %d", io->d->name, __LINE__);
1281 case CSTATE_WRITE_REQUEST:
1284 snprintf(cmd, sizeof(cmd), "%s%d%s", "{ \"prefix\": \"",
1285 io->request_type, "\" }\n");
1286 size_t cmd_len = strlen(cmd);
1288 write(io->asok, ((char*)&cmd) + io->amt, cmd_len - io->amt));
1289 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,amt=%d,ret=%d)",
1290 io->d->name, io->state, io->amt, ret);
1296 if(io->amt >= cmd_len)
1299 switch (io->request_type)
1301 case ASOK_REQ_VERSION:
1302 io->state = CSTATE_READ_VERSION;
1305 io->state = CSTATE_READ_AMT;
1311 case CSTATE_READ_VERSION:
1314 read(io->asok, ((char*)(&io->d->version)) + io->amt,
1315 sizeof(io->d->version) - io->amt));
1316 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1317 io->d->name, io->state, ret);
1323 if(io->amt >= sizeof(io->d->version))
1325 io->d->version = ntohl(io->d->version);
1326 if(io->d->version != 1)
1328 ERROR("ceph plugin: cconn_handle_event(name=%s) not "
1329 "expecting version %d!", io->d->name, io->d->version);
1332 DEBUG("ceph plugin: cconn_handle_event(name=%s): identified as "
1333 "version %d", io->d->name, io->d->version);
1336 io->request_type = ASOK_REQ_SCHEMA;
1340 case CSTATE_READ_AMT:
1343 read(io->asok, ((char*)(&io->json_len)) + io->amt,
1344 sizeof(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 >= sizeof(io->json_len))
1354 io->json_len = ntohl(io->json_len);
1356 io->state = CSTATE_READ_JSON;
1357 io->json = calloc(1, io->json_len + 1);
1360 ERROR("ceph plugin: error callocing io->json");
1366 case CSTATE_READ_JSON:
1369 read(io->asok, io->json + io->amt, io->json_len - io->amt));
1370 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1371 io->d->name, io->state, ret);
1377 if(io->amt >= io->json_len)
1379 ret = cconn_process_json(io);
1385 io->request_type = ASOK_REQ_NONE;
1390 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1391 "state on line %d", io->d->name, __LINE__);
1396 static int cconn_prepare(struct cconn *io, struct pollfd* fds)
1399 if(io->request_type == ASOK_REQ_NONE)
1401 /* The request has already been serviced. */
1404 else if((io->request_type == ASOK_REQ_DATA) && (io->d->ds_num == 0))
1406 /* If there are no counters to report on, don't bother
1413 case CSTATE_UNCONNECTED:
1414 ret = cconn_connect(io);
1424 fds->events = POLLOUT;
1426 case CSTATE_WRITE_REQUEST:
1428 fds->events = POLLOUT;
1430 case CSTATE_READ_VERSION:
1431 case CSTATE_READ_AMT:
1432 case CSTATE_READ_JSON:
1434 fds->events = POLLIN;
1437 ERROR("ceph plugin: cconn_prepare(name=%s) got to illegal state "
1438 "on line %d", io->d->name, __LINE__);
1443 /** Returns the difference between two struct timevals in milliseconds.
1444 * On overflow, we return max/min int.
1446 static int milli_diff(const struct timeval *t1, const struct timeval *t2)
1449 int sec_diff = t1->tv_sec - t2->tv_sec;
1450 int usec_diff = t1->tv_usec - t2->tv_usec;
1451 ret = usec_diff / 1000;
1452 ret += (sec_diff * 1000);
1453 return (ret > INT_MAX) ? INT_MAX : ((ret < INT_MIN) ? INT_MIN : (int)ret);
1456 /** This handles the actual network I/O to talk to the Ceph daemons.
1458 static int cconn_main_loop(uint32_t request_type)
1460 int i, ret, some_unreachable = 0;
1461 struct timeval end_tv;
1462 struct cconn io_array[g_num_daemons];
1464 DEBUG("ceph plugin: entering cconn_main_loop(request_type = %d)", request_type);
1466 /* create cconn array */
1467 memset(io_array, 0, sizeof(io_array));
1468 for(i = 0; i < g_num_daemons; ++i)
1470 io_array[i].d = g_daemons[i];
1471 io_array[i].request_type = request_type;
1472 io_array[i].state = CSTATE_UNCONNECTED;
1475 /** Calculate the time at which we should give up */
1476 gettimeofday(&end_tv, NULL);
1477 end_tv.tv_sec += CEPH_TIMEOUT_INTERVAL;
1483 struct cconn *polled_io_array[g_num_daemons];
1484 struct pollfd fds[g_num_daemons];
1485 memset(fds, 0, sizeof(fds));
1487 for(i = 0; i < g_num_daemons; ++i)
1489 struct cconn *io = io_array + i;
1490 ret = cconn_prepare(io, fds + nfds);
1493 WARNING("ceph plugin: cconn_prepare(name=%s,i=%d,st=%d)=%d",
1494 io->d->name, i, io->state, ret);
1496 io->request_type = ASOK_REQ_NONE;
1497 some_unreachable = 1;
1501 polled_io_array[nfds++] = io_array + i;
1510 gettimeofday(&tv, NULL);
1511 diff = milli_diff(&end_tv, &tv);
1516 WARNING("ceph plugin: cconn_main_loop: timed out.");
1519 RETRY_ON_EINTR(ret, poll(fds, nfds, diff));
1522 ERROR("ceph plugin: poll(2) error: %d", ret);
1525 for(i = 0; i < nfds; ++i)
1527 struct cconn *io = polled_io_array[i];
1528 int revents = fds[i].revents;
1533 else if(cconn_validate_revents(io, revents))
1535 WARNING("ceph plugin: cconn(name=%s,i=%d,st=%d): "
1536 "revents validation error: "
1537 "revents=0x%08x", io->d->name, i, io->state, revents);
1539 io->request_type = ASOK_REQ_NONE;
1540 some_unreachable = 1;
1544 ret = cconn_handle_event(io);
1547 WARNING("ceph plugin: cconn_handle_event(name=%s,"
1548 "i=%d,st=%d): error %d", io->d->name, i, io->state, ret);
1550 io->request_type = ASOK_REQ_NONE;
1551 some_unreachable = 1;
1556 done: for(i = 0; i < g_num_daemons; ++i)
1558 cconn_close(io_array + i);
1560 if(some_unreachable)
1562 DEBUG("ceph plugin: cconn_main_loop: some Ceph daemons were unreachable.");
1566 DEBUG("ceph plugin: cconn_main_loop: reached all Ceph daemons :)");
1571 static int ceph_read(void)
1573 return cconn_main_loop(ASOK_REQ_DATA);
1576 /******* lifecycle *******/
1577 static int ceph_init(void)
1580 ceph_daemons_print();
1582 ret = cconn_main_loop(ASOK_REQ_VERSION);
1584 return (ret) ? ret : 0;
1587 static int ceph_shutdown(void)
1590 for(i = 0; i < g_num_daemons; ++i)
1592 ceph_daemon_free(g_daemons[i]);
1597 DEBUG("ceph plugin: finished ceph_shutdown");
1601 void module_register(void)
1603 plugin_register_complex_config("ceph", ceph_config);
1604 plugin_register_init("ceph", ceph_init);
1605 plugin_register_read("ceph", ceph_read);
1606 plugin_register_shutdown("ceph", ceph_shutdown);
1608 /* vim: set sw=4 sts=4 et : */