3 * Copyright (C) 2008-2015 Florian octo Forster
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
24 * Florian octo Forster <octo at collectd.org>
31 #include "utils_db_query.h"
35 /* libdbi 0.9.0 introduced a new thread-safe interface and marked the old
36 * functions "deprecated". These macros convert the new functions to their old
37 * counterparts for backwards compatibility. */
38 #if !defined(LIBDBI_VERSION) || (LIBDBI_VERSION < 900)
39 #define HAVE_LEGACY_LIBDBI 1
40 #define dbi_initialize_r(a, inst) dbi_initialize(a)
41 #define dbi_shutdown_r(inst) dbi_shutdown()
42 #define dbi_set_verbosity_r(a, inst) dbi_set_verbosity(a)
43 #define dbi_driver_list_r(a, inst) dbi_driver_list(a)
44 #define dbi_driver_open_r(a, inst) dbi_driver_open(a)
50 struct cdbi_driver_option_s /* {{{ */
59 typedef struct cdbi_driver_option_s cdbi_driver_option_t; /* }}} */
61 struct cdbi_database_s /* {{{ */
70 cdbi_driver_option_t *driver_options;
71 size_t driver_options_num;
73 udb_query_preparation_area_t **q_prep_areas;
74 udb_query_t **queries;
79 typedef struct cdbi_database_s cdbi_database_t; /* }}} */
84 #if !defined(HAVE_LEGACY_LIBDBI) || !HAVE_LEGACY_LIBDBI
85 static dbi_inst dbi_instance = 0;
87 static udb_query_t **queries = NULL;
88 static size_t queries_num = 0;
89 static cdbi_database_t **databases = NULL;
90 static size_t databases_num = 0;
92 static int cdbi_read_database(user_data_t *ud);
97 static const char *cdbi_strerror(dbi_conn conn, /* {{{ */
98 char *buffer, size_t buffer_size) {
103 sstrncpy(buffer, "connection is NULL", buffer_size);
108 status = dbi_conn_error(conn, &msg);
109 if ((status >= 0) && (msg != NULL))
110 ssnprintf(buffer, buffer_size, "%s (status %i)", msg, status);
112 ssnprintf(buffer, buffer_size, "dbi_conn_error failed with status %i",
116 } /* }}} const char *cdbi_conn_error */
118 static int cdbi_result_get_field(dbi_result res, /* {{{ */
119 unsigned int index, char *buffer,
120 size_t buffer_size) {
121 unsigned short src_type;
123 src_type = dbi_result_get_field_type_idx(res, index);
124 if (src_type == DBI_TYPE_ERROR) {
125 ERROR("dbi plugin: cdbi_result_get: "
126 "dbi_result_get_field_type_idx failed.");
130 if (src_type == DBI_TYPE_INTEGER) {
133 value = dbi_result_get_longlong_idx(res, index);
134 ssnprintf(buffer, buffer_size, "%lli", value);
135 } else if (src_type == DBI_TYPE_DECIMAL) {
138 value = dbi_result_get_double_idx(res, index);
139 ssnprintf(buffer, buffer_size, "%63.15g", value);
140 } else if (src_type == DBI_TYPE_STRING) {
143 value = dbi_result_get_string_idx(res, index);
145 sstrncpy(buffer, "", buffer_size);
146 else if (strcmp("ERROR", value) == 0)
149 sstrncpy(buffer, value, buffer_size);
151 /* DBI_TYPE_BINARY */
152 /* DBI_TYPE_DATETIME */
154 const char *field_name;
156 field_name = dbi_result_get_field_name(res, index);
157 if (field_name == NULL)
158 field_name = "<unknown>";
160 ERROR("dbi plugin: Column `%s': Don't know how to handle "
162 field_name, src_type);
167 } /* }}} int cdbi_result_get_field */
169 static void cdbi_database_free(cdbi_database_t *db) /* {{{ */
177 for (size_t i = 0; i < db->driver_options_num; i++) {
178 sfree(db->driver_options[i].key);
179 if (!db->driver_options[i].is_numeric)
180 sfree(db->driver_options[i].value.string);
182 sfree(db->driver_options);
184 if (db->q_prep_areas)
185 for (size_t i = 0; i < db->queries_num; ++i)
186 udb_query_delete_preparation_area(db->q_prep_areas[i]);
187 free(db->q_prep_areas);
190 } /* }}} void cdbi_database_free */
192 /* Configuration handling functions {{{
195 * <Query "plugin_instance0">
196 * Statement "SELECT name, value FROM table"
199 * InstancesFrom "name"
205 * <Database "plugin_instance1">
208 * DriverOption "hostname" "localhost"
210 * Query "plugin_instance0"
215 static int cdbi_config_add_database_driver_option(cdbi_database_t *db, /* {{{ */
216 oconfig_item_t *ci) {
217 cdbi_driver_option_t *option;
219 if ((ci->values_num != 2) || (ci->values[0].type != OCONFIG_TYPE_STRING) ||
220 ((ci->values[1].type != OCONFIG_TYPE_STRING) &&
221 (ci->values[1].type != OCONFIG_TYPE_NUMBER))) {
222 WARNING("dbi plugin: The `DriverOption' config option "
223 "needs exactly two arguments.");
227 option = realloc(db->driver_options,
228 sizeof(*option) * (db->driver_options_num + 1));
229 if (option == NULL) {
230 ERROR("dbi plugin: realloc failed");
234 db->driver_options = option;
235 option = db->driver_options + db->driver_options_num;
236 memset(option, 0, sizeof(*option));
238 option->key = strdup(ci->values[0].value.string);
239 if (option->key == NULL) {
240 ERROR("dbi plugin: strdup failed.");
244 if (ci->values[1].type == OCONFIG_TYPE_STRING) {
245 option->value.string = strdup(ci->values[1].value.string);
246 if (option->value.string == NULL) {
247 ERROR("dbi plugin: strdup failed.");
252 assert(ci->values[1].type == OCONFIG_TYPE_NUMBER);
253 option->value.numeric = (int)(ci->values[1].value.number + .5);
254 option->is_numeric = 1;
257 db->driver_options_num++;
259 } /* }}} int cdbi_config_add_database_driver_option */
261 static int cdbi_config_add_database(oconfig_item_t *ci) /* {{{ */
266 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
267 WARNING("dbi plugin: The `Database' block "
268 "needs exactly one string argument.");
272 db = calloc(1, sizeof(*db));
274 ERROR("dbi plugin: calloc failed.");
278 status = cf_util_get_string(ci, &db->name);
284 /* Fill the `cdbi_database_t' structure.. */
285 for (int i = 0; i < ci->children_num; i++) {
286 oconfig_item_t *child = ci->children + i;
288 if (strcasecmp("Driver", child->key) == 0)
289 status = cf_util_get_string(child, &db->driver);
290 else if (strcasecmp("DriverOption", child->key) == 0)
291 status = cdbi_config_add_database_driver_option(db, child);
292 else if (strcasecmp("SelectDB", child->key) == 0)
293 status = cf_util_get_string(child, &db->select_db);
294 else if (strcasecmp("Query", child->key) == 0)
295 status = udb_query_pick_from_list(child, queries, queries_num,
296 &db->queries, &db->queries_num);
297 else if (strcasecmp("Host", child->key) == 0)
298 status = cf_util_get_string(child, &db->host);
299 else if (strcasecmp("Interval", child->key) == 0)
300 status = cf_util_get_cdtime(child, &db->interval);
302 WARNING("dbi plugin: Option `%s' not allowed here.", child->key);
310 /* Check that all necessary options have been given. */
311 while (status == 0) {
312 if (db->driver == NULL) {
313 WARNING("dbi plugin: `Driver' not given for database `%s'", db->name);
316 if (db->driver_options_num == 0) {
317 WARNING("dbi plugin: No `DriverOption' given for database `%s'. "
318 "This will likely not work.",
323 } /* while (status == 0) */
325 while ((status == 0) && (db->queries_num > 0)) {
326 db->q_prep_areas = calloc(db->queries_num, sizeof(*db->q_prep_areas));
327 if (db->q_prep_areas == NULL) {
328 WARNING("dbi plugin: calloc failed");
333 for (size_t i = 0; i < db->queries_num; ++i) {
334 db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
336 if (db->q_prep_areas[i] == NULL) {
337 WARNING("dbi plugin: udb_query_allocate_preparation_area failed");
346 /* If all went well, add this database to the global list of databases. */
348 cdbi_database_t **temp;
350 temp = realloc(databases, sizeof(*databases) * (databases_num + 1));
352 ERROR("dbi plugin: realloc failed");
358 databases[databases_num] = db;
361 name = ssnprintf_alloc("dbi:%s", db->name);
363 user_data_t ud = {.data = db};
365 plugin_register_complex_read(
367 /* name = */ name ? name : db->name,
368 /* callback = */ cdbi_read_database,
369 /* interval = */ (db->interval > 0) ? db->interval : 0,
370 /* user_data = */ &ud);
376 cdbi_database_free(db);
381 } /* }}} int cdbi_config_add_database */
383 static int cdbi_config(oconfig_item_t *ci) /* {{{ */
385 for (int i = 0; i < ci->children_num; i++) {
386 oconfig_item_t *child = ci->children + i;
387 if (strcasecmp("Query", child->key) == 0)
388 udb_query_create(&queries, &queries_num, child,
389 /* callback = */ NULL);
390 else if (strcasecmp("Database", child->key) == 0)
391 cdbi_config_add_database(child);
393 WARNING("dbi plugin: Ignoring unknown config option `%s'.", child->key);
395 } /* for (ci->children) */
398 } /* }}} int cdbi_config */
400 /* }}} End of configuration handling functions */
402 static int cdbi_init(void) /* {{{ */
404 static int did_init = 0;
410 if (queries_num == 0) {
411 ERROR("dbi plugin: No <Query> blocks have been found. Without them, "
412 "this plugin can't do anything useful, so we will returns an error.");
416 if (databases_num == 0) {
417 ERROR("dbi plugin: No <Database> blocks have been found. Without them, "
418 "this plugin can't do anything useful, so we will returns an error.");
422 status = dbi_initialize_r(/* driverdir = */ NULL, &dbi_instance);
424 ERROR("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
427 } else if (status == 0) {
428 ERROR("dbi plugin: `dbi_initialize_r' could not load any drivers. Please "
429 "install at least one `DBD' or check your installation.");
432 DEBUG("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.", status,
433 (status == 1) ? "" : "s");
436 } /* }}} int cdbi_init */
438 static int cdbi_read_database_query(cdbi_database_t *db, /* {{{ */
440 udb_query_preparation_area_t *prep_area) {
441 const char *statement;
445 char **column_values;
448 /* Macro that cleans up dynamically allocated memory and returns the
449 * specified status. */
450 #define BAIL_OUT(status) \
451 if (column_names != NULL) { \
452 sfree(column_names[0]); \
453 sfree(column_names); \
455 if (column_values != NULL) { \
456 sfree(column_values[0]); \
457 sfree(column_values); \
460 dbi_result_free(res); \
466 column_values = NULL;
468 statement = udb_query_get_statement(q);
469 assert(statement != NULL);
471 res = dbi_conn_query(db->connection, statement);
474 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
475 "dbi_conn_query failed: %s",
476 db->name, udb_query_get_name(q),
477 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
479 } else /* Get the number of columns */
481 unsigned int db_status;
483 db_status = dbi_result_get_numfields(res);
484 if (db_status == DBI_FIELD_ERROR) {
486 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
487 "dbi_result_get_numfields failed: %s",
488 db->name, udb_query_get_name(q),
489 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
493 column_num = (size_t)db_status;
494 DEBUG("cdbi_read_database_query (%s, %s): There are %zu columns.", db->name,
495 udb_query_get_name(q), column_num);
498 /* Allocate `column_names' and `column_values'. {{{ */
499 column_names = calloc(column_num, sizeof(*column_names));
500 if (column_names == NULL) {
501 ERROR("dbi plugin: calloc failed.");
505 column_names[0] = calloc(column_num, DATA_MAX_NAME_LEN);
506 if (column_names[0] == NULL) {
507 ERROR("dbi plugin: calloc failed.");
510 for (size_t i = 1; i < column_num; i++)
511 column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
513 column_values = calloc(column_num, sizeof(*column_values));
514 if (column_values == NULL) {
515 ERROR("dbi plugin: calloc failed.");
519 column_values[0] = calloc(column_num, DATA_MAX_NAME_LEN);
520 if (column_values[0] == NULL) {
521 ERROR("dbi plugin: calloc failed.");
524 for (size_t i = 1; i < column_num; i++)
525 column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
528 /* Copy the field names to `column_names' */
529 for (size_t i = 0; i < column_num; i++) /* {{{ */
531 const char *column_name;
533 column_name = dbi_result_get_field_name(res, (unsigned int)(i + 1));
534 if (column_name == NULL) {
535 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
536 "Cannot retrieve name of field %zu.",
537 db->name, udb_query_get_name(q), i + 1);
541 sstrncpy(column_names[i], column_name, DATA_MAX_NAME_LEN);
542 } /* }}} for (i = 0; i < column_num; i++) */
544 udb_query_prepare_result(
545 q, prep_area, (db->host ? db->host : hostname_g),
546 /* plugin = */ "dbi", db->name, column_names, column_num,
547 /* interval = */ (db->interval > 0) ? db->interval : 0);
549 /* 0 = error; 1 = success; */
550 status = dbi_result_first_row(res); /* {{{ */
553 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
554 "dbi_result_first_row failed: %s. Maybe the statement didn't "
556 db->name, udb_query_get_name(q),
557 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
558 udb_query_finish_result(q, prep_area);
562 /* Iterate over all rows and call `udb_query_handle_result' with each list of
567 /* Copy the value of the columns to `column_values' */
568 for (size_t i = 0; i < column_num; i++) /* {{{ */
570 status = cdbi_result_get_field(res, (unsigned int)(i + 1),
571 column_values[i], DATA_MAX_NAME_LEN);
574 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
575 "cdbi_result_get_field (%zu) failed.",
576 db->name, udb_query_get_name(q), i + 1);
580 } /* }}} for (i = 0; i < column_num; i++) */
582 /* If all values were copied successfully, call `udb_query_handle_result'
583 * to dispatch the row to the daemon. */
584 if (status == 0) /* {{{ */
586 status = udb_query_handle_result(q, prep_area, column_values);
588 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
589 "udb_query_handle_result failed.",
590 db->name, udb_query_get_name(q));
594 /* Get the next row from the database. */
595 status = dbi_result_next_row(res); /* {{{ */
597 if (dbi_conn_error(db->connection, NULL) != 0) {
599 WARNING("dbi plugin: cdbi_read_database_query (%s, %s): "
600 "dbi_result_next_row failed: %s.",
601 db->name, udb_query_get_name(q),
602 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
606 } /* }}} while (42) */
608 /* Tell the db query interface that we're done with this query. */
609 udb_query_finish_result(q, prep_area);
611 /* Clean up and return `status = 0' (success) */
614 } /* }}} int cdbi_read_database_query */
616 static int cdbi_connect_database(cdbi_database_t *db) /* {{{ */
622 if (db->connection != NULL) {
623 status = dbi_conn_ping(db->connection);
624 if (status != 0) /* connection is alive */
627 dbi_conn_close(db->connection);
628 db->connection = NULL;
631 driver = dbi_driver_open_r(db->driver, dbi_instance);
632 if (driver == NULL) {
633 ERROR("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.",
635 INFO("dbi plugin: Maybe the driver isn't installed? "
636 "Known drivers are:");
637 for (driver = dbi_driver_list_r(NULL, dbi_instance); driver != NULL;
638 driver = dbi_driver_list_r(driver, dbi_instance)) {
639 INFO("dbi plugin: * %s", dbi_driver_get_name(driver));
644 connection = dbi_conn_open(driver);
645 if (connection == NULL) {
646 ERROR("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
651 /* Set all the driver options. Because this is a very very very generic
652 * interface, the error handling is kind of long. If an invalid option is
653 * encountered, it will get a list of options understood by the driver and
654 * report that as `INFO'. This way, users hopefully don't have too much
655 * trouble finding out how to configure the plugin correctly.. */
656 for (size_t i = 0; i < db->driver_options_num; i++) {
657 if (db->driver_options[i].is_numeric) {
659 dbi_conn_set_option_numeric(connection, db->driver_options[i].key,
660 db->driver_options[i].value.numeric);
663 ERROR("dbi plugin: cdbi_connect_database (%s): "
664 "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.",
665 db->name, db->driver_options[i].key,
666 db->driver_options[i].value.numeric,
667 cdbi_strerror(connection, errbuf, sizeof(errbuf)));
670 status = dbi_conn_set_option(connection, db->driver_options[i].key,
671 db->driver_options[i].value.string);
674 ERROR("dbi plugin: cdbi_connect_database (%s): "
675 "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.",
676 db->name, db->driver_options[i].key,
677 db->driver_options[i].value.string,
678 cdbi_strerror(connection, errbuf, sizeof(errbuf)));
683 INFO("dbi plugin: This is a list of all options understood "
684 "by the `%s' driver:",
686 for (const char *opt = dbi_conn_get_option_list(connection, NULL);
687 opt != NULL; opt = dbi_conn_get_option_list(connection, opt)) {
688 INFO("dbi plugin: * %s", opt);
691 dbi_conn_close(connection);
694 } /* for (i = 0; i < db->driver_options_num; i++) */
696 status = dbi_conn_connect(connection);
699 ERROR("dbi plugin: cdbi_connect_database (%s): "
700 "dbi_conn_connect failed: %s",
701 db->name, cdbi_strerror(connection, errbuf, sizeof(errbuf)));
702 dbi_conn_close(connection);
706 if (db->select_db != NULL) {
707 status = dbi_conn_select_db(connection, db->select_db);
711 "dbi plugin: cdbi_connect_database (%s): "
712 "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
713 db->name, db->select_db,
714 cdbi_strerror(connection, errbuf, sizeof(errbuf)));
715 dbi_conn_close(connection);
720 db->connection = connection;
722 } /* }}} int cdbi_connect_database */
724 static int cdbi_read_database(user_data_t *ud) /* {{{ */
726 cdbi_database_t *db = (cdbi_database_t *)ud->data;
730 unsigned int db_version;
732 status = cdbi_connect_database(db);
735 assert(db->connection != NULL);
737 db_version = dbi_conn_get_engine_version(db->connection);
738 /* TODO: Complain if `db_version == 0' */
741 for (size_t i = 0; i < db->queries_num; i++) {
742 /* Check if we know the database's version and if so, if this query applies
743 * to that version. */
744 if ((db_version != 0) &&
745 (udb_query_check_version(db->queries[i], db_version) == 0))
748 status = cdbi_read_database_query(db, db->queries[i], db->q_prep_areas[i]);
754 ERROR("dbi plugin: All queries failed for database `%s'.", db->name);
759 } /* }}} int cdbi_read_database */
761 static int cdbi_shutdown(void) /* {{{ */
763 for (size_t i = 0; i < databases_num; i++) {
764 if (databases[i]->connection != NULL) {
765 dbi_conn_close(databases[i]->connection);
766 databases[i]->connection = NULL;
768 cdbi_database_free(databases[i]);
773 udb_query_free(queries, queries_num);
778 } /* }}} int cdbi_shutdown */
780 void module_register(void) /* {{{ */
782 plugin_register_complex_config("dbi", cdbi_config);
783 plugin_register_init("dbi", cdbi_init);
784 plugin_register_shutdown("dbi", cdbi_shutdown);
785 } /* }}} void module_register */
788 * vim: shiftwidth=2 softtabstop=2 et fdm=marker