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 /* {{{ */
71 cdbi_driver_option_t *driver_options;
72 size_t driver_options_num;
74 udb_query_preparation_area_t **q_prep_areas;
75 udb_query_t **queries;
80 typedef struct cdbi_database_s cdbi_database_t; /* }}} */
85 #if !defined(HAVE_LEGACY_LIBDBI) || !HAVE_LEGACY_LIBDBI
86 static dbi_inst dbi_instance = 0;
88 static udb_query_t **queries = NULL;
89 static size_t queries_num = 0;
90 static cdbi_database_t **databases = NULL;
91 static size_t databases_num = 0;
93 static int cdbi_read_database(user_data_t *ud);
98 static const char *cdbi_strerror(dbi_conn conn, /* {{{ */
99 char *buffer, size_t buffer_size) {
104 sstrncpy(buffer, "connection is NULL", buffer_size);
109 status = dbi_conn_error(conn, &msg);
110 if ((status >= 0) && (msg != NULL))
111 ssnprintf(buffer, buffer_size, "%s (status %i)", msg, status);
113 ssnprintf(buffer, buffer_size, "dbi_conn_error failed with status %i",
117 } /* }}} const char *cdbi_conn_error */
119 static int cdbi_result_get_field(dbi_result res, /* {{{ */
120 unsigned int index, char *buffer,
121 size_t buffer_size) {
122 unsigned short src_type;
124 src_type = dbi_result_get_field_type_idx(res, index);
125 if (src_type == DBI_TYPE_ERROR) {
126 ERROR("dbi plugin: cdbi_result_get: "
127 "dbi_result_get_field_type_idx failed.");
131 if (src_type == DBI_TYPE_INTEGER) {
134 value = dbi_result_get_longlong_idx(res, index);
135 ssnprintf(buffer, buffer_size, "%lli", value);
136 } else if (src_type == DBI_TYPE_DECIMAL) {
139 value = dbi_result_get_double_idx(res, index);
140 ssnprintf(buffer, buffer_size, "%63.15g", value);
141 } else if (src_type == DBI_TYPE_STRING) {
144 value = dbi_result_get_string_idx(res, index);
146 sstrncpy(buffer, "", buffer_size);
147 else if (strcmp("ERROR", value) == 0)
150 sstrncpy(buffer, value, buffer_size);
152 /* DBI_TYPE_BINARY */
153 /* DBI_TYPE_DATETIME */
155 const char *field_name;
157 field_name = dbi_result_get_field_name(res, index);
158 if (field_name == NULL)
159 field_name = "<unknown>";
161 ERROR("dbi plugin: Column `%s': Don't know how to handle "
163 field_name, src_type);
168 } /* }}} int cdbi_result_get_field */
170 static void cdbi_database_free(cdbi_database_t *db) /* {{{ */
176 sfree(db->select_db);
177 sfree(db->plugin_name);
181 for (size_t i = 0; i < db->driver_options_num; i++) {
182 sfree(db->driver_options[i].key);
183 if (!db->driver_options[i].is_numeric)
184 sfree(db->driver_options[i].value.string);
186 sfree(db->driver_options);
188 if (db->q_prep_areas)
189 for (size_t i = 0; i < db->queries_num; ++i)
190 udb_query_delete_preparation_area(db->q_prep_areas[i]);
191 free(db->q_prep_areas);
194 } /* }}} void cdbi_database_free */
196 /* Configuration handling functions {{{
199 * <Query "plugin_instance0">
200 * Statement "SELECT name, value FROM table"
203 * InstancesFrom "name"
209 * <Database "plugin_instance1">
212 * DriverOption "hostname" "localhost"
214 * Query "plugin_instance0"
219 static int cdbi_config_add_database_driver_option(cdbi_database_t *db, /* {{{ */
220 oconfig_item_t *ci) {
221 cdbi_driver_option_t *option;
223 if ((ci->values_num != 2) || (ci->values[0].type != OCONFIG_TYPE_STRING) ||
224 ((ci->values[1].type != OCONFIG_TYPE_STRING) &&
225 (ci->values[1].type != OCONFIG_TYPE_NUMBER))) {
226 WARNING("dbi plugin: The `DriverOption' config option "
227 "needs exactly two arguments.");
231 option = realloc(db->driver_options,
232 sizeof(*option) * (db->driver_options_num + 1));
233 if (option == NULL) {
234 ERROR("dbi plugin: realloc failed");
238 db->driver_options = option;
239 option = db->driver_options + db->driver_options_num;
240 memset(option, 0, sizeof(*option));
242 option->key = strdup(ci->values[0].value.string);
243 if (option->key == NULL) {
244 ERROR("dbi plugin: strdup failed.");
248 if (ci->values[1].type == OCONFIG_TYPE_STRING) {
249 option->value.string = strdup(ci->values[1].value.string);
250 if (option->value.string == NULL) {
251 ERROR("dbi plugin: strdup failed.");
256 assert(ci->values[1].type == OCONFIG_TYPE_NUMBER);
257 option->value.numeric = (int)(ci->values[1].value.number + .5);
258 option->is_numeric = 1;
261 db->driver_options_num++;
263 } /* }}} int cdbi_config_add_database_driver_option */
265 static int cdbi_config_add_database(oconfig_item_t *ci) /* {{{ */
270 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
271 WARNING("dbi plugin: The `Database' block "
272 "needs exactly one string argument.");
276 db = calloc(1, sizeof(*db));
278 ERROR("dbi plugin: calloc failed.");
282 status = cf_util_get_string(ci, &db->name);
288 /* Fill the `cdbi_database_t' structure.. */
289 for (int i = 0; i < ci->children_num; i++) {
290 oconfig_item_t *child = ci->children + i;
292 if (strcasecmp("Driver", child->key) == 0)
293 status = cf_util_get_string(child, &db->driver);
294 else if (strcasecmp("DriverOption", child->key) == 0)
295 status = cdbi_config_add_database_driver_option(db, child);
296 else if (strcasecmp("SelectDB", child->key) == 0)
297 status = cf_util_get_string(child, &db->select_db);
298 else if (strcasecmp("Query", child->key) == 0)
299 status = udb_query_pick_from_list(child, queries, queries_num,
300 &db->queries, &db->queries_num);
301 else if (strcasecmp("Host", child->key) == 0)
302 status = cf_util_get_string(child, &db->host);
303 else if (strcasecmp("Interval", child->key) == 0)
304 status = cf_util_get_cdtime(child, &db->interval);
305 else if (strcasecmp("PluginName", child->key) == 0)
306 status = cf_util_get_string(child, &db->plugin_name);
308 WARNING("dbi plugin: Option `%s' not allowed here.", child->key);
316 /* Check that all necessary options have been given. */
317 while (status == 0) {
318 if (db->driver == NULL) {
319 WARNING("dbi plugin: `Driver' not given for database `%s'", db->name);
322 if (db->driver_options_num == 0) {
323 WARNING("dbi plugin: No `DriverOption' given for database `%s'. "
324 "This will likely not work.",
329 } /* while (status == 0) */
331 while ((status == 0) && (db->queries_num > 0)) {
332 db->q_prep_areas = calloc(db->queries_num, sizeof(*db->q_prep_areas));
333 if (db->q_prep_areas == NULL) {
334 WARNING("dbi plugin: calloc failed");
339 for (size_t i = 0; i < db->queries_num; ++i) {
340 db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
342 if (db->q_prep_areas[i] == NULL) {
343 WARNING("dbi plugin: udb_query_allocate_preparation_area failed");
352 /* If all went well, add this database to the global list of databases. */
354 cdbi_database_t **temp;
356 temp = realloc(databases, sizeof(*databases) * (databases_num + 1));
358 ERROR("dbi plugin: realloc failed");
362 databases[databases_num] = db;
365 char *name = ssnprintf_alloc("dbi:%s", db->name);
366 plugin_register_complex_read(
368 /* name = */ name ? name : db->name,
369 /* callback = */ cdbi_read_database,
370 /* interval = */ (db->interval > 0) ? db->interval : 0,
379 cdbi_database_free(db);
384 } /* }}} int cdbi_config_add_database */
386 static int cdbi_config(oconfig_item_t *ci) /* {{{ */
388 for (int i = 0; i < ci->children_num; i++) {
389 oconfig_item_t *child = ci->children + i;
390 if (strcasecmp("Query", child->key) == 0)
391 udb_query_create(&queries, &queries_num, child,
392 /* callback = */ NULL);
393 else if (strcasecmp("Database", child->key) == 0)
394 cdbi_config_add_database(child);
396 WARNING("dbi plugin: Ignoring unknown config option `%s'.", child->key);
398 } /* for (ci->children) */
401 } /* }}} int cdbi_config */
403 /* }}} End of configuration handling functions */
405 static int cdbi_init(void) /* {{{ */
407 static int did_init = 0;
413 if (queries_num == 0) {
414 ERROR("dbi plugin: No <Query> blocks have been found. Without them, "
415 "this plugin can't do anything useful, so we will return an error.");
419 if (databases_num == 0) {
420 ERROR("dbi plugin: No <Database> blocks have been found. Without them, "
421 "this plugin can't do anything useful, so we will return an error.");
425 status = dbi_initialize_r(/* driverdir = */ NULL, &dbi_instance);
427 ERROR("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
430 } else if (status == 0) {
431 ERROR("dbi plugin: `dbi_initialize_r' could not load any drivers. Please "
432 "install at least one `DBD' or check your installation.");
435 DEBUG("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.", status,
436 (status == 1) ? "" : "s");
439 } /* }}} int cdbi_init */
441 static int cdbi_read_database_query(cdbi_database_t *db, /* {{{ */
443 udb_query_preparation_area_t *prep_area) {
444 const char *statement;
448 char **column_values;
451 /* Macro that cleans up dynamically allocated memory and returns the
452 * specified status. */
453 #define BAIL_OUT(status) \
454 if (column_names != NULL) { \
455 sfree(column_names[0]); \
456 sfree(column_names); \
458 if (column_values != NULL) { \
459 sfree(column_values[0]); \
460 sfree(column_values); \
463 dbi_result_free(res); \
469 column_values = NULL;
471 statement = udb_query_get_statement(q);
472 assert(statement != NULL);
474 res = dbi_conn_query(db->connection, statement);
477 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
478 "dbi_conn_query failed: %s",
479 db->name, udb_query_get_name(q),
480 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
482 } else /* Get the number of columns */
484 unsigned int db_status;
486 db_status = dbi_result_get_numfields(res);
487 if (db_status == DBI_FIELD_ERROR) {
489 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
490 "dbi_result_get_numfields failed: %s",
491 db->name, udb_query_get_name(q),
492 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
496 column_num = (size_t)db_status;
497 DEBUG("cdbi_read_database_query (%s, %s): There are %zu columns.", db->name,
498 udb_query_get_name(q), column_num);
501 /* Allocate `column_names' and `column_values'. {{{ */
502 column_names = calloc(column_num, sizeof(*column_names));
503 if (column_names == NULL) {
504 ERROR("dbi plugin: calloc failed.");
508 column_names[0] = calloc(column_num, DATA_MAX_NAME_LEN);
509 if (column_names[0] == NULL) {
510 ERROR("dbi plugin: calloc failed.");
513 for (size_t i = 1; i < column_num; i++)
514 column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
516 column_values = calloc(column_num, sizeof(*column_values));
517 if (column_values == NULL) {
518 ERROR("dbi plugin: calloc failed.");
522 column_values[0] = calloc(column_num, DATA_MAX_NAME_LEN);
523 if (column_values[0] == NULL) {
524 ERROR("dbi plugin: calloc failed.");
527 for (size_t i = 1; i < column_num; i++)
528 column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
531 /* Copy the field names to `column_names' */
532 for (size_t i = 0; i < column_num; i++) /* {{{ */
534 const char *column_name;
536 column_name = dbi_result_get_field_name(res, (unsigned int)(i + 1));
537 if (column_name == NULL) {
538 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
539 "Cannot retrieve name of field %zu.",
540 db->name, udb_query_get_name(q), i + 1);
544 sstrncpy(column_names[i], column_name, DATA_MAX_NAME_LEN);
545 } /* }}} for (i = 0; i < column_num; i++) */
547 udb_query_prepare_result(
548 q, prep_area, (db->host ? db->host : hostname_g),
549 /* plugin = */ (db->plugin_name != NULL) ? db->plugin_name : "dbi",
550 db->name, column_names, column_num,
551 /* interval = */ (db->interval > 0) ? db->interval : 0);
553 /* 0 = error; 1 = success; */
554 status = dbi_result_first_row(res); /* {{{ */
557 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
558 "dbi_result_first_row failed: %s. Maybe the statement didn't "
560 db->name, udb_query_get_name(q),
561 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
562 udb_query_finish_result(q, prep_area);
566 /* Iterate over all rows and call `udb_query_handle_result' with each list of
571 /* Copy the value of the columns to `column_values' */
572 for (size_t i = 0; i < column_num; i++) /* {{{ */
574 status = cdbi_result_get_field(res, (unsigned int)(i + 1),
575 column_values[i], DATA_MAX_NAME_LEN);
578 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
579 "cdbi_result_get_field (%zu) failed.",
580 db->name, udb_query_get_name(q), i + 1);
584 } /* }}} for (i = 0; i < column_num; i++) */
586 /* If all values were copied successfully, call `udb_query_handle_result'
587 * to dispatch the row to the daemon. */
588 if (status == 0) /* {{{ */
590 status = udb_query_handle_result(q, prep_area, column_values);
592 ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
593 "udb_query_handle_result failed.",
594 db->name, udb_query_get_name(q));
598 /* Get the next row from the database. */
599 status = dbi_result_next_row(res); /* {{{ */
601 if (dbi_conn_error(db->connection, NULL) != 0) {
603 WARNING("dbi plugin: cdbi_read_database_query (%s, %s): "
604 "dbi_result_next_row failed: %s.",
605 db->name, udb_query_get_name(q),
606 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
610 } /* }}} while (42) */
612 /* Tell the db query interface that we're done with this query. */
613 udb_query_finish_result(q, prep_area);
615 /* Clean up and return `status = 0' (success) */
618 } /* }}} int cdbi_read_database_query */
620 static int cdbi_connect_database(cdbi_database_t *db) /* {{{ */
626 if (db->connection != NULL) {
627 status = dbi_conn_ping(db->connection);
628 if (status != 0) /* connection is alive */
631 dbi_conn_close(db->connection);
632 db->connection = NULL;
635 driver = dbi_driver_open_r(db->driver, dbi_instance);
636 if (driver == NULL) {
637 ERROR("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.",
639 INFO("dbi plugin: Maybe the driver isn't installed? "
640 "Known drivers are:");
641 for (driver = dbi_driver_list_r(NULL, dbi_instance); driver != NULL;
642 driver = dbi_driver_list_r(driver, dbi_instance)) {
643 INFO("dbi plugin: * %s", dbi_driver_get_name(driver));
648 connection = dbi_conn_open(driver);
649 if (connection == NULL) {
650 ERROR("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
655 /* Set all the driver options. Because this is a very very very generic
656 * interface, the error handling is kind of long. If an invalid option is
657 * encountered, it will get a list of options understood by the driver and
658 * report that as `INFO'. This way, users hopefully don't have too much
659 * trouble finding out how to configure the plugin correctly.. */
660 for (size_t i = 0; i < db->driver_options_num; i++) {
661 if (db->driver_options[i].is_numeric) {
663 dbi_conn_set_option_numeric(connection, db->driver_options[i].key,
664 db->driver_options[i].value.numeric);
667 ERROR("dbi plugin: cdbi_connect_database (%s): "
668 "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.",
669 db->name, db->driver_options[i].key,
670 db->driver_options[i].value.numeric,
671 cdbi_strerror(connection, errbuf, sizeof(errbuf)));
674 status = dbi_conn_set_option(connection, db->driver_options[i].key,
675 db->driver_options[i].value.string);
678 ERROR("dbi plugin: cdbi_connect_database (%s): "
679 "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.",
680 db->name, db->driver_options[i].key,
681 db->driver_options[i].value.string,
682 cdbi_strerror(connection, errbuf, sizeof(errbuf)));
687 INFO("dbi plugin: This is a list of all options understood "
688 "by the `%s' driver:",
690 for (const char *opt = dbi_conn_get_option_list(connection, NULL);
691 opt != NULL; opt = dbi_conn_get_option_list(connection, opt)) {
692 INFO("dbi plugin: * %s", opt);
695 dbi_conn_close(connection);
698 } /* for (i = 0; i < db->driver_options_num; i++) */
700 status = dbi_conn_connect(connection);
703 ERROR("dbi plugin: cdbi_connect_database (%s): "
704 "dbi_conn_connect failed: %s",
705 db->name, cdbi_strerror(connection, errbuf, sizeof(errbuf)));
706 dbi_conn_close(connection);
710 if (db->select_db != NULL) {
711 status = dbi_conn_select_db(connection, db->select_db);
715 "dbi plugin: cdbi_connect_database (%s): "
716 "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
717 db->name, db->select_db,
718 cdbi_strerror(connection, errbuf, sizeof(errbuf)));
719 dbi_conn_close(connection);
724 db->connection = connection;
726 } /* }}} int cdbi_connect_database */
728 static int cdbi_read_database(user_data_t *ud) /* {{{ */
730 cdbi_database_t *db = (cdbi_database_t *)ud->data;
734 unsigned int db_version;
736 status = cdbi_connect_database(db);
739 assert(db->connection != NULL);
741 db_version = dbi_conn_get_engine_version(db->connection);
742 /* TODO: Complain if `db_version == 0' */
745 for (size_t i = 0; i < db->queries_num; i++) {
746 /* Check if we know the database's version and if so, if this query applies
747 * to that version. */
748 if ((db_version != 0) &&
749 (udb_query_check_version(db->queries[i], db_version) == 0))
752 status = cdbi_read_database_query(db, db->queries[i], db->q_prep_areas[i]);
758 ERROR("dbi plugin: All queries failed for database `%s'.", db->name);
763 } /* }}} int cdbi_read_database */
765 static int cdbi_shutdown(void) /* {{{ */
767 for (size_t i = 0; i < databases_num; i++) {
768 if (databases[i]->connection != NULL) {
769 dbi_conn_close(databases[i]->connection);
770 databases[i]->connection = NULL;
772 cdbi_database_free(databases[i]);
777 udb_query_free(queries, queries_num);
782 } /* }}} int cdbi_shutdown */
784 void module_register(void) /* {{{ */
786 plugin_register_complex_config("dbi", cdbi_config);
787 plugin_register_init("dbi", cdbi_init);
788 plugin_register_shutdown("dbi", cdbi_shutdown);
789 } /* }}} void module_register */