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