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 /* {{{ */
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) /* {{{ */
189 for (i = 0; i < db->driver_options_num; i++)
191 sfree (db->driver_options[i].key);
192 if (!db->driver_options[i].is_numeric)
193 sfree (db->driver_options[i].value.string);
195 sfree (db->driver_options);
197 if (db->q_prep_areas)
198 for (i = 0; i < db->queries_num; ++i)
199 udb_query_delete_preparation_area (db->q_prep_areas[i]);
200 free (db->q_prep_areas);
203 } /* }}} void cdbi_database_free */
205 /* Configuration handling functions {{{
208 * <Query "plugin_instance0">
209 * Statement "SELECT name, value FROM table"
212 * InstancesFrom "name"
218 * <Database "plugin_instance1">
221 * DriverOption "hostname" "localhost"
223 * Query "plugin_instance0"
228 static int cdbi_config_add_database_driver_option (cdbi_database_t *db, /* {{{ */
231 cdbi_driver_option_t *option;
233 if ((ci->values_num != 2)
234 || (ci->values[0].type != OCONFIG_TYPE_STRING)
235 || ((ci->values[1].type != OCONFIG_TYPE_STRING)
236 && (ci->values[1].type != OCONFIG_TYPE_NUMBER)))
238 WARNING ("dbi plugin: The `DriverOption' config option "
239 "needs exactly two arguments.");
243 option = (cdbi_driver_option_t *) realloc (db->driver_options,
244 sizeof (*option) * (db->driver_options_num + 1));
247 ERROR ("dbi plugin: realloc failed");
251 db->driver_options = option;
252 option = db->driver_options + db->driver_options_num;
253 memset (option, 0, sizeof (*option));
255 option->key = strdup (ci->values[0].value.string);
256 if (option->key == NULL)
258 ERROR ("dbi plugin: strdup failed.");
262 if (ci->values[1].type == OCONFIG_TYPE_STRING)
264 option->value.string = strdup (ci->values[1].value.string);
265 if (option->value.string == NULL)
267 ERROR ("dbi plugin: strdup failed.");
274 assert (ci->values[1].type == OCONFIG_TYPE_NUMBER);
275 option->value.numeric = (int) (ci->values[1].value.number + .5);
276 option->is_numeric = 1;
279 db->driver_options_num++;
281 } /* }}} int cdbi_config_add_database_driver_option */
283 static int cdbi_config_add_database (oconfig_item_t *ci) /* {{{ */
289 if ((ci->values_num != 1)
290 || (ci->values[0].type != OCONFIG_TYPE_STRING))
292 WARNING ("dbi plugin: The `Database' block "
293 "needs exactly one string argument.");
297 db = malloc (sizeof (*db));
300 ERROR ("dbi plugin: malloc failed.");
303 memset (db, 0, sizeof (*db));
305 status = cf_util_get_string (ci, &db->name);
312 /* Fill the `cdbi_database_t' structure.. */
313 for (i = 0; i < ci->children_num; i++)
315 oconfig_item_t *child = ci->children + i;
317 if (strcasecmp ("Driver", child->key) == 0)
318 status = cf_util_get_string (child, &db->driver);
319 else if (strcasecmp ("DriverOption", child->key) == 0)
320 status = cdbi_config_add_database_driver_option (db, child);
321 else if (strcasecmp ("SelectDB", child->key) == 0)
322 status = cf_util_get_string (child, &db->select_db);
323 else if (strcasecmp ("Query", child->key) == 0)
324 status = udb_query_pick_from_list (child, queries, queries_num,
325 &db->queries, &db->queries_num);
326 else if (strcasecmp ("Host", child->key) == 0)
327 status = cf_util_get_string (child, &db->host);
328 else if (strcasecmp ("Interval", child->key) == 0)
329 status = cf_util_get_cdtime(child, &db->interval);
332 WARNING ("dbi plugin: Option `%s' not allowed here.", child->key);
340 /* Check that all necessary options have been given. */
343 if (db->driver == NULL)
345 WARNING ("dbi plugin: `Driver' not given for database `%s'", db->name);
348 if (db->driver_options_num == 0)
350 WARNING ("dbi plugin: No `DriverOption' given for database `%s'. "
351 "This will likely not work.", db->name);
355 } /* while (status == 0) */
357 while ((status == 0) && (db->queries_num > 0))
361 db->q_prep_areas = calloc (db->queries_num, sizeof (*db->q_prep_areas));
362 if (db->q_prep_areas == NULL)
364 WARNING ("dbi plugin: calloc failed");
369 for (j = 0; j < db->queries_num; ++j)
372 = udb_query_allocate_preparation_area (db->queries[j]);
374 if (db->q_prep_areas[j] == NULL)
376 WARNING ("dbi plugin: udb_query_allocate_preparation_area failed");
385 /* If all went well, add this database to the global list of databases. */
388 cdbi_database_t **temp;
390 temp = (cdbi_database_t **) realloc (databases,
391 sizeof (*databases) * (databases_num + 1));
394 ERROR ("dbi plugin: realloc failed");
403 databases[databases_num] = db;
406 memset (&ud, 0, sizeof (ud));
407 ud.data = (void *) db;
409 name = ssnprintf_alloc("dbi:%s", db->name);
411 plugin_register_complex_read (/* group = */ NULL,
412 /* name = */ name ? name : db->name,
413 /* callback = */ cdbi_read_database,
414 /* interval = */ (db->interval > 0) ? db->interval : 0,
415 /* user_data = */ &ud);
422 cdbi_database_free (db);
427 } /* }}} int cdbi_config_add_database */
429 static int cdbi_config (oconfig_item_t *ci) /* {{{ */
433 for (i = 0; i < ci->children_num; i++)
435 oconfig_item_t *child = ci->children + i;
436 if (strcasecmp ("Query", child->key) == 0)
437 udb_query_create (&queries, &queries_num, child,
438 /* callback = */ NULL);
439 else if (strcasecmp ("Database", child->key) == 0)
440 cdbi_config_add_database (child);
443 WARNING ("dbi plugin: Ignoring unknown config option `%s'.", child->key);
445 } /* for (ci->children) */
448 } /* }}} int cdbi_config */
450 /* }}} End of configuration handling functions */
452 static int cdbi_init (void) /* {{{ */
454 static int did_init = 0;
460 if (queries_num == 0)
462 ERROR ("dbi plugin: No <Query> blocks have been found. Without them, "
463 "this plugin can't do anything useful, so we will returns an error.");
467 if (databases_num == 0)
469 ERROR ("dbi plugin: No <Database> blocks have been found. Without them, "
470 "this plugin can't do anything useful, so we will returns an error.");
474 status = dbi_initialize_r (/* driverdir = */ NULL, &dbi_instance);
477 ERROR ("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
481 else if (status == 0)
483 ERROR ("dbi plugin: `dbi_initialize_r' could not load any drivers. Please "
484 "install at least one `DBD' or check your installation.");
487 DEBUG ("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.",
488 status, (status == 1) ? "" : "s");
491 } /* }}} int cdbi_init */
493 static int cdbi_read_database_query (cdbi_database_t *db, /* {{{ */
494 udb_query_t *q, udb_query_preparation_area_t *prep_area)
496 const char *statement;
500 char **column_values;
504 /* Macro that cleans up dynamically allocated memory and returns the
505 * specified status. */
506 #define BAIL_OUT(status) \
507 if (column_names != NULL) { sfree (column_names[0]); sfree (column_names); } \
508 if (column_values != NULL) { sfree (column_values[0]); sfree (column_values); } \
509 if (res != NULL) { dbi_result_free (res); res = NULL; } \
513 column_values = NULL;
516 statement = udb_query_get_statement (q);
517 assert (statement != NULL);
519 res = dbi_conn_query (db->connection, statement);
523 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
524 "dbi_conn_query failed: %s",
525 db->name, udb_query_get_name (q),
526 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
529 else /* Get the number of columns */
531 unsigned int db_status;
533 db_status = dbi_result_get_numfields (res);
534 if (db_status == DBI_FIELD_ERROR)
537 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
538 "dbi_result_get_numfields failed: %s",
539 db->name, udb_query_get_name (q),
540 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
544 column_num = (size_t) db_status;
545 DEBUG ("cdbi_read_database_query (%s, %s): There are %zu columns.",
546 db->name, udb_query_get_name (q), column_num);
549 /* Allocate `column_names' and `column_values'. {{{ */
550 column_names = calloc (column_num, sizeof (*column_names));
551 if (column_names == NULL)
553 ERROR ("dbi plugin: calloc failed.");
557 column_names[0] = calloc (column_num, DATA_MAX_NAME_LEN);
558 if (column_names[0] == NULL)
560 ERROR ("dbi plugin: calloc failed.");
563 for (i = 1; i < column_num; i++)
564 column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
566 column_values = calloc (column_num, sizeof (*column_values));
567 if (column_values == NULL)
569 ERROR ("dbi plugin: calloc failed.");
573 column_values[0] = calloc (column_num, DATA_MAX_NAME_LEN);
574 if (column_values[0] == NULL)
576 ERROR ("dbi plugin: calloc failed.");
579 for (i = 1; i < column_num; i++)
580 column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
583 /* Copy the field names to `column_names' */
584 for (i = 0; i < column_num; i++) /* {{{ */
586 const char *column_name;
588 column_name = dbi_result_get_field_name (res, (unsigned int) (i + 1));
589 if (column_name == NULL)
591 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
592 "Cannot retrieve name of field %zu.",
593 db->name, udb_query_get_name (q), i + 1);
597 sstrncpy (column_names[i], column_name, DATA_MAX_NAME_LEN);
598 } /* }}} for (i = 0; i < column_num; i++) */
600 udb_query_prepare_result (q, prep_area, (db->host ? db->host : hostname_g),
601 /* plugin = */ "dbi", db->name,
602 column_names, column_num, /* interval = */ (db->interval > 0) ? db->interval : 0);
604 /* 0 = error; 1 = success; */
605 status = dbi_result_first_row (res); /* {{{ */
609 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
610 "dbi_result_first_row failed: %s. Maybe the statement didn't "
612 db->name, udb_query_get_name (q),
613 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
614 udb_query_finish_result (q, prep_area);
618 /* Iterate over all rows and call `udb_query_handle_result' with each list of
623 /* Copy the value of the columns to `column_values' */
624 for (i = 0; i < column_num; i++) /* {{{ */
626 status = cdbi_result_get_field (res, (unsigned int) (i + 1),
627 column_values[i], DATA_MAX_NAME_LEN);
631 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
632 "cdbi_result_get_field (%zu) failed.",
633 db->name, udb_query_get_name (q), i + 1);
637 } /* }}} for (i = 0; i < column_num; i++) */
639 /* If all values were copied successfully, call `udb_query_handle_result'
640 * to dispatch the row to the daemon. */
641 if (status == 0) /* {{{ */
643 status = udb_query_handle_result (q, prep_area, column_values);
646 ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
647 "udb_query_handle_result failed.",
648 db->name, udb_query_get_name (q));
652 /* Get the next row from the database. */
653 status = dbi_result_next_row (res); /* {{{ */
656 if (dbi_conn_error (db->connection, NULL) != 0)
659 WARNING ("dbi plugin: cdbi_read_database_query (%s, %s): "
660 "dbi_result_next_row failed: %s.",
661 db->name, udb_query_get_name (q),
662 cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
666 } /* }}} while (42) */
668 /* Tell the db query interface that we're done with this query. */
669 udb_query_finish_result (q, prep_area);
671 /* Clean up and return `status = 0' (success) */
674 } /* }}} int cdbi_read_database_query */
676 static int cdbi_connect_database (cdbi_database_t *db) /* {{{ */
683 if (db->connection != NULL)
685 status = dbi_conn_ping (db->connection);
686 if (status != 0) /* connection is alive */
689 dbi_conn_close (db->connection);
690 db->connection = NULL;
693 driver = dbi_driver_open_r (db->driver, dbi_instance);
696 ERROR ("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.",
698 INFO ("dbi plugin: Maybe the driver isn't installed? "
699 "Known drivers are:");
700 for (driver = dbi_driver_list_r (NULL, dbi_instance);
702 driver = dbi_driver_list_r (driver, dbi_instance))
704 INFO ("dbi plugin: * %s", dbi_driver_get_name (driver));
709 connection = dbi_conn_open (driver);
710 if (connection == NULL)
712 ERROR ("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
717 /* Set all the driver options. Because this is a very very very generic
718 * interface, the error handling is kind of long. If an invalid option is
719 * encountered, it will get a list of options understood by the driver and
720 * report that as `INFO'. This way, users hopefully don't have too much
721 * trouble finding out how to configure the plugin correctly.. */
722 for (i = 0; i < db->driver_options_num; i++)
724 if (db->driver_options[i].is_numeric)
726 status = dbi_conn_set_option_numeric (connection,
727 db->driver_options[i].key, db->driver_options[i].value.numeric);
731 ERROR ("dbi plugin: cdbi_connect_database (%s): "
732 "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.",
734 db->driver_options[i].key, db->driver_options[i].value.numeric,
735 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
740 status = dbi_conn_set_option (connection,
741 db->driver_options[i].key, db->driver_options[i].value.string);
745 ERROR ("dbi plugin: cdbi_connect_database (%s): "
746 "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.",
748 db->driver_options[i].key, db->driver_options[i].value.string,
749 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
757 INFO ("dbi plugin: This is a list of all options understood "
758 "by the `%s' driver:", db->driver);
759 for (opt = dbi_conn_get_option_list (connection, NULL);
761 opt = dbi_conn_get_option_list (connection, opt))
763 INFO ("dbi plugin: * %s", opt);
766 dbi_conn_close (connection);
769 } /* for (i = 0; i < db->driver_options_num; i++) */
771 status = dbi_conn_connect (connection);
775 ERROR ("dbi plugin: cdbi_connect_database (%s): "
776 "dbi_conn_connect failed: %s",
777 db->name, cdbi_strerror (connection, errbuf, sizeof (errbuf)));
778 dbi_conn_close (connection);
782 if (db->select_db != NULL)
784 status = dbi_conn_select_db (connection, db->select_db);
788 WARNING ("dbi plugin: cdbi_connect_database (%s): "
789 "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
790 db->name, db->select_db,
791 cdbi_strerror (connection, errbuf, sizeof (errbuf)));
792 dbi_conn_close (connection);
797 db->connection = connection;
799 } /* }}} int cdbi_connect_database */
801 static int cdbi_read_database (user_data_t *ud) /* {{{ */
803 cdbi_database_t *db = (cdbi_database_t *) ud->data;
808 unsigned int db_version;
810 status = cdbi_connect_database (db);
813 assert (db->connection != NULL);
815 db_version = dbi_conn_get_engine_version (db->connection);
816 /* TODO: Complain if `db_version == 0' */
819 for (i = 0; i < db->queries_num; i++)
821 /* Check if we know the database's version and if so, if this query applies
822 * to that version. */
823 if ((db_version != 0)
824 && (udb_query_check_version (db->queries[i], db_version) == 0))
827 status = cdbi_read_database_query (db,
828 db->queries[i], db->q_prep_areas[i]);
835 ERROR ("dbi plugin: All queries failed for database `%s'.", db->name);
840 } /* }}} int cdbi_read_database */
842 static int cdbi_shutdown (void) /* {{{ */
846 for (i = 0; i < databases_num; i++)
848 if (databases[i]->connection != NULL)
850 dbi_conn_close (databases[i]->connection);
851 databases[i]->connection = NULL;
853 cdbi_database_free (databases[i]);
858 udb_query_free (queries, queries_num);
863 } /* }}} int cdbi_shutdown */
865 void module_register (void) /* {{{ */
867 plugin_register_complex_config ("dbi", cdbi_config);
868 plugin_register_init ("dbi", cdbi_init);
869 plugin_register_shutdown ("dbi", cdbi_shutdown);
870 } /* }}} void module_register */
873 * vim: shiftwidth=2 softtabstop=2 et fdm=marker