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 = ssnprintf(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 = ssnprintf(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 ssnprintf(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,
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) {
450 c_psql_user_data_t *data;
455 char **column_values;
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);
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));
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);
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))) {
492 return c_psql_exec_query(db, q, prep_area);
495 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
496 log_info("SQL query was: %s", udb_query_get_statement(q));
501 #define BAIL_OUT(status) \
502 sfree(column_names); \
503 sfree(column_values); \
505 pthread_mutex_lock(&db->db_lock); \
508 rows_num = PQntuples(res);
513 column_num = PQnfields(res);
514 column_names = (char **)calloc(column_num, sizeof(char *));
515 if (NULL == column_names) {
516 log_err("calloc failed.");
520 column_values = (char **)calloc(column_num, sizeof(char *));
521 if (NULL == column_values) {
522 log_err("calloc failed.");
526 for (int col = 0; col < column_num; ++col) {
527 /* Pointers returned by `PQfname' are freed by `PQclear' via
529 column_names[col] = PQfname(res, col);
530 if (NULL == column_names[col]) {
531 log_err("Failed to resolve name of column %i.", col);
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")))
544 udb_query_prepare_result(q, prep_area, host, "postgresql", db->instance,
545 column_names, (size_t)column_num, db->interval);
547 log_err("udb_query_prepare_result failed with status %i.", status);
551 for (int row = 0; row < rows_num; ++row) {
553 for (col = 0; col < column_num; ++col) {
554 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
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);
563 /* check for an error */
564 if (col < column_num)
567 status = udb_query_handle_result(q, prep_area, column_values);
569 log_err("udb_query_handle_result failed with status %i.", status);
571 } /* for (row = 0; row < rows_num; ++row) */
573 udb_query_finish_result(q, prep_area);
577 } /* c_psql_exec_query */
579 static int c_psql_read(user_data_t *ud) {
580 c_psql_database_t *db;
584 if ((ud == NULL) || (ud->data == NULL)) {
585 log_err("c_psql_read: Invalid user 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);
602 for (size_t i = 0; i < db->queries_num; ++i) {
603 udb_query_preparation_area_t *prep_area;
606 prep_area = db->q_prep_areas[i];
609 if ((0 != db->server_version) &&
610 (udb_query_check_version(q, db->server_version) <= 0))
613 if (0 == c_psql_exec_query(db, q, prep_area))
617 pthread_mutex_unlock(&db->db_lock);
624 static char *values_name_to_sqlarray(const data_set_t *ds, char *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);
637 else if ((size_t)status >= str_len) {
642 str_len -= (size_t)status;
647 log_err("c_psql_write: Failed to stringify value names");
651 /* overwrite the first comma */
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) {
665 str_len = string_len;
667 for (size_t i = 0; i < ds->ds_num; ++i) {
671 status = ssnprintf(str_ptr, str_len, ",'gauge'");
673 status = ssnprintf(str_ptr, str_len, ",'%s'",
674 DS_TYPE_TO_STRING(ds->ds[i].type));
679 } else if ((size_t)status >= str_len) {
684 str_len -= (size_t)status;
689 log_err("c_psql_write: Failed to stringify value types");
693 /* overwrite the first comma */
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,
707 gauge_t *rates = NULL;
710 str_len = string_len;
712 for (size_t i = 0; i < vl->values_len; ++i) {
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);
724 if (ds->ds[i].type == DS_TYPE_GAUGE)
726 ssnprintf(str_ptr, str_len, "," GAUGE_FORMAT, vl->values[i].gauge);
727 else if (store_rates) {
729 rates = uc_get_rate(ds, vl);
732 log_err("c_psql_write: Failed to determine rate");
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);
747 } else if ((size_t)status >= str_len) {
752 str_len -= (size_t)status;
759 log_err("c_psql_write: Failed to stringify value list");
763 /* overwrite the first comma */
769 } /* values_to_sqlarray */
771 static int c_psql_write(const data_set_t *ds, const value_list_t *vl,
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];
784 if ((ud == NULL) || (ud->data == NULL)) {
785 log_err("c_psql_write: Invalid user 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");
798 if (values_name_to_sqlarray(ds, values_name_str, sizeof(values_name_str)) ==
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;
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],
822 pthread_mutex_lock(&db->db_lock);
824 if (0 != c_psql_check_connection(db)) {
825 pthread_mutex_unlock(&db->db_lock);
829 if ((db->commit_interval > 0) && (db->next_commit == 0))
832 for (size_t i = 0; i < db->writers_num; ++i) {
833 c_psql_writer_t *writer;
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);
844 if (values_to_sqlarray(ds, vl, values_str, sizeof(values_str),
845 writer->store_rates) == NULL) {
846 pthread_mutex_unlock(&db->db_lock);
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))) {
861 if ((CONNECTION_OK != PQstatus(db->conn)) &&
862 (0 == c_psql_check_connection(db))) {
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))) {
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)
886 pthread_mutex_unlock(&db->db_lock);
894 if ((db->next_commit > 0) && (cdtime() > db->next_commit))
897 pthread_mutex_unlock(&db->db_lock);
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,
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;
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
924 if ((db->next_commit > 0) && (db->commit_interval > timeout))
930 static int c_psql_shutdown(void) {
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);
943 plugin_unregister_flush("postgresql");
947 plugin_unregister_flush(cb_name);
948 plugin_unregister_write(cb_name);
954 udb_query_free(queries, queries_num);
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;
975 data = udb_query_get_user_data(q);
977 data = calloc(1, sizeof(*data));
979 log_err("Out of memory.");
983 data->params_num = 0;
985 udb_query_set_user_data(q, data);
988 tmp = realloc(data->params, (data->params_num + 1) * sizeof(*data->params));
990 log_err("Out of memory.");
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;
1007 log_err("Invalid parameter \"%s\".", param_str);
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);
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) {
1032 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1035 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1036 log_err("`Writer' expects a single string argument.");
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)
1048 tmp = realloc(*dst_writers, sizeof(**dst_writers) * (*dst_writers_num + 1));
1050 log_err("Out of memory.");
1054 tmp[*dst_writers_num] = src_writers + i;
1057 ++(*dst_writers_num);
1061 if (i >= src_writers_num) {
1062 log_err("No such writer: `%s'", name);
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;
1075 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1076 log_err("<Writer> expects a single string argument.");
1080 tmp = realloc(writers, sizeof(*writers) * (writers_num + 1));
1082 log_err("Out of memory.");
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);
1102 log_warn("Ignoring unknown config key \"%s\".", c->key);
1106 sfree(writer->statement);
1107 sfree(writer->name);
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.");
1126 db = c_psql_database_new(ci->values[0].value.string);
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,
1152 else if (0 == strcasecmp(c->key, "Writer"))
1153 config_add_writer(c, writers, writers_num, &db->writers,
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);
1162 log_warn("Ignoring unknown config key \"%s\".", c->key);
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);
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);
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);
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) {
1204 plugin_register_complex_read("postgresql", cb_name, c_psql_read,
1205 /* interval = */ db->interval, &ud);
1207 if (db->writers_num > 0) {
1209 plugin_register_write(cb_name, c_psql_write, &ud);
1213 plugin_register_flush("postgresql", c_psql_flush, /* user data = */ NULL);
1217 /* flush this connection only */
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.",
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) {
1235 have_def_config = 1;
1237 c = oconfig_parse_file(C_PSQL_DEFAULT_CONF);
1239 log_err("Failed to read default config (" C_PSQL_DEFAULT_CONF ").");
1243 if (NULL == queries)
1244 log_err("Default config (" C_PSQL_DEFAULT_CONF ") did not define "
1245 "any queries - please check your installation.");
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);
1259 log_warn("Ignoring unknown config key \"%s\".", c->key);
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 : */