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;
128 /* writer "caching" settings */
129 cdtime_t commit_interval;
130 cdtime_t next_commit;
131 cdtime_t expire_delay;
151 static const char *const def_queries[] = {
152 "backends", "transactions", "queries", "query_plans",
153 "table_states", "disk_io", "disk_usage"};
154 static int def_queries_num = STATIC_ARRAY_SIZE(def_queries);
156 static c_psql_database_t **databases;
157 static size_t databases_num;
159 static udb_query_t **queries;
160 static size_t queries_num;
162 static c_psql_writer_t *writers;
163 static size_t writers_num;
165 static int c_psql_begin(c_psql_database_t *db) {
166 PGresult *r = PQexec(db->conn, "BEGIN");
171 if (PGRES_COMMAND_OK == PQresultStatus(r)) {
172 db->next_commit = cdtime() + db->commit_interval;
175 log_warn("Failed to initiate ('BEGIN') transaction: %s",
176 PQerrorMessage(db->conn));
182 static int c_psql_commit(c_psql_database_t *db) {
183 PGresult *r = PQexec(db->conn, "COMMIT");
188 if (PGRES_COMMAND_OK == PQresultStatus(r)) {
190 log_debug("Successfully committed transaction.");
193 log_warn("Failed to commit transaction: %s", PQerrorMessage(db->conn));
197 } /* c_psql_commit */
199 static c_psql_database_t *c_psql_database_new(const char *name) {
200 c_psql_database_t **tmp;
201 c_psql_database_t *db;
203 db = malloc(sizeof(*db));
205 log_err("Out of memory.");
209 tmp = realloc(databases, (databases_num + 1) * sizeof(*databases));
211 log_err("Out of memory.");
217 databases[databases_num] = db;
222 C_COMPLAIN_INIT(&db->conn_complaint);
224 db->proto_version = 0;
225 db->server_version = 0;
227 db->max_params_num = 0;
229 db->q_prep_areas = NULL;
236 pthread_mutex_init(&db->db_lock, /* attrs = */ NULL);
238 db->commit_interval = 0;
240 db->expire_delay = 0;
242 db->database = sstrdup(name);
248 db->instance = sstrdup(name);
250 db->plugin_name = NULL;
254 db->krbsrvname = NULL;
260 } /* c_psql_database_new */
262 static void c_psql_database_delete(void *data) {
263 c_psql_database_t *db = data;
266 /* readers and writers may access this database */
270 /* wait for the lock to be released by the last writer */
271 pthread_mutex_lock(&db->db_lock);
273 if (db->next_commit > 0)
279 if (db->q_prep_areas)
280 for (size_t i = 0; i < db->queries_num; ++i)
281 udb_query_delete_preparation_area(db->q_prep_areas[i]);
282 free(db->q_prep_areas);
290 pthread_mutex_unlock(&db->db_lock);
292 pthread_mutex_destroy(&db->db_lock);
302 sfree(db->plugin_name);
306 sfree(db->krbsrvname);
310 /* don't care about freeing or reordering the 'databases' array
311 * this is done in 'shutdown'; also, don't free the database instance
312 * object just to make sure that in case anybody accesses it before
313 * shutdown won't segfault */
315 } /* c_psql_database_delete */
317 static int c_psql_connect(c_psql_database_t *db) {
319 char *buf = conninfo;
320 int buf_len = sizeof(conninfo);
323 if ((!db) || (!db->database))
326 status = snprintf(buf, buf_len, "dbname = '%s'", db->database);
332 C_PSQL_PAR_APPEND(buf, buf_len, "host", db->host);
333 C_PSQL_PAR_APPEND(buf, buf_len, "port", db->port);
334 C_PSQL_PAR_APPEND(buf, buf_len, "user", db->user);
335 C_PSQL_PAR_APPEND(buf, buf_len, "password", db->password);
336 C_PSQL_PAR_APPEND(buf, buf_len, "sslmode", db->sslmode);
337 C_PSQL_PAR_APPEND(buf, buf_len, "krbsrvname", db->krbsrvname);
338 C_PSQL_PAR_APPEND(buf, buf_len, "service", db->service);
339 C_PSQL_PAR_APPEND(buf, buf_len, "application_name", "collectd_postgresql");
341 db->conn = PQconnectdb(conninfo);
342 db->proto_version = PQprotocolVersion(db->conn);
344 } /* c_psql_connect */
346 static int c_psql_check_connection(c_psql_database_t *db) {
352 /* trigger c_release() */
353 if (0 == db->conn_complaint.interval)
354 db->conn_complaint.interval = 1;
359 if (CONNECTION_OK != PQstatus(db->conn)) {
362 /* trigger c_release() */
363 if (0 == db->conn_complaint.interval)
364 db->conn_complaint.interval = 1;
366 if (CONNECTION_OK != PQstatus(db->conn)) {
367 c_complain(LOG_ERR, &db->conn_complaint,
368 "Failed to connect to database %s (%s): %s", db->database,
369 db->instance, PQerrorMessage(db->conn));
373 db->proto_version = PQprotocolVersion(db->conn);
376 db->server_version = PQserverVersion(db->conn);
378 if (c_would_release(&db->conn_complaint)) {
382 server_host = PQhost(db->conn);
383 server_version = PQserverVersion(db->conn);
385 c_do_release(LOG_INFO, &db->conn_complaint,
386 "Successfully %sconnected to database %s (user %s) "
387 "at server %s%s%s (server version: %d.%d.%d, "
388 "protocol version: %d, pid: %d)",
389 init ? "" : "re", PQdb(db->conn), PQuser(db->conn),
390 C_PSQL_SOCKET3(server_host, PQport(db->conn)),
391 C_PSQL_SERVER_VERSION3(server_version), db->proto_version,
392 PQbackendPID(db->conn));
394 if (3 > db->proto_version)
395 log_warn("Protocol version %d does not support parameters.",
399 } /* c_psql_check_connection */
401 static PGresult *c_psql_exec_query_noparams(c_psql_database_t *db,
403 return PQexec(db->conn, udb_query_get_statement(q));
404 } /* c_psql_exec_query_noparams */
406 static PGresult *c_psql_exec_query_params(c_psql_database_t *db, udb_query_t *q,
407 c_psql_user_data_t *data) {
408 const char *params[db->max_params_num];
411 if ((data == NULL) || (data->params_num == 0))
412 return c_psql_exec_query_noparams(db, q);
414 assert(db->max_params_num >= data->params_num);
416 for (int i = 0; i < data->params_num; ++i) {
417 switch (data->params[i]) {
418 case C_PSQL_PARAM_HOST:
420 C_PSQL_IS_UNIX_DOMAIN_SOCKET(db->host) ? "localhost" : db->host;
422 case C_PSQL_PARAM_DB:
423 params[i] = db->database;
425 case C_PSQL_PARAM_USER:
426 params[i] = db->user;
428 case C_PSQL_PARAM_INTERVAL:
429 snprintf(interval, sizeof(interval), "%.3f",
430 CDTIME_T_TO_DOUBLE(plugin_get_interval()));
431 params[i] = interval;
433 case C_PSQL_PARAM_INSTANCE:
434 params[i] = db->instance;
441 return PQexecParams(db->conn, udb_query_get_statement(q), data->params_num,
442 NULL, (const char *const *)params, NULL, NULL, 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")))
543 status = udb_query_prepare_result(
545 (db->plugin_name != NULL) ? db->plugin_name : "postgresql", db->instance,
546 column_names, (size_t)column_num);
549 log_err("udb_query_prepare_result failed with status %i.", status);
553 for (int row = 0; row < rows_num; ++row) {
555 for (col = 0; col < column_num; ++col) {
556 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
558 column_values[col] = PQgetvalue(res, row, col);
559 if (NULL == column_values[col]) {
560 log_err("Failed to get value at (row = %i, col = %i).", row, col);
565 /* check for an error */
566 if (col < column_num)
569 status = udb_query_handle_result(q, prep_area, column_values);
571 log_err("udb_query_handle_result failed with status %i.", status);
573 } /* for (row = 0; row < rows_num; ++row) */
575 udb_query_finish_result(q, prep_area);
579 } /* c_psql_exec_query */
581 static int c_psql_read(user_data_t *ud) {
582 c_psql_database_t *db;
586 if ((ud == NULL) || (ud->data == NULL)) {
587 log_err("c_psql_read: Invalid user data.");
593 assert(NULL != db->database);
594 assert(NULL != db->instance);
595 assert(NULL != db->queries);
597 pthread_mutex_lock(&db->db_lock);
599 if (0 != c_psql_check_connection(db)) {
600 pthread_mutex_unlock(&db->db_lock);
604 for (size_t i = 0; i < db->queries_num; ++i) {
605 udb_query_preparation_area_t *prep_area;
608 prep_area = db->q_prep_areas[i];
611 if ((0 != db->server_version) &&
612 (udb_query_check_version(q, db->server_version) <= 0))
615 if (0 == c_psql_exec_query(db, q, prep_area))
619 pthread_mutex_unlock(&db->db_lock);
626 static char *values_name_to_sqlarray(const data_set_t *ds, char *string,
632 str_len = string_len;
634 for (size_t i = 0; i < ds->ds_num; ++i) {
635 int status = snprintf(str_ptr, str_len, ",'%s'", ds->ds[i].name);
639 else if ((size_t)status >= str_len) {
644 str_len -= (size_t)status;
649 log_err("c_psql_write: Failed to stringify value names");
653 /* overwrite the first comma */
659 } /* values_name_to_sqlarray */
661 static char *values_type_to_sqlarray(const data_set_t *ds, char *string,
662 size_t string_len, bool store_rates) {
667 str_len = string_len;
669 for (size_t i = 0; i < ds->ds_num; ++i) {
673 status = snprintf(str_ptr, str_len, ",'gauge'");
675 status = snprintf(str_ptr, str_len, ",'%s'",
676 DS_TYPE_TO_STRING(ds->ds[i].type));
681 } else if ((size_t)status >= str_len) {
686 str_len -= (size_t)status;
691 log_err("c_psql_write: Failed to stringify value types");
695 /* overwrite the first comma */
701 } /* values_type_to_sqlarray */
703 static char *values_to_sqlarray(const data_set_t *ds, const value_list_t *vl,
704 char *string, size_t string_len,
709 gauge_t *rates = NULL;
712 str_len = string_len;
714 for (size_t i = 0; i < vl->values_len; ++i) {
717 if ((ds->ds[i].type != DS_TYPE_GAUGE) &&
718 (ds->ds[i].type != DS_TYPE_COUNTER) &&
719 (ds->ds[i].type != DS_TYPE_DERIVE) &&
720 (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
721 log_err("c_psql_write: Unknown data source type: %i", ds->ds[i].type);
726 if (ds->ds[i].type == DS_TYPE_GAUGE)
728 snprintf(str_ptr, str_len, "," GAUGE_FORMAT, vl->values[i].gauge);
729 else if (store_rates) {
731 rates = uc_get_rate(ds, vl);
734 log_err("c_psql_write: Failed to determine rate");
738 status = snprintf(str_ptr, str_len, ",%lf", rates[i]);
739 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
740 status = snprintf(str_ptr, str_len, ",%" PRIu64,
741 (uint64_t)vl->values[i].counter);
742 else if (ds->ds[i].type == DS_TYPE_DERIVE)
743 status = snprintf(str_ptr, str_len, ",%" PRIi64, vl->values[i].derive);
744 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
745 status = snprintf(str_ptr, str_len, ",%" PRIu64, vl->values[i].absolute);
750 } else if ((size_t)status >= str_len) {
755 str_len -= (size_t)status;
762 log_err("c_psql_write: Failed to stringify value list");
766 /* overwrite the first comma */
772 } /* values_to_sqlarray */
774 static int c_psql_write(const data_set_t *ds, const value_list_t *vl,
776 c_psql_database_t *db;
778 char time_str[RFC3339NANO_SIZE];
779 char values_name_str[1024];
780 char values_type_str[1024];
781 char values_str[1024];
783 const char *params[9];
787 if ((ud == NULL) || (ud->data == NULL)) {
788 log_err("c_psql_write: Invalid user data.");
793 assert(db->database != NULL);
794 assert(db->writers != NULL);
796 if (rfc3339nano_local(time_str, sizeof(time_str), vl->time) != 0) {
797 log_err("c_psql_write: Failed to convert time to RFC 3339 format");
801 if (values_name_to_sqlarray(ds, values_name_str, sizeof(values_name_str)) ==
805 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
807 params[0] = time_str;
808 params[1] = vl->host;
809 params[2] = vl->plugin;
810 params[3] = VALUE_OR_NULL(vl->plugin_instance);
811 params[4] = vl->type;
812 params[5] = VALUE_OR_NULL(vl->type_instance);
813 params[6] = values_name_str;
817 if (db->expire_delay > 0 &&
818 vl->time < (cdtime() - vl->interval - db->expire_delay)) {
819 log_info("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
820 params[0], params[1], params[2], params[3], params[4], params[5],
825 pthread_mutex_lock(&db->db_lock);
827 if (0 != c_psql_check_connection(db)) {
828 pthread_mutex_unlock(&db->db_lock);
832 if ((db->commit_interval > 0) && (db->next_commit == 0))
835 for (size_t i = 0; i < db->writers_num; ++i) {
836 c_psql_writer_t *writer;
839 writer = db->writers[i];
841 if (values_type_to_sqlarray(ds, values_type_str, sizeof(values_type_str),
842 writer->store_rates) == NULL) {
843 pthread_mutex_unlock(&db->db_lock);
847 if (values_to_sqlarray(ds, vl, values_str, sizeof(values_str),
848 writer->store_rates) == NULL) {
849 pthread_mutex_unlock(&db->db_lock);
853 params[7] = values_type_str;
854 params[8] = values_str;
856 res = PQexecParams(db->conn, writer->statement, STATIC_ARRAY_SIZE(params),
857 NULL, (const char *const *)params, NULL, NULL,
858 /* return text data */ 0);
860 if ((PGRES_COMMAND_OK != PQresultStatus(res)) &&
861 (PGRES_TUPLES_OK != PQresultStatus(res))) {
864 if ((CONNECTION_OK != PQstatus(db->conn)) &&
865 (0 == c_psql_check_connection(db))) {
868 db->conn, writer->statement, STATIC_ARRAY_SIZE(params), NULL,
869 (const char *const *)params, NULL, NULL, /* return text data */ 0);
871 if ((PGRES_COMMAND_OK == PQresultStatus(res)) ||
872 (PGRES_TUPLES_OK == PQresultStatus(res))) {
879 log_err("Failed to execute SQL query: %s", PQerrorMessage(db->conn));
880 log_info("SQL query was: '%s', "
881 "params: %s, %s, %s, %s, %s, %s, %s, %s",
882 writer->statement, params[0], params[1], params[2], params[3],
883 params[4], params[5], params[6], params[7]);
885 /* this will abort any current transaction -> restart */
886 if (db->next_commit > 0)
889 pthread_mutex_unlock(&db->db_lock);
897 if ((db->next_commit > 0) && (cdtime() > db->next_commit))
900 pthread_mutex_unlock(&db->db_lock);
907 /* We cannot flush single identifiers as all we do is to commit the currently
908 * running transaction, thus making sure that all written data is actually
909 * visible to everybody. */
910 static int c_psql_flush(cdtime_t timeout,
911 __attribute__((unused)) const char *ident,
913 c_psql_database_t **dbs = databases;
914 size_t dbs_num = databases_num;
916 if ((ud != NULL) && (ud->data != NULL)) {
917 dbs = (void *)&ud->data;
921 for (size_t i = 0; i < dbs_num; ++i) {
922 c_psql_database_t *db = dbs[i];
924 /* don't commit if the timeout is larger than the regular commit
925 * interval as in that case all requested data has already been
927 if ((db->next_commit > 0) && (db->commit_interval > timeout))
933 static int c_psql_shutdown(void) {
934 bool had_flush = false;
936 plugin_unregister_read_group("postgresql");
938 for (size_t i = 0; i < databases_num; ++i) {
939 c_psql_database_t *db = databases[i];
941 if (db->writers_num > 0) {
942 char cb_name[DATA_MAX_NAME_LEN];
943 snprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->database);
946 plugin_unregister_flush("postgresql");
950 plugin_unregister_flush(cb_name);
951 plugin_unregister_write(cb_name);
957 udb_query_free(queries, queries_num);
970 } /* c_psql_shutdown */
972 static int config_query_param_add(udb_query_t *q, oconfig_item_t *ci) {
973 c_psql_user_data_t *data;
974 const char *param_str;
978 data = udb_query_get_user_data(q);
980 data = calloc(1, sizeof(*data));
982 log_err("Out of memory.");
986 data->params_num = 0;
988 udb_query_set_user_data(q, data);
991 tmp = realloc(data->params, (data->params_num + 1) * sizeof(*data->params));
993 log_err("Out of memory.");
998 param_str = ci->values[0].value.string;
999 if (0 == strcasecmp(param_str, "hostname"))
1000 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1001 else if (0 == strcasecmp(param_str, "database"))
1002 data->params[data->params_num] = C_PSQL_PARAM_DB;
1003 else if (0 == strcasecmp(param_str, "username"))
1004 data->params[data->params_num] = C_PSQL_PARAM_USER;
1005 else if (0 == strcasecmp(param_str, "interval"))
1006 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1007 else if (0 == strcasecmp(param_str, "instance"))
1008 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1010 log_err("Invalid parameter \"%s\".", param_str);
1016 } /* config_query_param_add */
1018 static int config_query_callback(udb_query_t *q, oconfig_item_t *ci) {
1019 if (0 == strcasecmp("Param", ci->key))
1020 return config_query_param_add(q, ci);
1022 log_err("Option not allowed within a Query block: `%s'", ci->key);
1025 } /* config_query_callback */
1027 static int config_add_writer(oconfig_item_t *ci, c_psql_writer_t *src_writers,
1028 size_t src_writers_num,
1029 c_psql_writer_t ***dst_writers,
1030 size_t *dst_writers_num) {
1035 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1038 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1039 log_err("`Writer' expects a single string argument.");
1043 name = ci->values[0].value.string;
1045 for (i = 0; i < src_writers_num; ++i) {
1046 c_psql_writer_t **tmp;
1048 if (strcasecmp(name, src_writers[i].name) != 0)
1051 tmp = realloc(*dst_writers, sizeof(**dst_writers) * (*dst_writers_num + 1));
1053 log_err("Out of memory.");
1057 tmp[*dst_writers_num] = src_writers + i;
1060 ++(*dst_writers_num);
1064 if (i >= src_writers_num) {
1065 log_err("No such writer: `%s'", name);
1070 } /* config_add_writer */
1072 static int c_psql_config_writer(oconfig_item_t *ci) {
1073 c_psql_writer_t *writer;
1074 c_psql_writer_t *tmp;
1078 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1079 log_err("<Writer> expects a single string argument.");
1083 tmp = realloc(writers, sizeof(*writers) * (writers_num + 1));
1085 log_err("Out of memory.");
1090 writer = writers + writers_num;
1091 memset(writer, 0, sizeof(*writer));
1093 writer->name = sstrdup(ci->values[0].value.string);
1094 writer->statement = NULL;
1095 writer->store_rates = true;
1097 for (int i = 0; i < ci->children_num; ++i) {
1098 oconfig_item_t *c = ci->children + i;
1100 if (strcasecmp("Statement", c->key) == 0)
1101 status = cf_util_get_string(c, &writer->statement);
1102 else if (strcasecmp("StoreRates", c->key) == 0)
1103 status = cf_util_get_boolean(c, &writer->store_rates);
1105 log_warn("Ignoring unknown config key \"%s\".", c->key);
1109 sfree(writer->statement);
1110 sfree(writer->name);
1116 } /* c_psql_config_writer */
1118 static int c_psql_config_database(oconfig_item_t *ci) {
1119 c_psql_database_t *db;
1121 cdtime_t interval = 0;
1122 char cb_name[DATA_MAX_NAME_LEN];
1123 static bool have_flush;
1125 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1126 log_err("<Database> expects a single string argument.");
1130 db = c_psql_database_new(ci->values[0].value.string);
1134 for (int i = 0; i < ci->children_num; ++i) {
1135 oconfig_item_t *c = ci->children + i;
1137 if (0 == strcasecmp(c->key, "Host"))
1138 cf_util_get_string(c, &db->host);
1139 else if (0 == strcasecmp(c->key, "Port"))
1140 cf_util_get_service(c, &db->port);
1141 else if (0 == strcasecmp(c->key, "User"))
1142 cf_util_get_string(c, &db->user);
1143 else if (0 == strcasecmp(c->key, "Password"))
1144 cf_util_get_string(c, &db->password);
1145 else if (0 == strcasecmp(c->key, "Instance"))
1146 cf_util_get_string(c, &db->instance);
1147 else if (0 == strcasecmp(c->key, "Plugin"))
1148 cf_util_get_string(c, &db->plugin_name);
1149 else if (0 == strcasecmp(c->key, "SSLMode"))
1150 cf_util_get_string(c, &db->sslmode);
1151 else if (0 == strcasecmp(c->key, "KRBSrvName"))
1152 cf_util_get_string(c, &db->krbsrvname);
1153 else if (0 == strcasecmp(c->key, "Service"))
1154 cf_util_get_string(c, &db->service);
1155 else if (0 == strcasecmp(c->key, "Query"))
1156 udb_query_pick_from_list(c, queries, queries_num, &db->queries,
1158 else if (0 == strcasecmp(c->key, "Writer"))
1159 config_add_writer(c, writers, writers_num, &db->writers,
1161 else if (0 == strcasecmp(c->key, "Interval"))
1162 cf_util_get_cdtime(c, &interval);
1163 else if (strcasecmp("CommitInterval", c->key) == 0)
1164 cf_util_get_cdtime(c, &db->commit_interval);
1165 else if (strcasecmp("ExpireDelay", c->key) == 0)
1166 cf_util_get_cdtime(c, &db->expire_delay);
1168 log_warn("Ignoring unknown config key \"%s\".", c->key);
1171 /* If no `Query' options were given, add the default queries.. */
1172 if ((db->queries_num == 0) && (db->writers_num == 0)) {
1173 for (int i = 0; i < def_queries_num; i++)
1174 udb_query_pick_from_list_by_name(def_queries[i], queries, queries_num,
1175 &db->queries, &db->queries_num);
1178 if (db->queries_num > 0) {
1179 db->q_prep_areas = (udb_query_preparation_area_t **)calloc(
1180 db->queries_num, sizeof(*db->q_prep_areas));
1182 if (db->q_prep_areas == NULL) {
1183 log_err("Out of memory.");
1184 c_psql_database_delete(db);
1189 for (int i = 0; (size_t)i < db->queries_num; ++i) {
1190 c_psql_user_data_t *data;
1191 data = udb_query_get_user_data(db->queries[i]);
1192 if ((data != NULL) && (data->params_num > db->max_params_num))
1193 db->max_params_num = data->params_num;
1195 db->q_prep_areas[i] = udb_query_allocate_preparation_area(db->queries[i]);
1197 if (db->q_prep_areas[i] == NULL) {
1198 log_err("Out of memory.");
1199 c_psql_database_delete(db);
1204 snprintf(cb_name, sizeof(cb_name), "postgresql-%s", db->instance);
1206 user_data_t ud = {.data = db, .free_func = c_psql_database_delete};
1208 if (db->queries_num > 0) {
1210 plugin_register_complex_read("postgresql", cb_name, c_psql_read, interval,
1213 if (db->writers_num > 0) {
1215 plugin_register_write(cb_name, c_psql_write, &ud);
1219 plugin_register_flush("postgresql", c_psql_flush, /* user data = */ NULL);
1223 /* flush this connection only */
1225 plugin_register_flush(cb_name, c_psql_flush, &ud);
1226 } else if (db->commit_interval > 0) {
1227 log_warn("Database '%s': You do not have any writers assigned to "
1228 "this database connection. Setting 'CommitInterval' does "
1229 "not have any effect.",
1233 } /* c_psql_config_database */
1235 static int c_psql_config(oconfig_item_t *ci) {
1236 static int have_def_config;
1238 if (0 == have_def_config) {
1241 have_def_config = 1;
1243 c = oconfig_parse_file(C_PSQL_DEFAULT_CONF);
1245 log_err("Failed to read default config (" C_PSQL_DEFAULT_CONF ").");
1249 if (NULL == queries)
1250 log_err("Default config (" C_PSQL_DEFAULT_CONF ") did not define "
1251 "any queries - please check your installation.");
1254 for (int i = 0; i < ci->children_num; ++i) {
1255 oconfig_item_t *c = ci->children + i;
1257 if (0 == strcasecmp(c->key, "Query"))
1258 udb_query_create(&queries, &queries_num, c,
1259 /* callback = */ config_query_callback);
1260 else if (0 == strcasecmp(c->key, "Writer"))
1261 c_psql_config_writer(c);
1262 else if (0 == strcasecmp(c->key, "Database"))
1263 c_psql_config_database(c);
1265 log_warn("Ignoring unknown config key \"%s\".", c->key);
1268 } /* c_psql_config */
1270 void module_register(void) {
1271 plugin_register_complex_config("postgresql", c_psql_config);
1272 plugin_register_shutdown("postgresql", c_psql_shutdown);
1273 } /* module_register */