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