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