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