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 **/
29 /*
30 * This module collects PostgreSQL database statistics.
31 */
33 #include "collectd.h"
35 #include "common.h"
37 #include "plugin.h"
39 #include "utils_cache.h"
40 #include "utils_complain.h"
41 #include "utils_db_query.h"
43 #include <libpq-fe.h>
44 #include <pg_config_manual.h>
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__)
51 #ifndef C_PSQL_DEFAULT_CONF
52 #define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
53 #endif
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 }
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
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)))
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
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;
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;
102 typedef struct {
103 char *name;
104 char *statement;
105 _Bool store_rates;
106 } c_psql_writer_t;
108 typedef struct {
109 PGconn *conn;
110 c_complain_t conn_complaint;
112 int proto_version;
113 int server_version;
115 int max_params_num;
117 /* user configuration */
118 udb_query_preparation_area_t **q_prep_areas;
119 udb_query_t **queries;
120 size_t queries_num;
122 c_psql_writer_t **writers;
123 size_t writers_num;
125 /* make sure we don't access the database object in parallel */
126 pthread_mutex_t db_lock;
128 cdtime_t interval;
130 /* writer "caching" settings */
131 cdtime_t commit_interval;
132 cdtime_t next_commit;
133 cdtime_t expire_delay;
135 char *host;
136 char *port;
137 char *database;
138 char *user;
139 char *password;
141 char *instance;
143 char *sslmode;
145 char *krbsrvname;
147 char *service;
149 int ref_cnt;
150 } c_psql_database_t;
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);
157 static c_psql_database_t **databases = NULL;
158 static size_t databases_num = 0;
160 static udb_query_t **queries = NULL;
161 static size_t queries_num = 0;
163 static c_psql_writer_t *writers = NULL;
164 static size_t writers_num = 0;
166 static int c_psql_begin(c_psql_database_t *db) {
167 PGresult *r = PQexec(db->conn, "BEGIN");
169 int status = 1;
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 */
183 static int c_psql_commit(c_psql_database_t *db) {
184 PGresult *r = PQexec(db->conn, "COMMIT");
186 int status = 1;
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 */
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;
204 db = malloc(sizeof(*db));
205 if (NULL == db) {
206 log_err("Out of memory.");
207 return NULL;
208 }
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 }
217 databases = tmp;
218 databases[databases_num] = db;
219 ++databases_num;
221 db->conn = NULL;
223 C_COMPLAIN_INIT(&db->conn_complaint);
225 db->proto_version = 0;
226 db->server_version = 0;
228 db->max_params_num = 0;
230 db->q_prep_areas = NULL;
231 db->queries = NULL;
232 db->queries_num = 0;
234 db->writers = NULL;
235 db->writers_num = 0;
237 pthread_mutex_init(&db->db_lock, /* attrs = */ NULL);
239 db->interval = 0;
241 db->commit_interval = 0;
242 db->next_commit = 0;
243 db->expire_delay = 0;
245 db->database = sstrdup(name);
246 db->host = NULL;
247 db->port = NULL;
248 db->user = NULL;
249 db->password = NULL;
251 db->instance = sstrdup(name);
253 db->sslmode = NULL;
255 db->krbsrvname = NULL;
257 db->service = NULL;
259 db->ref_cnt = 0;
260 return db;
261 } /* c_psql_database_new */
263 static void c_psql_database_delete(void *data) {
264 c_psql_database_t *db = data;
266 --db->ref_cnt;
267 /* readers and writers may access this database */
268 if (db->ref_cnt > 0)
269 return;
271 /* wait for the lock to be released by the last writer */
272 pthread_mutex_lock(&db->db_lock);
274 if (db->next_commit > 0)
275 c_psql_commit(db);
277 PQfinish(db->conn);
278 db->conn = NULL;
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);
285 sfree(db->queries);
286 db->queries_num = 0;
288 sfree(db->writers);
289 db->writers_num = 0;
291 pthread_mutex_unlock(&db->db_lock);
293 pthread_mutex_destroy(&db->db_lock);
295 sfree(db->database);
296 sfree(db->host);
297 sfree(db->port);
298 sfree(db->user);
299 sfree(db->password);
301 sfree(db->instance);
303 sfree(db->sslmode);
305 sfree(db->krbsrvname);
307 sfree(db->service);
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 */
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;
322 if ((!db) || (!db->database))
323 return -1;
325 status = ssnprintf(buf, buf_len, "dbname = '%s'", db->database);
326 if (0 < status) {
327 buf += status;
328 buf_len -= status;
329 }
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);
339 db->conn = PQconnectdb(conninfo);
340 db->proto_version = PQprotocolVersion(db->conn);
341 return 0;
342 } /* c_psql_connect */
344 static int c_psql_check_connection(c_psql_database_t *db) {
345 _Bool init = 0;
347 if (!db->conn) {
348 init = 1;
350 /* trigger c_release() */
351 if (0 == db->conn_complaint.interval)
352 db->conn_complaint.interval = 1;
354 c_psql_connect(db);
355 }
357 if (CONNECTION_OK != PQstatus(db->conn)) {
358 PQreset(db->conn);
360 /* trigger c_release() */
361 if (0 == db->conn_complaint.interval)
362 db->conn_complaint.interval = 1;
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 }
371 db->proto_version = PQprotocolVersion(db->conn);
372 }
374 db->server_version = PQserverVersion(db->conn);
376 if (c_would_release(&db->conn_complaint)) {
377 char *server_host;
378 int server_version;
380 server_host = PQhost(db->conn);
381 server_version = PQserverVersion(db->conn);
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));
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 */
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 */
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];
409 if ((data == NULL) || (data->params_num == 0))
410 return (c_psql_exec_query_noparams(db, q));
412 assert(db->max_params_num >= data->params_num);
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 }
440 return PQexecParams(db->conn, udb_query_get_statement(q), data->params_num,
441 NULL, (const char *const *)params, NULL, NULL,
442 /* return text data */ 0);
443 } /* c_psql_exec_query_params */
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;
450 c_psql_user_data_t *data;
452 const char *host;
454 char **column_names;
455 char **column_values;
456 int column_num;
458 int rows_num;
459 int status;
461 /* The user data may hold parameter information, but may be NULL. */
462 data = udb_query_get_user_data(q);
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 }
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);
483 column_names = NULL;
484 column_values = NULL;
486 if (PGRES_TUPLES_OK != PQresultStatus(res)) {
487 pthread_mutex_lock(&db->db_lock);
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 }
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 }
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
508 rows_num = PQntuples(res);
509 if (1 > rows_num) {
510 BAIL_OUT(0);
511 }
513 column_num = PQnfields(res);
514 column_names = (char **)calloc(column_num, sizeof(char *));
515 if (NULL == column_names) {
516 log_err("calloc failed.");
517 BAIL_OUT(-1);
518 }
520 column_values = (char **)calloc(column_num, sizeof(char *));
521 if (NULL == column_values) {
522 log_err("calloc failed.");
523 BAIL_OUT(-1);
524 }
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 }
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;
543 status =
544 udb_query_prepare_result(q, prep_area, host, "postgresql", db->instance,
545 column_names, (size_t)column_num, db->interval);
546 if (0 != status) {
547 log_err("udb_query_prepare_result failed with status %i.", status);
548 BAIL_OUT(-1);
549 }
551 for (int row = 0; row < rows_num; ++row) {
552 int col;
553 for (col = 0; col < column_num; ++col) {
554 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
555 * `BAIL_OUT'. */
556 column_values[col] = PQgetvalue(res, row, col);
557 if (NULL == column_values[col]) {
558 log_err("Failed to get value at (row = %i, col = %i).", row, col);
559 break;
560 }
561 }
563 /* check for an error */
564 if (col < column_num)
565 continue;
567 status = udb_query_handle_result(q, prep_area, column_values);
568 if (status != 0) {
569 log_err("udb_query_handle_result failed with status %i.", status);
570 }
571 } /* for (row = 0; row < rows_num; ++row) */
573 udb_query_finish_result(q, prep_area);
575 BAIL_OUT(0);
576 #undef BAIL_OUT
577 } /* c_psql_exec_query */
579 static int c_psql_read(user_data_t *ud) {
580 c_psql_database_t *db;
582 int success = 0;
584 if ((ud == NULL) || (ud->data == NULL)) {
585 log_err("c_psql_read: Invalid user data.");
586 return -1;
587 }
589 db = ud->data;
591 assert(NULL != db->database);
592 assert(NULL != db->instance);
593 assert(NULL != db->queries);
595 pthread_mutex_lock(&db->db_lock);
597 if (0 != c_psql_check_connection(db)) {
598 pthread_mutex_unlock(&db->db_lock);
599 return -1;
600 }
602 for (size_t i = 0; i < db->queries_num; ++i) {
603 udb_query_preparation_area_t *prep_area;
604 udb_query_t *q;
606 prep_area = db->q_prep_areas[i];
607 q = db->queries[i];
609 if ((0 != db->server_version) &&
610 (udb_query_check_version(q, db->server_version) <= 0))
611 continue;
613 if (0 == c_psql_exec_query(db, q, prep_area))
614 success = 1;
615 }
617 pthread_mutex_unlock(&db->db_lock);
619 if (!success)
620 return -1;
621 return 0;
622 } /* c_psql_read */
624 static char *values_name_to_sqlarray(const data_set_t *ds, char *string,
625 size_t string_len) {
626 char *str_ptr;
627 size_t str_len;
629 str_ptr = string;
630 str_len = string_len;
632 for (size_t i = 0; i < ds->ds_num; ++i) {
633 int status = ssnprintf(str_ptr, str_len, ",'%s'", ds->ds[i].name);
635 if (status < 1)
636 return NULL;
637 else if ((size_t)status >= str_len) {
638 str_len = 0;
639 break;
640 } else {
641 str_ptr += status;
642 str_len -= (size_t)status;
643 }
644 }
646 if (str_len <= 2) {
647 log_err("c_psql_write: Failed to stringify value names");
648 return NULL;
649 }
651 /* overwrite the first comma */
652 string[0] = '{';
653 str_ptr[0] = '}';
654 str_ptr[1] = '\0';
656 return string;
657 } /* values_name_to_sqlarray */
659 static char *values_type_to_sqlarray(const data_set_t *ds, char *string,
660 size_t string_len, _Bool store_rates) {
661 char *str_ptr;
662 size_t str_len;
664 str_ptr = string;
665 str_len = string_len;
667 for (size_t i = 0; i < ds->ds_num; ++i) {
668 int status;
670 if (store_rates)
671 status = ssnprintf(str_ptr, str_len, ",'gauge'");
672 else
673 status = ssnprintf(str_ptr, str_len, ",'%s'",
674 DS_TYPE_TO_STRING(ds->ds[i].type));
676 if (status < 1) {
677 str_len = 0;
678 break;
679 } else if ((size_t)status >= str_len) {
680 str_len = 0;
681 break;
682 } else {
683 str_ptr += status;
684 str_len -= (size_t)status;
685 }
686 }
688 if (str_len <= 2) {
689 log_err("c_psql_write: Failed to stringify value types");
690 return NULL;
691 }
693 /* overwrite the first comma */
694 string[0] = '{';
695 str_ptr[0] = '}';
696 str_ptr[1] = '\0';
698 return string;
699 } /* values_type_to_sqlarray */
701 static char *values_to_sqlarray(const data_set_t *ds, const value_list_t *vl,
702 char *string, size_t string_len,
703 _Bool store_rates) {
704 char *str_ptr;
705 size_t str_len;
707 gauge_t *rates = NULL;
709 str_ptr = string;
710 str_len = string_len;
712 for (size_t i = 0; i < vl->values_len; ++i) {
713 int status = 0;
715 if ((ds->ds[i].type != DS_TYPE_GAUGE) &&
716 (ds->ds[i].type != DS_TYPE_COUNTER) &&
717 (ds->ds[i].type != DS_TYPE_DERIVE) &&
718 (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
719 log_err("c_psql_write: Unknown data source type: %i", ds->ds[i].type);
720 sfree(rates);
721 return NULL;
722 }
724 if (ds->ds[i].type == DS_TYPE_GAUGE)
725 status =
726 ssnprintf(str_ptr, str_len, "," GAUGE_FORMAT, vl->values[i].gauge);
727 else if (store_rates) {
728 if (rates == NULL)
729 rates = uc_get_rate(ds, vl);
731 if (rates == NULL) {
732 log_err("c_psql_write: Failed to determine rate");
733 return NULL;
734 }
736 status = ssnprintf(str_ptr, str_len, ",%lf", rates[i]);
737 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
738 status = ssnprintf(str_ptr, str_len, ",%llu", vl->values[i].counter);
739 else if (ds->ds[i].type == DS_TYPE_DERIVE)
740 status = ssnprintf(str_ptr, str_len, ",%" PRIi64, vl->values[i].derive);
741 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
742 status = ssnprintf(str_ptr, str_len, ",%" PRIu64, vl->values[i].absolute);
744 if (status < 1) {
745 str_len = 0;
746 break;
747 } else if ((size_t)status >= str_len) {
748 str_len = 0;
749 break;
750 } else {
751 str_ptr += status;
752 str_len -= (size_t)status;
753 }
754 }
756 sfree(rates);
758 if (str_len <= 2) {
759 log_err("c_psql_write: Failed to stringify value list");
760 return NULL;
761 }
763 /* overwrite the first comma */
764 string[0] = '{';
765 str_ptr[0] = '}';
766 str_ptr[1] = '\0';
768 return string;
769 } /* values_to_sqlarray */
771 static int c_psql_write(const data_set_t *ds, const value_list_t *vl,
772 user_data_t *ud) {
773 c_psql_database_t *db;
775 char time_str[RFC3339NANO_SIZE];
776 char values_name_str[1024];
777 char values_type_str[1024];
778 char values_str[1024];
780 const char *params[9];
782 int success = 0;
784 if ((ud == NULL) || (ud->data == NULL)) {
785 log_err("c_psql_write: Invalid user data.");
786 return -1;
787 }
789 db = ud->data;
790 assert(db->database != NULL);
791 assert(db->writers != NULL);
793 if (rfc3339nano_local(time_str, sizeof(time_str), vl->time) != 0) {
794 log_err("c_psql_write: Failed to convert time to RFC 3339 format");
795 return -1;
796 }
798 if (values_name_to_sqlarray(ds, values_name_str, sizeof(values_name_str)) ==
799 NULL)
800 return -1;
802 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
804 params[0] = time_str;
805 params[1] = vl->host;
806 params[2] = vl->plugin;
807 params[3] = VALUE_OR_NULL(vl->plugin_instance);
808 params[4] = vl->type;
809 params[5] = VALUE_OR_NULL(vl->type_instance);
810 params[6] = values_name_str;
812 #undef VALUE_OR_NULL
814 if (db->expire_delay > 0 &&
815 vl->time < (cdtime() - vl->interval - db->expire_delay)) {
816 log_info("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
817 params[0], params[1], params[2], params[3], params[4], params[5],
818 params[6]);
819 return 0;
820 }
822 pthread_mutex_lock(&db->db_lock);
824 if (0 != c_psql_check_connection(db)) {
825 pthread_mutex_unlock(&db->db_lock);
826 return -1;
827 }
829 if ((db->commit_interval > 0) && (db->next_commit == 0))
830 c_psql_begin(db);
832 for (size_t i = 0; i < db->writers_num; ++i) {
833 c_psql_writer_t *writer;
834 PGresult *res;
836 writer = db->writers[i];
838 if (values_type_to_sqlarray(ds, values_type_str, sizeof(values_type_str),
839 writer->store_rates) == NULL) {
840 pthread_mutex_unlock(&db->db_lock);
841 return -1;
842 }
844 if (values_to_sqlarray(ds, vl, values_str, sizeof(values_str),
845 writer->store_rates) == NULL) {
846 pthread_mutex_unlock(&db->db_lock);
847 return -1;
848 }
850 params[7] = values_type_str;
851 params[8] = values_str;
853 res = PQexecParams(db->conn, writer->statement, STATIC_ARRAY_SIZE(params),
854 NULL, (const char *const *)params, NULL, NULL,
855 /* return text data */ 0);
857 if ((PGRES_COMMAND_OK != PQresultStatus(res)) &&
858 (PGRES_TUPLES_OK != PQresultStatus(res))) {
859 PQclear(res);
861 if ((CONNECTION_OK != PQstatus(db->conn)) &&
862 (0 == c_psql_check_connection(db))) {
863 /* try again */
864 res = PQexecParams(
865 db->conn, writer->statement, STATIC_ARRAY_SIZE(params), NULL,
866 (const char *const *)params, NULL, NULL, /* return text data */ 0);
868 if ((PGRES_COMMAND_OK == PQresultStatus(res)) ||
869 (PGRES_TUPLES_OK == PQresultStatus(res))) {
870 PQclear(res);
871 success = 1;
872 continue;
873 }
874 }
876 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
877 log_info("SQL query was: '%s', "
878 "params: %s, %s, %s, %s, %s, %s, %s, %s",
879 writer->statement, params[0], params[1], params[2], params[3],
880 params[4], params[5], params[6], params[7]);
882 /* this will abort any current transaction -> restart */
883 if (db->next_commit > 0)
884 c_psql_commit(db);
886 pthread_mutex_unlock(&db->db_lock);
887 return -1;
888 }
890 PQclear(res);
891 success = 1;
892 }
894 if ((db->next_commit > 0) && (cdtime() > db->next_commit))
895 c_psql_commit(db);
897 pthread_mutex_unlock(&db->db_lock);
899 if (!success)
900 return -1;
901 return 0;
902 } /* c_psql_write */
904 /* We cannot flush single identifiers as all we do is to commit the currently
905 * running transaction, thus making sure that all written data is actually
906 * visible to everybody. */
907 static int c_psql_flush(cdtime_t timeout,
908 __attribute__((unused)) const char *ident,
909 user_data_t *ud) {
910 c_psql_database_t **dbs = databases;
911 size_t dbs_num = databases_num;
913 if ((ud != NULL) && (ud->data != NULL)) {
914 dbs = (void *)&ud->data;
915 dbs_num = 1;
916 }
918 for (size_t i = 0; i < dbs_num; ++i) {
919 c_psql_database_t *db = dbs[i];
921 /* don't commit if the timeout is larger than the regular commit
922 * interval as in that case all requested data has already been
923 * committed */
924 if ((db->next_commit > 0) && (db->commit_interval > timeout))
925 c_psql_commit(db);
926 }
927 return 0;
928 } /* c_psql_flush */
930 static int c_psql_shutdown(void) {
931 _Bool had_flush = 0;
933 plugin_unregister_read_group("postgresql");
935 for (size_t i = 0; i < databases_num; ++i) {
936 c_psql_database_t *db = databases[i];
938 if (db->writers_num > 0) {
939 char cb_name[DATA_MAX_NAME_LEN];
940 ssnprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->database);
942 if (!had_flush) {
943 plugin_unregister_flush("postgresql");
944 had_flush = 1;
945 }
947 plugin_unregister_flush(cb_name);
948 plugin_unregister_write(cb_name);
949 }
951 sfree(db);
952 }
954 udb_query_free(queries, queries_num);
955 queries = NULL;
956 queries_num = 0;
958 sfree(writers);
959 writers = NULL;
960 writers_num = 0;
962 sfree(databases);
963 databases = NULL;
964 databases_num = 0;
966 return 0;
967 } /* c_psql_shutdown */
969 static int config_query_param_add(udb_query_t *q, oconfig_item_t *ci) {
970 c_psql_user_data_t *data;
971 const char *param_str;
973 c_psql_param_t *tmp;
975 data = udb_query_get_user_data(q);
976 if (NULL == data) {
977 data = calloc(1, sizeof(*data));
978 if (NULL == data) {
979 log_err("Out of memory.");
980 return -1;
981 }
982 data->params = NULL;
983 data->params_num = 0;
985 udb_query_set_user_data(q, data);
986 }
988 tmp = realloc(data->params, (data->params_num + 1) * sizeof(*data->params));
989 if (NULL == tmp) {
990 log_err("Out of memory.");
991 return -1;
992 }
993 data->params = tmp;
995 param_str = ci->values[0].value.string;
996 if (0 == strcasecmp(param_str, "hostname"))
997 data->params[data->params_num] = C_PSQL_PARAM_HOST;
998 else if (0 == strcasecmp(param_str, "database"))
999 data->params[data->params_num] = C_PSQL_PARAM_DB;
1000 else if (0 == strcasecmp(param_str, "username"))
1001 data->params[data->params_num] = C_PSQL_PARAM_USER;
1002 else if (0 == strcasecmp(param_str, "interval"))
1003 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1004 else if (0 == strcasecmp(param_str, "instance"))
1005 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1006 else {
1007 log_err("Invalid parameter \"%s\".", param_str);
1008 return 1;
1009 }
1011 data->params_num++;
1012 return (0);
1013 } /* config_query_param_add */
1015 static int config_query_callback(udb_query_t *q, oconfig_item_t *ci) {
1016 if (0 == strcasecmp("Param", ci->key))
1017 return config_query_param_add(q, ci);
1019 log_err("Option not allowed within a Query block: `%s'", ci->key);
1021 return (-1);
1022 } /* config_query_callback */
1024 static int config_add_writer(oconfig_item_t *ci, c_psql_writer_t *src_writers,
1025 size_t src_writers_num,
1026 c_psql_writer_t ***dst_writers,
1027 size_t *dst_writers_num) {
1028 char *name;
1030 size_t i;
1032 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1033 return -1;
1035 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1036 log_err("`Writer' expects a single string argument.");
1037 return 1;
1038 }
1040 name = ci->values[0].value.string;
1042 for (i = 0; i < src_writers_num; ++i) {
1043 c_psql_writer_t **tmp;
1045 if (strcasecmp(name, src_writers[i].name) != 0)
1046 continue;
1048 tmp = realloc(*dst_writers, sizeof(**dst_writers) * (*dst_writers_num + 1));
1049 if (tmp == NULL) {
1050 log_err("Out of memory.");
1051 return -1;
1052 }
1054 tmp[*dst_writers_num] = src_writers + i;
1056 *dst_writers = tmp;
1057 ++(*dst_writers_num);
1058 break;
1059 }
1061 if (i >= src_writers_num) {
1062 log_err("No such writer: `%s'", name);
1063 return -1;
1064 }
1066 return 0;
1067 } /* config_add_writer */
1069 static int c_psql_config_writer(oconfig_item_t *ci) {
1070 c_psql_writer_t *writer;
1071 c_psql_writer_t *tmp;
1073 int status = 0;
1075 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1076 log_err("<Writer> expects a single string argument.");
1077 return 1;
1078 }
1080 tmp = realloc(writers, sizeof(*writers) * (writers_num + 1));
1081 if (tmp == NULL) {
1082 log_err("Out of memory.");
1083 return -1;
1084 }
1086 writers = tmp;
1087 writer = writers + writers_num;
1088 memset(writer, 0, sizeof(*writer));
1090 writer->name = sstrdup(ci->values[0].value.string);
1091 writer->statement = NULL;
1092 writer->store_rates = 1;
1094 for (int i = 0; i < ci->children_num; ++i) {
1095 oconfig_item_t *c = ci->children + i;
1097 if (strcasecmp("Statement", c->key) == 0)
1098 status = cf_util_get_string(c, &writer->statement);
1099 else if (strcasecmp("StoreRates", c->key) == 0)
1100 status = cf_util_get_boolean(c, &writer->store_rates);
1101 else
1102 log_warn("Ignoring unknown config key \"%s\".", c->key);
1103 }
1105 if (status != 0) {
1106 sfree(writer->statement);
1107 sfree(writer->name);
1108 return status;
1109 }
1111 ++writers_num;
1112 return 0;
1113 } /* c_psql_config_writer */
1115 static int c_psql_config_database(oconfig_item_t *ci) {
1116 c_psql_database_t *db;
1118 char cb_name[DATA_MAX_NAME_LEN];
1119 static _Bool have_flush = 0;
1121 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1122 log_err("<Database> expects a single string argument.");
1123 return 1;
1124 }
1126 db = c_psql_database_new(ci->values[0].value.string);
1127 if (db == NULL)
1128 return -1;
1130 for (int i = 0; i < ci->children_num; ++i) {
1131 oconfig_item_t *c = ci->children + i;
1133 if (0 == strcasecmp(c->key, "Host"))
1134 cf_util_get_string(c, &db->host);
1135 else if (0 == strcasecmp(c->key, "Port"))
1136 cf_util_get_service(c, &db->port);
1137 else if (0 == strcasecmp(c->key, "User"))
1138 cf_util_get_string(c, &db->user);
1139 else if (0 == strcasecmp(c->key, "Password"))
1140 cf_util_get_string(c, &db->password);
1141 else if (0 == strcasecmp(c->key, "Instance"))
1142 cf_util_get_string(c, &db->instance);
1143 else if (0 == strcasecmp(c->key, "SSLMode"))
1144 cf_util_get_string(c, &db->sslmode);
1145 else if (0 == strcasecmp(c->key, "KRBSrvName"))
1146 cf_util_get_string(c, &db->krbsrvname);
1147 else if (0 == strcasecmp(c->key, "Service"))
1148 cf_util_get_string(c, &db->service);
1149 else if (0 == strcasecmp(c->key, "Query"))
1150 udb_query_pick_from_list(c, queries, queries_num, &db->queries,
1151 &db->queries_num);
1152 else if (0 == strcasecmp(c->key, "Writer"))
1153 config_add_writer(c, writers, writers_num, &db->writers,
1154 &db->writers_num);
1155 else if (0 == strcasecmp(c->key, "Interval"))
1156 cf_util_get_cdtime(c, &db->interval);
1157 else if (strcasecmp("CommitInterval", c->key) == 0)
1158 cf_util_get_cdtime(c, &db->commit_interval);
1159 else if (strcasecmp("ExpireDelay", c->key) == 0)
1160 cf_util_get_cdtime(c, &db->expire_delay);
1161 else
1162 log_warn("Ignoring unknown config key \"%s\".", c->key);
1163 }
1165 /* If no `Query' options were given, add the default queries.. */
1166 if ((db->queries_num == 0) && (db->writers_num == 0)) {
1167 for (int i = 0; i < def_queries_num; i++)
1168 udb_query_pick_from_list_by_name(def_queries[i], queries, queries_num,
1169 &db->queries, &db->queries_num);
1170 }
1172 if (db->queries_num > 0) {
1173 db->q_prep_areas = (udb_query_preparation_area_t **)calloc(
1174 db->queries_num, sizeof(*db->q_prep_areas));
1176 if (db->q_prep_areas == NULL) {
1177 log_err("Out of memory.");
1178 c_psql_database_delete(db);
1179 return -1;
1180 }
1181 }
1183 for (int i = 0; (size_t)i < db->queries_num; ++i) {
1184 c_psql_user_data_t *data;
1185 data = udb_query_get_user_data(db->queries[i]);
1186 if ((data != NULL) && (data->params_num > db->max_params_num))
1187 db->max_params_num = data->params_num;
1189 db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
1191 if (db->q_prep_areas[i] == NULL) {
1192 log_err("Out of memory.");
1193 c_psql_database_delete(db);
1194 return -1;
1195 }
1196 }
1198 ssnprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->instance);
1200 user_data_t ud = {.data = db, .free_func = c_psql_database_delete};
1202 if (db->queries_num > 0) {
1203 ++db->ref_cnt;
1204 plugin_register_complex_read("postgresql", cb_name, c_psql_read,
1205 /* interval = */ db->interval, &ud);
1206 }
1207 if (db->writers_num > 0) {
1208 ++db->ref_cnt;
1209 plugin_register_write(cb_name, c_psql_write, &ud);
1211 if (!have_flush) {
1212 /* flush all */
1213 plugin_register_flush("postgresql", c_psql_flush, /* user data = */ NULL);
1214 have_flush = 1;
1215 }
1217 /* flush this connection only */
1218 ++db->ref_cnt;
1219 plugin_register_flush(cb_name, c_psql_flush, &ud);
1220 } else if (db->commit_interval > 0) {
1221 log_warn("Database '%s': You do not have any writers assigned to "
1222 "this database connection. Setting 'CommitInterval' does "
1223 "not have any effect.",
1224 db->database);
1225 }
1226 return 0;
1227 } /* c_psql_config_database */
1229 static int c_psql_config(oconfig_item_t *ci) {
1230 static int have_def_config = 0;
1232 if (0 == have_def_config) {
1233 oconfig_item_t *c;
1235 have_def_config = 1;
1237 c = oconfig_parse_file(C_PSQL_DEFAULT_CONF);
1238 if (NULL == c)
1239 log_err("Failed to read default config (" C_PSQL_DEFAULT_CONF ").");
1240 else
1241 c_psql_config(c);
1243 if (NULL == queries)
1244 log_err("Default config (" C_PSQL_DEFAULT_CONF ") did not define "
1245 "any queries - please check your installation.");
1246 }
1248 for (int i = 0; i < ci->children_num; ++i) {
1249 oconfig_item_t *c = ci->children + i;
1251 if (0 == strcasecmp(c->key, "Query"))
1252 udb_query_create(&queries, &queries_num, c,
1253 /* callback = */ config_query_callback);
1254 else if (0 == strcasecmp(c->key, "Writer"))
1255 c_psql_config_writer(c);
1256 else if (0 == strcasecmp(c->key, "Database"))
1257 c_psql_config_database(c);
1258 else
1259 log_warn("Ignoring unknown config key \"%s\".", c->key);
1260 }
1261 return 0;
1262 } /* c_psql_config */
1264 void module_register(void) {
1265 plugin_register_complex_config("postgresql", c_psql_config);
1266 plugin_register_shutdown("postgresql", c_psql_shutdown);
1267 } /* module_register */
1269 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */