postgresql plugin: Added 'StoreRates' feature to writers.
[collectd.git] / src / postgresql.c
1 /**
2  * collectd - src/postgresql.c
3  * Copyright (C) 2008, 2009  Sebastian Harl
4  * Copyright (C) 2009        Florian Forster
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * - Redistributions of source code must retain the above copyright
12  *   notice, this list of conditions and the following disclaimer.
13  *
14  * - Redistributions in binary form must reproduce the above copyright
15  *   notice, this list of conditions and the following disclaimer in the
16  *   documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Authors:
31  *   Sebastian Harl <sh at tokkee.org>
32  *   Florian Forster <octo at verplant.org>
33  **/
34
35 /*
36  * This module collects PostgreSQL database statistics.
37  */
38
39 #include "collectd.h"
40 #include "common.h"
41
42 #include "configfile.h"
43 #include "plugin.h"
44
45 #include "utils_cache.h"
46 #include "utils_db_query.h"
47 #include "utils_complain.h"
48
49 #if HAVE_PTHREAD_H
50 # include <pthread.h>
51 #endif
52
53 #include <pg_config_manual.h>
54 #include <libpq-fe.h>
55
56 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
57 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
58 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
59
60 #ifndef C_PSQL_DEFAULT_CONF
61 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
62 #endif
63
64 /* Appends the (parameter, value) pair to the string
65  * pointed to by 'buf' suitable to be used as argument
66  * for PQconnectdb(). If value equals NULL, the pair
67  * is ignored. */
68 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
69         if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
70                 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
71                 if (0 < s) { \
72                         buf     += s; \
73                         buf_len -= s; \
74                 } \
75         }
76
77 /* Returns the tuple (major, minor, patchlevel)
78  * for the given version number. */
79 #define C_PSQL_SERVER_VERSION3(server_version) \
80         (server_version) / 10000, \
81         (server_version) / 100 - (int)((server_version) / 10000) * 100, \
82         (server_version) - (int)((server_version) / 100) * 100
83
84 /* Returns true if the given host specifies a
85  * UNIX domain socket. */
86 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
87         ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
88
89 /* Returns the tuple (host, delimiter, port) for a
90  * given (host, port) pair. Depending on the value of
91  * 'host' a UNIX domain socket or a TCP socket is
92  * assumed. */
93 #define C_PSQL_SOCKET3(host, port) \
94         ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
95         C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
96         port
97
98 typedef enum {
99         C_PSQL_PARAM_HOST = 1,
100         C_PSQL_PARAM_DB,
101         C_PSQL_PARAM_USER,
102         C_PSQL_PARAM_INTERVAL,
103 } c_psql_param_t;
104
105 /* Parameter configuration. Stored as `user data' in the query objects. */
106 typedef struct {
107         c_psql_param_t *params;
108         int             params_num;
109 } c_psql_user_data_t;
110
111 typedef struct {
112         char *name;
113         char *statement;
114         _Bool store_rates;
115 } c_psql_writer_t;
116
117 typedef struct {
118         PGconn      *conn;
119         c_complain_t conn_complaint;
120
121         int proto_version;
122         int server_version;
123
124         int max_params_num;
125
126         /* user configuration */
127         udb_query_preparation_area_t **q_prep_areas;
128         udb_query_t    **queries;
129         size_t           queries_num;
130
131         c_psql_writer_t **writers;
132         size_t            writers_num;
133
134         /* make sure we don't access the database object in parallel */
135         pthread_mutex_t   db_lock;
136
137         cdtime_t interval;
138
139         char *host;
140         char *port;
141         char *database;
142         char *user;
143         char *password;
144
145         char *sslmode;
146
147         char *krbsrvname;
148
149         char *service;
150 } c_psql_database_t;
151
152 static char *def_queries[] = {
153         "backends",
154         "transactions",
155         "queries",
156         "query_plans",
157         "table_states",
158         "disk_io",
159         "disk_usage"
160 };
161 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
162
163 static udb_query_t      **queries       = NULL;
164 static size_t             queries_num   = 0;
165
166 static c_psql_writer_t   *writers       = NULL;
167 static size_t             writers_num   = 0;
168
169 static c_psql_database_t *c_psql_database_new (const char *name)
170 {
171         c_psql_database_t *db;
172
173         db = (c_psql_database_t *)malloc (sizeof (*db));
174         if (NULL == db) {
175                 log_err ("Out of memory.");
176                 return NULL;
177         }
178
179         db->conn = NULL;
180
181         C_COMPLAIN_INIT (&db->conn_complaint);
182
183         db->proto_version = 0;
184         db->server_version = 0;
185
186         db->max_params_num = 0;
187
188         db->q_prep_areas   = NULL;
189         db->queries        = NULL;
190         db->queries_num    = 0;
191
192         db->writers        = NULL;
193         db->writers_num    = 0;
194
195         pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
196
197         db->interval   = 0;
198
199         db->database   = sstrdup (name);
200         db->host       = NULL;
201         db->port       = NULL;
202         db->user       = NULL;
203         db->password   = NULL;
204
205         db->sslmode    = NULL;
206
207         db->krbsrvname = NULL;
208
209         db->service    = NULL;
210         return db;
211 } /* c_psql_database_new */
212
213 static void c_psql_database_delete (void *data)
214 {
215         size_t i;
216
217         c_psql_database_t *db = data;
218
219         PQfinish (db->conn);
220         db->conn = NULL;
221
222         if (db->q_prep_areas)
223                 for (i = 0; i < db->queries_num; ++i)
224                         udb_query_delete_preparation_area (db->q_prep_areas[i]);
225         free (db->q_prep_areas);
226
227         sfree (db->queries);
228         db->queries_num = 0;
229
230         sfree (db->writers);
231         db->writers_num = 0;
232
233         pthread_mutex_destroy (&db->db_lock);
234
235         sfree (db->database);
236         sfree (db->host);
237         sfree (db->port);
238         sfree (db->user);
239         sfree (db->password);
240
241         sfree (db->sslmode);
242
243         sfree (db->krbsrvname);
244
245         sfree (db->service);
246         return;
247 } /* c_psql_database_delete */
248
249 static int c_psql_connect (c_psql_database_t *db)
250 {
251         char  conninfo[4096];
252         char *buf     = conninfo;
253         int   buf_len = sizeof (conninfo);
254         int   status;
255
256         if (! db)
257                 return -1;
258
259         status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
260         if (0 < status) {
261                 buf     += status;
262                 buf_len -= status;
263         }
264
265         C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
266         C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
267         C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
268         C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
269         C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
270         C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
271         C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
272
273         db->conn = PQconnectdb (conninfo);
274         db->proto_version = PQprotocolVersion (db->conn);
275         return 0;
276 } /* c_psql_connect */
277
278 static int c_psql_check_connection (c_psql_database_t *db)
279 {
280         _Bool init = 0;
281
282         if (! db->conn) {
283                 init = 1;
284
285                 /* trigger c_release() */
286                 if (0 == db->conn_complaint.interval)
287                         db->conn_complaint.interval = 1;
288
289                 c_psql_connect (db);
290         }
291
292         /* "ping" */
293         PQclear (PQexec (db->conn, "SELECT 42;"));
294
295         if (CONNECTION_OK != PQstatus (db->conn)) {
296                 PQreset (db->conn);
297
298                 /* trigger c_release() */
299                 if (0 == db->conn_complaint.interval)
300                         db->conn_complaint.interval = 1;
301
302                 if (CONNECTION_OK != PQstatus (db->conn)) {
303                         c_complain (LOG_ERR, &db->conn_complaint,
304                                         "Failed to connect to database %s: %s",
305                                         db->database, PQerrorMessage (db->conn));
306                         return -1;
307                 }
308
309                 db->proto_version = PQprotocolVersion (db->conn);
310         }
311
312         db->server_version = PQserverVersion (db->conn);
313
314         if (c_would_release (&db->conn_complaint)) {
315                 char *server_host;
316                 int   server_version;
317
318                 server_host    = PQhost (db->conn);
319                 server_version = PQserverVersion (db->conn);
320
321                 c_do_release (LOG_INFO, &db->conn_complaint,
322                                 "Successfully %sconnected to database %s (user %s) "
323                                 "at server %s%s%s (server version: %d.%d.%d, "
324                                 "protocol version: %d, pid: %d)", init ? "" : "re",
325                                 PQdb (db->conn), PQuser (db->conn),
326                                 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
327                                 C_PSQL_SERVER_VERSION3 (server_version),
328                                 db->proto_version, PQbackendPID (db->conn));
329
330                 if (3 > db->proto_version)
331                         log_warn ("Protocol version %d does not support parameters.",
332                                         db->proto_version);
333         }
334         return 0;
335 } /* c_psql_check_connection */
336
337 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
338                 udb_query_t *q)
339 {
340         return PQexec (db->conn, udb_query_get_statement (q));
341 } /* c_psql_exec_query_noparams */
342
343 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
344                 udb_query_t *q, c_psql_user_data_t *data)
345 {
346         char *params[db->max_params_num];
347         char  interval[64];
348         int   i;
349
350         if ((data == NULL) || (data->params_num == 0))
351                 return (c_psql_exec_query_noparams (db, q));
352
353         assert (db->max_params_num >= data->params_num);
354
355         for (i = 0; i < data->params_num; ++i) {
356                 switch (data->params[i]) {
357                         case C_PSQL_PARAM_HOST:
358                                 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
359                                         ? "localhost" : db->host;
360                                 break;
361                         case C_PSQL_PARAM_DB:
362                                 params[i] = db->database;
363                                 break;
364                         case C_PSQL_PARAM_USER:
365                                 params[i] = db->user;
366                                 break;
367                         case C_PSQL_PARAM_INTERVAL:
368                                 ssnprintf (interval, sizeof (interval), "%.3f",
369                                                 (db->interval > 0)
370                                                 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
371                                 params[i] = interval;
372                                 break;
373                         default:
374                                 assert (0);
375                 }
376         }
377
378         return PQexecParams (db->conn, udb_query_get_statement (q),
379                         data->params_num, NULL,
380                         (const char *const *) params,
381                         NULL, NULL, /* return text data */ 0);
382 } /* c_psql_exec_query_params */
383
384 /* db->db_lock must be locked when calling this function */
385 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
386                 udb_query_preparation_area_t *prep_area)
387 {
388         PGresult *res;
389
390         c_psql_user_data_t *data;
391
392         const char *host;
393
394         char **column_names;
395         char **column_values;
396         int    column_num;
397
398         int rows_num;
399         int status;
400         int row, col;
401
402         /* The user data may hold parameter information, but may be NULL. */
403         data = udb_query_get_user_data (q);
404
405         /* Versions up to `3' don't know how to handle parameters. */
406         if (3 <= db->proto_version)
407                 res = c_psql_exec_query_params (db, q, data);
408         else if ((NULL == data) || (0 == data->params_num))
409                 res = c_psql_exec_query_noparams (db, q);
410         else {
411                 log_err ("Connection to database \"%s\" does not support parameters "
412                                 "(protocol version %d) - cannot execute query \"%s\".",
413                                 db->database, db->proto_version,
414                                 udb_query_get_name (q));
415                 return -1;
416         }
417
418         /* give c_psql_write() a chance to acquire the lock if called recursively
419          * through dispatch_values(); this will happen if, both, queries and
420          * writers are configured for a single connection */
421         pthread_mutex_unlock (&db->db_lock);
422
423         column_names = NULL;
424         column_values = NULL;
425
426         if (PGRES_TUPLES_OK != PQresultStatus (res)) {
427                 pthread_mutex_lock (&db->db_lock);
428
429                 log_err ("Failed to execute SQL query: %s",
430                                 PQerrorMessage (db->conn));
431                 log_info ("SQL query was: %s",
432                                 udb_query_get_statement (q));
433                 PQclear (res);
434                 return -1;
435         }
436
437 #define BAIL_OUT(status) \
438         sfree (column_names); \
439         sfree (column_values); \
440         PQclear (res); \
441         pthread_mutex_lock (&db->db_lock); \
442         return status
443
444         rows_num = PQntuples (res);
445         if (1 > rows_num) {
446                 BAIL_OUT (0);
447         }
448
449         column_num = PQnfields (res);
450         column_names = (char **) calloc (column_num, sizeof (char *));
451         if (NULL == column_names) {
452                 log_err ("calloc failed.");
453                 BAIL_OUT (-1);
454         }
455
456         column_values = (char **) calloc (column_num, sizeof (char *));
457         if (NULL == column_values) {
458                 log_err ("calloc failed.");
459                 BAIL_OUT (-1);
460         }
461         
462         for (col = 0; col < column_num; ++col) {
463                 /* Pointers returned by `PQfname' are freed by `PQclear' via
464                  * `BAIL_OUT'. */
465                 column_names[col] = PQfname (res, col);
466                 if (NULL == column_names[col]) {
467                         log_err ("Failed to resolve name of column %i.", col);
468                         BAIL_OUT (-1);
469                 }
470         }
471
472         if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
473                         || (0 == strcmp (db->host, "localhost")))
474                 host = hostname_g;
475         else
476                 host = db->host;
477
478         status = udb_query_prepare_result (q, prep_area, host, "postgresql",
479                         db->database, column_names, (size_t) column_num, db->interval);
480         if (0 != status) {
481                 log_err ("udb_query_prepare_result failed with status %i.",
482                                 status);
483                 BAIL_OUT (-1);
484         }
485
486         for (row = 0; row < rows_num; ++row) {
487                 for (col = 0; col < column_num; ++col) {
488                         /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
489                          * `BAIL_OUT'. */
490                         column_values[col] = PQgetvalue (res, row, col);
491                         if (NULL == column_values[col]) {
492                                 log_err ("Failed to get value at (row = %i, col = %i).",
493                                                 row, col);
494                                 break;
495                         }
496                 }
497
498                 /* check for an error */
499                 if (col < column_num)
500                         continue;
501
502                 status = udb_query_handle_result (q, prep_area, column_values);
503                 if (status != 0) {
504                         log_err ("udb_query_handle_result failed with status %i.",
505                                         status);
506                 }
507         } /* for (row = 0; row < rows_num; ++row) */
508
509         udb_query_finish_result (q, prep_area);
510
511         BAIL_OUT (0);
512 #undef BAIL_OUT
513 } /* c_psql_exec_query */
514
515 static int c_psql_read (user_data_t *ud)
516 {
517         c_psql_database_t *db;
518
519         int success = 0;
520         int i;
521
522         if ((ud == NULL) || (ud->data == NULL)) {
523                 log_err ("c_psql_read: Invalid user data.");
524                 return -1;
525         }
526
527         db = ud->data;
528
529         assert (NULL != db->database);
530         assert (NULL != db->queries);
531
532         pthread_mutex_lock (&db->db_lock);
533
534         if (0 != c_psql_check_connection (db)) {
535                 pthread_mutex_unlock (&db->db_lock);
536                 return -1;
537         }
538
539         for (i = 0; i < db->queries_num; ++i)
540         {
541                 udb_query_preparation_area_t *prep_area;
542                 udb_query_t *q;
543
544                 prep_area = db->q_prep_areas[i];
545                 q = db->queries[i];
546
547                 if ((0 != db->server_version)
548                                 && (udb_query_check_version (q, db->server_version) <= 0))
549                         continue;
550
551                 if (0 == c_psql_exec_query (db, q, prep_area))
552                         success = 1;
553         }
554
555         pthread_mutex_unlock (&db->db_lock);
556
557         if (! success)
558                 return -1;
559         return 0;
560 } /* c_psql_read */
561
562 static char *values_name_to_sqlarray (const data_set_t *ds,
563                 char *string, size_t string_len)
564 {
565         char  *str_ptr;
566         size_t str_len;
567
568         int i;
569
570         str_ptr = string;
571         str_len = string_len;
572
573         for (i = 0; i < ds->ds_num; ++i) {
574                 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
575
576                 if (status < 1)
577                         return NULL;
578                 else if ((size_t)status >= str_len) {
579                         str_len = 0;
580                         break;
581                 }
582                 else {
583                         str_ptr += status;
584                         str_len -= (size_t)status;
585                 }
586         }
587
588         if (str_len <= 2) {
589                 log_err ("c_psql_write: Failed to stringify value names");
590                 return NULL;
591         }
592
593         /* overwrite the first comma */
594         string[0] = '{';
595         str_ptr[0] = '}';
596         str_ptr[1] = '\0';
597
598         return string;
599 } /* values_name_to_sqlarray */
600
601 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
602                 char *string, size_t string_len, _Bool store_rates)
603 {
604         char  *str_ptr;
605         size_t str_len;
606
607         gauge_t *rates = NULL;
608
609         int i;
610
611         str_ptr = string;
612         str_len = string_len;
613
614         for (i = 0; i < vl->values_len; ++i) {
615                 int status;
616
617                 if ((ds->ds[i].type != DS_TYPE_GAUGE)
618                                 && (ds->ds[i].type != DS_TYPE_COUNTER)
619                                 && (ds->ds[i].type != DS_TYPE_DERIVE)
620                                 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
621                         log_err ("c_psql_write: Unknown data source type: %i",
622                                         ds->ds[i].type);
623                         sfree (rates);
624                         return NULL;
625                 }
626
627                 if (ds->ds[i].type == DS_TYPE_GAUGE)
628                         status = ssnprintf (str_ptr, str_len,
629                                         ",%f", vl->values[i].gauge);
630                 else if (store_rates) {
631                         if (rates == NULL)
632                                 rates = uc_get_rate (ds, vl);
633
634                         if (rates == NULL) {
635                                 log_err ("c_psql_write: Failed to determine rate");
636                                 return NULL;
637                         }
638
639                         status = ssnprintf (str_ptr, str_len,
640                                         ",%lf", rates[i]);
641                 }
642                 else if (ds->ds[i].type == DS_TYPE_COUNTER)
643                         status = ssnprintf (str_ptr, str_len,
644                                         ",%llu", vl->values[i].counter);
645                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
646                         status = ssnprintf (str_ptr, str_len,
647                                         ",%"PRIi64, vl->values[i].derive);
648                 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
649                         status = ssnprintf (str_ptr, str_len,
650                                         ",%"PRIu64, vl->values[i].absolute);
651
652                 if (status < 1) {
653                         str_len = 0;
654                         break;
655                 }
656                 else if ((size_t)status >= str_len) {
657                         str_len = 0;
658                         break;
659                 }
660                 else {
661                         str_ptr += status;
662                         str_len -= (size_t)status;
663                 }
664         }
665
666         sfree (rates);
667
668         if (str_len <= 2) {
669                 log_err ("c_psql_write: Failed to stringify value list");
670                 return NULL;
671         }
672
673         /* overwrite the first comma */
674         string[0] = '{';
675         str_ptr[0] = '}';
676         str_ptr[1] = '\0';
677
678         return string;
679 } /* values_to_sqlarray */
680
681 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
682                 user_data_t *ud)
683 {
684         c_psql_database_t *db;
685
686         char time_str[32];
687         char values_name_str[1024];
688         char values_str[1024];
689
690         const char *params[8];
691
692         int success = 0;
693         int i;
694
695         if ((ud == NULL) || (ud->data == NULL)) {
696                 log_err ("c_psql_write: Invalid user data.");
697                 return -1;
698         }
699
700         db = ud->data;
701         assert (db->database != NULL);
702         assert (db->writers != NULL);
703
704         if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
705                 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
706                 return -1;
707         }
708
709         if (values_name_to_sqlarray (ds,
710                                 values_name_str, sizeof (values_name_str)) == NULL)
711                 return -1;
712
713 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
714
715         params[0] = time_str;
716         params[1] = vl->host;
717         params[2] = vl->plugin;
718         params[3] = VALUE_OR_NULL(vl->plugin_instance);
719         params[4] = vl->type;
720         params[5] = VALUE_OR_NULL(vl->type_instance);
721         params[6] = values_name_str;
722
723 #undef VALUE_OR_NULL
724
725         pthread_mutex_lock (&db->db_lock);
726
727         if (0 != c_psql_check_connection (db)) {
728                 pthread_mutex_unlock (&db->db_lock);
729                 return -1;
730         }
731
732         for (i = 0; i < db->writers_num; ++i) {
733                 c_psql_writer_t *writer;
734                 PGresult *res;
735
736                 writer = db->writers[i];
737
738                 if (values_to_sqlarray (ds, vl,
739                                         values_str, sizeof (values_str),
740                                         writer->store_rates) == NULL)
741                         return -1;
742
743                 params[7] = values_str;
744
745                 res = PQexecParams (db->conn, writer->statement,
746                                 STATIC_ARRAY_SIZE (params), NULL,
747                                 (const char *const *)params,
748                                 NULL, NULL, /* return text data */ 0);
749
750                 if ((PGRES_COMMAND_OK != PQresultStatus (res))
751                                 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
752                         if ((CONNECTION_OK != PQstatus (db->conn))
753                                         && (0 == c_psql_check_connection (db))) {
754                                 PQclear (res);
755
756                                 /* try again */
757                                 res = PQexecParams (db->conn, writer->statement,
758                                                 STATIC_ARRAY_SIZE (params), NULL,
759                                                 (const char *const *)params,
760                                                 NULL, NULL, /* return text data */ 0);
761
762                                 if ((PGRES_COMMAND_OK == PQresultStatus (res))
763                                                 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
764                                         success = 1;
765                                         continue;
766                                 }
767                         }
768
769                         log_err ("Failed to execute SQL query: %s",
770                                         PQerrorMessage (db->conn));
771                         log_info ("SQL query was: '%s', "
772                                         "params: %s, %s, %s, %s, %s, %s, %s, %s",
773                                         writer->statement,
774                                         params[0], params[1], params[2], params[3],
775                                         params[4], params[5], params[6], params[7]);
776                         pthread_mutex_unlock (&db->db_lock);
777                         return -1;
778                 }
779                 success = 1;
780         }
781
782         pthread_mutex_unlock (&db->db_lock);
783
784         if (! success)
785                 return -1;
786         return 0;
787 } /* c_psql_write */
788
789 static int c_psql_shutdown (void)
790 {
791         plugin_unregister_read_group ("postgresql");
792
793         udb_query_free (queries, queries_num);
794         queries = NULL;
795         queries_num = 0;
796
797         sfree (writers);
798         writers = NULL;
799         writers_num = 0;
800
801         return 0;
802 } /* c_psql_shutdown */
803
804 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
805 {
806         c_psql_user_data_t *data;
807         const char *param_str;
808
809         c_psql_param_t *tmp;
810
811         data = udb_query_get_user_data (q);
812         if (NULL == data) {
813                 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
814                 if (NULL == data) {
815                         log_err ("Out of memory.");
816                         return -1;
817                 }
818                 memset (data, 0, sizeof (*data));
819                 data->params = NULL;
820         }
821
822         tmp = (c_psql_param_t *) realloc (data->params,
823                         (data->params_num + 1) * sizeof (c_psql_param_t));
824         if (NULL == tmp) {
825                 log_err ("Out of memory.");
826                 return -1;
827         }
828         data->params = tmp;
829
830         param_str = ci->values[0].value.string;
831         if (0 == strcasecmp (param_str, "hostname"))
832                 data->params[data->params_num] = C_PSQL_PARAM_HOST;
833         else if (0 == strcasecmp (param_str, "database"))
834                 data->params[data->params_num] = C_PSQL_PARAM_DB;
835         else if (0 == strcasecmp (param_str, "username"))
836                 data->params[data->params_num] = C_PSQL_PARAM_USER;
837         else if (0 == strcasecmp (param_str, "interval"))
838                 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
839         else {
840                 log_err ("Invalid parameter \"%s\".", param_str);
841                 return 1;
842         }
843
844         data->params_num++;
845         udb_query_set_user_data (q, data);
846
847         return (0);
848 } /* config_query_param_add */
849
850 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
851 {
852         if (0 == strcasecmp ("Param", ci->key))
853                 return config_query_param_add (q, ci);
854
855         log_err ("Option not allowed within a Query block: `%s'", ci->key);
856
857         return (-1);
858 } /* config_query_callback */
859
860 static int config_add_writer (oconfig_item_t *ci,
861                 c_psql_writer_t *src_writers, size_t src_writers_num,
862                 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
863 {
864         char *name;
865
866         size_t i;
867
868         if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
869                 return -1;
870
871         if ((ci->values_num != 1)
872                         || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
873                 log_err ("`Writer' expects a single string argument.");
874                 return 1;
875         }
876
877         name = ci->values[0].value.string;
878
879         for (i = 0; i < src_writers_num; ++i) {
880                 c_psql_writer_t **tmp;
881
882                 if (strcasecmp (name, src_writers[i].name) != 0)
883                         continue;
884
885                 tmp = (c_psql_writer_t **)realloc (*dst_writers,
886                                 sizeof (**dst_writers) * (*dst_writers_num + 1));
887                 if (tmp == NULL) {
888                         log_err ("Out of memory.");
889                         return -1;
890                 }
891
892                 tmp[*dst_writers_num] = src_writers + i;
893
894                 *dst_writers = tmp;
895                 ++(*dst_writers_num);
896                 break;
897         }
898
899         if (i >= src_writers_num) {
900                 log_err ("No such writer: `%s'", name);
901                 return -1;
902         }
903
904         return 0;
905 } /* config_add_writer */
906
907 static int c_psql_config_writer (oconfig_item_t *ci)
908 {
909         c_psql_writer_t *writer;
910         c_psql_writer_t *tmp;
911
912         int status = 0;
913         int i;
914
915         if ((ci->values_num != 1)
916                         || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
917                 log_err ("<Writer> expects a single string argument.");
918                 return 1;
919         }
920
921         tmp = (c_psql_writer_t *)realloc (writers,
922                         sizeof (*writers) * (writers_num + 1));
923         if (tmp == NULL) {
924                 log_err ("Out of memory.");
925                 return -1;
926         }
927
928         writers = tmp;
929         writer  = writers + writers_num;
930         ++writers_num;
931
932         writer->name = sstrdup (ci->values[0].value.string);
933         writer->statement = NULL;
934         writer->store_rates = 1;
935
936         for (i = 0; i < ci->children_num; ++i) {
937                 oconfig_item_t *c = ci->children + i;
938
939                 if (strcasecmp ("Statement", c->key) == 0)
940                         status = cf_util_get_string (c, &writer->statement);
941                 if (strcasecmp ("StoreRates", c->key) == 0)
942                         status = cf_util_get_boolean (c, &writer->store_rates);
943                 else
944                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
945         }
946
947         if (status != 0) {
948                 sfree (writer->statement);
949                 sfree (writer->name);
950                 sfree (writer);
951                 return status;
952         }
953
954         return 0;
955 } /* c_psql_config_writer */
956
957 static int c_psql_config_database (oconfig_item_t *ci)
958 {
959         c_psql_database_t *db;
960
961         char cb_name[DATA_MAX_NAME_LEN];
962         struct timespec cb_interval = { 0, 0 };
963         user_data_t ud;
964
965         int i;
966
967         if ((1 != ci->values_num)
968                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
969                 log_err ("<Database> expects a single string argument.");
970                 return 1;
971         }
972
973         memset (&ud, 0, sizeof (ud));
974
975         db = c_psql_database_new (ci->values[0].value.string);
976         if (db == NULL)
977                 return -1;
978
979         for (i = 0; i < ci->children_num; ++i) {
980                 oconfig_item_t *c = ci->children + i;
981
982                 if (0 == strcasecmp (c->key, "Host"))
983                         cf_util_get_string (c, &db->host);
984                 else if (0 == strcasecmp (c->key, "Port"))
985                         cf_util_get_service (c, &db->port);
986                 else if (0 == strcasecmp (c->key, "User"))
987                         cf_util_get_string (c, &db->user);
988                 else if (0 == strcasecmp (c->key, "Password"))
989                         cf_util_get_string (c, &db->password);
990                 else if (0 == strcasecmp (c->key, "SSLMode"))
991                         cf_util_get_string (c, &db->sslmode);
992                 else if (0 == strcasecmp (c->key, "KRBSrvName"))
993                         cf_util_get_string (c, &db->krbsrvname);
994                 else if (0 == strcasecmp (c->key, "Service"))
995                         cf_util_get_string (c, &db->service);
996                 else if (0 == strcasecmp (c->key, "Query"))
997                         udb_query_pick_from_list (c, queries, queries_num,
998                                         &db->queries, &db->queries_num);
999                 else if (0 == strcasecmp (c->key, "Writer"))
1000                         config_add_writer (c, writers, writers_num,
1001                                         &db->writers, &db->writers_num);
1002                 else if (0 == strcasecmp (c->key, "Interval"))
1003                         cf_util_get_cdtime (c, &db->interval);
1004                 else
1005                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
1006         }
1007
1008         /* If no `Query' options were given, add the default queries.. */
1009         if ((db->queries_num == 0) && (db->writers_num == 0)){
1010                 for (i = 0; i < def_queries_num; i++)
1011                         udb_query_pick_from_list_by_name (def_queries[i],
1012                                         queries, queries_num,
1013                                         &db->queries, &db->queries_num);
1014         }
1015
1016         if (db->queries_num > 0) {
1017                 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1018                                 db->queries_num, sizeof (*db->q_prep_areas));
1019
1020                 if (db->q_prep_areas == NULL) {
1021                         log_err ("Out of memory.");
1022                         c_psql_database_delete (db);
1023                         return -1;
1024                 }
1025         }
1026
1027         for (i = 0; (size_t)i < db->queries_num; ++i) {
1028                 c_psql_user_data_t *data;
1029                 data = udb_query_get_user_data (db->queries[i]);
1030                 if ((data != NULL) && (data->params_num > db->max_params_num))
1031                         db->max_params_num = data->params_num;
1032
1033                 db->q_prep_areas[i]
1034                         = udb_query_allocate_preparation_area (db->queries[i]);
1035
1036                 if (db->q_prep_areas[i] == NULL) {
1037                         log_err ("Out of memory.");
1038                         c_psql_database_delete (db);
1039                         return -1;
1040                 }
1041         }
1042
1043         ud.data = db;
1044         ud.free_func = c_psql_database_delete;
1045
1046         ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
1047
1048         if (db->queries_num > 0) {
1049                 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1050
1051                 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1052                                 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1053                                 &ud);
1054         }
1055         if (db->writers_num > 0) {
1056                 plugin_register_write (cb_name, c_psql_write, &ud);
1057         }
1058         return 0;
1059 } /* c_psql_config_database */
1060
1061 static int c_psql_config (oconfig_item_t *ci)
1062 {
1063         static int have_def_config = 0;
1064
1065         int i;
1066
1067         if (0 == have_def_config) {
1068                 oconfig_item_t *c;
1069
1070                 have_def_config = 1;
1071
1072                 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1073                 if (NULL == c)
1074                         log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1075                 else
1076                         c_psql_config (c);
1077
1078                 if (NULL == queries)
1079                         log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1080                                         "any queries - please check your installation.");
1081         }
1082
1083         for (i = 0; i < ci->children_num; ++i) {
1084                 oconfig_item_t *c = ci->children + i;
1085
1086                 if (0 == strcasecmp (c->key, "Query"))
1087                         udb_query_create (&queries, &queries_num, c,
1088                                         /* callback = */ config_query_callback);
1089                 else if (0 == strcasecmp (c->key, "Writer"))
1090                         c_psql_config_writer (c);
1091                 else if (0 == strcasecmp (c->key, "Database"))
1092                         c_psql_config_database (c);
1093                 else
1094                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
1095         }
1096         return 0;
1097 } /* c_psql_config */
1098
1099 void module_register (void)
1100 {
1101         plugin_register_complex_config ("postgresql", c_psql_config);
1102         plugin_register_shutdown ("postgresql", c_psql_shutdown);
1103 } /* module_register */
1104
1105 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */