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