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