2 * collectd - src/postgresql.c
3 * Copyright (C) 2008-2012 Sebastian Harl
4 * Copyright (C) 2009 Florian Forster
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 * Sebastian Harl <sh at tokkee.org>
26 * Florian Forster <octo at collectd.org>
30 * This module collects PostgreSQL database statistics.
39 #include "utils_cache.h"
40 #include "utils_complain.h"
41 #include "utils_db_query.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"
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
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); \
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
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
89 C_PSQL_PARAM_HOST = 1,
92 C_PSQL_PARAM_INTERVAL,
93 C_PSQL_PARAM_INSTANCE,
96 /* Parameter configuration. Stored as `user data' in the query objects. */
98 c_psql_param_t *params;
100 } c_psql_user_data_t;
110 c_complain_t conn_complaint;
117 /* user configuration */
118 udb_query_preparation_area_t **q_prep_areas;
119 udb_query_t **queries;
122 c_psql_writer_t **writers;
125 /* make sure we don't access the database object in parallel */
126 pthread_mutex_t db_lock;
130 /* writer "caching" settings */
131 cdtime_t commit_interval;
132 cdtime_t next_commit;
133 cdtime_t expire_delay;
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);
158 static c_psql_database_t **databases = NULL;
159 static size_t databases_num = 0;
161 static udb_query_t **queries = NULL;
162 static size_t queries_num = 0;
164 static c_psql_writer_t *writers = NULL;
165 static size_t writers_num = 0;
167 static int c_psql_begin(c_psql_database_t *db) {
168 PGresult *r = PQexec(db->conn, "BEGIN");
173 if (PGRES_COMMAND_OK == PQresultStatus(r)) {
174 db->next_commit = cdtime() + db->commit_interval;
177 log_warn("Failed to initiate ('BEGIN') transaction: %s",
178 PQerrorMessage(db->conn));
184 static int c_psql_commit(c_psql_database_t *db) {
185 PGresult *r = PQexec(db->conn, "COMMIT");
190 if (PGRES_COMMAND_OK == PQresultStatus(r)) {
192 log_debug("Successfully committed transaction.");
195 log_warn("Failed to commit transaction: %s", PQerrorMessage(db->conn));
199 } /* c_psql_commit */
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;
205 db = malloc(sizeof(*db));
207 log_err("Out of memory.");
211 tmp = realloc(databases, (databases_num + 1) * sizeof(*databases));
213 log_err("Out of memory.");
219 databases[databases_num] = db;
224 C_COMPLAIN_INIT(&db->conn_complaint);
226 db->proto_version = 0;
227 db->server_version = 0;
229 db->max_params_num = 0;
231 db->q_prep_areas = NULL;
238 pthread_mutex_init(&db->db_lock, /* attrs = */ NULL);
242 db->commit_interval = 0;
244 db->expire_delay = 0;
246 db->database = sstrdup(name);
252 db->instance = sstrdup(name);
254 db->plugin_name = NULL;
258 db->krbsrvname = NULL;
264 } /* c_psql_database_new */
266 static void c_psql_database_delete(void *data) {
267 c_psql_database_t *db = data;
270 /* readers and writers may access this database */
274 /* wait for the lock to be released by the last writer */
275 pthread_mutex_lock(&db->db_lock);
277 if (db->next_commit > 0)
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);
294 pthread_mutex_unlock(&db->db_lock);
296 pthread_mutex_destroy(&db->db_lock);
306 sfree(db->plugin_name);
310 sfree(db->krbsrvname);
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 */
319 } /* c_psql_database_delete */
321 static int c_psql_connect(c_psql_database_t *db) {
323 char *buf = conninfo;
324 int buf_len = sizeof(conninfo);
327 if ((!db) || (!db->database))
330 status = snprintf(buf, buf_len, "dbname = '%s'", db->database);
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");
345 db->conn = PQconnectdb(conninfo);
346 db->proto_version = PQprotocolVersion(db->conn);
348 } /* c_psql_connect */
350 static int c_psql_check_connection(c_psql_database_t *db) {
356 /* trigger c_release() */
357 if (0 == db->conn_complaint.interval)
358 db->conn_complaint.interval = 1;
363 if (CONNECTION_OK != PQstatus(db->conn)) {
366 /* trigger c_release() */
367 if (0 == db->conn_complaint.interval)
368 db->conn_complaint.interval = 1;
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));
377 db->proto_version = PQprotocolVersion(db->conn);
380 db->server_version = PQserverVersion(db->conn);
382 if (c_would_release(&db->conn_complaint)) {
386 server_host = PQhost(db->conn);
387 server_version = PQserverVersion(db->conn);
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));
398 if (3 > db->proto_version)
399 log_warn("Protocol version %d does not support parameters.",
403 } /* c_psql_check_connection */
405 static PGresult *c_psql_exec_query_noparams(c_psql_database_t *db,
407 return PQexec(db->conn, udb_query_get_statement(q));
408 } /* c_psql_exec_query_noparams */
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];
415 if ((data == NULL) || (data->params_num == 0))
416 return c_psql_exec_query_noparams(db, q);
418 assert(db->max_params_num >= data->params_num);
420 for (int i = 0; i < data->params_num; ++i) {
421 switch (data->params[i]) {
422 case C_PSQL_PARAM_HOST:
424 C_PSQL_IS_UNIX_DOMAIN_SOCKET(db->host) ? "localhost" : db->host;
426 case C_PSQL_PARAM_DB:
427 params[i] = db->database;
429 case C_PSQL_PARAM_USER:
430 params[i] = db->user;
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;
438 case C_PSQL_PARAM_INSTANCE:
439 params[i] = db->instance;
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 */
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) {
455 c_psql_user_data_t *data;
460 char **column_values;
466 /* The user data may hold parameter information, but may be NULL. */
467 data = udb_query_get_user_data(q);
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);
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));
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);
489 column_values = NULL;
491 if (PGRES_TUPLES_OK != PQresultStatus(res)) {
492 pthread_mutex_lock(&db->db_lock);
494 if ((CONNECTION_OK != PQstatus(db->conn)) &&
495 (0 == c_psql_check_connection(db))) {
497 return c_psql_exec_query(db, q, prep_area);
500 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
501 log_info("SQL query was: %s", udb_query_get_statement(q));
506 #define BAIL_OUT(status) \
507 sfree(column_names); \
508 sfree(column_values); \
510 pthread_mutex_lock(&db->db_lock); \
513 rows_num = PQntuples(res);
518 column_num = PQnfields(res);
519 column_names = (char **)calloc(column_num, sizeof(char *));
520 if (NULL == column_names) {
521 log_err("calloc failed.");
525 column_values = (char **)calloc(column_num, sizeof(char *));
526 if (NULL == column_values) {
527 log_err("calloc failed.");
531 for (int col = 0; col < column_num; ++col) {
532 /* Pointers returned by `PQfname' are freed by `PQclear' via
534 column_names[col] = PQfname(res, col);
535 if (NULL == column_names[col]) {
536 log_err("Failed to resolve name of column %i.", col);
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")))
548 status = udb_query_prepare_result(
550 (db->plugin_name != NULL) ? db->plugin_name : "postgresql",
551 db->instance, column_names, (size_t)column_num, db->interval);
554 log_err("udb_query_prepare_result failed with status %i.", status);
558 for (int row = 0; row < rows_num; ++row) {
560 for (col = 0; col < column_num; ++col) {
561 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
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);
570 /* check for an error */
571 if (col < column_num)
574 status = udb_query_handle_result(q, prep_area, column_values);
576 log_err("udb_query_handle_result failed with status %i.", status);
578 } /* for (row = 0; row < rows_num; ++row) */
580 udb_query_finish_result(q, prep_area);
584 } /* c_psql_exec_query */
586 static int c_psql_read(user_data_t *ud) {
587 c_psql_database_t *db;
591 if ((ud == NULL) || (ud->data == NULL)) {
592 log_err("c_psql_read: Invalid user data.");
598 assert(NULL != db->database);
599 assert(NULL != db->instance);
600 assert(NULL != db->queries);
602 pthread_mutex_lock(&db->db_lock);
604 if (0 != c_psql_check_connection(db)) {
605 pthread_mutex_unlock(&db->db_lock);
609 for (size_t i = 0; i < db->queries_num; ++i) {
610 udb_query_preparation_area_t *prep_area;
613 prep_area = db->q_prep_areas[i];
616 if ((0 != db->server_version) &&
617 (udb_query_check_version(q, db->server_version) <= 0))
620 if (0 == c_psql_exec_query(db, q, prep_area))
624 pthread_mutex_unlock(&db->db_lock);
631 static char *values_name_to_sqlarray(const data_set_t *ds, char *string,
637 str_len = string_len;
639 for (size_t i = 0; i < ds->ds_num; ++i) {
640 int status = snprintf(str_ptr, str_len, ",'%s'", ds->ds[i].name);
644 else if ((size_t)status >= str_len) {
649 str_len -= (size_t)status;
654 log_err("c_psql_write: Failed to stringify value names");
658 /* overwrite the first comma */
664 } /* values_name_to_sqlarray */
666 static char *values_type_to_sqlarray(const data_set_t *ds, char *string,
667 size_t string_len, _Bool store_rates) {
672 str_len = string_len;
674 for (size_t i = 0; i < ds->ds_num; ++i) {
678 status = snprintf(str_ptr, str_len, ",'gauge'");
680 status = snprintf(str_ptr, str_len, ",'%s'",
681 DS_TYPE_TO_STRING(ds->ds[i].type));
686 } else if ((size_t)status >= str_len) {
691 str_len -= (size_t)status;
696 log_err("c_psql_write: Failed to stringify value types");
700 /* overwrite the first comma */
706 } /* values_type_to_sqlarray */
708 static char *values_to_sqlarray(const data_set_t *ds, const value_list_t *vl,
709 char *string, size_t string_len,
714 gauge_t *rates = NULL;
717 str_len = string_len;
719 for (size_t i = 0; i < vl->values_len; ++i) {
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);
731 if (ds->ds[i].type == DS_TYPE_GAUGE)
733 snprintf(str_ptr, str_len, "," GAUGE_FORMAT, vl->values[i].gauge);
734 else if (store_rates) {
736 rates = uc_get_rate(ds, vl);
739 log_err("c_psql_write: Failed to determine rate");
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, ",%llu", vl->values[i].counter);
746 else if (ds->ds[i].type == DS_TYPE_DERIVE)
747 status = snprintf(str_ptr, str_len, ",%" PRIi64, vl->values[i].derive);
748 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
749 status = snprintf(str_ptr, str_len, ",%" PRIu64, vl->values[i].absolute);
754 } else if ((size_t)status >= str_len) {
759 str_len -= (size_t)status;
766 log_err("c_psql_write: Failed to stringify value list");
770 /* overwrite the first comma */
776 } /* values_to_sqlarray */
778 static int c_psql_write(const data_set_t *ds, const value_list_t *vl,
780 c_psql_database_t *db;
782 char time_str[RFC3339NANO_SIZE];
783 char values_name_str[1024];
784 char values_type_str[1024];
785 char values_str[1024];
787 const char *params[9];
791 if ((ud == NULL) || (ud->data == NULL)) {
792 log_err("c_psql_write: Invalid user data.");
797 assert(db->database != NULL);
798 assert(db->writers != NULL);
800 if (rfc3339nano_local(time_str, sizeof(time_str), vl->time) != 0) {
801 log_err("c_psql_write: Failed to convert time to RFC 3339 format");
805 if (values_name_to_sqlarray(ds, values_name_str, sizeof(values_name_str)) ==
809 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
811 params[0] = time_str;
812 params[1] = vl->host;
813 params[2] = vl->plugin;
814 params[3] = VALUE_OR_NULL(vl->plugin_instance);
815 params[4] = vl->type;
816 params[5] = VALUE_OR_NULL(vl->type_instance);
817 params[6] = values_name_str;
821 if (db->expire_delay > 0 &&
822 vl->time < (cdtime() - vl->interval - db->expire_delay)) {
823 log_info("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
824 params[0], params[1], params[2], params[3], params[4], params[5],
829 pthread_mutex_lock(&db->db_lock);
831 if (0 != c_psql_check_connection(db)) {
832 pthread_mutex_unlock(&db->db_lock);
836 if ((db->commit_interval > 0) && (db->next_commit == 0))
839 for (size_t i = 0; i < db->writers_num; ++i) {
840 c_psql_writer_t *writer;
843 writer = db->writers[i];
845 if (values_type_to_sqlarray(ds, values_type_str, sizeof(values_type_str),
846 writer->store_rates) == NULL) {
847 pthread_mutex_unlock(&db->db_lock);
851 if (values_to_sqlarray(ds, vl, values_str, sizeof(values_str),
852 writer->store_rates) == NULL) {
853 pthread_mutex_unlock(&db->db_lock);
857 params[7] = values_type_str;
858 params[8] = values_str;
860 res = PQexecParams(db->conn, writer->statement, STATIC_ARRAY_SIZE(params),
861 NULL, (const char *const *)params, NULL, NULL,
862 /* return text data */ 0);
864 if ((PGRES_COMMAND_OK != PQresultStatus(res)) &&
865 (PGRES_TUPLES_OK != PQresultStatus(res))) {
868 if ((CONNECTION_OK != PQstatus(db->conn)) &&
869 (0 == c_psql_check_connection(db))) {
872 db->conn, writer->statement, STATIC_ARRAY_SIZE(params), NULL,
873 (const char *const *)params, NULL, NULL, /* return text data */ 0);
875 if ((PGRES_COMMAND_OK == PQresultStatus(res)) ||
876 (PGRES_TUPLES_OK == PQresultStatus(res))) {
883 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
884 log_info("SQL query was: '%s', "
885 "params: %s, %s, %s, %s, %s, %s, %s, %s",
886 writer->statement, params[0], params[1], params[2], params[3],
887 params[4], params[5], params[6], params[7]);
889 /* this will abort any current transaction -> restart */
890 if (db->next_commit > 0)
893 pthread_mutex_unlock(&db->db_lock);
901 if ((db->next_commit > 0) && (cdtime() > db->next_commit))
904 pthread_mutex_unlock(&db->db_lock);
911 /* We cannot flush single identifiers as all we do is to commit the currently
912 * running transaction, thus making sure that all written data is actually
913 * visible to everybody. */
914 static int c_psql_flush(cdtime_t timeout,
915 __attribute__((unused)) const char *ident,
917 c_psql_database_t **dbs = databases;
918 size_t dbs_num = databases_num;
920 if ((ud != NULL) && (ud->data != NULL)) {
921 dbs = (void *)&ud->data;
925 for (size_t i = 0; i < dbs_num; ++i) {
926 c_psql_database_t *db = dbs[i];
928 /* don't commit if the timeout is larger than the regular commit
929 * interval as in that case all requested data has already been
931 if ((db->next_commit > 0) && (db->commit_interval > timeout))
937 static int c_psql_shutdown(void) {
940 plugin_unregister_read_group("postgresql");
942 for (size_t i = 0; i < databases_num; ++i) {
943 c_psql_database_t *db = databases[i];
945 if (db->writers_num > 0) {
946 char cb_name[DATA_MAX_NAME_LEN];
947 snprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->database);
950 plugin_unregister_flush("postgresql");
954 plugin_unregister_flush(cb_name);
955 plugin_unregister_write(cb_name);
961 udb_query_free(queries, queries_num);
974 } /* c_psql_shutdown */
976 static int config_query_param_add(udb_query_t *q, oconfig_item_t *ci) {
977 c_psql_user_data_t *data;
978 const char *param_str;
982 data = udb_query_get_user_data(q);
984 data = calloc(1, sizeof(*data));
986 log_err("Out of memory.");
990 data->params_num = 0;
992 udb_query_set_user_data(q, data);
995 tmp = realloc(data->params, (data->params_num + 1) * sizeof(*data->params));
997 log_err("Out of memory.");
1002 param_str = ci->values[0].value.string;
1003 if (0 == strcasecmp(param_str, "hostname"))
1004 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1005 else if (0 == strcasecmp(param_str, "database"))
1006 data->params[data->params_num] = C_PSQL_PARAM_DB;
1007 else if (0 == strcasecmp(param_str, "username"))
1008 data->params[data->params_num] = C_PSQL_PARAM_USER;
1009 else if (0 == strcasecmp(param_str, "interval"))
1010 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1011 else if (0 == strcasecmp(param_str, "instance"))
1012 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1014 log_err("Invalid parameter \"%s\".", param_str);
1020 } /* config_query_param_add */
1022 static int config_query_callback(udb_query_t *q, oconfig_item_t *ci) {
1023 if (0 == strcasecmp("Param", ci->key))
1024 return config_query_param_add(q, ci);
1026 log_err("Option not allowed within a Query block: `%s'", ci->key);
1029 } /* config_query_callback */
1031 static int config_add_writer(oconfig_item_t *ci, c_psql_writer_t *src_writers,
1032 size_t src_writers_num,
1033 c_psql_writer_t ***dst_writers,
1034 size_t *dst_writers_num) {
1039 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1042 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1043 log_err("`Writer' expects a single string argument.");
1047 name = ci->values[0].value.string;
1049 for (i = 0; i < src_writers_num; ++i) {
1050 c_psql_writer_t **tmp;
1052 if (strcasecmp(name, src_writers[i].name) != 0)
1055 tmp = realloc(*dst_writers, sizeof(**dst_writers) * (*dst_writers_num + 1));
1057 log_err("Out of memory.");
1061 tmp[*dst_writers_num] = src_writers + i;
1064 ++(*dst_writers_num);
1068 if (i >= src_writers_num) {
1069 log_err("No such writer: `%s'", name);
1074 } /* config_add_writer */
1076 static int c_psql_config_writer(oconfig_item_t *ci) {
1077 c_psql_writer_t *writer;
1078 c_psql_writer_t *tmp;
1082 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1083 log_err("<Writer> expects a single string argument.");
1087 tmp = realloc(writers, sizeof(*writers) * (writers_num + 1));
1089 log_err("Out of memory.");
1094 writer = writers + writers_num;
1095 memset(writer, 0, sizeof(*writer));
1097 writer->name = sstrdup(ci->values[0].value.string);
1098 writer->statement = NULL;
1099 writer->store_rates = 1;
1101 for (int i = 0; i < ci->children_num; ++i) {
1102 oconfig_item_t *c = ci->children + i;
1104 if (strcasecmp("Statement", c->key) == 0)
1105 status = cf_util_get_string(c, &writer->statement);
1106 else if (strcasecmp("StoreRates", c->key) == 0)
1107 status = cf_util_get_boolean(c, &writer->store_rates);
1109 log_warn("Ignoring unknown config key \"%s\".", c->key);
1113 sfree(writer->statement);
1114 sfree(writer->name);
1120 } /* c_psql_config_writer */
1122 static int c_psql_config_database(oconfig_item_t *ci) {
1123 c_psql_database_t *db;
1125 char cb_name[DATA_MAX_NAME_LEN];
1126 static _Bool have_flush = 0;
1128 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1129 log_err("<Database> expects a single string argument.");
1133 db = c_psql_database_new(ci->values[0].value.string);
1137 for (int i = 0; i < ci->children_num; ++i) {
1138 oconfig_item_t *c = ci->children + i;
1140 if (0 == strcasecmp(c->key, "Host"))
1141 cf_util_get_string(c, &db->host);
1142 else if (0 == strcasecmp(c->key, "Port"))
1143 cf_util_get_service(c, &db->port);
1144 else if (0 == strcasecmp(c->key, "User"))
1145 cf_util_get_string(c, &db->user);
1146 else if (0 == strcasecmp(c->key, "Password"))
1147 cf_util_get_string(c, &db->password);
1148 else if (0 == strcasecmp(c->key, "Instance"))
1149 cf_util_get_string(c, &db->instance);
1150 else if (0 == strcasecmp (c->key, "Plugin"))
1151 cf_util_get_string (c, &db->plugin_name);
1152 else if (0 == strcasecmp(c->key, "SSLMode"))
1153 cf_util_get_string(c, &db->sslmode);
1154 else if (0 == strcasecmp(c->key, "KRBSrvName"))
1155 cf_util_get_string(c, &db->krbsrvname);
1156 else if (0 == strcasecmp(c->key, "Service"))
1157 cf_util_get_string(c, &db->service);
1158 else if (0 == strcasecmp(c->key, "Query"))
1159 udb_query_pick_from_list(c, queries, queries_num, &db->queries,
1161 else if (0 == strcasecmp(c->key, "Writer"))
1162 config_add_writer(c, writers, writers_num, &db->writers,
1164 else if (0 == strcasecmp(c->key, "Interval"))
1165 cf_util_get_cdtime(c, &db->interval);
1166 else if (strcasecmp("CommitInterval", c->key) == 0)
1167 cf_util_get_cdtime(c, &db->commit_interval);
1168 else if (strcasecmp("ExpireDelay", c->key) == 0)
1169 cf_util_get_cdtime(c, &db->expire_delay);
1171 log_warn("Ignoring unknown config key \"%s\".", c->key);
1174 /* If no `Query' options were given, add the default queries.. */
1175 if ((db->queries_num == 0) && (db->writers_num == 0)) {
1176 for (int i = 0; i < def_queries_num; i++)
1177 udb_query_pick_from_list_by_name(def_queries[i], queries, queries_num,
1178 &db->queries, &db->queries_num);
1181 if (db->queries_num > 0) {
1182 db->q_prep_areas = (udb_query_preparation_area_t **)calloc(
1183 db->queries_num, sizeof(*db->q_prep_areas));
1185 if (db->q_prep_areas == NULL) {
1186 log_err("Out of memory.");
1187 c_psql_database_delete(db);
1192 for (int i = 0; (size_t)i < db->queries_num; ++i) {
1193 c_psql_user_data_t *data;
1194 data = udb_query_get_user_data(db->queries[i]);
1195 if ((data != NULL) && (data->params_num > db->max_params_num))
1196 db->max_params_num = data->params_num;
1198 db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
1200 if (db->q_prep_areas[i] == NULL) {
1201 log_err("Out of memory.");
1202 c_psql_database_delete(db);
1207 snprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->instance);
1209 user_data_t ud = {.data = db, .free_func = c_psql_database_delete};
1211 if (db->queries_num > 0) {
1213 plugin_register_complex_read("postgresql", cb_name, c_psql_read,
1214 /* interval = */ db->interval, &ud);
1216 if (db->writers_num > 0) {
1218 plugin_register_write(cb_name, c_psql_write, &ud);
1222 plugin_register_flush("postgresql", c_psql_flush, /* user data = */ NULL);
1226 /* flush this connection only */
1228 plugin_register_flush(cb_name, c_psql_flush, &ud);
1229 } else if (db->commit_interval > 0) {
1230 log_warn("Database '%s': You do not have any writers assigned to "
1231 "this database connection. Setting 'CommitInterval' does "
1232 "not have any effect.",
1236 } /* c_psql_config_database */
1238 static int c_psql_config(oconfig_item_t *ci) {
1239 static int have_def_config = 0;
1241 if (0 == have_def_config) {
1244 have_def_config = 1;
1246 c = oconfig_parse_file(C_PSQL_DEFAULT_CONF);
1248 log_err("Failed to read default config (" C_PSQL_DEFAULT_CONF ").");
1252 if (NULL == queries)
1253 log_err("Default config (" C_PSQL_DEFAULT_CONF ") did not define "
1254 "any queries - please check your installation.");
1257 for (int i = 0; i < ci->children_num; ++i) {
1258 oconfig_item_t *c = ci->children + i;
1260 if (0 == strcasecmp(c->key, "Query"))
1261 udb_query_create(&queries, &queries_num, c,
1262 /* callback = */ config_query_callback);
1263 else if (0 == strcasecmp(c->key, "Writer"))
1264 c_psql_config_writer(c);
1265 else if (0 == strcasecmp(c->key, "Database"))
1266 c_psql_config_database(c);
1268 log_warn("Ignoring unknown config key \"%s\".", c->key);
1271 } /* c_psql_config */
1273 void module_register(void) {
1274 plugin_register_complex_config("postgresql", c_psql_config);
1275 plugin_register_shutdown("postgresql", c_psql_shutdown);
1276 } /* module_register */