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>
30 #include "configfile.h"
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 /* {{{ */
69 cdbi_driver_option_t *driver_options;
70 size_t driver_options_num;
72 udb_query_preparation_area_t **q_prep_areas;
73 udb_query_t **queries;
78 typedef struct cdbi_database_s cdbi_database_t; /* }}} */
83 #if !defined(HAVE_LEGACY_LIBDBI) || !HAVE_LEGACY_LIBDBI
84 static dbi_inst dbi_instance = 0;
86 static udb_query_t **queries = NULL;
87 static size_t queries_num = 0;
88 static cdbi_database_t **databases = NULL;
89 static size_t databases_num = 0;
91 static int cdbi_read_database (user_data_t *ud);
96 static const char *cdbi_strerror (dbi_conn conn, /* {{{ */
97 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, 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)
127 ERROR ("dbi plugin: cdbi_result_get: "
128 "dbi_result_get_field_type_idx failed.");
132 if (src_type == DBI_TYPE_INTEGER)
136 value = dbi_result_get_longlong_idx (res, index);
137 ssnprintf (buffer, buffer_size, "%lli", value);
139 else if (src_type == DBI_TYPE_DECIMAL)
143 value = dbi_result_get_double_idx (res, index);
144 ssnprintf (buffer, buffer_size, "%63.15g", value);
146 else if (src_type == DBI_TYPE_STRING)
150 value = dbi_result_get_string_idx (res, index);
152 sstrncpy (buffer, "", buffer_size);
153 else if (strcmp ("ERROR", value) == 0)
156 sstrncpy (buffer, value, buffer_size);
158 /* DBI_TYPE_BINARY */
159 /* DBI_TYPE_DATETIME */
162 const char *field_name;
164 field_name = dbi_result_get_field_name (res, index);
165 if (field_name == NULL)
166 field_name = "<unknown>";
168 ERROR ("dbi plugin: Column `%s': Don't know how to handle "
170 field_name, src_type);
175 } /* }}} int cdbi_result_get_field */
177 static void cdbi_database_free (cdbi_database_t *db) /* {{{ */
187 for (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 (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">
218 * DriverOption "hostname" "localhost"
220 * Query "plugin_instance0"
225 static int cdbi_config_add_database_driver_option (cdbi_database_t *db, /* {{{ */
228 cdbi_driver_option_t *option;
230 if ((ci->values_num != 2)
231 || (ci->values[0].type != OCONFIG_TYPE_STRING)
232 || ((ci->values[1].type != OCONFIG_TYPE_STRING)
233 && (ci->values[1].type != OCONFIG_TYPE_NUMBER)))
235 WARNING ("dbi plugin: The `DriverOption' config option "
236 "needs exactly two arguments.");
240 option = (cdbi_driver_option_t *) realloc (db->driver_options,
241 sizeof (*option) * (db->driver_options_num + 1));
244 ERROR ("dbi plugin: realloc failed");
248 db->driver_options = option;
249 option = db->driver_options + db->driver_options_num;
250 memset (option, 0, sizeof (*option));
252 option->key = strdup (ci->values[0].value.string);
253 if (option->key == NULL)
255 ERROR ("dbi plugin: strdup failed.");
259 if (ci->values[1].type == OCONFIG_TYPE_STRING)
261 option->value.string = strdup (ci->values[1].value.string);
262 if (option->value.string == NULL)
264 ERROR ("dbi plugin: strdup failed.");
271 assert (ci->values[1].type == OCONFIG_TYPE_NUMBER);
272 option->value.numeric = (int) (ci->values[1].value.number + .5);
273 option->is_numeric = 1;
276 db->driver_options_num++;
278 } /* }}} int cdbi_config_add_database_driver_option */
280 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 = (cdbi_database_t *) malloc (sizeof (*db));
297 ERROR ("dbi plugin: malloc failed.");
300 memset (db, 0, sizeof (*db));
302 status = cf_util_get_string (ci, &db->name);
309 /* Fill the `cdbi_database_t' structure.. */
310 for (i = 0; i < ci->children_num; i++)
312 oconfig_item_t *child = ci->children + i;
314 if (strcasecmp ("Driver", child->key) == 0)
315 status = cf_util_get_string (child, &db->driver);
316 else if (strcasecmp ("DriverOption", child->key) == 0)
317 status = cdbi_config_add_database_driver_option (db, child);
318 else if (strcasecmp ("SelectDB", child->key) == 0)
319 status = cf_util_get_string (child, &db->select_db);
320 else if (strcasecmp ("Query", child->key) == 0)
321 status = udb_query_pick_from_list (child, queries, queries_num,
322 &db->queries, &db->queries_num);
323 else if (strcasecmp ("Host", child->key) == 0)
324 status = cf_util_get_string (child, &db->host);
327 WARNING ("dbi plugin: Option `%s' not allowed here.", child->key);
335 /* Check that all necessary options have been given. */
338 if (db->driver == NULL)
340 WARNING ("dbi plugin: `Driver' not given for database `%s'", db->name);
343 if (db->driver_options_num == 0)
345 WARNING ("dbi plugin: No `DriverOption' given for database `%s'. "
346 "This will likely not work.", db->name);
350 } /* while (status == 0) */
352 while ((status == 0) && (db->queries_num > 0))
355 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
356 db->queries_num, sizeof (*db->q_prep_areas));
358 if (db->q_prep_areas == NULL)
360 WARNING ("dbi plugin: malloc failed");
365 for (j = 0; j < db->queries_num; ++j)
368 = udb_query_allocate_preparation_area (db->queries[j]);
370 if (db->q_prep_areas[j] == NULL)
372 WARNING ("dbi plugin: udb_query_allocate_preparation_area failed");
381 /* If all went well, add this database to the global list of databases. */
384 cdbi_database_t **temp;
386 temp = (cdbi_database_t **) realloc (databases,
387 sizeof (*databases) * (databases_num + 1));
390 ERROR ("dbi plugin: realloc failed");
399 databases[databases_num] = db;
402 memset (&ud, 0, sizeof (ud));
403 ud.data = (void *) db;
405 name = ssnprintf_alloc("dbi:%s", db->name);
407 plugin_register_complex_read (/* group = */ NULL,
408 /* name = */ name ? name : db->name,
409 /* callback = */ cdbi_read_database,
411 /* user_data = */ &ud);
418 cdbi_database_free (db);
423 } /* }}} int cdbi_config_add_database */
425 static int cdbi_config (oconfig_item_t *ci) /* {{{ */
429 for (i = 0; i < ci->children_num; i++)
431 oconfig_item_t *child = ci->children + i;
432 if (strcasecmp ("Query", child->key) == 0)
433 udb_query_create (&queries, &queries_num, child,
434 /* callback = */ NULL);
435 else if (strcasecmp ("Database", child->key) == 0)
436 cdbi_config_add_database (child);
439 WARNING ("dbi plugin: Ignoring unknown config option `%s'.", child->key);
441 } /* for (ci->children) */
444 } /* }}} int cdbi_config */
446 /* }}} End of configuration handling functions */
448 static int cdbi_init (void) /* {{{ */
450 static int did_init = 0;
456 if (queries_num == 0)
458 ERROR ("dbi plugin: No <Query> blocks have been found. Without them, "
459 "this plugin can't do anything useful, so we will returns an error.");
463 if (databases_num == 0)
465 ERROR ("dbi plugin: No <Database> blocks have been found. Without them, "
466 "this plugin can't do anything useful, so we will returns an error.");
470 status = dbi_initialize_r (/* driverdir = */ NULL, &dbi_instance);
473 ERROR ("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
477 else if (status == 0)
479 ERROR ("dbi plugin: `dbi_initialize_r' could not load any drivers. Please "
480 "install at least one `DBD' or check your installation.");
483 DEBUG ("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.",
484 status, (status == 1) ? "" : "s");
487 } /* }}} int cdbi_init */
489 static int cdbi_read_database_query (cdbi_database_t *db, /* {{{ */
490 udb_query_t *q, udb_query_preparation_area_t *prep_area)
492 const char *statement;
496 char **column_values;
500 /* Macro that cleans up dynamically allocated memory and returns the
501 * specified status. */
502 #define BAIL_OUT(status) \
503 if (column_names != NULL) { sfree (column_names[0]); sfree (column_names); } \
504 if (column_values != NULL) { sfree (column_values[0]); sfree (column_values); } \
505 if (res != NULL) { dbi_result_free (res); res = NULL; } \
509 column_values = NULL;
512 statement = udb_query_get_statement (q);
513 assert (statement != NULL);
515 res = dbi_conn_query (db->connection, statement);
519 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
520 "dbi_conn_query failed: %s",
521 db->name, udb_query_get_name (q),
522 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
525 else /* Get the number of columns */
527 unsigned int db_status;
529 db_status = dbi_result_get_numfields (res);
530 if (db_status == DBI_FIELD_ERROR)
533 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
534 "dbi_result_get_numfields failed: %s",
535 db->name, udb_query_get_name (q),
536 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
540 column_num = (size_t) db_status;
541 DEBUG ("cdbi_read_database_query (%s, %s): There are %zu columns.",
542 db->name, udb_query_get_name (q), column_num);
545 /* Allocate `column_names' and `column_values'. {{{ */
546 column_names = (char **) calloc (column_num, sizeof (char *));
547 if (column_names == NULL)
549 ERROR ("dbi plugin: malloc failed.");
553 column_names[0] = (char *) calloc (column_num,
554 DATA_MAX_NAME_LEN * sizeof (char));
555 if (column_names[0] == NULL)
557 ERROR ("dbi plugin: malloc failed.");
560 for (i = 1; i < column_num; i++)
561 column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
563 column_values = (char **) calloc (column_num, sizeof (char *));
564 if (column_values == NULL)
566 ERROR ("dbi plugin: malloc failed.");
570 column_values[0] = (char *) calloc (column_num,
571 DATA_MAX_NAME_LEN * sizeof (char));
572 if (column_values[0] == NULL)
574 ERROR ("dbi plugin: malloc failed.");
577 for (i = 1; i < column_num; i++)
578 column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
581 /* Copy the field names to `column_names' */
582 for (i = 0; i < column_num; i++) /* {{{ */
584 const char *column_name;
586 column_name = dbi_result_get_field_name (res, (unsigned int) (i + 1));
587 if (column_name == NULL)
589 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
590 "Cannot retrieve name of field %zu.",
591 db->name, udb_query_get_name (q), i + 1);
595 sstrncpy (column_names[i], column_name, DATA_MAX_NAME_LEN);
596 } /* }}} for (i = 0; i < column_num; i++) */
598 udb_query_prepare_result (q, prep_area, (db->host ? db->host : hostname_g),
599 /* plugin = */ "dbi", db->name,
600 column_names, column_num, /* interval = */ 0);
602 /* 0 = error; 1 = success; */
603 status = dbi_result_first_row (res); /* {{{ */
607 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
608 "dbi_result_first_row failed: %s. Maybe the statement didn't "
610 db->name, udb_query_get_name (q),
611 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
612 udb_query_finish_result (q, prep_area);
616 /* Iterate over all rows and call `udb_query_handle_result' with each list of
621 /* Copy the value of the columns to `column_values' */
622 for (i = 0; i < column_num; i++) /* {{{ */
624 status = cdbi_result_get_field (res, (unsigned int) (i + 1),
625 column_values[i], DATA_MAX_NAME_LEN);
629 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
630 "cdbi_result_get_field (%zu) failed.",
631 db->name, udb_query_get_name (q), i + 1);
635 } /* }}} for (i = 0; i < column_num; i++) */
637 /* If all values were copied successfully, call `udb_query_handle_result'
638 * to dispatch the row to the daemon. */
639 if (status == 0) /* {{{ */
641 status = udb_query_handle_result (q, prep_area, column_values);
644 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
645 "udb_query_handle_result failed.",
646 db->name, udb_query_get_name (q));
650 /* Get the next row from the database. */
651 status = dbi_result_next_row (res); /* {{{ */
654 if (dbi_conn_error (db->connection, NULL) != 0)
657 WARNING ("dbi plugin: cdbi_read_database_query (%s, %s): "
658 "dbi_result_next_row failed: %s.",
659 db->name, udb_query_get_name (q),
660 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
664 } /* }}} while (42) */
666 /* Tell the db query interface that we're done with this query. */
667 udb_query_finish_result (q, prep_area);
669 /* Clean up and return `status = 0' (success) */
672 } /* }}} int cdbi_read_database_query */
674 static int cdbi_connect_database (cdbi_database_t *db) /* {{{ */
681 if (db->connection != NULL)
683 status = dbi_conn_ping (db->connection);
684 if (status != 0) /* connection is alive */
687 dbi_conn_close (db->connection);
688 db->connection = NULL;
691 driver = dbi_driver_open_r (db->driver, dbi_instance);
694 ERROR ("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.",
696 INFO ("dbi plugin: Maybe the driver isn't installed? "
697 "Known drivers are:");
698 for (driver = dbi_driver_list_r (NULL, dbi_instance);
700 driver = dbi_driver_list_r (driver, dbi_instance))
702 INFO ("dbi plugin: * %s", dbi_driver_get_name (driver));
707 connection = dbi_conn_open (driver);
708 if (connection == NULL)
710 ERROR ("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
715 /* Set all the driver options. Because this is a very very very generic
716 * interface, the error handling is kind of long. If an invalid option is
717 * encountered, it will get a list of options understood by the driver and
718 * report that as `INFO'. This way, users hopefully don't have too much
719 * trouble finding out how to configure the plugin correctly.. */
720 for (i = 0; i < db->driver_options_num; i++)
722 if (db->driver_options[i].is_numeric)
724 status = dbi_conn_set_option_numeric (connection,
725 db->driver_options[i].key, db->driver_options[i].value.numeric);
729 ERROR ("dbi plugin: cdbi_connect_database (%s): "
730 "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.",
732 db->driver_options[i].key, db->driver_options[i].value.numeric,
733 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
738 status = dbi_conn_set_option (connection,
739 db->driver_options[i].key, db->driver_options[i].value.string);
743 ERROR ("dbi plugin: cdbi_connect_database (%s): "
744 "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.",
746 db->driver_options[i].key, db->driver_options[i].value.string,
747 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
755 INFO ("dbi plugin: This is a list of all options understood "
756 "by the `%s' driver:", db->driver);
757 for (opt = dbi_conn_get_option_list (connection, NULL);
759 opt = dbi_conn_get_option_list (connection, opt))
761 INFO ("dbi plugin: * %s", opt);
764 dbi_conn_close (connection);
767 } /* for (i = 0; i < db->driver_options_num; i++) */
769 status = dbi_conn_connect (connection);
773 ERROR ("dbi plugin: cdbi_connect_database (%s): "
774 "dbi_conn_connect failed: %s",
775 db->name, cdbi_strerror (connection, errbuf, sizeof (errbuf)));
776 dbi_conn_close (connection);
780 if (db->select_db != NULL)
782 status = dbi_conn_select_db (connection, db->select_db);
786 WARNING ("dbi plugin: cdbi_connect_database (%s): "
787 "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
788 db->name, db->select_db,
789 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
790 dbi_conn_close (connection);
795 db->connection = connection;
797 } /* }}} int cdbi_connect_database */
799 static int cdbi_read_database (user_data_t *ud) /* {{{ */
801 cdbi_database_t *db = (cdbi_database_t *) ud->data;
806 unsigned int db_version;
808 status = cdbi_connect_database (db);
811 assert (db->connection != NULL);
813 db_version = dbi_conn_get_engine_version (db->connection);
814 /* TODO: Complain if `db_version == 0' */
817 for (i = 0; i < db->queries_num; i++)
819 /* Check if we know the database's version and if so, if this query applies
820 * to that version. */
821 if ((db_version != 0)
822 && (udb_query_check_version (db->queries[i], db_version) == 0))
825 status = cdbi_read_database_query (db,
826 db->queries[i], db->q_prep_areas[i]);
833 ERROR ("dbi plugin: All queries failed for database `%s'.", db->name);
838 } /* }}} int cdbi_read_database */
840 static int cdbi_shutdown (void) /* {{{ */
844 for (i = 0; i < databases_num; i++)
846 if (databases[i]->connection != NULL)
848 dbi_conn_close (databases[i]->connection);
849 databases[i]->connection = NULL;
851 cdbi_database_free (databases[i]);
856 udb_query_free (queries, queries_num);
861 } /* }}} int cdbi_shutdown */
863 void module_register (void) /* {{{ */
865 plugin_register_complex_config ("dbi", cdbi_config);
866 plugin_register_init ("dbi", cdbi_init);
867 plugin_register_shutdown ("dbi", cdbi_shutdown);
868 } /* }}} void module_register */
871 * vim: shiftwidth=2 softtabstop=2 et fdm=marker