2 * collectd - src/postgresql.c
3 * Copyright (C) 2008-2012 Sebastian Harl
4 * Copyright (C) 2009 Florian Forster
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
31 * Sebastian Harl <sh at tokkee.org>
32 * Florian Forster <octo at verplant.org>
36 * This module collects PostgreSQL database statistics.
42 #include "configfile.h"
45 #include "utils_cache.h"
46 #include "utils_db_query.h"
47 #include "utils_complain.h"
53 #include <pg_config_manual.h>
56 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
57 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
58 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
59 #define log_debug(...) DEBUG ("postgresql: " __VA_ARGS__)
61 #ifndef C_PSQL_DEFAULT_CONF
62 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
65 /* Appends the (parameter, value) pair to the string
66 * pointed to by 'buf' suitable to be used as argument
67 * for PQconnectdb(). If value equals NULL, the pair
69 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
70 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
71 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
78 /* Returns the tuple (major, minor, patchlevel)
79 * for the given version number. */
80 #define C_PSQL_SERVER_VERSION3(server_version) \
81 (server_version) / 10000, \
82 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
83 (server_version) - (int)((server_version) / 100) * 100
85 /* Returns true if the given host specifies a
86 * UNIX domain socket. */
87 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
88 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
90 /* Returns the tuple (host, delimiter, port) for a
91 * given (host, port) pair. Depending on the value of
92 * 'host' a UNIX domain socket or a TCP socket is
94 #define C_PSQL_SOCKET3(host, port) \
95 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
96 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
100 C_PSQL_PARAM_HOST = 1,
103 C_PSQL_PARAM_INTERVAL,
104 C_PSQL_PARAM_INSTANCE,
107 /* Parameter configuration. Stored as `user data' in the query objects. */
109 c_psql_param_t *params;
111 } c_psql_user_data_t;
121 c_complain_t conn_complaint;
128 /* user configuration */
129 udb_query_preparation_area_t **q_prep_areas;
130 udb_query_t **queries;
133 c_psql_writer_t **writers;
136 /* make sure we don't access the database object in parallel */
137 pthread_mutex_t db_lock;
141 /* writer "caching" settings */
142 cdtime_t commit_interval;
143 cdtime_t next_commit;
162 static char *def_queries[] = {
171 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
173 static c_psql_database_t **databases = NULL;
174 static size_t databases_num = 0;
176 static udb_query_t **queries = NULL;
177 static size_t queries_num = 0;
179 static c_psql_writer_t *writers = NULL;
180 static size_t writers_num = 0;
182 static int c_psql_begin (c_psql_database_t *db)
184 PGresult *r = PQexec (db->conn, "BEGIN");
189 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
190 db->next_commit = cdtime() + db->commit_interval;
194 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
195 PQerrorMessage (db->conn));
201 static int c_psql_commit (c_psql_database_t *db)
203 PGresult *r = PQexec (db->conn, "COMMIT");
208 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
210 log_debug ("Successfully committed transaction.");
214 log_warn ("Failed to commit transaction: %s",
215 PQerrorMessage (db->conn));
219 } /* c_psql_commit */
221 static c_psql_database_t *c_psql_database_new (const char *name)
223 c_psql_database_t **tmp;
224 c_psql_database_t *db;
226 db = (c_psql_database_t *)malloc (sizeof(*db));
228 log_err ("Out of memory.");
232 tmp = (c_psql_database_t **)realloc (databases,
233 (databases_num + 1) * sizeof (*databases));
235 log_err ("Out of memory.");
241 databases[databases_num] = db;
246 C_COMPLAIN_INIT (&db->conn_complaint);
248 db->proto_version = 0;
249 db->server_version = 0;
251 db->max_params_num = 0;
253 db->q_prep_areas = NULL;
260 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
264 db->commit_interval = 0;
267 db->database = sstrdup (name);
273 db->instance = sstrdup (name);
277 db->krbsrvname = NULL;
283 } /* c_psql_database_new */
285 static void c_psql_database_delete (void *data)
289 c_psql_database_t *db = data;
292 /* readers and writers may access this database */
296 /* wait for the lock to be released by the last writer */
297 pthread_mutex_lock (&db->db_lock);
299 if (db->next_commit > 0)
305 if (db->q_prep_areas)
306 for (i = 0; i < db->queries_num; ++i)
307 udb_query_delete_preparation_area (db->q_prep_areas[i]);
308 free (db->q_prep_areas);
316 pthread_mutex_unlock (&db->db_lock);
318 pthread_mutex_destroy (&db->db_lock);
320 sfree (db->database);
324 sfree (db->password);
326 sfree (db->instance);
330 sfree (db->krbsrvname);
334 /* don't care about freeing or reordering the 'databases' array
335 * this is done in 'shutdown'; also, don't free the database instance
336 * object just to make sure that in case anybody accesses it before
337 * shutdown won't segfault */
339 } /* c_psql_database_delete */
341 static int c_psql_connect (c_psql_database_t *db)
344 char *buf = conninfo;
345 int buf_len = sizeof (conninfo);
348 if ((! db) || (! db->database))
351 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
357 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
358 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
359 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
360 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
361 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
362 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
363 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
365 db->conn = PQconnectdb (conninfo);
366 db->proto_version = PQprotocolVersion (db->conn);
368 } /* c_psql_connect */
370 static int c_psql_check_connection (c_psql_database_t *db)
377 /* trigger c_release() */
378 if (0 == db->conn_complaint.interval)
379 db->conn_complaint.interval = 1;
384 if (CONNECTION_OK != PQstatus (db->conn)) {
387 /* trigger c_release() */
388 if (0 == db->conn_complaint.interval)
389 db->conn_complaint.interval = 1;
391 if (CONNECTION_OK != PQstatus (db->conn)) {
392 c_complain (LOG_ERR, &db->conn_complaint,
393 "Failed to connect to database %s (%s): %s",
394 db->database, db->instance,
395 PQerrorMessage (db->conn));
399 db->proto_version = PQprotocolVersion (db->conn);
402 db->server_version = PQserverVersion (db->conn);
404 if (c_would_release (&db->conn_complaint)) {
408 server_host = PQhost (db->conn);
409 server_version = PQserverVersion (db->conn);
411 c_do_release (LOG_INFO, &db->conn_complaint,
412 "Successfully %sconnected to database %s (user %s) "
413 "at server %s%s%s (server version: %d.%d.%d, "
414 "protocol version: %d, pid: %d)", init ? "" : "re",
415 PQdb (db->conn), PQuser (db->conn),
416 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
417 C_PSQL_SERVER_VERSION3 (server_version),
418 db->proto_version, PQbackendPID (db->conn));
420 if (3 > db->proto_version)
421 log_warn ("Protocol version %d does not support parameters.",
425 } /* c_psql_check_connection */
427 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
430 return PQexec (db->conn, udb_query_get_statement (q));
431 } /* c_psql_exec_query_noparams */
433 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
434 udb_query_t *q, c_psql_user_data_t *data)
436 char *params[db->max_params_num];
440 if ((data == NULL) || (data->params_num == 0))
441 return (c_psql_exec_query_noparams (db, q));
443 assert (db->max_params_num >= data->params_num);
445 for (i = 0; i < data->params_num; ++i) {
446 switch (data->params[i]) {
447 case C_PSQL_PARAM_HOST:
448 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
449 ? "localhost" : db->host;
451 case C_PSQL_PARAM_DB:
452 params[i] = db->database;
454 case C_PSQL_PARAM_USER:
455 params[i] = db->user;
457 case C_PSQL_PARAM_INTERVAL:
458 ssnprintf (interval, sizeof (interval), "%.3f",
460 ? CDTIME_T_TO_DOUBLE (db->interval)
461 : plugin_get_interval ());
462 params[i] = interval;
464 case C_PSQL_PARAM_INSTANCE:
465 params[i] = db->instance;
472 return PQexecParams (db->conn, udb_query_get_statement (q),
473 data->params_num, NULL,
474 (const char *const *) params,
475 NULL, NULL, /* return text data */ 0);
476 } /* c_psql_exec_query_params */
478 /* db->db_lock must be locked when calling this function */
479 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
480 udb_query_preparation_area_t *prep_area)
484 c_psql_user_data_t *data;
489 char **column_values;
496 /* The user data may hold parameter information, but may be NULL. */
497 data = udb_query_get_user_data (q);
499 /* Versions up to `3' don't know how to handle parameters. */
500 if (3 <= db->proto_version)
501 res = c_psql_exec_query_params (db, q, data);
502 else if ((NULL == data) || (0 == data->params_num))
503 res = c_psql_exec_query_noparams (db, q);
505 log_err ("Connection to database \"%s\" (%s) does not support "
506 "parameters (protocol version %d) - "
507 "cannot execute query \"%s\".",
508 db->database, db->instance, db->proto_version,
509 udb_query_get_name (q));
513 /* give c_psql_write() a chance to acquire the lock if called recursively
514 * through dispatch_values(); this will happen if, both, queries and
515 * writers are configured for a single connection */
516 pthread_mutex_unlock (&db->db_lock);
519 column_values = NULL;
521 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
522 pthread_mutex_lock (&db->db_lock);
524 if ((CONNECTION_OK != PQstatus (db->conn))
525 && (0 == c_psql_check_connection (db))) {
527 return c_psql_exec_query (db, q, prep_area);
530 log_err ("Failed to execute SQL query: %s",
531 PQerrorMessage (db->conn));
532 log_info ("SQL query was: %s",
533 udb_query_get_statement (q));
538 #define BAIL_OUT(status) \
539 sfree (column_names); \
540 sfree (column_values); \
542 pthread_mutex_lock (&db->db_lock); \
545 rows_num = PQntuples (res);
550 column_num = PQnfields (res);
551 column_names = (char **) calloc (column_num, sizeof (char *));
552 if (NULL == column_names) {
553 log_err ("calloc failed.");
557 column_values = (char **) calloc (column_num, sizeof (char *));
558 if (NULL == column_values) {
559 log_err ("calloc failed.");
563 for (col = 0; col < column_num; ++col) {
564 /* Pointers returned by `PQfname' are freed by `PQclear' via
566 column_names[col] = PQfname (res, col);
567 if (NULL == column_names[col]) {
568 log_err ("Failed to resolve name of column %i.", col);
573 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
574 || (0 == strcmp (db->host, "localhost")))
579 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
580 db->instance, column_names, (size_t) column_num, db->interval);
582 log_err ("udb_query_prepare_result failed with status %i.",
587 for (row = 0; row < rows_num; ++row) {
588 for (col = 0; col < column_num; ++col) {
589 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
591 column_values[col] = PQgetvalue (res, row, col);
592 if (NULL == column_values[col]) {
593 log_err ("Failed to get value at (row = %i, col = %i).",
599 /* check for an error */
600 if (col < column_num)
603 status = udb_query_handle_result (q, prep_area, column_values);
605 log_err ("udb_query_handle_result failed with status %i.",
608 } /* for (row = 0; row < rows_num; ++row) */
610 udb_query_finish_result (q, prep_area);
614 } /* c_psql_exec_query */
616 static int c_psql_read (user_data_t *ud)
618 c_psql_database_t *db;
623 if ((ud == NULL) || (ud->data == NULL)) {
624 log_err ("c_psql_read: Invalid user data.");
630 assert (NULL != db->database);
631 assert (NULL != db->instance);
632 assert (NULL != db->queries);
634 pthread_mutex_lock (&db->db_lock);
636 if (0 != c_psql_check_connection (db)) {
637 pthread_mutex_unlock (&db->db_lock);
641 for (i = 0; i < db->queries_num; ++i)
643 udb_query_preparation_area_t *prep_area;
646 prep_area = db->q_prep_areas[i];
649 if ((0 != db->server_version)
650 && (udb_query_check_version (q, db->server_version) <= 0))
653 if (0 == c_psql_exec_query (db, q, prep_area))
657 pthread_mutex_unlock (&db->db_lock);
664 static char *values_name_to_sqlarray (const data_set_t *ds,
665 char *string, size_t string_len)
673 str_len = string_len;
675 for (i = 0; i < ds->ds_num; ++i) {
676 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
680 else if ((size_t)status >= str_len) {
686 str_len -= (size_t)status;
691 log_err ("c_psql_write: Failed to stringify value names");
695 /* overwrite the first comma */
701 } /* values_name_to_sqlarray */
703 static char *values_type_to_sqlarray (const data_set_t *ds,
704 char *string, size_t string_len, _Bool store_rates)
712 str_len = string_len;
714 for (i = 0; i < ds->ds_num; ++i) {
718 status = ssnprintf(str_ptr, str_len, ",'gauge'");
720 status = ssnprintf(str_ptr, str_len, ",'%s'",
721 DS_TYPE_TO_STRING (ds->ds[i].type));
727 else if ((size_t)status >= str_len) {
733 str_len -= (size_t)status;
738 log_err ("c_psql_write: Failed to stringify value types");
742 /* overwrite the first comma */
748 } /* values_type_to_sqlarray */
750 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
751 char *string, size_t string_len, _Bool store_rates)
756 gauge_t *rates = NULL;
761 str_len = string_len;
763 for (i = 0; i < vl->values_len; ++i) {
766 if ((ds->ds[i].type != DS_TYPE_GAUGE)
767 && (ds->ds[i].type != DS_TYPE_COUNTER)
768 && (ds->ds[i].type != DS_TYPE_DERIVE)
769 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
770 log_err ("c_psql_write: Unknown data source type: %i",
776 if (ds->ds[i].type == DS_TYPE_GAUGE)
777 status = ssnprintf (str_ptr, str_len,
778 ","GAUGE_FORMAT, vl->values[i].gauge);
779 else if (store_rates) {
781 rates = uc_get_rate (ds, vl);
784 log_err ("c_psql_write: Failed to determine rate");
788 status = ssnprintf (str_ptr, str_len,
791 else if (ds->ds[i].type == DS_TYPE_COUNTER)
792 status = ssnprintf (str_ptr, str_len,
793 ",%llu", vl->values[i].counter);
794 else if (ds->ds[i].type == DS_TYPE_DERIVE)
795 status = ssnprintf (str_ptr, str_len,
796 ",%"PRIi64, vl->values[i].derive);
797 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
798 status = ssnprintf (str_ptr, str_len,
799 ",%"PRIu64, vl->values[i].absolute);
805 else if ((size_t)status >= str_len) {
811 str_len -= (size_t)status;
818 log_err ("c_psql_write: Failed to stringify value list");
822 /* overwrite the first comma */
828 } /* values_to_sqlarray */
830 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
833 c_psql_database_t *db;
836 char values_name_str[1024];
837 char values_type_str[1024];
838 char values_str[1024];
840 const char *params[9];
845 if ((ud == NULL) || (ud->data == NULL)) {
846 log_err ("c_psql_write: Invalid user data.");
851 assert (db->database != NULL);
852 assert (db->writers != NULL);
854 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
855 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
859 if (values_name_to_sqlarray (ds,
860 values_name_str, sizeof (values_name_str)) == NULL)
863 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
865 params[0] = time_str;
866 params[1] = vl->host;
867 params[2] = vl->plugin;
868 params[3] = VALUE_OR_NULL(vl->plugin_instance);
869 params[4] = vl->type;
870 params[5] = VALUE_OR_NULL(vl->type_instance);
871 params[6] = values_name_str;
875 pthread_mutex_lock (&db->db_lock);
877 if (0 != c_psql_check_connection (db)) {
878 pthread_mutex_unlock (&db->db_lock);
882 if ((db->commit_interval > 0)
883 && (db->next_commit == 0))
886 for (i = 0; i < db->writers_num; ++i) {
887 c_psql_writer_t *writer;
890 writer = db->writers[i];
892 if (values_type_to_sqlarray (ds,
893 values_type_str, sizeof (values_type_str),
894 writer->store_rates) == NULL) {
895 pthread_mutex_unlock (&db->db_lock);
899 if (values_to_sqlarray (ds, vl,
900 values_str, sizeof (values_str),
901 writer->store_rates) == NULL) {
902 pthread_mutex_unlock (&db->db_lock);
906 params[7] = values_type_str;
907 params[8] = values_str;
909 res = PQexecParams (db->conn, writer->statement,
910 STATIC_ARRAY_SIZE (params), NULL,
911 (const char *const *)params,
912 NULL, NULL, /* return text data */ 0);
914 if ((PGRES_COMMAND_OK != PQresultStatus (res))
915 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
918 if ((CONNECTION_OK != PQstatus (db->conn))
919 && (0 == c_psql_check_connection (db))) {
921 res = PQexecParams (db->conn, writer->statement,
922 STATIC_ARRAY_SIZE (params), NULL,
923 (const char *const *)params,
924 NULL, NULL, /* return text data */ 0);
926 if ((PGRES_COMMAND_OK == PQresultStatus (res))
927 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
934 log_err ("Failed to execute SQL query: %s",
935 PQerrorMessage (db->conn));
936 log_info ("SQL query was: '%s', "
937 "params: %s, %s, %s, %s, %s, %s, %s, %s",
939 params[0], params[1], params[2], params[3],
940 params[4], params[5], params[6], params[7]);
942 /* this will abort any current transaction -> restart */
943 if (db->next_commit > 0)
946 pthread_mutex_unlock (&db->db_lock);
954 if ((db->next_commit > 0)
955 && (cdtime () > db->next_commit))
958 pthread_mutex_unlock (&db->db_lock);
965 /* We cannot flush single identifiers as all we do is to commit the currently
966 * running transaction, thus making sure that all written data is actually
967 * visible to everybody. */
968 static int c_psql_flush (cdtime_t timeout,
969 __attribute__((unused)) const char *ident,
972 c_psql_database_t **dbs = databases;
973 size_t dbs_num = databases_num;
976 if ((ud != NULL) && (ud->data != NULL)) {
977 dbs = (void *)&ud->data;
981 for (i = 0; i < dbs_num; ++i) {
982 c_psql_database_t *db = dbs[i];
984 /* don't commit if the timeout is larger than the regular commit
985 * interval as in that case all requested data has already been
987 if ((db->next_commit > 0) && (db->commit_interval > timeout))
993 static int c_psql_shutdown (void)
999 plugin_unregister_read_group ("postgresql");
1001 for (i = 0; i < databases_num; ++i) {
1002 c_psql_database_t *db = databases[i];
1004 if (db->writers_num > 0) {
1005 char cb_name[DATA_MAX_NAME_LEN];
1006 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s",
1010 plugin_unregister_flush ("postgresql");
1014 plugin_unregister_flush (cb_name);
1015 plugin_unregister_write (cb_name);
1021 udb_query_free (queries, queries_num);
1034 } /* c_psql_shutdown */
1036 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
1038 c_psql_user_data_t *data;
1039 const char *param_str;
1041 c_psql_param_t *tmp;
1043 data = udb_query_get_user_data (q);
1045 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
1047 log_err ("Out of memory.");
1050 memset (data, 0, sizeof (*data));
1051 data->params = NULL;
1054 tmp = (c_psql_param_t *) realloc (data->params,
1055 (data->params_num + 1) * sizeof (c_psql_param_t));
1057 log_err ("Out of memory.");
1062 param_str = ci->values[0].value.string;
1063 if (0 == strcasecmp (param_str, "hostname"))
1064 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1065 else if (0 == strcasecmp (param_str, "database"))
1066 data->params[data->params_num] = C_PSQL_PARAM_DB;
1067 else if (0 == strcasecmp (param_str, "username"))
1068 data->params[data->params_num] = C_PSQL_PARAM_USER;
1069 else if (0 == strcasecmp (param_str, "interval"))
1070 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1071 else if (0 == strcasecmp (param_str, "instance"))
1072 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1074 log_err ("Invalid parameter \"%s\".", param_str);
1079 udb_query_set_user_data (q, data);
1082 } /* config_query_param_add */
1084 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
1086 if (0 == strcasecmp ("Param", ci->key))
1087 return config_query_param_add (q, ci);
1089 log_err ("Option not allowed within a Query block: `%s'", ci->key);
1092 } /* config_query_callback */
1094 static int config_add_writer (oconfig_item_t *ci,
1095 c_psql_writer_t *src_writers, size_t src_writers_num,
1096 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
1102 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1105 if ((ci->values_num != 1)
1106 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1107 log_err ("`Writer' expects a single string argument.");
1111 name = ci->values[0].value.string;
1113 for (i = 0; i < src_writers_num; ++i) {
1114 c_psql_writer_t **tmp;
1116 if (strcasecmp (name, src_writers[i].name) != 0)
1119 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1120 sizeof (**dst_writers) * (*dst_writers_num + 1));
1122 log_err ("Out of memory.");
1126 tmp[*dst_writers_num] = src_writers + i;
1129 ++(*dst_writers_num);
1133 if (i >= src_writers_num) {
1134 log_err ("No such writer: `%s'", name);
1139 } /* config_add_writer */
1141 static int c_psql_config_writer (oconfig_item_t *ci)
1143 c_psql_writer_t *writer;
1144 c_psql_writer_t *tmp;
1149 if ((ci->values_num != 1)
1150 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1151 log_err ("<Writer> expects a single string argument.");
1155 tmp = (c_psql_writer_t *)realloc (writers,
1156 sizeof (*writers) * (writers_num + 1));
1158 log_err ("Out of memory.");
1163 writer = writers + writers_num;
1166 writer->name = sstrdup (ci->values[0].value.string);
1167 writer->statement = NULL;
1168 writer->store_rates = 1;
1170 for (i = 0; i < ci->children_num; ++i) {
1171 oconfig_item_t *c = ci->children + i;
1173 if (strcasecmp ("Statement", c->key) == 0)
1174 status = cf_util_get_string (c, &writer->statement);
1175 else if (strcasecmp ("StoreRates", c->key) == 0)
1176 status = cf_util_get_boolean (c, &writer->store_rates);
1178 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1182 sfree (writer->statement);
1183 sfree (writer->name);
1189 } /* c_psql_config_writer */
1191 static int c_psql_config_database (oconfig_item_t *ci)
1193 c_psql_database_t *db;
1195 char cb_name[DATA_MAX_NAME_LEN];
1196 struct timespec cb_interval = { 0, 0 };
1199 static _Bool have_flush = 0;
1203 if ((1 != ci->values_num)
1204 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1205 log_err ("<Database> expects a single string argument.");
1209 memset (&ud, 0, sizeof (ud));
1211 db = c_psql_database_new (ci->values[0].value.string);
1215 for (i = 0; i < ci->children_num; ++i) {
1216 oconfig_item_t *c = ci->children + i;
1218 if (0 == strcasecmp (c->key, "Host"))
1219 cf_util_get_string (c, &db->host);
1220 else if (0 == strcasecmp (c->key, "Port"))
1221 cf_util_get_service (c, &db->port);
1222 else if (0 == strcasecmp (c->key, "User"))
1223 cf_util_get_string (c, &db->user);
1224 else if (0 == strcasecmp (c->key, "Password"))
1225 cf_util_get_string (c, &db->password);
1226 else if (0 == strcasecmp (c->key, "Instance"))
1227 cf_util_get_string (c, &db->instance);
1228 else if (0 == strcasecmp (c->key, "SSLMode"))
1229 cf_util_get_string (c, &db->sslmode);
1230 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1231 cf_util_get_string (c, &db->krbsrvname);
1232 else if (0 == strcasecmp (c->key, "Service"))
1233 cf_util_get_string (c, &db->service);
1234 else if (0 == strcasecmp (c->key, "Query"))
1235 udb_query_pick_from_list (c, queries, queries_num,
1236 &db->queries, &db->queries_num);
1237 else if (0 == strcasecmp (c->key, "Writer"))
1238 config_add_writer (c, writers, writers_num,
1239 &db->writers, &db->writers_num);
1240 else if (0 == strcasecmp (c->key, "Interval"))
1241 cf_util_get_cdtime (c, &db->interval);
1242 else if (strcasecmp ("CommitInterval", c->key) == 0)
1243 cf_util_get_cdtime (c, &db->commit_interval);
1245 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1248 /* If no `Query' options were given, add the default queries.. */
1249 if ((db->queries_num == 0) && (db->writers_num == 0)){
1250 for (i = 0; i < def_queries_num; i++)
1251 udb_query_pick_from_list_by_name (def_queries[i],
1252 queries, queries_num,
1253 &db->queries, &db->queries_num);
1256 if (db->queries_num > 0) {
1257 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1258 db->queries_num, sizeof (*db->q_prep_areas));
1260 if (db->q_prep_areas == NULL) {
1261 log_err ("Out of memory.");
1262 c_psql_database_delete (db);
1267 for (i = 0; (size_t)i < db->queries_num; ++i) {
1268 c_psql_user_data_t *data;
1269 data = udb_query_get_user_data (db->queries[i]);
1270 if ((data != NULL) && (data->params_num > db->max_params_num))
1271 db->max_params_num = data->params_num;
1274 = udb_query_allocate_preparation_area (db->queries[i]);
1276 if (db->q_prep_areas[i] == NULL) {
1277 log_err ("Out of memory.");
1278 c_psql_database_delete (db);
1284 ud.free_func = c_psql_database_delete;
1286 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
1288 if (db->queries_num > 0) {
1289 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1292 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1293 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1296 if (db->writers_num > 0) {
1298 plugin_register_write (cb_name, c_psql_write, &ud);
1302 plugin_register_flush ("postgresql",
1303 c_psql_flush, /* user data = */ NULL);
1307 /* flush this connection only */
1309 plugin_register_flush (cb_name, c_psql_flush, &ud);
1311 else if (db->commit_interval > 0) {
1312 log_warn ("Database '%s': You do not have any writers assigned to "
1313 "this database connection. Setting 'CommitInterval' does "
1314 "not have any effect.", db->database);
1317 } /* c_psql_config_database */
1319 static int c_psql_config (oconfig_item_t *ci)
1321 static int have_def_config = 0;
1325 if (0 == have_def_config) {
1328 have_def_config = 1;
1330 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1332 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1336 if (NULL == queries)
1337 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1338 "any queries - please check your installation.");
1341 for (i = 0; i < ci->children_num; ++i) {
1342 oconfig_item_t *c = ci->children + i;
1344 if (0 == strcasecmp (c->key, "Query"))
1345 udb_query_create (&queries, &queries_num, c,
1346 /* callback = */ config_query_callback);
1347 else if (0 == strcasecmp (c->key, "Writer"))
1348 c_psql_config_writer (c);
1349 else if (0 == strcasecmp (c->key, "Database"))
1350 c_psql_config_database (c);
1352 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1355 } /* c_psql_config */
1357 void module_register (void)
1359 plugin_register_complex_config ("postgresql", c_psql_config);
1360 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1361 } /* module_register */
1363 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */