Merge remote-tracking branch 'github/pr/1707'
[collectd.git] / src / dbi.c
1 /**
2  * collectd - src/dbi.c
3  * Copyright (C) 2008-2015  Florian octo Forster
4  *
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:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
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.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31 #include "utils_db_query.h"
32
33 #include <dbi/dbi.h>
34
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)
45 #endif
46
47 /*
48  * Data types
49  */
50 struct cdbi_driver_option_s /* {{{ */
51 {
52   char *key;
53   union {
54     char *string;
55     int numeric;
56   } value;
57   _Bool is_numeric;
58 };
59 typedef struct cdbi_driver_option_s cdbi_driver_option_t; /* }}} */
60
61 struct cdbi_database_s /* {{{ */
62 {
63   char *name;
64   char *select_db;
65   char *plugin_name;
66
67   cdtime_t interval;
68
69   char *driver;
70   char *host;
71   cdbi_driver_option_t *driver_options;
72   size_t driver_options_num;
73
74   udb_query_preparation_area_t **q_prep_areas;
75   udb_query_t **queries;
76   size_t queries_num;
77
78   dbi_conn connection;
79 };
80 typedef struct cdbi_database_s cdbi_database_t; /* }}} */
81
82 /*
83  * Global variables
84  */
85 #if !defined(HAVE_LEGACY_LIBDBI) || !HAVE_LEGACY_LIBDBI
86 static dbi_inst dbi_instance = 0;
87 #endif
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;
92
93 static int cdbi_read_database(user_data_t *ud);
94
95 /*
96  * Functions
97  */
98 static const char *cdbi_strerror(dbi_conn conn, /* {{{ */
99                                  char *buffer, size_t buffer_size) {
100   const char *msg;
101   int status;
102
103   if (conn == NULL) {
104     sstrncpy(buffer, "connection is NULL", buffer_size);
105     return buffer;
106   }
107
108   msg = NULL;
109   status = dbi_conn_error(conn, &msg);
110   if ((status >= 0) && (msg != NULL))
111     snprintf(buffer, buffer_size, "%s (status %i)", msg, status);
112   else
113     snprintf(buffer, buffer_size, "dbi_conn_error failed with status %i",
114              status);
115
116   return buffer;
117 } /* }}} const char *cdbi_conn_error */
118
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;
123
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.");
128     return -1;
129   }
130
131   if (src_type == DBI_TYPE_INTEGER) {
132     long long value;
133
134     value = dbi_result_get_longlong_idx(res, index);
135     snprintf(buffer, buffer_size, "%lli", value);
136   } else if (src_type == DBI_TYPE_DECIMAL) {
137     double value;
138
139     value = dbi_result_get_double_idx(res, index);
140     snprintf(buffer, buffer_size, "%63.15g", value);
141   } else if (src_type == DBI_TYPE_STRING) {
142     const char *value;
143
144     value = dbi_result_get_string_idx(res, index);
145     if (value == NULL)
146       sstrncpy(buffer, "", buffer_size);
147     else if (strcmp("ERROR", value) == 0)
148       return -1;
149     else
150       sstrncpy(buffer, value, buffer_size);
151   }
152   /* DBI_TYPE_BINARY */
153   /* DBI_TYPE_DATETIME */
154   else {
155     const char *field_name;
156
157     field_name = dbi_result_get_field_name(res, index);
158     if (field_name == NULL)
159       field_name = "<unknown>";
160
161     ERROR("dbi plugin: Column `%s': Don't know how to handle "
162           "source type %hu.",
163           field_name, src_type);
164     return -1;
165   }
166
167   return 0;
168 } /* }}} int cdbi_result_get_field */
169
170 static void cdbi_database_free(cdbi_database_t *db) /* {{{ */
171 {
172   if (db == NULL)
173     return;
174
175   sfree(db->name);
176   sfree(db->select_db);
177   sfree(db->plugin_name);
178   sfree(db->driver);
179   sfree(db->host);
180
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);
185   }
186   sfree(db->driver_options);
187
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);
192
193   sfree(db);
194 } /* }}} void cdbi_database_free */
195
196 /* Configuration handling functions {{{
197  *
198  * <Plugin dbi>
199  *   <Query "plugin_instance0">
200  *     Statement "SELECT name, value FROM table"
201  *     <Result>
202  *       Type "gauge"
203  *       InstancesFrom "name"
204  *       ValuesFrom "value"
205  *     </Result>
206  *     ...
207  *   </Query>
208  *
209  *   <Database "plugin_instance1">
210  *     Driver "mysql"
211  *     Interval 120
212  *     DriverOption "hostname" "localhost"
213  *     ...
214  *     Query "plugin_instance0"
215  *   </Database>
216  * </Plugin>
217  */
218
219 static int cdbi_config_add_database_driver_option(cdbi_database_t *db, /* {{{ */
220                                                   oconfig_item_t *ci) {
221   cdbi_driver_option_t *option;
222
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.");
228     return -1;
229   }
230
231   option = realloc(db->driver_options,
232                    sizeof(*option) * (db->driver_options_num + 1));
233   if (option == NULL) {
234     ERROR("dbi plugin: realloc failed");
235     return -1;
236   }
237
238   db->driver_options = option;
239   option = db->driver_options + db->driver_options_num;
240   memset(option, 0, sizeof(*option));
241
242   option->key = strdup(ci->values[0].value.string);
243   if (option->key == NULL) {
244     ERROR("dbi plugin: strdup failed.");
245     return -1;
246   }
247
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.");
252       sfree(option->key);
253       return -1;
254     }
255   } else {
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;
259   }
260
261   db->driver_options_num++;
262   return 0;
263 } /* }}} int cdbi_config_add_database_driver_option */
264
265 static int cdbi_config_add_database(oconfig_item_t *ci) /* {{{ */
266 {
267   cdbi_database_t *db;
268   int status;
269
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.");
273     return -1;
274   }
275
276   db = calloc(1, sizeof(*db));
277   if (db == NULL) {
278     ERROR("dbi plugin: calloc failed.");
279     return -1;
280   }
281
282   status = cf_util_get_string(ci, &db->name);
283   if (status != 0) {
284     sfree(db);
285     return status;
286   }
287
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;
291
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("Plugin", child->key) == 0)
306       status = cf_util_get_string(child, &db->plugin_name);
307     else {
308       WARNING("dbi plugin: Option `%s' not allowed here.", child->key);
309       status = -1;
310     }
311
312     if (status != 0)
313       break;
314   }
315
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);
320       status = -1;
321     }
322     if (db->driver_options_num == 0) {
323       WARNING("dbi plugin: No `DriverOption' given for database `%s'. "
324               "This will likely not work.",
325               db->name);
326     }
327
328     break;
329   } /* while (status == 0) */
330
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");
335       status = -1;
336       break;
337     }
338
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]);
341
342       if (db->q_prep_areas[i] == NULL) {
343         WARNING("dbi plugin: udb_query_allocate_preparation_area failed");
344         status = -1;
345         break;
346       }
347     }
348
349     break;
350   }
351
352   /* If all went well, add this database to the global list of databases. */
353   if (status == 0) {
354     cdbi_database_t **temp;
355
356     temp = realloc(databases, sizeof(*databases) * (databases_num + 1));
357     if (temp == NULL) {
358       ERROR("dbi plugin: realloc failed");
359       status = -1;
360     } else {
361       databases = temp;
362       databases[databases_num] = db;
363       databases_num++;
364
365       char *name = ssnprintf_alloc("dbi:%s", db->name);
366       plugin_register_complex_read(
367           /* group = */ NULL,
368           /* name = */ name ? name : db->name,
369           /* callback = */ cdbi_read_database,
370           /* interval = */ (db->interval > 0) ? db->interval : 0,
371           &(user_data_t){
372               .data = db,
373           });
374       sfree(name);
375     }
376   }
377
378   if (status != 0) {
379     cdbi_database_free(db);
380     return -1;
381   }
382
383   return 0;
384 } /* }}} int cdbi_config_add_database */
385
386 static int cdbi_config(oconfig_item_t *ci) /* {{{ */
387 {
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);
395     else {
396       WARNING("dbi plugin: Ignoring unknown config option `%s'.", child->key);
397     }
398   } /* for (ci->children) */
399
400   return 0;
401 } /* }}} int cdbi_config */
402
403 /* }}} End of configuration handling functions */
404
405 static int cdbi_init(void) /* {{{ */
406 {
407   static int did_init = 0;
408   int status;
409
410   if (did_init != 0)
411     return 0;
412
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.");
416     return -1;
417   }
418
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.");
422     return -1;
423   }
424
425   status = dbi_initialize_r(/* driverdir = */ NULL, &dbi_instance);
426   if (status < 0) {
427     ERROR("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
428           status);
429     return -1;
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.");
433     return -1;
434   }
435   DEBUG("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.", status,
436         (status == 1) ? "" : "s");
437
438   return 0;
439 } /* }}} int cdbi_init */
440
441 static int cdbi_read_database_query(cdbi_database_t *db, /* {{{ */
442                                     udb_query_t *q,
443                                     udb_query_preparation_area_t *prep_area) {
444   const char *statement;
445   dbi_result res;
446   size_t column_num;
447   char **column_names;
448   char **column_values;
449   int status;
450
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);                                                       \
457   }                                                                            \
458   if (column_values != NULL) {                                                 \
459     sfree(column_values[0]);                                                   \
460     sfree(column_values);                                                      \
461   }                                                                            \
462   if (res != NULL) {                                                           \
463     dbi_result_free(res);                                                      \
464     res = NULL;                                                                \
465   }                                                                            \
466   return (status)
467
468   column_names = NULL;
469   column_values = NULL;
470
471   statement = udb_query_get_statement(q);
472   assert(statement != NULL);
473
474   res = dbi_conn_query(db->connection, statement);
475   if (res == NULL) {
476     char errbuf[1024];
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)));
481     BAIL_OUT(-1);
482   } else /* Get the number of columns */
483   {
484     unsigned int db_status;
485
486     db_status = dbi_result_get_numfields(res);
487     if (db_status == DBI_FIELD_ERROR) {
488       char errbuf[1024];
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)));
493       BAIL_OUT(-1);
494     }
495
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);
499   }
500
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.");
505     BAIL_OUT(-1);
506   }
507
508   column_names[0] = calloc(column_num, DATA_MAX_NAME_LEN);
509   if (column_names[0] == NULL) {
510     ERROR("dbi plugin: calloc failed.");
511     BAIL_OUT(-1);
512   }
513   for (size_t i = 1; i < column_num; i++)
514     column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
515
516   column_values = calloc(column_num, sizeof(*column_values));
517   if (column_values == NULL) {
518     ERROR("dbi plugin: calloc failed.");
519     BAIL_OUT(-1);
520   }
521
522   column_values[0] = calloc(column_num, DATA_MAX_NAME_LEN);
523   if (column_values[0] == NULL) {
524     ERROR("dbi plugin: calloc failed.");
525     BAIL_OUT(-1);
526   }
527   for (size_t i = 1; i < column_num; i++)
528     column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
529   /* }}} */
530
531   /* Copy the field names to `column_names' */
532   for (size_t i = 0; i < column_num; i++) /* {{{ */
533   {
534     const char *column_name;
535
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);
541       BAIL_OUT(-1);
542     }
543
544     sstrncpy(column_names[i], column_name, DATA_MAX_NAME_LEN);
545   } /* }}} for (i = 0; i < column_num; i++) */
546
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);
552
553   /* 0 = error; 1 = success; */
554   status = dbi_result_first_row(res); /* {{{ */
555   if (status != 1) {
556     char errbuf[1024];
557     ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
558           "dbi_result_first_row failed: %s. Maybe the statement didn't "
559           "return any rows?",
560           db->name, udb_query_get_name(q),
561           cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
562     udb_query_finish_result(q, prep_area);
563     BAIL_OUT(-1);
564   } /* }}} */
565
566   /* Iterate over all rows and call `udb_query_handle_result' with each list of
567    * values. */
568   while (42) /* {{{ */
569   {
570     status = 0;
571     /* Copy the value of the columns to `column_values' */
572     for (size_t i = 0; i < column_num; i++) /* {{{ */
573     {
574       status = cdbi_result_get_field(res, (unsigned int)(i + 1),
575                                      column_values[i], DATA_MAX_NAME_LEN);
576
577       if (status != 0) {
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);
581         status = -1;
582         break;
583       }
584     } /* }}} for (i = 0; i < column_num; i++) */
585
586     /* If all values were copied successfully, call `udb_query_handle_result'
587      * to dispatch the row to the daemon. */
588     if (status == 0) /* {{{ */
589     {
590       status = udb_query_handle_result(q, prep_area, column_values);
591       if (status != 0) {
592         ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
593               "udb_query_handle_result failed.",
594               db->name, udb_query_get_name(q));
595       }
596     } /* }}} */
597
598     /* Get the next row from the database. */
599     status = dbi_result_next_row(res); /* {{{ */
600     if (status != 1) {
601       if (dbi_conn_error(db->connection, NULL) != 0) {
602         char errbuf[1024];
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)));
607       }
608       break;
609     } /* }}} */
610   }   /* }}} while (42) */
611
612   /* Tell the db query interface that we're done with this query. */
613   udb_query_finish_result(q, prep_area);
614
615   /* Clean up and return `status = 0' (success) */
616   BAIL_OUT(0);
617 #undef BAIL_OUT
618 } /* }}} int cdbi_read_database_query */
619
620 static int cdbi_connect_database(cdbi_database_t *db) /* {{{ */
621 {
622   dbi_driver driver;
623   dbi_conn connection;
624   int status;
625
626   if (db->connection != NULL) {
627     status = dbi_conn_ping(db->connection);
628     if (status != 0) /* connection is alive */
629       return 0;
630
631     dbi_conn_close(db->connection);
632     db->connection = NULL;
633   }
634
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.",
638           db->driver);
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));
644     }
645     return -1;
646   }
647
648   connection = dbi_conn_open(driver);
649   if (connection == NULL) {
650     ERROR("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
651           db->driver);
652     return -1;
653   }
654
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) {
662       status =
663           dbi_conn_set_option_numeric(connection, db->driver_options[i].key,
664                                       db->driver_options[i].value.numeric);
665       if (status != 0) {
666         char errbuf[1024];
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)));
672       }
673     } else {
674       status = dbi_conn_set_option(connection, db->driver_options[i].key,
675                                    db->driver_options[i].value.string);
676       if (status != 0) {
677         char errbuf[1024];
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)));
683       }
684     }
685
686     if (status != 0) {
687       INFO("dbi plugin: This is a list of all options understood "
688            "by the `%s' driver:",
689            db->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);
693       }
694
695       dbi_conn_close(connection);
696       return -1;
697     }
698   } /* for (i = 0; i < db->driver_options_num; i++) */
699
700   status = dbi_conn_connect(connection);
701   if (status != 0) {
702     char errbuf[1024];
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);
707     return -1;
708   }
709
710   if (db->select_db != NULL) {
711     status = dbi_conn_select_db(connection, db->select_db);
712     if (status != 0) {
713       char errbuf[1024];
714       WARNING(
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);
720       return -1;
721     }
722   }
723
724   db->connection = connection;
725   return 0;
726 } /* }}} int cdbi_connect_database */
727
728 static int cdbi_read_database(user_data_t *ud) /* {{{ */
729 {
730   cdbi_database_t *db = (cdbi_database_t *)ud->data;
731   int success;
732   int status;
733
734   unsigned int db_version;
735
736   status = cdbi_connect_database(db);
737   if (status != 0)
738     return status;
739   assert(db->connection != NULL);
740
741   db_version = dbi_conn_get_engine_version(db->connection);
742   /* TODO: Complain if `db_version == 0' */
743
744   success = 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))
750       continue;
751
752     status = cdbi_read_database_query(db, db->queries[i], db->q_prep_areas[i]);
753     if (status == 0)
754       success++;
755   }
756
757   if (success == 0) {
758     ERROR("dbi plugin: All queries failed for database `%s'.", db->name);
759     return -1;
760   }
761
762   return 0;
763 } /* }}} int cdbi_read_database */
764
765 static int cdbi_shutdown(void) /* {{{ */
766 {
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;
771     }
772     cdbi_database_free(databases[i]);
773   }
774   sfree(databases);
775   databases_num = 0;
776
777   udb_query_free(queries, queries_num);
778   queries = NULL;
779   queries_num = 0;
780
781   return 0;
782 } /* }}} int cdbi_shutdown */
783
784 void module_register(void) /* {{{ */
785 {
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 */