Treewide: replace ssnprintf with snprintf
[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
66   cdtime_t interval;
67
68   char *driver;
69   char *host;
70   cdbi_driver_option_t *driver_options;
71   size_t driver_options_num;
72
73   udb_query_preparation_area_t **q_prep_areas;
74   udb_query_t **queries;
75   size_t queries_num;
76
77   dbi_conn connection;
78 };
79 typedef struct cdbi_database_s cdbi_database_t; /* }}} */
80
81 /*
82  * Global variables
83  */
84 #if !defined(HAVE_LEGACY_LIBDBI) || !HAVE_LEGACY_LIBDBI
85 static dbi_inst dbi_instance = 0;
86 #endif
87 static udb_query_t **queries = NULL;
88 static size_t queries_num = 0;
89 static cdbi_database_t **databases = NULL;
90 static size_t databases_num = 0;
91
92 static int cdbi_read_database(user_data_t *ud);
93
94 /*
95  * Functions
96  */
97 static const char *cdbi_strerror(dbi_conn conn, /* {{{ */
98                                  char *buffer, size_t buffer_size) {
99   const char *msg;
100   int status;
101
102   if (conn == NULL) {
103     sstrncpy(buffer, "connection is NULL", buffer_size);
104     return buffer;
105   }
106
107   msg = NULL;
108   status = dbi_conn_error(conn, &msg);
109   if ((status >= 0) && (msg != NULL))
110     snprintf(buffer, buffer_size, "%s (status %i)", msg, status);
111   else
112     snprintf(buffer, buffer_size, "dbi_conn_error failed with status %i",
113               status);
114
115   return buffer;
116 } /* }}} const char *cdbi_conn_error */
117
118 static int cdbi_result_get_field(dbi_result res, /* {{{ */
119                                  unsigned int index, char *buffer,
120                                  size_t buffer_size) {
121   unsigned short src_type;
122
123   src_type = dbi_result_get_field_type_idx(res, index);
124   if (src_type == DBI_TYPE_ERROR) {
125     ERROR("dbi plugin: cdbi_result_get: "
126           "dbi_result_get_field_type_idx failed.");
127     return -1;
128   }
129
130   if (src_type == DBI_TYPE_INTEGER) {
131     long long value;
132
133     value = dbi_result_get_longlong_idx(res, index);
134     snprintf(buffer, buffer_size, "%lli", value);
135   } else if (src_type == DBI_TYPE_DECIMAL) {
136     double value;
137
138     value = dbi_result_get_double_idx(res, index);
139     snprintf(buffer, buffer_size, "%63.15g", value);
140   } else if (src_type == DBI_TYPE_STRING) {
141     const char *value;
142
143     value = dbi_result_get_string_idx(res, index);
144     if (value == NULL)
145       sstrncpy(buffer, "", buffer_size);
146     else if (strcmp("ERROR", value) == 0)
147       return -1;
148     else
149       sstrncpy(buffer, value, buffer_size);
150   }
151   /* DBI_TYPE_BINARY */
152   /* DBI_TYPE_DATETIME */
153   else {
154     const char *field_name;
155
156     field_name = dbi_result_get_field_name(res, index);
157     if (field_name == NULL)
158       field_name = "<unknown>";
159
160     ERROR("dbi plugin: Column `%s': Don't know how to handle "
161           "source type %hu.",
162           field_name, src_type);
163     return -1;
164   }
165
166   return 0;
167 } /* }}} int cdbi_result_get_field */
168
169 static void cdbi_database_free(cdbi_database_t *db) /* {{{ */
170 {
171   if (db == NULL)
172     return;
173
174   sfree(db->name);
175   sfree(db->driver);
176
177   for (size_t i = 0; i < db->driver_options_num; i++) {
178     sfree(db->driver_options[i].key);
179     if (!db->driver_options[i].is_numeric)
180       sfree(db->driver_options[i].value.string);
181   }
182   sfree(db->driver_options);
183
184   if (db->q_prep_areas)
185     for (size_t i = 0; i < db->queries_num; ++i)
186       udb_query_delete_preparation_area(db->q_prep_areas[i]);
187   free(db->q_prep_areas);
188
189   sfree(db);
190 } /* }}} void cdbi_database_free */
191
192 /* Configuration handling functions {{{
193  *
194  * <Plugin dbi>
195  *   <Query "plugin_instance0">
196  *     Statement "SELECT name, value FROM table"
197  *     <Result>
198  *       Type "gauge"
199  *       InstancesFrom "name"
200  *       ValuesFrom "value"
201  *     </Result>
202  *     ...
203  *   </Query>
204  *
205  *   <Database "plugin_instance1">
206  *     Driver "mysql"
207  *     Interval 120
208  *     DriverOption "hostname" "localhost"
209  *     ...
210  *     Query "plugin_instance0"
211  *   </Database>
212  * </Plugin>
213  */
214
215 static int cdbi_config_add_database_driver_option(cdbi_database_t *db, /* {{{ */
216                                                   oconfig_item_t *ci) {
217   cdbi_driver_option_t *option;
218
219   if ((ci->values_num != 2) || (ci->values[0].type != OCONFIG_TYPE_STRING) ||
220       ((ci->values[1].type != OCONFIG_TYPE_STRING) &&
221        (ci->values[1].type != OCONFIG_TYPE_NUMBER))) {
222     WARNING("dbi plugin: The `DriverOption' config option "
223             "needs exactly two arguments.");
224     return -1;
225   }
226
227   option = realloc(db->driver_options,
228                    sizeof(*option) * (db->driver_options_num + 1));
229   if (option == NULL) {
230     ERROR("dbi plugin: realloc failed");
231     return -1;
232   }
233
234   db->driver_options = option;
235   option = db->driver_options + db->driver_options_num;
236   memset(option, 0, sizeof(*option));
237
238   option->key = strdup(ci->values[0].value.string);
239   if (option->key == NULL) {
240     ERROR("dbi plugin: strdup failed.");
241     return -1;
242   }
243
244   if (ci->values[1].type == OCONFIG_TYPE_STRING) {
245     option->value.string = strdup(ci->values[1].value.string);
246     if (option->value.string == NULL) {
247       ERROR("dbi plugin: strdup failed.");
248       sfree(option->key);
249       return -1;
250     }
251   } else {
252     assert(ci->values[1].type == OCONFIG_TYPE_NUMBER);
253     option->value.numeric = (int)(ci->values[1].value.number + .5);
254     option->is_numeric = 1;
255   }
256
257   db->driver_options_num++;
258   return 0;
259 } /* }}} int cdbi_config_add_database_driver_option */
260
261 static int cdbi_config_add_database(oconfig_item_t *ci) /* {{{ */
262 {
263   cdbi_database_t *db;
264   int status;
265
266   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
267     WARNING("dbi plugin: The `Database' block "
268             "needs exactly one string argument.");
269     return -1;
270   }
271
272   db = calloc(1, sizeof(*db));
273   if (db == NULL) {
274     ERROR("dbi plugin: calloc failed.");
275     return -1;
276   }
277
278   status = cf_util_get_string(ci, &db->name);
279   if (status != 0) {
280     sfree(db);
281     return status;
282   }
283
284   /* Fill the `cdbi_database_t' structure.. */
285   for (int i = 0; i < ci->children_num; i++) {
286     oconfig_item_t *child = ci->children + i;
287
288     if (strcasecmp("Driver", child->key) == 0)
289       status = cf_util_get_string(child, &db->driver);
290     else if (strcasecmp("DriverOption", child->key) == 0)
291       status = cdbi_config_add_database_driver_option(db, child);
292     else if (strcasecmp("SelectDB", child->key) == 0)
293       status = cf_util_get_string(child, &db->select_db);
294     else if (strcasecmp("Query", child->key) == 0)
295       status = udb_query_pick_from_list(child, queries, queries_num,
296                                         &db->queries, &db->queries_num);
297     else if (strcasecmp("Host", child->key) == 0)
298       status = cf_util_get_string(child, &db->host);
299     else if (strcasecmp("Interval", child->key) == 0)
300       status = cf_util_get_cdtime(child, &db->interval);
301     else {
302       WARNING("dbi plugin: Option `%s' not allowed here.", child->key);
303       status = -1;
304     }
305
306     if (status != 0)
307       break;
308   }
309
310   /* Check that all necessary options have been given. */
311   while (status == 0) {
312     if (db->driver == NULL) {
313       WARNING("dbi plugin: `Driver' not given for database `%s'", db->name);
314       status = -1;
315     }
316     if (db->driver_options_num == 0) {
317       WARNING("dbi plugin: No `DriverOption' given for database `%s'. "
318               "This will likely not work.",
319               db->name);
320     }
321
322     break;
323   } /* while (status == 0) */
324
325   while ((status == 0) && (db->queries_num > 0)) {
326     db->q_prep_areas = calloc(db->queries_num, sizeof(*db->q_prep_areas));
327     if (db->q_prep_areas == NULL) {
328       WARNING("dbi plugin: calloc failed");
329       status = -1;
330       break;
331     }
332
333     for (size_t i = 0; i < db->queries_num; ++i) {
334       db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
335
336       if (db->q_prep_areas[i] == NULL) {
337         WARNING("dbi plugin: udb_query_allocate_preparation_area failed");
338         status = -1;
339         break;
340       }
341     }
342
343     break;
344   }
345
346   /* If all went well, add this database to the global list of databases. */
347   if (status == 0) {
348     cdbi_database_t **temp;
349
350     temp = realloc(databases, sizeof(*databases) * (databases_num + 1));
351     if (temp == NULL) {
352       ERROR("dbi plugin: realloc failed");
353       status = -1;
354     } else {
355       databases = temp;
356       databases[databases_num] = db;
357       databases_num++;
358
359       char *name = ssnprintf_alloc("dbi:%s", db->name);
360       plugin_register_complex_read(
361           /* group = */ NULL,
362           /* name = */ name ? name : db->name,
363           /* callback = */ cdbi_read_database,
364           /* interval = */ (db->interval > 0) ? db->interval : 0,
365           &(user_data_t){
366               .data = db,
367           });
368       sfree(name);
369     }
370   }
371
372   if (status != 0) {
373     cdbi_database_free(db);
374     return -1;
375   }
376
377   return 0;
378 } /* }}} int cdbi_config_add_database */
379
380 static int cdbi_config(oconfig_item_t *ci) /* {{{ */
381 {
382   for (int i = 0; i < ci->children_num; i++) {
383     oconfig_item_t *child = ci->children + i;
384     if (strcasecmp("Query", child->key) == 0)
385       udb_query_create(&queries, &queries_num, child,
386                        /* callback = */ NULL);
387     else if (strcasecmp("Database", child->key) == 0)
388       cdbi_config_add_database(child);
389     else {
390       WARNING("dbi plugin: Ignoring unknown config option `%s'.", child->key);
391     }
392   } /* for (ci->children) */
393
394   return 0;
395 } /* }}} int cdbi_config */
396
397 /* }}} End of configuration handling functions */
398
399 static int cdbi_init(void) /* {{{ */
400 {
401   static int did_init = 0;
402   int status;
403
404   if (did_init != 0)
405     return 0;
406
407   if (queries_num == 0) {
408     ERROR("dbi plugin: No <Query> blocks have been found. Without them, "
409           "this plugin can't do anything useful, so we will return an error.");
410     return -1;
411   }
412
413   if (databases_num == 0) {
414     ERROR("dbi plugin: No <Database> 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   status = dbi_initialize_r(/* driverdir = */ NULL, &dbi_instance);
420   if (status < 0) {
421     ERROR("dbi plugin: cdbi_init: dbi_initialize_r failed with status %i.",
422           status);
423     return -1;
424   } else if (status == 0) {
425     ERROR("dbi plugin: `dbi_initialize_r' could not load any drivers. Please "
426           "install at least one `DBD' or check your installation.");
427     return -1;
428   }
429   DEBUG("dbi plugin: cdbi_init: dbi_initialize_r reports %i driver%s.", status,
430         (status == 1) ? "" : "s");
431
432   return 0;
433 } /* }}} int cdbi_init */
434
435 static int cdbi_read_database_query(cdbi_database_t *db, /* {{{ */
436                                     udb_query_t *q,
437                                     udb_query_preparation_area_t *prep_area) {
438   const char *statement;
439   dbi_result res;
440   size_t column_num;
441   char **column_names;
442   char **column_values;
443   int status;
444
445 /* Macro that cleans up dynamically allocated memory and returns the
446  * specified status. */
447 #define BAIL_OUT(status)                                                       \
448   if (column_names != NULL) {                                                  \
449     sfree(column_names[0]);                                                    \
450     sfree(column_names);                                                       \
451   }                                                                            \
452   if (column_values != NULL) {                                                 \
453     sfree(column_values[0]);                                                   \
454     sfree(column_values);                                                      \
455   }                                                                            \
456   if (res != NULL) {                                                           \
457     dbi_result_free(res);                                                      \
458     res = NULL;                                                                \
459   }                                                                            \
460   return (status)
461
462   column_names = NULL;
463   column_values = NULL;
464
465   statement = udb_query_get_statement(q);
466   assert(statement != NULL);
467
468   res = dbi_conn_query(db->connection, statement);
469   if (res == NULL) {
470     char errbuf[1024];
471     ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
472           "dbi_conn_query failed: %s",
473           db->name, udb_query_get_name(q),
474           cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
475     BAIL_OUT(-1);
476   } else /* Get the number of columns */
477   {
478     unsigned int db_status;
479
480     db_status = dbi_result_get_numfields(res);
481     if (db_status == DBI_FIELD_ERROR) {
482       char errbuf[1024];
483       ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
484             "dbi_result_get_numfields failed: %s",
485             db->name, udb_query_get_name(q),
486             cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
487       BAIL_OUT(-1);
488     }
489
490     column_num = (size_t)db_status;
491     DEBUG("cdbi_read_database_query (%s, %s): There are %zu columns.", db->name,
492           udb_query_get_name(q), column_num);
493   }
494
495   /* Allocate `column_names' and `column_values'. {{{ */
496   column_names = calloc(column_num, sizeof(*column_names));
497   if (column_names == NULL) {
498     ERROR("dbi plugin: calloc failed.");
499     BAIL_OUT(-1);
500   }
501
502   column_names[0] = calloc(column_num, DATA_MAX_NAME_LEN);
503   if (column_names[0] == NULL) {
504     ERROR("dbi plugin: calloc failed.");
505     BAIL_OUT(-1);
506   }
507   for (size_t i = 1; i < column_num; i++)
508     column_names[i] = column_names[i - 1] + DATA_MAX_NAME_LEN;
509
510   column_values = calloc(column_num, sizeof(*column_values));
511   if (column_values == NULL) {
512     ERROR("dbi plugin: calloc failed.");
513     BAIL_OUT(-1);
514   }
515
516   column_values[0] = calloc(column_num, DATA_MAX_NAME_LEN);
517   if (column_values[0] == NULL) {
518     ERROR("dbi plugin: calloc failed.");
519     BAIL_OUT(-1);
520   }
521   for (size_t i = 1; i < column_num; i++)
522     column_values[i] = column_values[i - 1] + DATA_MAX_NAME_LEN;
523   /* }}} */
524
525   /* Copy the field names to `column_names' */
526   for (size_t i = 0; i < column_num; i++) /* {{{ */
527   {
528     const char *column_name;
529
530     column_name = dbi_result_get_field_name(res, (unsigned int)(i + 1));
531     if (column_name == NULL) {
532       ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
533             "Cannot retrieve name of field %zu.",
534             db->name, udb_query_get_name(q), i + 1);
535       BAIL_OUT(-1);
536     }
537
538     sstrncpy(column_names[i], column_name, DATA_MAX_NAME_LEN);
539   } /* }}} for (i = 0; i < column_num; i++) */
540
541   udb_query_prepare_result(
542       q, prep_area, (db->host ? db->host : hostname_g),
543       /* plugin = */ "dbi", db->name, column_names, column_num,
544       /* interval = */ (db->interval > 0) ? db->interval : 0);
545
546   /* 0 = error; 1 = success; */
547   status = dbi_result_first_row(res); /* {{{ */
548   if (status != 1) {
549     char errbuf[1024];
550     ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
551           "dbi_result_first_row failed: %s. Maybe the statement didn't "
552           "return any rows?",
553           db->name, udb_query_get_name(q),
554           cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
555     udb_query_finish_result(q, prep_area);
556     BAIL_OUT(-1);
557   } /* }}} */
558
559   /* Iterate over all rows and call `udb_query_handle_result' with each list of
560    * values. */
561   while (42) /* {{{ */
562   {
563     status = 0;
564     /* Copy the value of the columns to `column_values' */
565     for (size_t i = 0; i < column_num; i++) /* {{{ */
566     {
567       status = cdbi_result_get_field(res, (unsigned int)(i + 1),
568                                      column_values[i], DATA_MAX_NAME_LEN);
569
570       if (status != 0) {
571         ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
572               "cdbi_result_get_field (%zu) failed.",
573               db->name, udb_query_get_name(q), i + 1);
574         status = -1;
575         break;
576       }
577     } /* }}} for (i = 0; i < column_num; i++) */
578
579     /* If all values were copied successfully, call `udb_query_handle_result'
580      * to dispatch the row to the daemon. */
581     if (status == 0) /* {{{ */
582     {
583       status = udb_query_handle_result(q, prep_area, column_values);
584       if (status != 0) {
585         ERROR("dbi plugin: cdbi_read_database_query (%s, %s): "
586               "udb_query_handle_result failed.",
587               db->name, udb_query_get_name(q));
588       }
589     } /* }}} */
590
591     /* Get the next row from the database. */
592     status = dbi_result_next_row(res); /* {{{ */
593     if (status != 1) {
594       if (dbi_conn_error(db->connection, NULL) != 0) {
595         char errbuf[1024];
596         WARNING("dbi plugin: cdbi_read_database_query (%s, %s): "
597                 "dbi_result_next_row failed: %s.",
598                 db->name, udb_query_get_name(q),
599                 cdbi_strerror(db->connection, errbuf, sizeof(errbuf)));
600       }
601       break;
602     } /* }}} */
603   }   /* }}} while (42) */
604
605   /* Tell the db query interface that we're done with this query. */
606   udb_query_finish_result(q, prep_area);
607
608   /* Clean up and return `status = 0' (success) */
609   BAIL_OUT(0);
610 #undef BAIL_OUT
611 } /* }}} int cdbi_read_database_query */
612
613 static int cdbi_connect_database(cdbi_database_t *db) /* {{{ */
614 {
615   dbi_driver driver;
616   dbi_conn connection;
617   int status;
618
619   if (db->connection != NULL) {
620     status = dbi_conn_ping(db->connection);
621     if (status != 0) /* connection is alive */
622       return 0;
623
624     dbi_conn_close(db->connection);
625     db->connection = NULL;
626   }
627
628   driver = dbi_driver_open_r(db->driver, dbi_instance);
629   if (driver == NULL) {
630     ERROR("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.",
631           db->driver);
632     INFO("dbi plugin: Maybe the driver isn't installed? "
633          "Known drivers are:");
634     for (driver = dbi_driver_list_r(NULL, dbi_instance); driver != NULL;
635          driver = dbi_driver_list_r(driver, dbi_instance)) {
636       INFO("dbi plugin: * %s", dbi_driver_get_name(driver));
637     }
638     return -1;
639   }
640
641   connection = dbi_conn_open(driver);
642   if (connection == NULL) {
643     ERROR("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
644           db->driver);
645     return -1;
646   }
647
648   /* Set all the driver options. Because this is a very very very generic
649    * interface, the error handling is kind of long. If an invalid option is
650    * encountered, it will get a list of options understood by the driver and
651    * report that as `INFO'. This way, users hopefully don't have too much
652    * trouble finding out how to configure the plugin correctly.. */
653   for (size_t i = 0; i < db->driver_options_num; i++) {
654     if (db->driver_options[i].is_numeric) {
655       status =
656           dbi_conn_set_option_numeric(connection, db->driver_options[i].key,
657                                       db->driver_options[i].value.numeric);
658       if (status != 0) {
659         char errbuf[1024];
660         ERROR("dbi plugin: cdbi_connect_database (%s): "
661               "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.",
662               db->name, db->driver_options[i].key,
663               db->driver_options[i].value.numeric,
664               cdbi_strerror(connection, errbuf, sizeof(errbuf)));
665       }
666     } else {
667       status = dbi_conn_set_option(connection, db->driver_options[i].key,
668                                    db->driver_options[i].value.string);
669       if (status != 0) {
670         char errbuf[1024];
671         ERROR("dbi plugin: cdbi_connect_database (%s): "
672               "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.",
673               db->name, db->driver_options[i].key,
674               db->driver_options[i].value.string,
675               cdbi_strerror(connection, errbuf, sizeof(errbuf)));
676       }
677     }
678
679     if (status != 0) {
680       INFO("dbi plugin: This is a list of all options understood "
681            "by the `%s' driver:",
682            db->driver);
683       for (const char *opt = dbi_conn_get_option_list(connection, NULL);
684            opt != NULL; opt = dbi_conn_get_option_list(connection, opt)) {
685         INFO("dbi plugin: * %s", opt);
686       }
687
688       dbi_conn_close(connection);
689       return -1;
690     }
691   } /* for (i = 0; i < db->driver_options_num; i++) */
692
693   status = dbi_conn_connect(connection);
694   if (status != 0) {
695     char errbuf[1024];
696     ERROR("dbi plugin: cdbi_connect_database (%s): "
697           "dbi_conn_connect failed: %s",
698           db->name, cdbi_strerror(connection, errbuf, sizeof(errbuf)));
699     dbi_conn_close(connection);
700     return -1;
701   }
702
703   if (db->select_db != NULL) {
704     status = dbi_conn_select_db(connection, db->select_db);
705     if (status != 0) {
706       char errbuf[1024];
707       WARNING(
708           "dbi plugin: cdbi_connect_database (%s): "
709           "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
710           db->name, db->select_db,
711           cdbi_strerror(connection, errbuf, sizeof(errbuf)));
712       dbi_conn_close(connection);
713       return -1;
714     }
715   }
716
717   db->connection = connection;
718   return 0;
719 } /* }}} int cdbi_connect_database */
720
721 static int cdbi_read_database(user_data_t *ud) /* {{{ */
722 {
723   cdbi_database_t *db = (cdbi_database_t *)ud->data;
724   int success;
725   int status;
726
727   unsigned int db_version;
728
729   status = cdbi_connect_database(db);
730   if (status != 0)
731     return status;
732   assert(db->connection != NULL);
733
734   db_version = dbi_conn_get_engine_version(db->connection);
735   /* TODO: Complain if `db_version == 0' */
736
737   success = 0;
738   for (size_t i = 0; i < db->queries_num; i++) {
739     /* Check if we know the database's version and if so, if this query applies
740      * to that version. */
741     if ((db_version != 0) &&
742         (udb_query_check_version(db->queries[i], db_version) == 0))
743       continue;
744
745     status = cdbi_read_database_query(db, db->queries[i], db->q_prep_areas[i]);
746     if (status == 0)
747       success++;
748   }
749
750   if (success == 0) {
751     ERROR("dbi plugin: All queries failed for database `%s'.", db->name);
752     return -1;
753   }
754
755   return 0;
756 } /* }}} int cdbi_read_database */
757
758 static int cdbi_shutdown(void) /* {{{ */
759 {
760   for (size_t i = 0; i < databases_num; i++) {
761     if (databases[i]->connection != NULL) {
762       dbi_conn_close(databases[i]->connection);
763       databases[i]->connection = NULL;
764     }
765     cdbi_database_free(databases[i]);
766   }
767   sfree(databases);
768   databases_num = 0;
769
770   udb_query_free(queries, queries_num);
771   queries = NULL;
772   queries_num = 0;
773
774   return 0;
775 } /* }}} int cdbi_shutdown */
776
777 void module_register(void) /* {{{ */
778 {
779   plugin_register_complex_config("dbi", cdbi_config);
780   plugin_register_init("dbi", cdbi_init);
781   plugin_register_shutdown("dbi", cdbi_shutdown);
782 } /* }}} void module_register */