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>
41 #ifdef HAVE_SYS_CAPABILITY_H
42 #include <sys/capability.h>
55 #include <sys/types.h>
59 #define RETRY_AVGCOUNT -1
61 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
62 #define HAVE_YAJL_V2 1
65 #define RETRY_ON_EINTR(ret, expr) \
75 /** Timeout interval in seconds */
76 #define CEPH_TIMEOUT_INTERVAL 1
78 /** Maximum path length for a UNIX domain socket on this system */
79 #define UNIX_DOMAIN_SOCK_PATH_MAX (sizeof(((struct sockaddr_un *)0)->sun_path))
81 /** Yajl callback returns */
82 #define CEPH_CB_CONTINUE 1
83 #define CEPH_CB_ABORT 0
86 typedef size_t yajl_len_t;
88 typedef unsigned int yajl_len_t;
91 /** Number of types for ceph defined in types.db */
92 #define CEPH_DSET_TYPES_NUM 3
93 /** ceph types enum */
94 enum ceph_dset_type_d {
98 DSET_TYPE_UNFOUND = 1000
101 /** Valid types for ceph defined in types.db */
102 static const char *const ceph_dset_types[CEPH_DSET_TYPES_NUM] = {
103 "ceph_latency", "ceph_bytes", "ceph_rate"};
105 /******* ceph_daemon *******/
107 /** Version of the admin_socket interface */
110 char name[DATA_MAX_NAME_LEN];
112 /** Path to the socket that we use to talk to the ceph daemon */
113 char asok_path[UNIX_DOMAIN_SOCK_PATH_MAX];
115 /** Number of counters */
117 /** Track ds types */
119 /** Track ds names to match with types */
123 * Keep track of last data for latency values so we can calculate rate
126 struct last_data **last_poll_data;
127 /** index of last poll data */
131 /******* JSON parsing *******/
132 typedef int (*node_handler_t)(void *, const char *, const char *);
134 /** 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 {
146 PERFCOUNTER_LATENCY = 0x4,
147 PERFCOUNTER_DERIVE = 0x8,
150 /** Give user option to use default (long run = since daemon started) avg */
151 static int long_run_latency_avg;
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;
166 /** Number of elements in g_daemons */
167 static size_t g_num_daemons;
170 * 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 */
180 * similar to index, but current index of latency type counters -
181 * used to get last poll data of counter
185 * values list - maintain across counters since
186 * host/plugin/plugin instance are always the same
192 * A set of count/sum pairs to keep track of latency types and get difference
193 * between this poll data and last poll data.
196 char ds_name[DATA_MAX_NAME_LEN];
201 /******* network I/O *******/
203 CSTATE_UNCONNECTED = 0,
204 CSTATE_WRITE_REQUEST,
210 enum request_type_t {
211 ASOK_REQ_VERSION = 0,
214 ASOK_REQ_NONE = 1000,
218 /** The Ceph daemon that we're talking to */
219 struct ceph_daemon *d;
222 uint32_t request_type;
224 /** The connection state */
227 /** The socket we use to talk to this daemon */
230 /** The amount of data remaining to read / write. */
233 /** Length of the JSON to read */
236 /** Buffer containing JSON data */
239 /** Keep data important to yajl processing */
240 struct yajl_struct yajl;
243 static int ceph_cb_null(void *ctx) { return CEPH_CB_CONTINUE; }
245 static int ceph_cb_boolean(void *ctx, int bool_val) { return CEPH_CB_CONTINUE; }
247 #define BUFFER_ADD(dest, src) \
249 size_t dest_size = sizeof(dest); \
250 size_t dest_len = strlen(dest); \
251 if (dest_size > dest_len) { \
252 sstrncpy((dest) + dest_len, (src), dest_size - dest_len); \
254 (dest)[dest_size - 1] = 0; \
257 static int ceph_cb_number(void *ctx, const char *number_val,
258 yajl_len_t number_len) {
259 yajl_struct *state = (yajl_struct *)ctx;
260 char buffer[number_len + 1];
261 char key[2 * DATA_MAX_NAME_LEN] = {0};
264 memcpy(buffer, number_val, number_len);
265 buffer[sizeof(buffer) - 1] = '\0';
267 for (size_t i = 0; i < state->depth; i++) {
268 if (state->stack[i] == NULL)
271 if (strlen(key) != 0)
272 BUFFER_ADD(key, ".");
273 BUFFER_ADD(key, state->stack[i]);
276 /* Super-special case for filestore.journal_wr_bytes.avgcount: For
277 * some reason, Ceph schema encodes this as a count/sum pair while all
278 * other "Bytes" data (excluding used/capacity bytes for OSD space) uses
279 * a single "Derive" type. To spare further confusion, keep this KPI as
280 * the same type of other "Bytes". Instead of keeping an "average" or
281 * "rate", use the "sum" in the pair and assign that to the derive
283 if (convert_special_metrics && (state->depth > 2) &&
284 (strcmp("filestore", state->stack[state->depth - 2]) == 0) &&
285 (strcmp("journal_wr_bytes", state->stack[state->depth - 1]) == 0) &&
286 (strcmp("avgcount", state->key) == 0)) {
287 DEBUG("ceph plugin: Skipping avgcount for filestore.JournalWrBytes");
288 return CEPH_CB_CONTINUE;
291 BUFFER_ADD(key, ".");
292 BUFFER_ADD(key, state->key);
294 status = state->handler(state->handler_arg, buffer, key);
297 ERROR("ceph plugin: JSON handler failed with status %d.", status);
298 return CEPH_CB_ABORT;
301 return CEPH_CB_CONTINUE;
304 static int ceph_cb_string(void *ctx, const unsigned char *string_val,
305 yajl_len_t string_len) {
306 return CEPH_CB_CONTINUE;
309 static int ceph_cb_start_map(void *ctx) {
310 yajl_struct *state = (yajl_struct *)ctx;
312 /* Push key to the stack */
313 if (state->depth == YAJL_MAX_DEPTH)
314 return CEPH_CB_ABORT;
316 state->stack[state->depth] = state->key;
320 return CEPH_CB_CONTINUE;
323 static int ceph_cb_end_map(void *ctx) {
324 yajl_struct *state = (yajl_struct *)ctx;
326 /* Pop key from the stack */
327 if (state->depth == 0)
328 return CEPH_CB_ABORT;
332 state->key = state->stack[state->depth];
333 state->stack[state->depth] = NULL;
335 return CEPH_CB_CONTINUE;
338 static int ceph_cb_map_key(void *ctx, const unsigned char *key,
339 yajl_len_t string_len) {
340 yajl_struct *state = (yajl_struct *)ctx;
341 size_t sz = ((size_t)string_len) + 1;
344 state->key = malloc(sz);
345 if (state->key == NULL) {
346 ERROR("ceph plugin: malloc failed.");
347 return CEPH_CB_ABORT;
350 memmove(state->key, key, sz - 1);
351 state->key[sz - 1] = 0;
353 return CEPH_CB_CONTINUE;
356 static int ceph_cb_start_array(void *ctx) { return CEPH_CB_CONTINUE; }
358 static int ceph_cb_end_array(void *ctx) { return CEPH_CB_CONTINUE; }
360 static yajl_callbacks callbacks = {ceph_cb_null,
372 static void ceph_daemon_print(const struct ceph_daemon *d) {
373 DEBUG("ceph plugin: name=%s, asok_path=%s", d->name, d->asok_path);
376 static void ceph_daemons_print(void) {
377 for (size_t i = 0; i < g_num_daemons; ++i) {
378 ceph_daemon_print(g_daemons[i]);
382 static void ceph_daemon_free(struct ceph_daemon *d) {
383 for (int i = 0; i < d->last_idx; i++) {
384 sfree(d->last_poll_data[i]);
386 sfree(d->last_poll_data);
387 d->last_poll_data = NULL;
390 for (int i = 0; i < d->ds_num; i++) {
391 sfree(d->ds_names[i]);
398 /* compact_ds_name removed the special characters ":", "_", "-" and "+" from the
399 * input string. Characters following these special characters are capitalized.
400 * Trailing "+" and "-" characters are replaces with the strings "Plus" and
402 static int compact_ds_name(char *buffer, size_t buffer_size, char const *src) {
406 size_t ptr_size = buffer_size;
407 bool append_plus = false;
408 bool append_minus = false;
410 if ((buffer == NULL) || (buffer_size <= strlen("Minus")) || (src == NULL))
413 src_copy = strdup(src);
414 src_len = strlen(src);
416 /* Remove trailing "+" and "-". */
417 if (src_copy[src_len - 1] == '+') {
420 src_copy[src_len] = 0;
421 } else if (src_copy[src_len - 1] == '-') {
424 src_copy[src_len] = 0;
427 /* Split at special chars, capitalize first character, append to buffer. */
428 char *dummy = src_copy;
430 char *save_ptr = NULL;
431 while ((token = strtok_r(dummy, ":_-+", &save_ptr)) != NULL) {
436 token[0] = toupper((int)token[0]);
438 assert(ptr_size > 1);
445 assert(len < ptr_size);
447 sstrncpy(ptr, token, len + 1);
456 /* Append "Plus" or "Minus" if "+" or "-" has been stripped above. */
457 if (append_plus || append_minus) {
458 char const *append = "Plus";
462 size_t offset = buffer_size - (strlen(append) + 1);
463 if (offset > strlen(buffer))
464 offset = strlen(buffer);
466 sstrncpy(buffer + offset, append, buffer_size - offset);
473 static bool has_suffix(char const *str, char const *suffix) {
474 size_t str_len = strlen(str);
475 size_t suffix_len = strlen(suffix);
478 if (suffix_len > str_len)
480 offset = str_len - suffix_len;
482 if (strcmp(str + offset, suffix) == 0)
488 static void cut_suffix(char *buffer, size_t buffer_size, char const *str,
489 char const *suffix) {
491 size_t str_len = strlen(str);
492 size_t suffix_len = strlen(suffix);
494 size_t offset = str_len - suffix_len + 1;
496 if (offset > buffer_size) {
497 offset = buffer_size;
500 sstrncpy(buffer, str, offset);
503 /* count_parts returns the number of elements a "foo.bar.baz" style key has. */
504 static size_t count_parts(char const *key) {
505 size_t parts_num = 0;
507 for (const char *ptr = key; ptr != NULL; ptr = strchr(ptr + 1, '.'))
514 * Parse key to remove "type" if this is for schema and initiate compaction
516 static int parse_keys(char *buffer, size_t buffer_size, const char *key_str) {
517 char tmp[2 * buffer_size];
518 size_t tmp_size = sizeof(tmp);
519 const char *cut_suffixes[] = {".type", ".avgcount", ".sum", ".avgtime"};
521 if (buffer == NULL || buffer_size == 0 || key_str == NULL ||
522 strlen(key_str) == 0)
525 sstrncpy(tmp, key_str, tmp_size);
527 /* Strip suffix if it is ".type" or one of latency metric suffix. */
528 if (count_parts(key_str) > 2) {
529 for (size_t i = 0; i < STATIC_ARRAY_SIZE(cut_suffixes); i++) {
530 if (has_suffix(key_str, cut_suffixes[i])) {
531 cut_suffix(tmp, tmp_size, key_str, cut_suffixes[i]);
537 return compact_ds_name(buffer, buffer_size, tmp);
541 * while parsing ceph admin socket schema, save counter name and type for later
544 static int ceph_daemon_add_ds_entry(struct ceph_daemon *d, const char *name,
547 char ds_name[DATA_MAX_NAME_LEN];
549 if (convert_special_metrics) {
551 * Special case for filestore:JournalWrBytes. For some reason, Ceph
552 * schema encodes this as a count/sum pair while all other "Bytes" data
553 * (excluding used/capacity bytes for OSD space) uses a single "Derive"
554 * type. To spare further confusion, keep this KPI as the same type of
555 * other "Bytes". Instead of keeping an "average" or "rate", use the
556 * "sum" in the pair and assign that to the derive value.
558 if ((strcmp(name, "filestore.journal_wr_bytes.type") == 0)) {
563 d->ds_names = realloc(d->ds_names, sizeof(char *) * (d->ds_num + 1));
568 d->ds_types = realloc(d->ds_types, sizeof(uint32_t) * (d->ds_num + 1));
573 d->ds_names[d->ds_num] = malloc(DATA_MAX_NAME_LEN);
574 if (!d->ds_names[d->ds_num]) {
578 type = (pc_type & PERFCOUNTER_DERIVE)
580 : ((pc_type & PERFCOUNTER_LATENCY) ? DSET_LATENCY : DSET_BYTES);
581 d->ds_types[d->ds_num] = type;
583 if (parse_keys(ds_name, sizeof(ds_name), name)) {
587 sstrncpy(d->ds_names[d->ds_num], ds_name, DATA_MAX_NAME_LEN - 1);
588 d->ds_num = (d->ds_num + 1);
593 /******* ceph_config *******/
594 static int cc_handle_str(struct oconfig_item_s *item, char *dest,
597 if (item->values_num != 1) {
600 if (item->values[0].type != OCONFIG_TYPE_STRING) {
603 val = item->values[0].value.string;
604 if (snprintf(dest, dest_len, "%s", val) > (dest_len - 1)) {
605 ERROR("ceph plugin: configuration parameter '%s' is too long.\n",
607 return -ENAMETOOLONG;
612 static int cc_handle_bool(struct oconfig_item_s *item, int *dest) {
613 if (item->values_num != 1) {
617 if (item->values[0].type != OCONFIG_TYPE_BOOLEAN) {
621 *dest = (item->values[0].value.boolean) ? 1 : 0;
625 static int cc_add_daemon_config(oconfig_item_t *ci) {
627 struct ceph_daemon *nd, cd = {0};
628 struct ceph_daemon **tmp;
630 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
631 WARNING("ceph plugin: `Daemon' blocks need exactly one string "
636 ret = cc_handle_str(ci, cd.name, DATA_MAX_NAME_LEN);
641 for (int i = 0; i < ci->children_num; i++) {
642 oconfig_item_t *child = ci->children + i;
644 if (strcasecmp("SocketPath", child->key) == 0) {
645 ret = cc_handle_str(child, cd.asok_path, sizeof(cd.asok_path));
650 WARNING("ceph plugin: ignoring unknown option %s", child->key);
653 if (cd.name[0] == '\0') {
654 ERROR("ceph plugin: you must configure a daemon name.\n");
656 } else if (cd.asok_path[0] == '\0') {
657 ERROR("ceph plugin(name=%s): you must configure an administrative "
661 } else if (!((cd.asok_path[0] == '/') ||
662 (cd.asok_path[0] == '.' && cd.asok_path[1] == '/'))) {
663 ERROR("ceph plugin(name=%s): administrative socket paths must begin "
664 "with '/' or './' Can't parse: '%s'\n",
665 cd.name, cd.asok_path);
669 tmp = realloc(g_daemons, (g_num_daemons + 1) * sizeof(*g_daemons));
671 /* The positive return value here indicates that this is a
672 * runtime error, not a configuration error. */
677 nd = malloc(sizeof(*nd));
681 memcpy(nd, &cd, sizeof(*nd));
682 g_daemons[g_num_daemons] = nd;
687 static int ceph_config(oconfig_item_t *ci) {
690 for (int i = 0; i < ci->children_num; ++i) {
691 oconfig_item_t *child = ci->children + i;
692 if (strcasecmp("Daemon", child->key) == 0) {
693 ret = cc_add_daemon_config(child);
695 ERROR("ceph plugin: Couldn't allocate memory");
698 // process other daemons and ignore this one
701 } else if (strcasecmp("LongRunAvgLatency", child->key) == 0) {
702 ret = cc_handle_bool(child, &long_run_latency_avg);
706 } else if (strcasecmp("ConvertSpecialMetricTypes", child->key) == 0) {
707 ret = cc_handle_bool(child, &convert_special_metrics);
712 WARNING("ceph plugin: ignoring unknown option %s", child->key);
719 * Parse JSON and get error message if present
721 static int traverse_json(const unsigned char *json, uint32_t json_len,
723 yajl_status status = yajl_parse(hand, json, json_len);
727 case yajl_status_error:
728 msg = yajl_get_error(hand, /* verbose = */ 1,
729 /* jsonText = */ (unsigned char *)json,
730 (unsigned int)json_len);
731 ERROR("ceph plugin: yajl_parse failed: %s", msg);
732 yajl_free_error(hand, msg);
734 case yajl_status_client_canceled:
742 * Add entry for each counter while parsing schema
744 static int node_handler_define_schema(void *arg, const char *val,
746 struct ceph_daemon *d = (struct ceph_daemon *)arg;
749 return ceph_daemon_add_ds_entry(d, key, pc_type);
753 * Latency counter does not yet have an entry in last poll data - add it.
755 static int add_last(struct ceph_daemon *d, const char *ds_n, double cur_sum,
756 uint64_t cur_count) {
757 d->last_poll_data[d->last_idx] =
758 malloc(sizeof(*d->last_poll_data[d->last_idx]));
759 if (!d->last_poll_data[d->last_idx]) {
762 sstrncpy(d->last_poll_data[d->last_idx]->ds_name, ds_n,
763 sizeof(d->last_poll_data[d->last_idx]->ds_name));
764 d->last_poll_data[d->last_idx]->last_sum = cur_sum;
765 d->last_poll_data[d->last_idx]->last_count = cur_count;
766 d->last_idx = (d->last_idx + 1);
771 * Update latency counter or add new entry if it doesn't exist
773 static int update_last(struct ceph_daemon *d, const char *ds_n, int index,
774 double cur_sum, uint64_t cur_count) {
775 if ((d->last_idx > index) &&
776 (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0)) {
777 d->last_poll_data[index]->last_sum = cur_sum;
778 d->last_poll_data[index]->last_count = cur_count;
782 if (!d->last_poll_data) {
783 d->last_poll_data = malloc(sizeof(*d->last_poll_data));
784 if (!d->last_poll_data) {
788 struct last_data **tmp_last = realloc(
789 d->last_poll_data, ((d->last_idx + 1) * sizeof(struct last_data *)));
793 d->last_poll_data = tmp_last;
795 return add_last(d, ds_n, cur_sum, cur_count);
799 * If using index guess failed (shouldn't happen, but possible if counters
800 * get rearranged), resort to searching for counter name
802 static int backup_search_for_last_avg(struct ceph_daemon *d, const char *ds_n) {
803 for (int i = 0; i < d->last_idx; i++) {
804 if (strcmp(d->last_poll_data[i]->ds_name, ds_n) == 0) {
812 * Calculate average b/t current data and last poll data
813 * if last poll data exists
815 static double get_last_avg(struct ceph_daemon *d, const char *ds_n, int index,
816 double cur_sum, uint64_t cur_count) {
817 double result = -1.1, sum_delt = 0.0;
818 uint64_t count_delt = 0;
820 if (d->last_idx > index) {
821 if (strcmp(d->last_poll_data[index]->ds_name, ds_n) == 0) {
824 // test previous index
825 else if ((index > 0) &&
826 (strcmp(d->last_poll_data[index - 1]->ds_name, ds_n) == 0)) {
827 tmp_index = (index - 1);
829 tmp_index = backup_search_for_last_avg(d, ds_n);
832 if ((tmp_index > -1) &&
833 (cur_count > d->last_poll_data[tmp_index]->last_count)) {
834 sum_delt = (cur_sum - d->last_poll_data[tmp_index]->last_sum);
835 count_delt = (cur_count - d->last_poll_data[tmp_index]->last_count);
836 result = (sum_delt / count_delt);
840 if (result == -1.1) {
843 if (update_last(d, ds_n, tmp_index, cur_sum, cur_count) == -ENOMEM) {
850 * If using index guess failed, resort to searching for counter name
852 static uint32_t backup_search_for_type(struct ceph_daemon *d, char *ds_name) {
853 for (int i = 0; i < d->ds_num; i++) {
854 if (strcmp(d->ds_names[i], ds_name) == 0) {
855 return d->ds_types[i];
858 return DSET_TYPE_UNFOUND;
862 * Process counter data and dispatch values
864 static int node_handler_fetch_data(void *arg, const char *val,
869 struct values_tmp *vtmp = (struct values_tmp *)arg;
870 uint32_t type = DSET_TYPE_UNFOUND;
871 int index = vtmp->index;
873 char ds_name[DATA_MAX_NAME_LEN];
875 if (parse_keys(ds_name, sizeof(ds_name), key)) {
879 if (index >= vtmp->d->ds_num) {
880 // don't overflow bounds of array
881 index = (vtmp->d->ds_num - 1);
885 * counters should remain in same order we parsed schema... we maintain the
886 * index variable to keep track of current point in list of counters. first
887 * use index to guess point in array for retrieving type. if that doesn't
888 * work, use the old way to get the counter type
890 if (strcmp(ds_name, vtmp->d->ds_names[index]) == 0) {
892 type = vtmp->d->ds_types[index];
893 } else if ((index > 0) &&
894 (strcmp(ds_name, vtmp->d->ds_names[index - 1]) == 0)) {
896 type = vtmp->d->ds_types[index - 1];
899 if (type == DSET_TYPE_UNFOUND) {
900 // couldn't find right type by guessing, check the old way
901 type = backup_search_for_type(vtmp->d, ds_name);
906 if (has_suffix(key, ".avgcount")) {
907 sscanf(val, "%" PRIu64, &vtmp->avgcount);
908 // return after saving avgcount - don't dispatch value
909 // until latency calculation
911 } else if (has_suffix(key, ".sum")) {
912 if (vtmp->avgcount == 0) {
915 // user wants latency values as long run avg
917 if (long_run_latency_avg) {
921 sscanf(val, "%lf", &sum);
922 result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum,
924 if (result == -ENOMEM) {
928 vtmp->latency_index = (vtmp->latency_index + 1);
929 } else if (has_suffix(key, ".avgtime")) {
931 /* The "avgtime" metric reports ("sum" / "avgcount"), i.e. the average
932 * time per request since the start of the Ceph daemon. Report this only
933 * when the user has configured "long running average". Otherwise, use the
934 * rate of "sum" and "avgcount" to calculate the current latency.
937 if (!long_run_latency_avg) {
941 sscanf(val, "%lf", &result);
943 vtmp->latency_index = (vtmp->latency_index + 1);
945 WARNING("ceph plugin: ignoring unknown latency metric: %s", key);
950 sscanf(val, "%lf", &tmp_d);
954 sscanf(val, "%" PRIu64, &tmp_u);
957 case DSET_TYPE_UNFOUND:
959 ERROR("ceph plugin: ds %s was not properly initialized.", ds_name);
963 sstrncpy(vtmp->vlist.type, ceph_dset_types[type], sizeof(vtmp->vlist.type));
964 sstrncpy(vtmp->vlist.type_instance, ds_name,
965 sizeof(vtmp->vlist.type_instance));
966 vtmp->vlist.values = &uv;
967 vtmp->vlist.values_len = 1;
969 vtmp->index = (vtmp->index + 1);
970 plugin_dispatch_values(&vtmp->vlist);
975 static int cconn_connect(struct cconn *io) {
976 struct sockaddr_un address = {0};
978 if (io->state != CSTATE_UNCONNECTED) {
979 ERROR("ceph plugin: cconn_connect: io->state != CSTATE_UNCONNECTED");
982 fd = socket(PF_UNIX, SOCK_STREAM, 0);
985 ERROR("ceph plugin: cconn_connect: socket(PF_UNIX, SOCK_STREAM, 0) "
990 address.sun_family = AF_UNIX;
991 snprintf(address.sun_path, sizeof(address.sun_path), "%s", io->d->asok_path);
992 RETRY_ON_EINTR(err, connect(fd, (struct sockaddr *)&address,
993 sizeof(struct sockaddr_un)));
995 ERROR("ceph plugin: cconn_connect: connect(%d) failed: error %d", fd, err);
1000 flags = fcntl(fd, F_GETFL, 0);
1001 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
1003 ERROR("ceph plugin: cconn_connect: fcntl(%d, O_NONBLOCK) error %d", fd,
1009 io->state = CSTATE_WRITE_REQUEST;
1016 static void cconn_close(struct cconn *io) {
1017 io->state = CSTATE_UNCONNECTED;
1018 if (io->asok != -1) {
1020 RETRY_ON_EINTR(res, close(io->asok));
1029 /* Process incoming JSON counter data */
1030 static int cconn_process_data(struct cconn *io, yajl_struct *yajl,
1033 struct values_tmp *vtmp = calloc(1, sizeof(struct values_tmp) * 1);
1038 vtmp->vlist = (value_list_t)VALUE_LIST_INIT;
1039 sstrncpy(vtmp->vlist.plugin, "ceph", sizeof(vtmp->vlist.plugin));
1040 sstrncpy(vtmp->vlist.plugin_instance, io->d->name,
1041 sizeof(vtmp->vlist.plugin_instance));
1044 vtmp->latency_index = 0;
1046 yajl->handler_arg = vtmp;
1047 ret = traverse_json(io->json, io->json_len, hand);
1053 * Initiate JSON parsing and print error if one occurs
1055 static int cconn_process_json(struct cconn *io) {
1056 if ((io->request_type != ASOK_REQ_DATA) &&
1057 (io->request_type != ASOK_REQ_SCHEMA)) {
1065 hand = yajl_alloc(&callbacks,
1067 /* alloc funcs = */ NULL,
1069 /* alloc funcs = */ NULL, NULL,
1071 /* context = */ (void *)(&io->yajl));
1074 ERROR("ceph plugin: yajl_alloc failed.");
1080 switch (io->request_type) {
1082 io->yajl.handler = node_handler_fetch_data;
1083 result = cconn_process_data(io, &io->yajl, hand);
1085 case ASOK_REQ_SCHEMA:
1086 // init daemon specific variables
1088 io->d->last_idx = 0;
1089 io->d->last_poll_data = NULL;
1090 io->yajl.handler = node_handler_define_schema;
1091 io->yajl.handler_arg = io->d;
1092 result = traverse_json(io->json, io->json_len, hand);
1101 status = yajl_complete_parse(hand);
1103 status = yajl_parse_complete(hand);
1106 if (status != yajl_status_ok) {
1107 unsigned char *errmsg =
1108 yajl_get_error(hand, /* verbose = */ 0,
1109 /* jsonText = */ NULL, /* jsonTextLen = */ 0);
1110 ERROR("ceph plugin: yajl_parse_complete failed: %s", (char *)errmsg);
1111 yajl_free_error(hand, errmsg);
1121 static int cconn_validate_revents(struct cconn *io, int revents) {
1122 if (revents & POLLERR) {
1123 ERROR("ceph plugin: cconn_validate_revents(name=%s): got POLLERR",
1127 switch (io->state) {
1128 case CSTATE_WRITE_REQUEST:
1129 return (revents & POLLOUT) ? 0 : -EINVAL;
1130 case CSTATE_READ_VERSION:
1131 case CSTATE_READ_AMT:
1132 case CSTATE_READ_JSON:
1133 return (revents & POLLIN) ? 0 : -EINVAL;
1135 ERROR("ceph plugin: cconn_validate_revents(name=%s) got to "
1136 "illegal state on line %d",
1137 io->d->name, __LINE__);
1142 /** Handle a network event for a connection */
1143 static int cconn_handle_event(struct cconn *io) {
1145 switch (io->state) {
1146 case CSTATE_UNCONNECTED:
1147 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1149 io->d->name, __LINE__);
1152 case CSTATE_WRITE_REQUEST: {
1154 snprintf(cmd, sizeof(cmd), "%s%d%s", "{ \"prefix\": \"", io->request_type,
1156 size_t cmd_len = strlen(cmd);
1158 ret, write(io->asok, ((char *)&cmd) + io->amt, cmd_len - io->amt));
1159 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,amt=%d,ret=%d)",
1160 io->d->name, io->state, io->amt, ret);
1165 if (io->amt >= cmd_len) {
1167 switch (io->request_type) {
1168 case ASOK_REQ_VERSION:
1169 io->state = CSTATE_READ_VERSION;
1172 io->state = CSTATE_READ_AMT;
1178 case CSTATE_READ_VERSION: {
1179 RETRY_ON_EINTR(ret, read(io->asok, ((char *)(&io->d->version)) + io->amt,
1180 sizeof(io->d->version) - io->amt));
1181 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1182 io->d->name, io->state, ret);
1187 if (io->amt >= sizeof(io->d->version)) {
1188 io->d->version = ntohl(io->d->version);
1189 if (io->d->version != 1) {
1190 ERROR("ceph plugin: cconn_handle_event(name=%s) not "
1191 "expecting version %d!",
1192 io->d->name, io->d->version);
1195 DEBUG("ceph plugin: cconn_handle_event(name=%s): identified as "
1197 io->d->name, io->d->version);
1200 io->request_type = ASOK_REQ_SCHEMA;
1204 case CSTATE_READ_AMT: {
1205 RETRY_ON_EINTR(ret, read(io->asok, ((char *)(&io->json_len)) + io->amt,
1206 sizeof(io->json_len) - io->amt));
1207 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1208 io->d->name, io->state, ret);
1213 if (io->amt >= sizeof(io->json_len)) {
1214 io->json_len = ntohl(io->json_len);
1216 io->state = CSTATE_READ_JSON;
1217 io->json = calloc(1, io->json_len + 1);
1219 ERROR("ceph plugin: error callocing io->json");
1225 case CSTATE_READ_JSON: {
1227 read(io->asok, io->json + io->amt, io->json_len - io->amt));
1228 DEBUG("ceph plugin: cconn_handle_event(name=%s,state=%d,ret=%d)",
1229 io->d->name, io->state, ret);
1234 if (io->amt >= io->json_len) {
1235 ret = cconn_process_json(io);
1240 io->request_type = ASOK_REQ_NONE;
1245 ERROR("ceph plugin: cconn_handle_event(name=%s) got to illegal "
1247 io->d->name, __LINE__);
1252 static int cconn_prepare(struct cconn *io, struct pollfd *fds) {
1254 if (io->request_type == ASOK_REQ_NONE) {
1255 /* The request has already been serviced. */
1257 } else if ((io->request_type == ASOK_REQ_DATA) && (io->d->ds_num == 0)) {
1258 /* If there are no counters to report on, don't bother
1263 switch (io->state) {
1264 case CSTATE_UNCONNECTED:
1265 ret = cconn_connect(io);
1268 } else if (ret < 0) {
1272 fds->events = POLLOUT;
1274 case CSTATE_WRITE_REQUEST:
1276 fds->events = POLLOUT;
1278 case CSTATE_READ_VERSION:
1279 case CSTATE_READ_AMT:
1280 case CSTATE_READ_JSON:
1282 fds->events = POLLIN;
1285 ERROR("ceph plugin: cconn_prepare(name=%s) got to illegal state "
1287 io->d->name, __LINE__);
1292 /** Returns the difference between two struct timevals in milliseconds.
1293 * On overflow, we return max/min int.
1295 static int milli_diff(const struct timeval *t1, const struct timeval *t2) {
1297 int sec_diff = t1->tv_sec - t2->tv_sec;
1298 int usec_diff = t1->tv_usec - t2->tv_usec;
1299 ret = usec_diff / 1000;
1300 ret += (sec_diff * 1000);
1301 return (ret > INT_MAX) ? INT_MAX : ((ret < INT_MIN) ? INT_MIN : (int)ret);
1304 /** This handles the actual network I/O to talk to the Ceph daemons.
1306 static int cconn_main_loop(uint32_t request_type) {
1307 int ret, some_unreachable = 0;
1308 struct timeval end_tv;
1309 struct cconn io_array[g_num_daemons];
1311 DEBUG("ceph plugin: entering cconn_main_loop(request_type = %" PRIu32 ")",
1314 if (g_num_daemons < 1) {
1315 ERROR("ceph plugin: No daemons configured. See the \"Daemon\" config "
1320 /* create cconn array */
1321 for (size_t i = 0; i < g_num_daemons; i++) {
1322 io_array[i] = (struct cconn){
1324 .request_type = request_type,
1325 .state = CSTATE_UNCONNECTED,
1329 /** Calculate the time at which we should give up */
1330 gettimeofday(&end_tv, NULL);
1331 end_tv.tv_sec += CEPH_TIMEOUT_INTERVAL;
1336 struct cconn *polled_io_array[g_num_daemons];
1337 struct pollfd fds[g_num_daemons];
1338 memset(fds, 0, sizeof(fds));
1340 for (size_t i = 0; i < g_num_daemons; ++i) {
1341 struct cconn *io = io_array + i;
1342 ret = cconn_prepare(io, fds + nfds);
1344 WARNING("ceph plugin: cconn_prepare(name=%s,i=%" PRIsz ",st=%d)=%d",
1345 io->d->name, i, io->state, ret);
1347 io->request_type = ASOK_REQ_NONE;
1348 some_unreachable = 1;
1349 } else if (ret == 1) {
1350 polled_io_array[nfds++] = io_array + i;
1358 gettimeofday(&tv, NULL);
1359 diff = milli_diff(&end_tv, &tv);
1363 WARNING("ceph plugin: cconn_main_loop: timed out.");
1366 RETRY_ON_EINTR(ret, poll(fds, nfds, diff));
1368 ERROR("ceph plugin: poll(2) error: %d", ret);
1371 for (int i = 0; i < nfds; ++i) {
1372 struct cconn *io = polled_io_array[i];
1373 int revents = fds[i].revents;
1377 } else if (cconn_validate_revents(io, revents)) {
1378 WARNING("ceph plugin: cconn(name=%s,i=%d,st=%d): "
1379 "revents validation error: "
1381 io->d->name, i, io->state, revents);
1383 io->request_type = ASOK_REQ_NONE;
1384 some_unreachable = 1;
1386 ret = cconn_handle_event(io);
1388 WARNING("ceph plugin: cconn_handle_event(name=%s,"
1389 "i=%d,st=%d): error %d",
1390 io->d->name, i, io->state, ret);
1392 io->request_type = ASOK_REQ_NONE;
1393 some_unreachable = 1;
1399 for (size_t i = 0; i < g_num_daemons; ++i) {
1400 cconn_close(io_array + i);
1402 if (some_unreachable) {
1403 DEBUG("ceph plugin: cconn_main_loop: some Ceph daemons were unreachable.");
1405 DEBUG("ceph plugin: cconn_main_loop: reached all Ceph daemons :)");
1410 static int ceph_read(void) { return cconn_main_loop(ASOK_REQ_DATA); }
1412 /******* lifecycle *******/
1413 static int ceph_init(void) {
1414 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_DAC_OVERRIDE)
1415 if (check_capability(CAP_DAC_OVERRIDE) != 0) {
1417 WARNING("ceph plugin: Running collectd as root, but the "
1418 "CAP_DAC_OVERRIDE capability is missing. The plugin's read "
1419 "function will probably fail. Is your init system dropping "
1423 "ceph plugin: collectd doesn't have the CAP_DAC_OVERRIDE "
1424 "capability. If you don't want to run collectd as root, try running "
1425 "\"setcap cap_dac_override=ep\" on the collectd binary.");
1429 ceph_daemons_print();
1431 if (g_num_daemons < 1) {
1432 ERROR("ceph plugin: No daemons configured. See the \"Daemon\" config "
1437 return cconn_main_loop(ASOK_REQ_VERSION);
1440 static int ceph_shutdown(void) {
1441 for (size_t i = 0; i < g_num_daemons; ++i) {
1442 ceph_daemon_free(g_daemons[i]);
1447 DEBUG("ceph plugin: finished ceph_shutdown");
1451 void module_register(void) {
1452 plugin_register_complex_config("ceph", ceph_config);
1453 plugin_register_init("ceph", ceph_init);
1454 plugin_register_read("ceph", ceph_read);
1455 plugin_register_shutdown("ceph", ceph_shutdown);