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;
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");
172 if (PGRES_COMMAND_OK == PQresultStatus(r)) {
173 db->next_commit = cdtime() + db->commit_interval;
176 log_warn("Failed to initiate ('BEGIN') transaction: %s",
177 PQerrorMessage(db->conn));
183 static int c_psql_commit(c_psql_database_t *db) {
184 PGresult *r = PQexec(db->conn, "COMMIT");
189 if (PGRES_COMMAND_OK == PQresultStatus(r)) {
191 log_debug("Successfully committed transaction.");
194 log_warn("Failed to commit transaction: %s", PQerrorMessage(db->conn));
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));
206 log_err("Out of memory.");
210 tmp = realloc(databases, (databases_num + 1) * sizeof(*databases));
212 log_err("Out of memory.");
218 databases[databases_num] = db;
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;
237 pthread_mutex_init(&db->db_lock, /* attrs = */ NULL);
241 db->commit_interval = 0;
243 db->expire_delay = 0;
245 db->database = sstrdup(name);
251 db->instance = sstrdup(name);
255 db->krbsrvname = NULL;
261 } /* c_psql_database_new */
263 static void c_psql_database_delete(void *data) {
264 c_psql_database_t *db = data;
267 /* readers and writers may access this database */
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)
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);
291 pthread_mutex_unlock(&db->db_lock);
293 pthread_mutex_destroy(&db->db_lock);
305 sfree(db->krbsrvname);
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 */
314 } /* c_psql_database_delete */
316 static int c_psql_connect(c_psql_database_t *db) {
318 char *buf = conninfo;
319 int buf_len = sizeof(conninfo);
322 if ((!db) || (!db->database))
325 status = snprintf(buf, buf_len, "dbname = '%s'", db->database);
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);
342 } /* c_psql_connect */
344 static int c_psql_check_connection(c_psql_database_t *db) {
350 /* trigger c_release() */
351 if (0 == db->conn_complaint.interval)
352 db->conn_complaint.interval = 1;
357 if (CONNECTION_OK != PQstatus(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));
371 db->proto_version = PQprotocolVersion(db->conn);
374 db->server_version = PQserverVersion(db->conn);
376 if (c_would_release(&db->conn_complaint)) {
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.",
397 } /* c_psql_check_connection */
399 static PGresult *c_psql_exec_query_noparams(c_psql_database_t *db,
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];
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:
418 C_PSQL_IS_UNIX_DOMAIN_SOCKET(db->host) ? "localhost" : db->host;
420 case C_PSQL_PARAM_DB:
421 params[i] = db->database;
423 case C_PSQL_PARAM_USER:
424 params[i] = db->user;
426 case C_PSQL_PARAM_INTERVAL:
427 snprintf(interval, sizeof(interval), "%.3f",
428 (db->interval > 0) ? CDTIME_T_TO_DOUBLE(db->interval)
429 : plugin_get_interval());
430 params[i] = interval;
432 case C_PSQL_PARAM_INSTANCE:
433 params[i] = db->instance;
440 return PQexecParams(db->conn, udb_query_get_statement(q), data->params_num,
441 NULL, (const char *const *)params, NULL, NULL, 0);
442 } /* c_psql_exec_query_params */
444 /* db->db_lock must be locked when calling this function */
445 static int c_psql_exec_query(c_psql_database_t *db, udb_query_t *q,
446 udb_query_preparation_area_t *prep_area) {
449 c_psql_user_data_t *data;
454 char **column_values;
460 /* The user data may hold parameter information, but may be NULL. */
461 data = udb_query_get_user_data(q);
463 /* Versions up to `3' don't know how to handle parameters. */
464 if (3 <= db->proto_version)
465 res = c_psql_exec_query_params(db, q, data);
466 else if ((NULL == data) || (0 == data->params_num))
467 res = c_psql_exec_query_noparams(db, q);
469 log_err("Connection to database \"%s\" (%s) does not support "
470 "parameters (protocol version %d) - "
471 "cannot execute query \"%s\".",
472 db->database, db->instance, db->proto_version,
473 udb_query_get_name(q));
477 /* give c_psql_write() a chance to acquire the lock if called recursively
478 * through dispatch_values(); this will happen if, both, queries and
479 * writers are configured for a single connection */
480 pthread_mutex_unlock(&db->db_lock);
483 column_values = NULL;
485 if (PGRES_TUPLES_OK != PQresultStatus(res)) {
486 pthread_mutex_lock(&db->db_lock);
488 if ((CONNECTION_OK != PQstatus(db->conn)) &&
489 (0 == c_psql_check_connection(db))) {
491 return c_psql_exec_query(db, q, prep_area);
494 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
495 log_info("SQL query was: %s", udb_query_get_statement(q));
500 #define BAIL_OUT(status) \
501 sfree(column_names); \
502 sfree(column_values); \
504 pthread_mutex_lock(&db->db_lock); \
507 rows_num = PQntuples(res);
512 column_num = PQnfields(res);
513 column_names = (char **)calloc(column_num, sizeof(char *));
514 if (NULL == column_names) {
515 log_err("calloc failed.");
519 column_values = (char **)calloc(column_num, sizeof(char *));
520 if (NULL == column_values) {
521 log_err("calloc failed.");
525 for (int col = 0; col < column_num; ++col) {
526 /* Pointers returned by `PQfname' are freed by `PQclear' via
528 column_names[col] = PQfname(res, col);
529 if (NULL == column_names[col]) {
530 log_err("Failed to resolve name of column %i.", col);
535 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET(db->host) ||
536 (0 == strcmp(db->host, "127.0.0.1")) ||
537 (0 == strcmp(db->host, "localhost")))
543 udb_query_prepare_result(q, prep_area, host, "postgresql", db->instance,
544 column_names, (size_t)column_num, db->interval);
546 log_err("udb_query_prepare_result failed with status %i.", status);
550 for (int row = 0; row < rows_num; ++row) {
552 for (col = 0; col < column_num; ++col) {
553 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
555 column_values[col] = PQgetvalue(res, row, col);
556 if (NULL == column_values[col]) {
557 log_err("Failed to get value at (row = %i, col = %i).", row, col);
562 /* check for an error */
563 if (col < column_num)
566 status = udb_query_handle_result(q, prep_area, column_values);
568 log_err("udb_query_handle_result failed with status %i.", status);
570 } /* for (row = 0; row < rows_num; ++row) */
572 udb_query_finish_result(q, prep_area);
576 } /* c_psql_exec_query */
578 static int c_psql_read(user_data_t *ud) {
579 c_psql_database_t *db;
583 if ((ud == NULL) || (ud->data == NULL)) {
584 log_err("c_psql_read: Invalid user data.");
590 assert(NULL != db->database);
591 assert(NULL != db->instance);
592 assert(NULL != db->queries);
594 pthread_mutex_lock(&db->db_lock);
596 if (0 != c_psql_check_connection(db)) {
597 pthread_mutex_unlock(&db->db_lock);
601 for (size_t i = 0; i < db->queries_num; ++i) {
602 udb_query_preparation_area_t *prep_area;
605 prep_area = db->q_prep_areas[i];
608 if ((0 != db->server_version) &&
609 (udb_query_check_version(q, db->server_version) <= 0))
612 if (0 == c_psql_exec_query(db, q, prep_area))
616 pthread_mutex_unlock(&db->db_lock);
623 static char *values_name_to_sqlarray(const data_set_t *ds, char *string,
629 str_len = string_len;
631 for (size_t i = 0; i < ds->ds_num; ++i) {
632 int status = snprintf(str_ptr, str_len, ",'%s'", ds->ds[i].name);
636 else if ((size_t)status >= str_len) {
641 str_len -= (size_t)status;
646 log_err("c_psql_write: Failed to stringify value names");
650 /* overwrite the first comma */
656 } /* values_name_to_sqlarray */
658 static char *values_type_to_sqlarray(const data_set_t *ds, char *string,
659 size_t string_len, _Bool store_rates) {
664 str_len = string_len;
666 for (size_t i = 0; i < ds->ds_num; ++i) {
670 status = snprintf(str_ptr, str_len, ",'gauge'");
672 status = snprintf(str_ptr, str_len, ",'%s'",
673 DS_TYPE_TO_STRING(ds->ds[i].type));
678 } else if ((size_t)status >= str_len) {
683 str_len -= (size_t)status;
688 log_err("c_psql_write: Failed to stringify value types");
692 /* overwrite the first comma */
698 } /* values_type_to_sqlarray */
700 static char *values_to_sqlarray(const data_set_t *ds, const value_list_t *vl,
701 char *string, size_t string_len,
706 gauge_t *rates = NULL;
709 str_len = string_len;
711 for (size_t i = 0; i < vl->values_len; ++i) {
714 if ((ds->ds[i].type != DS_TYPE_GAUGE) &&
715 (ds->ds[i].type != DS_TYPE_COUNTER) &&
716 (ds->ds[i].type != DS_TYPE_DERIVE) &&
717 (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
718 log_err("c_psql_write: Unknown data source type: %i", ds->ds[i].type);
723 if (ds->ds[i].type == DS_TYPE_GAUGE)
725 snprintf(str_ptr, str_len, "," GAUGE_FORMAT, vl->values[i].gauge);
726 else if (store_rates) {
728 rates = uc_get_rate(ds, vl);
731 log_err("c_psql_write: Failed to determine rate");
735 status = snprintf(str_ptr, str_len, ",%lf", rates[i]);
736 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
737 status = snprintf(str_ptr, str_len, ",%llu", vl->values[i].counter);
738 else if (ds->ds[i].type == DS_TYPE_DERIVE)
739 status = snprintf(str_ptr, str_len, ",%" PRIi64, vl->values[i].derive);
740 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
741 status = snprintf(str_ptr, str_len, ",%" PRIu64, vl->values[i].absolute);
746 } else if ((size_t)status >= str_len) {
751 str_len -= (size_t)status;
758 log_err("c_psql_write: Failed to stringify value list");
762 /* overwrite the first comma */
768 } /* values_to_sqlarray */
770 static int c_psql_write(const data_set_t *ds, const value_list_t *vl,
772 c_psql_database_t *db;
774 char time_str[RFC3339NANO_SIZE];
775 char values_name_str[1024];
776 char values_type_str[1024];
777 char values_str[1024];
779 const char *params[9];
783 if ((ud == NULL) || (ud->data == NULL)) {
784 log_err("c_psql_write: Invalid user data.");
789 assert(db->database != NULL);
790 assert(db->writers != NULL);
792 if (rfc3339nano_local(time_str, sizeof(time_str), vl->time) != 0) {
793 log_err("c_psql_write: Failed to convert time to RFC 3339 format");
797 if (values_name_to_sqlarray(ds, values_name_str, sizeof(values_name_str)) ==
801 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
803 params[0] = time_str;
804 params[1] = vl->host;
805 params[2] = vl->plugin;
806 params[3] = VALUE_OR_NULL(vl->plugin_instance);
807 params[4] = vl->type;
808 params[5] = VALUE_OR_NULL(vl->type_instance);
809 params[6] = values_name_str;
813 if (db->expire_delay > 0 &&
814 vl->time < (cdtime() - vl->interval - db->expire_delay)) {
815 log_info("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
816 params[0], params[1], params[2], params[3], params[4], params[5],
821 pthread_mutex_lock(&db->db_lock);
823 if (0 != c_psql_check_connection(db)) {
824 pthread_mutex_unlock(&db->db_lock);
828 if ((db->commit_interval > 0) && (db->next_commit == 0))
831 for (size_t i = 0; i < db->writers_num; ++i) {
832 c_psql_writer_t *writer;
835 writer = db->writers[i];
837 if (values_type_to_sqlarray(ds, values_type_str, sizeof(values_type_str),
838 writer->store_rates) == NULL) {
839 pthread_mutex_unlock(&db->db_lock);
843 if (values_to_sqlarray(ds, vl, values_str, sizeof(values_str),
844 writer->store_rates) == NULL) {
845 pthread_mutex_unlock(&db->db_lock);
849 params[7] = values_type_str;
850 params[8] = values_str;
852 res = PQexecParams(db->conn, writer->statement, STATIC_ARRAY_SIZE(params),
853 NULL, (const char *const *)params, NULL, NULL,
854 /* return text data */ 0);
856 if ((PGRES_COMMAND_OK != PQresultStatus(res)) &&
857 (PGRES_TUPLES_OK != PQresultStatus(res))) {
860 if ((CONNECTION_OK != PQstatus(db->conn)) &&
861 (0 == c_psql_check_connection(db))) {
864 db->conn, writer->statement, STATIC_ARRAY_SIZE(params), NULL,
865 (const char *const *)params, NULL, NULL, /* return text data */ 0);
867 if ((PGRES_COMMAND_OK == PQresultStatus(res)) ||
868 (PGRES_TUPLES_OK == PQresultStatus(res))) {
875 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
876 log_info("SQL query was: '%s', "
877 "params: %s, %s, %s, %s, %s, %s, %s, %s",
878 writer->statement, params[0], params[1], params[2], params[3],
879 params[4], params[5], params[6], params[7]);
881 /* this will abort any current transaction -> restart */
882 if (db->next_commit > 0)
885 pthread_mutex_unlock(&db->db_lock);
893 if ((db->next_commit > 0) && (cdtime() > db->next_commit))
896 pthread_mutex_unlock(&db->db_lock);
903 /* We cannot flush single identifiers as all we do is to commit the currently
904 * running transaction, thus making sure that all written data is actually
905 * visible to everybody. */
906 static int c_psql_flush(cdtime_t timeout,
907 __attribute__((unused)) const char *ident,
909 c_psql_database_t **dbs = databases;
910 size_t dbs_num = databases_num;
912 if ((ud != NULL) && (ud->data != NULL)) {
913 dbs = (void *)&ud->data;
917 for (size_t i = 0; i < dbs_num; ++i) {
918 c_psql_database_t *db = dbs[i];
920 /* don't commit if the timeout is larger than the regular commit
921 * interval as in that case all requested data has already been
923 if ((db->next_commit > 0) && (db->commit_interval > timeout))
929 static int c_psql_shutdown(void) {
932 plugin_unregister_read_group("postgresql");
934 for (size_t i = 0; i < databases_num; ++i) {
935 c_psql_database_t *db = databases[i];
937 if (db->writers_num > 0) {
938 char cb_name[DATA_MAX_NAME_LEN];
939 snprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->database);
942 plugin_unregister_flush("postgresql");
946 plugin_unregister_flush(cb_name);
947 plugin_unregister_write(cb_name);
953 udb_query_free(queries, queries_num);
966 } /* c_psql_shutdown */
968 static int config_query_param_add(udb_query_t *q, oconfig_item_t *ci) {
969 c_psql_user_data_t *data;
970 const char *param_str;
974 data = udb_query_get_user_data(q);
976 data = calloc(1, sizeof(*data));
978 log_err("Out of memory.");
982 data->params_num = 0;
984 udb_query_set_user_data(q, data);
987 tmp = realloc(data->params, (data->params_num + 1) * sizeof(*data->params));
989 log_err("Out of memory.");
994 param_str = ci->values[0].value.string;
995 if (0 == strcasecmp(param_str, "hostname"))
996 data->params[data->params_num] = C_PSQL_PARAM_HOST;
997 else if (0 == strcasecmp(param_str, "database"))
998 data->params[data->params_num] = C_PSQL_PARAM_DB;
999 else if (0 == strcasecmp(param_str, "username"))
1000 data->params[data->params_num] = C_PSQL_PARAM_USER;
1001 else if (0 == strcasecmp(param_str, "interval"))
1002 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1003 else if (0 == strcasecmp(param_str, "instance"))
1004 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1006 log_err("Invalid parameter \"%s\".", param_str);
1012 } /* config_query_param_add */
1014 static int config_query_callback(udb_query_t *q, oconfig_item_t *ci) {
1015 if (0 == strcasecmp("Param", ci->key))
1016 return config_query_param_add(q, ci);
1018 log_err("Option not allowed within a Query block: `%s'", ci->key);
1021 } /* config_query_callback */
1023 static int config_add_writer(oconfig_item_t *ci, c_psql_writer_t *src_writers,
1024 size_t src_writers_num,
1025 c_psql_writer_t ***dst_writers,
1026 size_t *dst_writers_num) {
1031 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1034 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1035 log_err("`Writer' expects a single string argument.");
1039 name = ci->values[0].value.string;
1041 for (i = 0; i < src_writers_num; ++i) {
1042 c_psql_writer_t **tmp;
1044 if (strcasecmp(name, src_writers[i].name) != 0)
1047 tmp = realloc(*dst_writers, sizeof(**dst_writers) * (*dst_writers_num + 1));
1049 log_err("Out of memory.");
1053 tmp[*dst_writers_num] = src_writers + i;
1056 ++(*dst_writers_num);
1060 if (i >= src_writers_num) {
1061 log_err("No such writer: `%s'", name);
1066 } /* config_add_writer */
1068 static int c_psql_config_writer(oconfig_item_t *ci) {
1069 c_psql_writer_t *writer;
1070 c_psql_writer_t *tmp;
1074 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1075 log_err("<Writer> expects a single string argument.");
1079 tmp = realloc(writers, sizeof(*writers) * (writers_num + 1));
1081 log_err("Out of memory.");
1086 writer = writers + writers_num;
1087 memset(writer, 0, sizeof(*writer));
1089 writer->name = sstrdup(ci->values[0].value.string);
1090 writer->statement = NULL;
1091 writer->store_rates = 1;
1093 for (int i = 0; i < ci->children_num; ++i) {
1094 oconfig_item_t *c = ci->children + i;
1096 if (strcasecmp("Statement", c->key) == 0)
1097 status = cf_util_get_string(c, &writer->statement);
1098 else if (strcasecmp("StoreRates", c->key) == 0)
1099 status = cf_util_get_boolean(c, &writer->store_rates);
1101 log_warn("Ignoring unknown config key \"%s\".", c->key);
1105 sfree(writer->statement);
1106 sfree(writer->name);
1112 } /* c_psql_config_writer */
1114 static int c_psql_config_database(oconfig_item_t *ci) {
1115 c_psql_database_t *db;
1117 char cb_name[DATA_MAX_NAME_LEN];
1118 static _Bool have_flush = 0;
1120 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1121 log_err("<Database> expects a single string argument.");
1125 db = c_psql_database_new(ci->values[0].value.string);
1129 for (int i = 0; i < ci->children_num; ++i) {
1130 oconfig_item_t *c = ci->children + i;
1132 if (0 == strcasecmp(c->key, "Host"))
1133 cf_util_get_string(c, &db->host);
1134 else if (0 == strcasecmp(c->key, "Port"))
1135 cf_util_get_service(c, &db->port);
1136 else if (0 == strcasecmp(c->key, "User"))
1137 cf_util_get_string(c, &db->user);
1138 else if (0 == strcasecmp(c->key, "Password"))
1139 cf_util_get_string(c, &db->password);
1140 else if (0 == strcasecmp(c->key, "Instance"))
1141 cf_util_get_string(c, &db->instance);
1142 else if (0 == strcasecmp(c->key, "SSLMode"))
1143 cf_util_get_string(c, &db->sslmode);
1144 else if (0 == strcasecmp(c->key, "KRBSrvName"))
1145 cf_util_get_string(c, &db->krbsrvname);
1146 else if (0 == strcasecmp(c->key, "Service"))
1147 cf_util_get_string(c, &db->service);
1148 else if (0 == strcasecmp(c->key, "Query"))
1149 udb_query_pick_from_list(c, queries, queries_num, &db->queries,
1151 else if (0 == strcasecmp(c->key, "Writer"))
1152 config_add_writer(c, writers, writers_num, &db->writers,
1154 else if (0 == strcasecmp(c->key, "Interval"))
1155 cf_util_get_cdtime(c, &db->interval);
1156 else if (strcasecmp("CommitInterval", c->key) == 0)
1157 cf_util_get_cdtime(c, &db->commit_interval);
1158 else if (strcasecmp("ExpireDelay", c->key) == 0)
1159 cf_util_get_cdtime(c, &db->expire_delay);
1161 log_warn("Ignoring unknown config key \"%s\".", c->key);
1164 /* If no `Query' options were given, add the default queries.. */
1165 if ((db->queries_num == 0) && (db->writers_num == 0)) {
1166 for (int i = 0; i < def_queries_num; i++)
1167 udb_query_pick_from_list_by_name(def_queries[i], queries, queries_num,
1168 &db->queries, &db->queries_num);
1171 if (db->queries_num > 0) {
1172 db->q_prep_areas = (udb_query_preparation_area_t **)calloc(
1173 db->queries_num, sizeof(*db->q_prep_areas));
1175 if (db->q_prep_areas == NULL) {
1176 log_err("Out of memory.");
1177 c_psql_database_delete(db);
1182 for (int i = 0; (size_t)i < db->queries_num; ++i) {
1183 c_psql_user_data_t *data;
1184 data = udb_query_get_user_data(db->queries[i]);
1185 if ((data != NULL) && (data->params_num > db->max_params_num))
1186 db->max_params_num = data->params_num;
1188 db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
1190 if (db->q_prep_areas[i] == NULL) {
1191 log_err("Out of memory.");
1192 c_psql_database_delete(db);
1197 snprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->instance);
1199 user_data_t ud = {.data = db, .free_func = c_psql_database_delete};
1201 if (db->queries_num > 0) {
1203 plugin_register_complex_read("postgresql", cb_name, c_psql_read,
1204 /* interval = */ db->interval, &ud);
1206 if (db->writers_num > 0) {
1208 plugin_register_write(cb_name, c_psql_write, &ud);
1212 plugin_register_flush("postgresql", c_psql_flush, /* user data = */ NULL);
1216 /* flush this connection only */
1218 plugin_register_flush(cb_name, c_psql_flush, &ud);
1219 } else if (db->commit_interval > 0) {
1220 log_warn("Database '%s': You do not have any writers assigned to "
1221 "this database connection. Setting 'CommitInterval' does "
1222 "not have any effect.",
1226 } /* c_psql_config_database */
1228 static int c_psql_config(oconfig_item_t *ci) {
1229 static int have_def_config = 0;
1231 if (0 == have_def_config) {
1234 have_def_config = 1;
1236 c = oconfig_parse_file(C_PSQL_DEFAULT_CONF);
1238 log_err("Failed to read default config (" C_PSQL_DEFAULT_CONF ").");
1242 if (NULL == queries)
1243 log_err("Default config (" C_PSQL_DEFAULT_CONF ") did not define "
1244 "any queries - please check your installation.");
1247 for (int i = 0; i < ci->children_num; ++i) {
1248 oconfig_item_t *c = ci->children + i;
1250 if (0 == strcasecmp(c->key, "Query"))
1251 udb_query_create(&queries, &queries_num, c,
1252 /* callback = */ config_query_callback);
1253 else if (0 == strcasecmp(c->key, "Writer"))
1254 c_psql_config_writer(c);
1255 else if (0 == strcasecmp(c->key, "Database"))
1256 c_psql_config_database(c);
1258 log_warn("Ignoring unknown config key \"%s\".", c->key);
1261 } /* c_psql_config */
1263 void module_register(void) {
1264 plugin_register_complex_config("postgresql", c_psql_config);
1265 plugin_register_shutdown("postgresql", c_psql_shutdown);
1266 } /* module_register */