dbi plugin: Fixed error handling in an inner loop.
[collectd.git] / src / dbi.c
1 /**
2  * collectd - src/dbi.c
3  * Copyright (C) 2008,2009  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
26
27 #include <dbi/dbi.h>
28
29 /*
30  * Data types
31  */
32 struct cdbi_driver_option_s
33 {
34   char *key;
35   char *value;
36 };
37 typedef struct cdbi_driver_option_s cdbi_driver_option_t;
38
39 struct cdbi_result_s;
40 typedef struct cdbi_result_s cdbi_result_t;
41 struct cdbi_result_s
42 {
43   char    *type;
44   char   **instances;
45   size_t   instances_num;
46   char   **values;
47   size_t   values_num;
48
49   cdbi_result_t *next;
50 };
51
52 struct cdbi_query_s
53 {
54   char    *name;
55   char    *statement;
56
57   cdbi_result_t *results;
58 };
59 typedef struct cdbi_query_s cdbi_query_t;
60
61 struct cdbi_database_s
62 {
63   char *name;
64   char *select_db;
65
66   char *driver;
67   cdbi_driver_option_t *driver_options;
68   size_t driver_options_num;
69
70   cdbi_query_t **queries;
71   size_t      queries_num;
72
73   dbi_conn connection;
74 };
75 typedef struct cdbi_database_s cdbi_database_t;
76
77 /*
78  * Global variables
79  */
80 static cdbi_query_t    **queries       = NULL;
81 static size_t            queries_num   = 0;
82 static cdbi_database_t **databases     = NULL;
83 static size_t            databases_num = 0;
84
85 /*
86  * Functions
87  */
88 static const char *cdbi_strerror (dbi_conn conn, /* {{{ */
89     char *buffer, size_t buffer_size)
90 {
91   const char *msg;
92   int status;
93
94   if (conn == NULL)
95   {
96     sstrncpy (buffer, "connection is NULL", buffer_size);
97     return (buffer);
98   }
99
100   msg = NULL;
101   status = dbi_conn_error (conn, &msg);
102   if ((status >= 0) && (msg != NULL))
103     ssnprintf (buffer, buffer_size, "%s (status %i)", msg, status);
104   else
105     ssnprintf (buffer, buffer_size, "dbi_conn_error failed with status %i",
106         status);
107
108   return (buffer);
109 } /* }}} const char *cdbi_conn_error */
110
111 static int cdbi_result_get_field (dbi_result res, /* {{{ */
112     const char *name, int dst_type, value_t *ret_value)
113 {
114   value_t value;
115   unsigned int index;
116   unsigned short src_type;
117   dbi_conn connection;
118
119   index = dbi_result_get_field_idx (res, name);
120   if (index < 1)
121   {
122     ERROR ("dbi plugin: cdbi_result_get: No such column: %s.", name);
123     return (-1);
124   }
125
126   src_type = dbi_result_get_field_type_idx (res, index);
127   if (src_type == DBI_TYPE_ERROR)
128   {
129     ERROR ("dbi plugin: cdbi_result_get: "
130         "dbi_result_get_field_type_idx failed.");
131     return (-1);
132   }
133
134   if ((dst_type != DS_TYPE_COUNTER) && (dst_type != DS_TYPE_GAUGE))
135   {
136     ERROR ("dbi plugin: cdbi_result_get: Don't know how to handle "
137         "destination type %i.", dst_type);
138     return (-1);
139   }
140
141   if (src_type == DBI_TYPE_INTEGER)
142   {
143     if (dst_type == DS_TYPE_COUNTER)
144       value.counter = dbi_result_get_ulonglong_idx (res, index);
145     else
146       value.gauge = (gauge_t) dbi_result_get_longlong_idx (res, index);
147   }
148   else if (src_type == DBI_TYPE_DECIMAL)
149   {
150     value.gauge = dbi_result_get_double_idx (res, index);
151     if (dst_type == DS_TYPE_COUNTER)
152       value.counter = (counter_t) round (value.gauge);
153   }
154   else if (src_type == DBI_TYPE_STRING)
155   {
156     const char *string = dbi_result_get_string_idx (res, index);
157     char *endptr = NULL;
158
159     if (string == NULL)
160       value.gauge = NAN;
161     else if (dst_type == DS_TYPE_COUNTER)
162       value.counter = (counter_t) strtoll (string, &endptr, 0);
163     else
164       value.gauge = (gauge_t) strtod (string, &endptr);
165
166     if (string == endptr)
167     {
168       ERROR ("dbi plugin: cdbi_result_get: Can't parse string as number: %s.",
169           string);
170       return (-1);
171     }
172   }
173   else
174   {
175     ERROR ("dbi plugin: cdbi_result_get: Don't know how to handle "
176         "source type %hu.", src_type);
177     return (-1);
178   }
179
180   connection = dbi_result_get_conn (res);
181   if (dbi_conn_error (connection, NULL) != 0)
182   {
183     char errbuf[1024];
184     ERROR ("dbi plugin: cdbi_result_get: dbi_result_get_*_idx failed: %s.",
185         cdbi_strerror (connection, errbuf, sizeof (errbuf)));
186     return (-1);
187   }
188
189   *ret_value = value;
190   return (0);
191 } /* }}} int cdbi_result_get_field */
192
193 static void cdbi_result_free (cdbi_result_t *r) /* {{{ */
194 {
195   size_t i;
196
197   if (r == NULL)
198     return;
199
200   sfree (r->type);
201
202   for (i = 0; i < r->instances_num; i++)
203     sfree (r->instances[i]);
204   sfree (r->instances);
205
206   for (i = 0; i < r->values_num; i++)
207     sfree (r->values[i]);
208   sfree (r->values);
209
210   cdbi_result_free (r->next);
211
212   sfree (r);
213 } /* }}} void cdbi_result_free */
214
215 static void cdbi_query_free (cdbi_query_t *q) /* {{{ */
216 {
217   if (q == NULL)
218     return;
219
220   sfree (q->name);
221   sfree (q->statement);
222
223   cdbi_result_free (q->results);
224
225   sfree (q);
226 } /* }}} void cdbi_query_free */
227
228 static void cdbi_database_free (cdbi_database_t *db) /* {{{ */
229 {
230   size_t i;
231
232   if (db == NULL)
233     return;
234
235   sfree (db->name);
236   sfree (db->driver);
237
238   for (i = 0; i < db->driver_options_num; i++)
239   {
240     sfree (db->driver_options[i].key);
241     sfree (db->driver_options[i].value);
242   }
243   sfree (db->driver_options);
244
245   sfree (db);
246 } /* }}} void cdbi_database_free */
247
248 static void cdbi_submit (cdbi_database_t *db, cdbi_result_t *r, /* {{{ */
249     char **instances, value_t *values)
250 {
251   value_list_t vl = VALUE_LIST_INIT;
252
253   vl.values = values;
254   vl.values_len = (int) r->values_num;
255   vl.time = time (NULL);
256   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
257   sstrncpy (vl.plugin, "dbi", sizeof (vl.plugin));
258   sstrncpy (vl.plugin_instance, db->name, sizeof (vl.type_instance));
259   sstrncpy (vl.type, r->type, sizeof (vl.type));
260   strjoin (vl.type_instance, sizeof (vl.type_instance),
261       instances, r->instances_num, "-");
262   vl.type_instance[sizeof (vl.type_instance) - 1] = 0;
263
264   plugin_dispatch_values (&vl);
265 } /* }}} void cdbi_submit */
266
267 /* Configuration handling functions {{{
268  *
269  * <Plugin dbi>
270  *   <Query "plugin_instance0">
271  *     Statement "SELECT name, value FROM table"
272  *     <Result>
273  *       Type "gauge"
274  *       InstancesFrom "name"
275  *       ValuesFrom "value"
276  *     </Result>
277  *     ...
278  *   </Query>
279  *     
280  *   <Database "plugin_instance1">
281  *     Driver "mysql"
282  *     DriverOption "hostname" "localhost"
283  *     ...
284  *     Query "plugin_instance0"
285  *   </Database>
286  * </Plugin>
287  */
288
289 static int cdbi_config_set_string (char **ret_string, /* {{{ */
290     oconfig_item_t *ci)
291 {
292   char *string;
293
294   if ((ci->values_num != 1)
295       || (ci->values[0].type != OCONFIG_TYPE_STRING))
296   {
297     WARNING ("dbi plugin: The `%s' config option "
298         "needs exactly one string argument.", ci->key);
299     return (-1);
300   }
301
302   string = strdup (ci->values[0].value.string);
303   if (string == NULL)
304   {
305     ERROR ("dbi plugin: strdup failed.");
306     return (-1);
307   }
308
309   if (*ret_string != NULL)
310     free (*ret_string);
311   *ret_string = string;
312
313   return (0);
314 } /* }}} int cdbi_config_set_string */
315
316 static int cdbi_config_add_string (char ***ret_array, /* {{{ */
317     size_t *ret_array_len, oconfig_item_t *ci)
318 {
319   char **array;
320   size_t array_len;
321   int i;
322
323   if (ci->values_num < 1)
324   {
325     WARNING ("dbi plugin: The `%s' config option "
326         "needs at least one argument.", ci->key);
327     return (-1);
328   }
329
330   for (i = 0; i < ci->values_num; i++)
331   {
332     if (ci->values[i].type != OCONFIG_TYPE_STRING)
333     {
334       WARNING ("dbi plugin: Argument %i to the `%s' option "
335           "is not a string.", i + 1, ci->key);
336       return (-1);
337     }
338   }
339
340   array_len = *ret_array_len;
341   array = (char **) realloc (*ret_array,
342       sizeof (char *) * (array_len + ci->values_num));
343   if (array == NULL)
344   {
345     ERROR ("dbi plugin: realloc failed.");
346     return (-1);
347   }
348   *ret_array = array;
349
350   for (i = 0; i < ci->values_num; i++)
351   {
352     array[array_len] = strdup (ci->values[i].value.string);
353     if (array[array_len] == NULL)
354     {
355       ERROR ("dbi plugin: strdup failed.");
356       *ret_array_len = array_len;
357       return (-1);
358     }
359     array_len++;
360   }
361
362   *ret_array_len = array_len;
363   return (0);
364 } /* }}} int cdbi_config_add_string */
365
366 static int cdbi_config_add_query_result (cdbi_query_t *q, /* {{{ */
367     oconfig_item_t *ci)
368 {
369   cdbi_result_t *r;
370   int status;
371   int i;
372
373   if (ci->values_num != 0)
374   {
375     WARNING ("dbi plugin: The `Result' block doesn't accept any arguments. "
376         "Ignoring %i argument%s.",
377         ci->values_num, (ci->values_num == 1) ? "" : "s");
378   }
379
380   r = (cdbi_result_t *) malloc (sizeof (*r));
381   if (r == NULL)
382   {
383     ERROR ("dbi plugin: malloc failed.");
384     return (-1);
385   }
386   memset (r, 0, sizeof (*r));
387   r->type = NULL;
388   r->instances = NULL;
389   r->values = NULL;
390   r->next = NULL;
391
392   /* Fill the `cdbi_result_t' structure.. */
393   for (i = 0; i < ci->children_num; i++)
394   {
395     oconfig_item_t *child = ci->children + i;
396
397     if (strcasecmp ("Type", child->key) == 0)
398       status = cdbi_config_set_string (&r->type, child);
399     else if (strcasecmp ("InstancesFrom", child->key) == 0)
400       status = cdbi_config_add_string (&r->instances, &r->instances_num, child);
401     else if (strcasecmp ("ValuesFrom", child->key) == 0)
402       status = cdbi_config_add_string (&r->values, &r->values_num, child);
403     else
404     {
405       WARNING ("dbi plugin: Option `%s' not allowed here.", child->key);
406       status = -1;
407     }
408
409     if (status != 0)
410       break;
411   }
412
413   /* Check that all necessary options have been given. */
414   while (status == 0)
415   {
416     if (r->type == NULL)
417     {
418       WARNING ("dbi plugin: `Type' not given for "
419           "result in query `%s'", q->name);
420       status = -1;
421     }
422     if (r->instances == NULL)
423     {
424       WARNING ("dbi plugin: `InstancesFrom' not given for "
425           "result in query `%s'", q->name);
426       status = -1;
427     }
428     if (r->values == NULL)
429     {
430       WARNING ("dbi plugin: `ValuesFrom' not given for "
431           "result in query `%s'", q->name);
432       status = -1;
433     }
434
435     break;
436   } /* while (status == 0) */
437
438   /* If all went well, add this result to the list of results within the
439    * query structure. */
440   if (status == 0)
441   {
442     if (q->results == NULL)
443     {
444       q->results = r;
445     }
446     else
447     {
448       cdbi_result_t *last;
449
450       last = q->results;
451       while (last->next != NULL)
452         last = last->next;
453
454       last->next = r;
455     }
456   }
457
458   if (status != 0)
459   {
460     cdbi_result_free (r);
461     return (-1);
462   }
463
464   return (0);
465 } /* }}} int cdbi_config_add_query_result */
466
467 static int cdbi_config_add_query (oconfig_item_t *ci) /* {{{ */
468 {
469   cdbi_query_t *q;
470   int status;
471   int i;
472
473   if ((ci->values_num != 1)
474       || (ci->values[0].type != OCONFIG_TYPE_STRING))
475   {
476     WARNING ("dbi plugin: The `Query' block "
477         "needs exactly one string argument.");
478     return (-1);
479   }
480
481   q = (cdbi_query_t *) malloc (sizeof (*q));
482   if (q == NULL)
483   {
484     ERROR ("dbi plugin: malloc failed.");
485     return (-1);
486   }
487   memset (q, 0, sizeof (*q));
488
489   status = cdbi_config_set_string (&q->name, ci);
490   if (status != 0)
491   {
492     sfree (q);
493     return (status);
494   }
495
496   /* Fill the `cdbi_query_t' structure.. */
497   for (i = 0; i < ci->children_num; i++)
498   {
499     oconfig_item_t *child = ci->children + i;
500
501     if (strcasecmp ("Statement", child->key) == 0)
502       status = cdbi_config_set_string (&q->statement, child);
503     else if (strcasecmp ("Result", child->key) == 0)
504       status = cdbi_config_add_query_result (q, child);
505     else
506     {
507       WARNING ("dbi plugin: Option `%s' not allowed here.", child->key);
508       status = -1;
509     }
510
511     if (status != 0)
512       break;
513   }
514
515   /* Check that all necessary options have been given. */
516   while (status == 0)
517   {
518     if (q->statement == NULL)
519     {
520       WARNING ("dbi plugin: `Statement' not given for query `%s'", q->name);
521       status = -1;
522     }
523     if (q->results == NULL)
524     {
525       WARNING ("dbi plugin: No (valid) `Result' block given for query `%s'",
526           q->name);
527       status = -1;
528     }
529
530     break;
531   } /* while (status == 0) */
532
533   /* If all went well, add this query to the list of queries within the
534    * database structure. */
535   if (status == 0)
536   {
537     cdbi_query_t **temp;
538
539     temp = (cdbi_query_t **) realloc (queries,
540         sizeof (*queries) * (queries_num + 1));
541     if (temp == NULL)
542     {
543       ERROR ("dbi plugin: realloc failed");
544       status = -1;
545     }
546     else
547     {
548       queries = temp;
549       queries[queries_num] = q;
550       queries_num++;
551     }
552   }
553
554   if (status != 0)
555   {
556     cdbi_query_free (q);
557     return (-1);
558   }
559
560   return (0);
561 } /* }}} int cdbi_config_add_query */
562
563 static int cdbi_config_add_database_driver_option (cdbi_database_t *db, /* {{{ */
564     oconfig_item_t *ci)
565 {
566   cdbi_driver_option_t *option;
567
568   if ((ci->values_num != 2)
569       || (ci->values[0].type != OCONFIG_TYPE_STRING)
570       || (ci->values[1].type != OCONFIG_TYPE_STRING))
571   {
572     WARNING ("dbi plugin: The `DriverOption' config option "
573         "needs exactly two string arguments.");
574     return (-1);
575   }
576
577   option = (cdbi_driver_option_t *) realloc (db->driver_options,
578       sizeof (*option) * (db->driver_options_num + 1));
579   if (option == NULL)
580   {
581     ERROR ("dbi plugin: realloc failed");
582     return (-1);
583   }
584
585   db->driver_options = option;
586   option = db->driver_options + db->driver_options_num;
587
588   option->key = strdup (ci->values[0].value.string);
589   if (option->key == NULL)
590   {
591     ERROR ("dbi plugin: strdup failed.");
592     return (-1);
593   }
594
595   option->value = strdup (ci->values[1].value.string);
596   if (option->value == NULL)
597   {
598     ERROR ("dbi plugin: strdup failed.");
599     sfree (option->key);
600     return (-1);
601   }
602
603   db->driver_options_num++;
604   return (0);
605 } /* }}} int cdbi_config_add_database_driver_option */
606
607 static int cdbi_config_add_database_query (cdbi_database_t *db, /* {{{ */
608     oconfig_item_t *ci)
609 {
610   cdbi_query_t *q;
611   cdbi_query_t **temp;
612   size_t i;
613
614   if ((ci->values_num != 1)
615       || (ci->values[0].type != OCONFIG_TYPE_STRING))
616   {
617     WARNING ("dbi plugin: The `Query' config option "
618         "needs exactly one string argument.");
619     return (-1);
620   }
621
622   q = NULL;
623   for (i = 0; i < queries_num; i++)
624   {
625     if (strcasecmp (queries[i]->name, ci->values[0].value.string) == 0)
626     {
627       q = queries[i];
628       break;
629     }
630   }
631
632   if (q == NULL)
633   {
634     WARNING ("dbi plugin: Database `%s': Unknown query `%s'. "
635         "Please make sure that the <Query \"%s\"> block comes before "
636         "the <Database \"%s\"> block.",
637         db->name, ci->values[0].value.string,
638         ci->values[0].value.string, db->name);
639     return (-1);
640   }
641
642   temp = (cdbi_query_t **) realloc (db->queries,
643       sizeof (*db->queries) * (db->queries_num + 1));
644   if (temp == NULL)
645   {
646     ERROR ("dbi plugin: realloc failed");
647     return (-1);
648   }
649   else
650   {
651     db->queries = temp;
652     db->queries[db->queries_num] = q;
653     db->queries_num++;
654   }
655
656   return (0);
657 } /* }}} int cdbi_config_add_database_query */
658
659 static int cdbi_config_add_database (oconfig_item_t *ci) /* {{{ */
660 {
661   cdbi_database_t *db;
662   int status;
663   int i;
664
665   if ((ci->values_num != 1)
666       || (ci->values[0].type != OCONFIG_TYPE_STRING))
667   {
668     WARNING ("dbi plugin: The `Database' block "
669         "needs exactly one string argument.");
670     return (-1);
671   }
672
673   db = (cdbi_database_t *) malloc (sizeof (*db));
674   if (db == NULL)
675   {
676     ERROR ("dbi plugin: malloc failed.");
677     return (-1);
678   }
679   memset (db, 0, sizeof (*db));
680
681   status = cdbi_config_set_string (&db->name, ci);
682   if (status != 0)
683   {
684     sfree (db);
685     return (status);
686   }
687
688   /* Fill the `cdbi_database_t' structure.. */
689   for (i = 0; i < ci->children_num; i++)
690   {
691     oconfig_item_t *child = ci->children + i;
692
693     if (strcasecmp ("Driver", child->key) == 0)
694       status = cdbi_config_set_string (&db->driver, child);
695     else if (strcasecmp ("DriverOption", child->key) == 0)
696       status = cdbi_config_add_database_driver_option (db, child);
697     else if (strcasecmp ("SelectDB", child->key) == 0)
698       status = cdbi_config_set_string (&db->select_db, child);
699     else if (strcasecmp ("Query", child->key) == 0)
700       status = cdbi_config_add_database_query (db, child);
701     else
702     {
703       WARNING ("dbi plugin: Option `%s' not allowed here.", child->key);
704       status = -1;
705     }
706
707     if (status != 0)
708       break;
709   }
710
711   /* Check that all necessary options have been given. */
712   while (status == 0)
713   {
714     if (db->driver == NULL)
715     {
716       WARNING ("dbi plugin: `Driver' not given for database `%s'", db->name);
717       status = -1;
718     }
719     if (db->driver_options_num == 0)
720     {
721       WARNING ("dbi plugin: No `DriverOption' given for database `%s'. "
722           "This will likely not work.", db->name);
723     }
724
725     break;
726   } /* while (status == 0) */
727
728   /* If all went well, add this database to the global list of databases. */
729   if (status == 0)
730   {
731     cdbi_database_t **temp;
732
733     temp = (cdbi_database_t **) realloc (databases,
734         sizeof (*databases) * (databases_num + 1));
735     if (temp == NULL)
736     {
737       ERROR ("dbi plugin: realloc failed");
738       status = -1;
739     }
740     else
741     {
742       databases = temp;
743       databases[databases_num] = db;
744       databases_num++;
745     }
746   }
747
748   if (status != 0)
749   {
750     cdbi_database_free (db);
751     return (-1);
752   }
753
754   return (0);
755 } /* }}} int cdbi_config_add_database */
756
757 static int cdbi_config (oconfig_item_t *ci) /* {{{ */
758 {
759   int i;
760
761   for (i = 0; i < ci->children_num; i++)
762   {
763     oconfig_item_t *child = ci->children + i;
764     if (strcasecmp ("Query", child->key) == 0)
765       cdbi_config_add_query (child);
766     else if (strcasecmp ("Database", child->key) == 0)
767       cdbi_config_add_database (child);
768     else
769     {
770       WARNING ("snmp plugin: Ignoring unknown config option `%s'.", child->key);
771     }
772   } /* for (ci->children) */
773
774   return (0);
775 } /* }}} int cdbi_config */
776
777 /* }}} End of configuration handling functions */
778
779 static int cdbi_init (void) /* {{{ */
780 {
781   static int did_init = 0;
782   int status;
783
784   if (did_init != 0)
785     return (0);
786
787   if (queries_num == 0)
788   {
789     ERROR ("dbi plugin: No <Query> blocks have been found. Without them, "
790         "this plugin can't do anything useful, so we will returns an error.");
791     return (-1);
792   }
793
794   if (databases_num == 0)
795   {
796     ERROR ("dbi plugin: No <Database> blocks have been found. Without them, "
797         "this plugin can't do anything useful, so we will returns an error.");
798     return (-1);
799   }
800
801   status = dbi_initialize (NULL);
802   if (status < 0)
803   {
804     ERROR ("dbi plugin: cdbi_init: dbi_initialize failed with status %i.",
805         status);
806     return (-1);
807   }
808   else if (status == 0)
809   {
810     ERROR ("dbi plugin: `dbi_initialize' could not load any drivers. Please "
811         "install at least one `DBD' or check your installation.");
812     return (-1);
813   }
814   DEBUG ("dbi plugin: cdbi_init: dbi_initialize reports %i driver%s.",
815       status, (status == 1) ? "" : "s");
816
817   return (0);
818 } /* }}} int cdbi_init */
819
820 static int cdbi_read_database_query (cdbi_database_t *db, /* {{{ */
821     cdbi_query_t *q)
822 {
823   dbi_result res;
824   int status;
825
826   /* Macro that cleans up dynamically allocated memory and returns the
827    * specified status. */
828 #define BAIL_OUT(status) \
829   if (res != NULL) { dbi_result_free (res); res = NULL; } \
830   return (status)
831
832   res = dbi_conn_query (db->connection, q->statement);
833   if (res == NULL)
834   {
835     char errbuf[1024];
836     ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
837         "dbi_conn_query failed: %s",
838         db->name, q->name,
839         cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
840     BAIL_OUT (-1);
841   }
842
843   /* 0 = error; 1 = success; */
844   status = dbi_result_first_row (res);
845   if (status != 1)
846   {
847     char errbuf[1024];
848     ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
849         "dbi_result_first_row failed: %s. Maybe the statement didn't "
850         "return any rows?",
851         db->name, q->name, 
852         cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
853     BAIL_OUT (-1);
854   }
855
856   /* Iterate over all rows and use every result with each row. */
857   while (42) /* {{{ */
858   {
859     cdbi_result_t *r;
860
861     /* Iterate over all results, get the appropriate data_set, allocate memory
862      * for the instance(s) and value(s), copy the values and finally call
863      * `cdbi_submit' to create and dispatch a value_list. */
864     for (r = q->results; r != NULL; r = r->next) /* {{{ */
865     {
866       const data_set_t *ds;
867       char **instances;
868       value_t *values;
869       size_t i;
870
871       instances = NULL;
872       values = NULL;
873
874       /* Macro to clean up dynamically allocated memory and continue with the
875        * next iteration of the containing loop, i. e. the `for' loop iterating
876        * over all `Result' sets. */
877 #define BAIL_OUT_CONTINUE \
878       if (instances != NULL) { sfree (instances[0]); sfree (instances); } \
879       sfree (values); \
880       continue
881
882       /* Read `ds' and check number of values {{{ */
883       ds = plugin_get_ds (r->type);
884       if (ds == NULL)
885       {
886         ERROR ("dbi plugin: cdbi_read_database_query: Query `%s': Type `%s' is not "
887             "known by the daemon. See types.db(5) for details.",
888             q->name, r->type);
889         BAIL_OUT_CONTINUE;
890       }
891
892       if (((size_t) ds->ds_num) != r->values_num)
893       {
894         ERROR ("dbi plugin: cdbi_read_database_query: Query `%s': The type `%s' "
895             "requires exactly %i value%s, but the configuration specifies %zu.",
896             q->name, r->type,
897             ds->ds_num, (ds->ds_num == 1) ? "" : "s",
898             r->values_num);
899         BAIL_OUT_CONTINUE;
900       }
901       /* }}} */
902
903       /* Allocate `instances' and `values' {{{ */
904       instances = (char **) malloc (sizeof (*instances) * r->instances_num);
905       if (instances == NULL)
906       {
907         ERROR ("dbi plugin: malloc failed.");
908         BAIL_OUT_CONTINUE;
909       }
910
911       instances[0] = (char *) malloc (r->instances_num * DATA_MAX_NAME_LEN);
912       if (instances[0] == NULL)
913       {
914         ERROR ("dbi plugin: malloc failed.");
915         BAIL_OUT_CONTINUE;
916       }
917       for (i = 1; i < r->instances_num; i++)
918         instances[i] = instances[i - 1] + DATA_MAX_NAME_LEN;
919
920       values = (value_t *) malloc (sizeof (*values) * r->values_num);
921       if (values == NULL)
922       {
923         ERROR ("dbi plugin: malloc failed.");
924         BAIL_OUT_CONTINUE;
925       }
926       /* }}} */
927
928       /* Get instance names and values from the result: */
929       for (i = 0; i < r->instances_num; i++) /* {{{ */
930       {
931         const char *inst;
932
933         inst = dbi_result_get_string (res, r->instances[i]);
934         if (dbi_conn_error (db->connection, NULL) != 0)
935         {
936           char errbuf[1024];
937           ERROR ("dbi plugin: cdbi_read_database_query (%s, %s): "
938               "dbi_result_get_string (%s) failed: %s",
939               db->name, q->name, r->instances[i],
940               cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
941           status = -1;
942           break;
943         }
944
945         sstrncpy (instances[i], (inst == NULL) ? "" : inst, DATA_MAX_NAME_LEN);
946         DEBUG ("dbi plugin: cdbi_read_database_query (%s, %s): "
947             "instances[%zu] = %s;",
948             db->name, q->name, i, instances[i]);
949       } /* }}} for (i = 0; i < q->instances_num; i++) */
950
951       if (status != 0)
952       {
953         BAIL_OUT_CONTINUE;
954       }
955
956       for (i = 0; i < r->values_num; i++) /* {{{ */
957       {
958         status = cdbi_result_get_field (res, r->values[i], ds->ds[i].type,
959             values + i);
960         if (status != 0)
961         {
962           break;
963         }
964
965         if (ds->ds[i].type == DS_TYPE_COUNTER)
966         {
967           DEBUG ("dbi plugin: cdbi_read_database_query (%s, %s): values[%zu] = %llu;",
968               db->name, q->name, i, values[i].counter);
969         }
970         else
971         {
972           DEBUG ("dbi plugin: cdbi_read_database_query (%s, %s): values[%zu] = %g;",
973               db->name, q->name, i, values[i].gauge);
974         }
975       } /* }}} for (i = 0; i < q->values_num; i++) */
976
977       if (status != 0)
978       {
979         BAIL_OUT_CONTINUE;
980       }
981
982       /* Dispatch this row to the daemon. */
983       cdbi_submit (db, r, instances, values);
984
985       BAIL_OUT_CONTINUE;
986 #undef BAIL_OUT_CONTINUE
987     } /* }}} for (r = q->results; r != NULL; r = r->next) */
988
989     /* Get the next row from the database. */
990     status = dbi_result_next_row (res);
991     if (status != 1)
992     {
993       if (dbi_conn_error (db->connection, NULL) != 0)
994       {
995         char errbuf[1024];
996         WARNING ("dbi plugin: cdbi_read_database_query (%s, %s): "
997             "dbi_result_next_row failed: %s.",
998             db->name, q->name,
999             cdbi_strerror (db->connection, errbuf, sizeof (errbuf)));
1000       }
1001       break;
1002     }
1003   } /* }}} while (42) */
1004
1005   /* Clean up and return `status = 0' (success) */
1006   BAIL_OUT (0);
1007 #undef BAIL_OUT
1008 } /* }}} int cdbi_read_database_query */
1009
1010 static int cdbi_connect_database (cdbi_database_t *db) /* {{{ */
1011 {
1012   dbi_driver driver;
1013   dbi_conn connection;
1014   size_t i;
1015   int status;
1016
1017   if (db->connection != NULL)
1018   {
1019     status = dbi_conn_ping (db->connection);
1020     if (status != 0) /* connection is alive */
1021       return (0);
1022
1023     dbi_conn_close (db->connection);
1024     db->connection = NULL;
1025   }
1026
1027   driver = dbi_driver_open (db->driver);
1028   if (driver == NULL)
1029   {
1030     ERROR ("dbi plugin: cdbi_connect_database: dbi_driver_open (%s) failed.",
1031         db->driver);
1032     INFO ("dbi plugin: Maybe the driver isn't installed? "
1033         "Known drivers are:");
1034     for (driver = dbi_driver_list (NULL);
1035         driver != NULL;
1036         driver = dbi_driver_list (driver))
1037     {
1038       INFO ("dbi plugin: * %s", dbi_driver_get_name (driver));
1039     }
1040     return (-1);
1041   }
1042
1043   connection = dbi_conn_open (driver);
1044   if (connection == NULL)
1045   {
1046     ERROR ("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.",
1047         db->driver);
1048     return (-1);
1049   }
1050
1051   /* Set all the driver options. Because this is a very very very generic
1052    * interface, the error handling is kind of long. If an invalid option is
1053    * encountered, it will get a list of options understood by the driver and
1054    * report that as `INFO'. This way, users hopefully don't have too much
1055    * trouble finding out how to configure the plugin correctly.. */
1056   for (i = 0; i < db->driver_options_num; i++)
1057   {
1058     DEBUG ("dbi plugin: cdbi_connect_database (%s): "
1059         "key = %s; value = %s;",
1060         db->name,
1061         db->driver_options[i].key,
1062         db->driver_options[i].value);
1063
1064     status = dbi_conn_set_option (connection,
1065         db->driver_options[i].key, db->driver_options[i].value);
1066     if (status != 0)
1067     {
1068       char errbuf[1024];
1069       const char *opt;
1070
1071       ERROR ("dbi plugin: cdbi_connect_database (%s): "
1072           "dbi_conn_set_option (%s, %s) failed: %s.",
1073           db->name,
1074           db->driver_options[i].key, db->driver_options[i].value,
1075           cdbi_strerror (connection, errbuf, sizeof (errbuf)));
1076
1077       INFO ("dbi plugin: This is a list of all options understood "
1078           "by the `%s' driver:", db->driver);
1079       for (opt = dbi_conn_get_option_list (connection, NULL);
1080           opt != NULL;
1081           opt = dbi_conn_get_option_list (connection, opt))
1082       {
1083         INFO ("dbi plugin: * %s", opt);
1084       }
1085
1086       dbi_conn_close (connection);
1087       return (-1);
1088     }
1089   } /* for (i = 0; i < db->driver_options_num; i++) */
1090
1091   status = dbi_conn_connect (connection);
1092   if (status != 0)
1093   {
1094     char errbuf[1024];
1095     ERROR ("dbi plugin: cdbi_connect_database (%s): "
1096         "dbi_conn_connect failed: %s",
1097         db->name, cdbi_strerror (connection, errbuf, sizeof (errbuf)));
1098     dbi_conn_close (connection);
1099     return (-1);
1100   }
1101
1102   if (db->select_db != NULL)
1103   {
1104     status = dbi_conn_select_db (connection, db->select_db);
1105     if (status != 0)
1106     {
1107       char errbuf[1024];
1108       WARNING ("dbi plugin: cdbi_connect_database (%s): "
1109           "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.",
1110           db->name, db->select_db,
1111           cdbi_strerror (connection, errbuf, sizeof (errbuf)));
1112       dbi_conn_close (connection);
1113       return (-1);
1114     }
1115   }
1116
1117   db->connection = connection;
1118   return (0);
1119 } /* }}} int cdbi_connect_database */
1120
1121 static int cdbi_read_database (cdbi_database_t *db) /* {{{ */
1122 {
1123   size_t i;
1124   int success;
1125   int status;
1126
1127   status = cdbi_connect_database (db);
1128   if (status != 0)
1129     return (status);
1130   assert (db->connection != NULL);
1131
1132   success = 0;
1133   for (i = 0; i < db->queries_num; i++)
1134   {
1135     status = cdbi_read_database_query (db, db->queries[i]);
1136     if (status == 0)
1137       success++;
1138   }
1139
1140   if (success == 0)
1141   {
1142     ERROR ("dbi plugin: All queries failed for database `%s'.", db->name);
1143     return (-1);
1144   }
1145
1146   return (0);
1147 } /* }}} int cdbi_read_database */
1148
1149 static int cdbi_read (void) /* {{{ */
1150 {
1151   size_t i;
1152   int success = 0;
1153   int status;
1154
1155   for (i = 0; i < databases_num; i++)
1156   {
1157     status = cdbi_read_database (databases[i]);
1158     if (status == 0)
1159       success++;
1160   }
1161
1162   if (success == 0)
1163   {
1164     ERROR ("dbi plugin: No database could be read. Will return an error so "
1165         "the plugin will be delayed.");
1166     return (-1);
1167   }
1168
1169   return (0);
1170 } /* }}} int cdbi_read */
1171
1172 static int cdbi_shutdown (void) /* {{{ */
1173 {
1174   size_t i;
1175
1176   for (i = 0; i < databases_num; i++)
1177   {
1178     if (databases[i]->connection != NULL)
1179     {
1180       dbi_conn_close (databases[i]->connection);
1181       databases[i]->connection = NULL;
1182     }
1183     cdbi_database_free (databases[i]);
1184   }
1185   sfree (databases);
1186   databases_num = 0;
1187
1188   for (i = 0; i < queries_num; i++)
1189     cdbi_query_free (queries[i]);
1190   sfree (queries);
1191   queries_num = 0;
1192
1193   return (0);
1194 } /* }}} int cdbi_shutdown */
1195
1196 void module_register (void) /* {{{ */
1197 {
1198   plugin_register_complex_config ("dbi", cdbi_config);
1199   plugin_register_init ("dbi", cdbi_init);
1200   plugin_register_read ("dbi", cdbi_read);
1201   plugin_register_shutdown ("dbi", cdbi_shutdown);
1202 } /* }}} void module_register */
1203
1204 /*
1205  * vim: shiftwidth=2 softtabstop=2 et fdm=marker
1206  */