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 /* {{{ */
60 typedef struct cdbi_driver_option_s cdbi_driver_option_t; /* }}} */
62 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)
106 sstrncpy (buffer, "connection is NULL", buffer_size);
111 status = dbi_conn_error (conn, &msg);
112 if ((status >= 0) && (msg != NULL))
113 ssnprintf (buffer, buffer_size, "%s (status %i)", msg, status);
115 ssnprintf (buffer, buffer_size, "dbi_conn_error failed with status %i",
119 } /* }}} const char *cdbi_conn_error */
121 static int cdbi_result_get_field (dbi_result res, /* {{{ */
122 unsigned int index, char *buffer, size_t buffer_size)
124 unsigned short src_type;
126 src_type = dbi_result_get_field_type_idx (res, index);
127 if (src_type == DBI_TYPE_ERROR)
129 ERROR ("dbi plugin: cdbi_result_get: "
130 "dbi_result_get_field_type_idx failed.");
134 if (src_type == DBI_TYPE_INTEGER)
138 value = dbi_result_get_longlong_idx (res, index);
139 ssnprintf (buffer, buffer_size, "%lli", value);
141 else if (src_type == DBI_TYPE_DECIMAL)
145 value = dbi_result_get_double_idx (res, index);
146 ssnprintf (buffer, buffer_size, "%63.15g", value);
148 else if (src_type == DBI_TYPE_STRING)
152 value = dbi_result_get_string_idx (res, index);
154 sstrncpy (buffer, "", buffer_size);
155 else if (strcmp ("ERROR", value) == 0)
158 sstrncpy (buffer, value, buffer_size);
160 /* DBI_TYPE_BINARY */
161 /* DBI_TYPE_DATETIME */
164 const char *field_name;
166 field_name = dbi_result_get_field_name (res, index);
167 if (field_name == NULL)
168 field_name = "<unknown>";
170 ERROR ("dbi plugin: Column `%s': Don't know how to handle "
172 field_name, src_type);
177 } /* }}} int cdbi_result_get_field */
179 static void cdbi_database_free (cdbi_database_t *db) /* {{{ */
187 for (size_t i = 0; i < db->driver_options_num; i++)
189 sfree (db->driver_options[i].key);
190 if (!db->driver_options[i].is_numeric)
191 sfree (db->driver_options[i].value.string);
193 sfree (db->driver_options);
195 if (db->q_prep_areas)
196 for (size_t i = 0; i < db->queries_num; ++i)
197 udb_query_delete_preparation_area (db->q_prep_areas[i]);
198 free (db->q_prep_areas);
201 } /* }}} void cdbi_database_free */
203 /* Configuration handling functions {{{
206 * <Query "plugin_instance0">
207 * Statement "SELECT name, value FROM table"
210 * InstancesFrom "name"
216 * <Database "plugin_instance1">
219 * DriverOption "hostname" "localhost"
221 * Query "plugin_instance0"
226 static int cdbi_config_add_database_driver_option (cdbi_database_t *db, /* {{{ */
229 cdbi_driver_option_t *option;
231 if ((ci->values_num != 2)
232 || (ci->values[0].type != OCONFIG_TYPE_STRING)
233 || ((ci->values[1].type != OCONFIG_TYPE_STRING)
234 && (ci->values[1].type != OCONFIG_TYPE_NUMBER)))
236 WARNING ("dbi plugin: The `DriverOption' config option "
237 "needs exactly two arguments.");
241 option = realloc (db->driver_options,
242 sizeof (*option) * (db->driver_options_num + 1));
245 ERROR ("dbi plugin: realloc failed");
249 db->driver_options = option;
250 option = db->driver_options + db->driver_options_num;
251 memset (option, 0, sizeof (*option));
253 option->key = strdup (ci->values[0].value.string);
254 if (option->key == NULL)
256 ERROR ("dbi plugin: strdup failed.");
260 if (ci->values[1].type == OCONFIG_TYPE_STRING)
262 option->value.string = strdup (ci->values[1].value.string);
263 if (option->value.string == NULL)
265 ERROR ("dbi plugin: strdup failed.");
272 assert (ci->values[1].type == OCONFIG_TYPE_NUMBER);
273 option->value.numeric = (int) (ci->values[1].value.number + .5);
274 option->is_numeric = 1;
277 db->driver_options_num++;
279 } /* }}} int cdbi_config_add_database_driver_option */
281 static int cdbi_config_add_database (oconfig_item_t *ci) /* {{{ */
286 if ((ci->values_num != 1)
287 || (ci->values[0].type != OCONFIG_TYPE_STRING))
289 WARNING ("dbi plugin: The `Database' block "
290 "needs exactly one string argument.");
294 db = calloc (1, sizeof (*db));
297 ERROR ("dbi plugin: calloc failed.");
301 status = cf_util_get_string (ci, &db->name);
308 /* Fill the `cdbi_database_t' structure.. */
309 for (int i = 0; i < ci->children_num; i++)
311 oconfig_item_t *child = ci->children + i;
313 if (strcasecmp ("Driver", child->key) == 0)
314 status = cf_util_get_string (child, &db->driver);
315 else if (strcasecmp ("DriverOption", child->key) == 0)
316 status = cdbi_config_add_database_driver_option (db, child);
317 else if (strcasecmp ("SelectDB", child->key) == 0)
318 status = cf_util_get_string (child, &db->select_db);
319 else if (strcasecmp ("Query", child->key) == 0)
320 status = udb_query_pick_from_list (child, queries, queries_num,
321 &db->queries, &db->queries_num);
322 else if (strcasecmp ("Host", child->key) == 0)
323 status = cf_util_get_string (child, &db->host);
324 else if (strcasecmp ("Interval", child->key) == 0)
325 status = cf_util_get_cdtime(child, &db->interval);
328 WARNING ("dbi plugin: Option `%s' not allowed here.", child->key);
336 /* Check that all necessary options have been given. */
339 if (db->driver == NULL)
341 WARNING ("dbi plugin: `Driver' not given for database `%s'", db->name);
344 if (db->driver_options_num == 0)
346 WARNING ("dbi plugin: No `DriverOption' given for database `%s'. "
347 "This will likely not work.", db->name);
351 } /* while (status == 0) */
353 while ((status == 0) && (db->queries_num > 0))
355 db->q_prep_areas = calloc (db->queries_num, sizeof (*db->q_prep_areas));
356 if (db->q_prep_areas == NULL)
358 WARNING ("dbi plugin: calloc failed");
363 for (size_t i = 0; i < db->queries_num; ++i)
366 = udb_query_allocate_preparation_area (db->queries[i]);
368 if (db->q_prep_areas[i] == NULL)
370 WARNING ("dbi plugin: udb_query_allocate_preparation_area failed");
379 /* If all went well, add this database to the global list of databases. */
382 cdbi_database_t **temp;
384 temp = realloc (databases,
385 sizeof (*databases) * (databases_num + 1));
388 ERROR ("dbi plugin: realloc failed");
394 databases[databases_num] = db;
397 char *name = ssnprintf_alloc("dbi:%s", db->name);
398 plugin_register_complex_read (/* group = */ NULL,
399 /* name = */ name ? name : db->name,
400 /* callback = */ cdbi_read_database,
401 /* interval = */ (db->interval > 0) ? db->interval : 0,
411 cdbi_database_free (db);
416 } /* }}} int cdbi_config_add_database */
418 static int cdbi_config (oconfig_item_t *ci) /* {{{ */
420 for (int i = 0; i < ci->children_num; i++)
422 oconfig_item_t *child = ci->children + i;
423 if (strcasecmp ("Query", child->key) == 0)
424 udb_query_create (&queries, &queries_num, child,
425 /* callback = */ NULL);
426 else if (strcasecmp ("Database", child->key) == 0)
427 cdbi_config_add_database (child);
430 WARNING ("dbi plugin: Ignoring unknown config option `%s'.", child->key);
432 } /* for (ci->children) */
435 } /* }}} int cdbi_config */
437 /* }}} End of configuration handling functions */
439 static int cdbi_init (void) /* {{{ */
441 static int did_init = 0;
447 if (queries_num == 0)
449 ERROR ("dbi plugin: No <Query> blocks have been found. Without them, "
450 "this plugin can't do anything useful, so we will return an error.");
454 if (databases_num == 0)
456 ERROR ("dbi plugin: No <Database> blocks have been found. Without them, "
457 "this plugin can't do anything useful, so we will return an error.");
461 status = dbi_initialize_r (/* driverdir = */ NULL, &dbi_instance);
464 ERROR ("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
468 else if (status == 0)
470 ERROR ("dbi plugin: `dbi_initialize_r' could not load any drivers. Please "
471 "install at least one `DBD' or check your installation.");
474 DEBUG ("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.",
475 status, (status == 1) ? "" : "s");
478 } /* }}} int cdbi_init */
480 static int cdbi_read_database_query (cdbi_database_t *db, /* {{{ */
481 udb_query_t *q, udb_query_preparation_area_t *prep_area)
483 const char *statement;
487 char **column_values;
490 /* Macro that cleans up dynamically allocated memory and returns the
491 * specified status. */
492 #define BAIL_OUT(status) \
493 if (column_names != NULL) { sfree (column_names[0]); sfree (column_names); } \
494 if (column_values != NULL) { sfree (column_values[0]); sfree (column_values); } \
495 if (res != NULL) { dbi_result_free (res); res = NULL; } \
499 column_values = NULL;
501 statement = udb_query_get_statement (q);
502 assert (statement != NULL);
504 res = dbi_conn_query (db->connection, statement);
508 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
509 "dbi_conn_query failed: %s",
510 db->name, udb_query_get_name (q),
511 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
514 else /* Get the number of columns */
516 unsigned int db_status;
518 db_status = dbi_result_get_numfields (res);
519 if (db_status == DBI_FIELD_ERROR)
522 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
523 "dbi_result_get_numfields failed: %s",
524 db->name, udb_query_get_name (q),
525 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
529 column_num = (size_t) db_status;
530 DEBUG ("cdbi_read_database_query (%s, %s): There are %zu columns.",
531 db->name, udb_query_get_name (q), column_num);
534 /* Allocate `column_names' and `column_values'. {{{ */
535 column_names = calloc (column_num, sizeof (*column_names));
536 if (column_names == NULL)
538 ERROR ("dbi plugin: calloc failed.");
542 column_names[0] = calloc (column_num, DATA_MAX_NAME_LEN);
543 if (column_names[0] == NULL)
545 ERROR ("dbi plugin: calloc failed.");
548 for (size_t i = 1; i < column_num; i++)
549 column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
551 column_values = calloc (column_num, sizeof (*column_values));
552 if (column_values == NULL)
554 ERROR ("dbi plugin: calloc failed.");
558 column_values[0] = calloc (column_num, DATA_MAX_NAME_LEN);
559 if (column_values[0] == NULL)
561 ERROR ("dbi plugin: calloc failed.");
564 for (size_t i = 1; i < column_num; i++)
565 column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
568 /* Copy the field names to `column_names' */
569 for (size_t i = 0; i < column_num; i++) /* {{{ */
571 const char *column_name;
573 column_name = dbi_result_get_field_name (res, (unsigned int) (i + 1));
574 if (column_name == NULL)
576 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
577 "Cannot retrieve name of field %zu.",
578 db->name, udb_query_get_name (q), i + 1);
582 sstrncpy (column_names[i], column_name, DATA_MAX_NAME_LEN);
583 } /* }}} for (i = 0; i < column_num; i++) */
585 udb_query_prepare_result (q, prep_area, (db->host ? db->host : hostname_g),
586 /* plugin = */ "dbi", db->name,
587 column_names, column_num, /* interval = */ (db->interval > 0) ? db->interval : 0);
589 /* 0 = error; 1 = success; */
590 status = dbi_result_first_row (res); /* {{{ */
594 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
595 "dbi_result_first_row failed: %s. Maybe the statement didn't "
597 db->name, udb_query_get_name (q),
598 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
599 udb_query_finish_result (q, prep_area);
603 /* Iterate over all rows and call `udb_query_handle_result' with each list of
608 /* Copy the value of the columns to `column_values' */
609 for (size_t i = 0; i < column_num; i++) /* {{{ */
611 status = cdbi_result_get_field (res, (unsigned int) (i + 1),
612 column_values[i], DATA_MAX_NAME_LEN);
616 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
617 "cdbi_result_get_field (%zu) failed.",
618 db->name, udb_query_get_name (q), i + 1);
622 } /* }}} for (i = 0; i < column_num; i++) */
624 /* If all values were copied successfully, call `udb_query_handle_result'
625 * to dispatch the row to the daemon. */
626 if (status == 0) /* {{{ */
628 status = udb_query_handle_result (q, prep_area, column_values);
631 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
632 "udb_query_handle_result failed.",
633 db->name, udb_query_get_name (q));
637 /* Get the next row from the database. */
638 status = dbi_result_next_row (res); /* {{{ */
641 if (dbi_conn_error (db->connection, NULL) != 0)
644 WARNING ("dbi plugin: cdbi_read_database_query (%s, %s): "
645 "dbi_result_next_row failed: %s.",
646 db->name, udb_query_get_name (q),
647 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
651 } /* }}} while (42) */
653 /* Tell the db query interface that we're done with this query. */
654 udb_query_finish_result (q, prep_area);
656 /* Clean up and return `status = 0' (success) */
659 } /* }}} int cdbi_read_database_query */
661 static int cdbi_connect_database (cdbi_database_t *db) /* {{{ */
667 if (db->connection != NULL)
669 status = dbi_conn_ping (db->connection);
670 if (status != 0) /* connection is alive */
673 dbi_conn_close (db->connection);
674 db->connection = NULL;
677 driver = dbi_driver_open_r (db->driver, dbi_instance);
680 ERROR ("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.",
682 INFO ("dbi plugin: Maybe the driver isn't installed? "
683 "Known drivers are:");
684 for (driver = dbi_driver_list_r (NULL, dbi_instance);
686 driver = dbi_driver_list_r (driver, dbi_instance))
688 INFO ("dbi plugin: * %s", dbi_driver_get_name (driver));
693 connection = dbi_conn_open (driver);
694 if (connection == NULL)
696 ERROR ("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
701 /* Set all the driver options. Because this is a very very very generic
702 * interface, the error handling is kind of long. If an invalid option is
703 * encountered, it will get a list of options understood by the driver and
704 * report that as `INFO'. This way, users hopefully don't have too much
705 * trouble finding out how to configure the plugin correctly.. */
706 for (size_t i = 0; i < db->driver_options_num; i++)
708 if (db->driver_options[i].is_numeric)
710 status = dbi_conn_set_option_numeric (connection,
711 db->driver_options[i].key, db->driver_options[i].value.numeric);
715 ERROR ("dbi plugin: cdbi_connect_database (%s): "
716 "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.",
718 db->driver_options[i].key, db->driver_options[i].value.numeric,
719 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
724 status = dbi_conn_set_option (connection,
725 db->driver_options[i].key, db->driver_options[i].value.string);
729 ERROR ("dbi plugin: cdbi_connect_database (%s): "
730 "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.",
732 db->driver_options[i].key, db->driver_options[i].value.string,
733 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
739 INFO ("dbi plugin: This is a list of all options understood "
740 "by the `%s' driver:", db->driver);
741 for (const char *opt = dbi_conn_get_option_list (connection, NULL);
743 opt = dbi_conn_get_option_list (connection, opt))
745 INFO ("dbi plugin: * %s", opt);
748 dbi_conn_close (connection);
751 } /* for (i = 0; i < db->driver_options_num; i++) */
753 status = dbi_conn_connect (connection);
757 ERROR ("dbi plugin: cdbi_connect_database (%s): "
758 "dbi_conn_connect failed: %s",
759 db->name, cdbi_strerror (connection, errbuf, sizeof (errbuf)));
760 dbi_conn_close (connection);
764 if (db->select_db != NULL)
766 status = dbi_conn_select_db (connection, db->select_db);
770 WARNING ("dbi plugin: cdbi_connect_database (%s): "
771 "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
772 db->name, db->select_db,
773 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
774 dbi_conn_close (connection);
779 db->connection = connection;
781 } /* }}} int cdbi_connect_database */
783 static int cdbi_read_database (user_data_t *ud) /* {{{ */
785 cdbi_database_t *db = (cdbi_database_t *) ud->data;
789 unsigned int db_version;
791 status = cdbi_connect_database (db);
794 assert (db->connection != NULL);
796 db_version = dbi_conn_get_engine_version (db->connection);
797 /* TODO: Complain if `db_version == 0' */
800 for (size_t i = 0; i < db->queries_num; i++)
802 /* Check if we know the database's version and if so, if this query applies
803 * to that version. */
804 if ((db_version != 0)
805 && (udb_query_check_version (db->queries[i], db_version) == 0))
808 status = cdbi_read_database_query (db,
809 db->queries[i], db->q_prep_areas[i]);
816 ERROR ("dbi plugin: All queries failed for database `%s'.", db->name);
821 } /* }}} int cdbi_read_database */
823 static int cdbi_shutdown (void) /* {{{ */
825 for (size_t i = 0; i < databases_num; i++)
827 if (databases[i]->connection != NULL)
829 dbi_conn_close (databases[i]->connection);
830 databases[i]->connection = NULL;
832 cdbi_database_free (databases[i]);
837 udb_query_free (queries, queries_num);
842 } /* }}} int cdbi_shutdown */
844 void module_register (void) /* {{{ */
846 plugin_register_complex_config ("dbi", cdbi_config);
847 plugin_register_init ("dbi", cdbi_init);
848 plugin_register_shutdown ("dbi", cdbi_shutdown);
849 } /* }}} void module_register */
852 * vim: shiftwidth=2 softtabstop=2 et fdm=marker