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,
106 /* Parameter configuration. Stored as `user data' in the query objects. */
108 c_psql_param_t *params;
110 } c_psql_user_data_t;
120 c_complain_t conn_complaint;
127 /* user configuration */
128 udb_query_preparation_area_t **q_prep_areas;
129 udb_query_t **queries;
132 c_psql_writer_t **writers;
135 /* make sure we don't access the database object in parallel */
136 pthread_mutex_t db_lock;
140 /* writer "caching" settings */
141 cdtime_t commit_interval;
142 cdtime_t next_commit;
157 static char *def_queries[] = {
166 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
168 static udb_query_t **queries = NULL;
169 static size_t queries_num = 0;
171 static c_psql_writer_t *writers = NULL;
172 static size_t writers_num = 0;
174 static c_psql_database_t *c_psql_database_new (const char *name)
176 c_psql_database_t *db;
178 db = (c_psql_database_t *)malloc (sizeof (*db));
180 log_err ("Out of memory.");
186 C_COMPLAIN_INIT (&db->conn_complaint);
188 db->proto_version = 0;
189 db->server_version = 0;
191 db->max_params_num = 0;
193 db->q_prep_areas = NULL;
200 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
204 db->commit_interval = 0;
207 db->database = sstrdup (name);
215 db->krbsrvname = NULL;
219 } /* c_psql_database_new */
221 static void c_psql_database_delete (void *data)
225 c_psql_database_t *db = data;
230 if (db->q_prep_areas)
231 for (i = 0; i < db->queries_num; ++i)
232 udb_query_delete_preparation_area (db->q_prep_areas[i]);
233 free (db->q_prep_areas);
241 /* wait for the lock to be released by the last writer */
242 pthread_mutex_lock (&db->db_lock);
243 pthread_mutex_unlock (&db->db_lock);
245 pthread_mutex_destroy (&db->db_lock);
247 sfree (db->database);
251 sfree (db->password);
255 sfree (db->krbsrvname);
259 } /* c_psql_database_delete */
261 static int c_psql_connect (c_psql_database_t *db)
264 char *buf = conninfo;
265 int buf_len = sizeof (conninfo);
271 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
277 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
278 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
279 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
280 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
281 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
282 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
283 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
285 db->conn = PQconnectdb (conninfo);
286 db->proto_version = PQprotocolVersion (db->conn);
288 } /* c_psql_connect */
290 static int c_psql_check_connection (c_psql_database_t *db)
297 /* trigger c_release() */
298 if (0 == db->conn_complaint.interval)
299 db->conn_complaint.interval = 1;
305 PQclear (PQexec (db->conn, "SELECT 42;"));
307 if (CONNECTION_OK != PQstatus (db->conn)) {
310 /* trigger c_release() */
311 if (0 == db->conn_complaint.interval)
312 db->conn_complaint.interval = 1;
314 if (CONNECTION_OK != PQstatus (db->conn)) {
315 c_complain (LOG_ERR, &db->conn_complaint,
316 "Failed to connect to database %s: %s",
317 db->database, PQerrorMessage (db->conn));
321 db->proto_version = PQprotocolVersion (db->conn);
324 db->server_version = PQserverVersion (db->conn);
326 if (c_would_release (&db->conn_complaint)) {
330 server_host = PQhost (db->conn);
331 server_version = PQserverVersion (db->conn);
333 c_do_release (LOG_INFO, &db->conn_complaint,
334 "Successfully %sconnected to database %s (user %s) "
335 "at server %s%s%s (server version: %d.%d.%d, "
336 "protocol version: %d, pid: %d)", init ? "" : "re",
337 PQdb (db->conn), PQuser (db->conn),
338 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
339 C_PSQL_SERVER_VERSION3 (server_version),
340 db->proto_version, PQbackendPID (db->conn));
342 if (3 > db->proto_version)
343 log_warn ("Protocol version %d does not support parameters.",
347 } /* c_psql_check_connection */
349 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
352 return PQexec (db->conn, udb_query_get_statement (q));
353 } /* c_psql_exec_query_noparams */
355 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
356 udb_query_t *q, c_psql_user_data_t *data)
358 char *params[db->max_params_num];
362 if ((data == NULL) || (data->params_num == 0))
363 return (c_psql_exec_query_noparams (db, q));
365 assert (db->max_params_num >= data->params_num);
367 for (i = 0; i < data->params_num; ++i) {
368 switch (data->params[i]) {
369 case C_PSQL_PARAM_HOST:
370 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
371 ? "localhost" : db->host;
373 case C_PSQL_PARAM_DB:
374 params[i] = db->database;
376 case C_PSQL_PARAM_USER:
377 params[i] = db->user;
379 case C_PSQL_PARAM_INTERVAL:
380 ssnprintf (interval, sizeof (interval), "%.3f",
382 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
383 params[i] = interval;
390 return PQexecParams (db->conn, udb_query_get_statement (q),
391 data->params_num, NULL,
392 (const char *const *) params,
393 NULL, NULL, /* return text data */ 0);
394 } /* c_psql_exec_query_params */
396 /* db->db_lock must be locked when calling this function */
397 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
398 udb_query_preparation_area_t *prep_area)
402 c_psql_user_data_t *data;
407 char **column_values;
414 /* The user data may hold parameter information, but may be NULL. */
415 data = udb_query_get_user_data (q);
417 /* Versions up to `3' don't know how to handle parameters. */
418 if (3 <= db->proto_version)
419 res = c_psql_exec_query_params (db, q, data);
420 else if ((NULL == data) || (0 == data->params_num))
421 res = c_psql_exec_query_noparams (db, q);
423 log_err ("Connection to database \"%s\" does not support parameters "
424 "(protocol version %d) - cannot execute query \"%s\".",
425 db->database, db->proto_version,
426 udb_query_get_name (q));
430 /* give c_psql_write() a chance to acquire the lock if called recursively
431 * through dispatch_values(); this will happen if, both, queries and
432 * writers are configured for a single connection */
433 pthread_mutex_unlock (&db->db_lock);
436 column_values = NULL;
438 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
439 pthread_mutex_lock (&db->db_lock);
441 log_err ("Failed to execute SQL query: %s",
442 PQerrorMessage (db->conn));
443 log_info ("SQL query was: %s",
444 udb_query_get_statement (q));
449 #define BAIL_OUT(status) \
450 sfree (column_names); \
451 sfree (column_values); \
453 pthread_mutex_lock (&db->db_lock); \
456 rows_num = PQntuples (res);
461 column_num = PQnfields (res);
462 column_names = (char **) calloc (column_num, sizeof (char *));
463 if (NULL == column_names) {
464 log_err ("calloc failed.");
468 column_values = (char **) calloc (column_num, sizeof (char *));
469 if (NULL == column_values) {
470 log_err ("calloc failed.");
474 for (col = 0; col < column_num; ++col) {
475 /* Pointers returned by `PQfname' are freed by `PQclear' via
477 column_names[col] = PQfname (res, col);
478 if (NULL == column_names[col]) {
479 log_err ("Failed to resolve name of column %i.", col);
484 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
485 || (0 == strcmp (db->host, "localhost")))
490 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
491 db->database, column_names, (size_t) column_num, db->interval);
493 log_err ("udb_query_prepare_result failed with status %i.",
498 for (row = 0; row < rows_num; ++row) {
499 for (col = 0; col < column_num; ++col) {
500 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
502 column_values[col] = PQgetvalue (res, row, col);
503 if (NULL == column_values[col]) {
504 log_err ("Failed to get value at (row = %i, col = %i).",
510 /* check for an error */
511 if (col < column_num)
514 status = udb_query_handle_result (q, prep_area, column_values);
516 log_err ("udb_query_handle_result failed with status %i.",
519 } /* for (row = 0; row < rows_num; ++row) */
521 udb_query_finish_result (q, prep_area);
525 } /* c_psql_exec_query */
527 static int c_psql_read (user_data_t *ud)
529 c_psql_database_t *db;
534 if ((ud == NULL) || (ud->data == NULL)) {
535 log_err ("c_psql_read: Invalid user data.");
541 assert (NULL != db->database);
542 assert (NULL != db->queries);
544 pthread_mutex_lock (&db->db_lock);
546 if (0 != c_psql_check_connection (db)) {
547 pthread_mutex_unlock (&db->db_lock);
551 for (i = 0; i < db->queries_num; ++i)
553 udb_query_preparation_area_t *prep_area;
556 prep_area = db->q_prep_areas[i];
559 if ((0 != db->server_version)
560 && (udb_query_check_version (q, db->server_version) <= 0))
563 if (0 == c_psql_exec_query (db, q, prep_area))
567 pthread_mutex_unlock (&db->db_lock);
574 static char *values_name_to_sqlarray (const data_set_t *ds,
575 char *string, size_t string_len)
583 str_len = string_len;
585 for (i = 0; i < ds->ds_num; ++i) {
586 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
590 else if ((size_t)status >= str_len) {
596 str_len -= (size_t)status;
601 log_err ("c_psql_write: Failed to stringify value names");
605 /* overwrite the first comma */
611 } /* values_name_to_sqlarray */
613 static char *values_type_to_sqlarray (const data_set_t *ds,
614 char *string, size_t string_len, _Bool store_rates)
622 str_len = string_len;
624 for (i = 0; i < ds->ds_num; ++i) {
628 status = ssnprintf(str_ptr, str_len, ",'gauge'");
630 status = ssnprintf(str_ptr, str_len, ",'%s'",
631 DS_TYPE_TO_STRING (ds->ds[i].type));
637 else if ((size_t)status >= str_len) {
643 str_len -= (size_t)status;
648 log_err ("c_psql_write: Failed to stringify value types");
652 /* overwrite the first comma */
658 } /* values_type_to_sqlarray */
660 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
661 char *string, size_t string_len, _Bool store_rates)
666 gauge_t *rates = NULL;
671 str_len = string_len;
673 for (i = 0; i < vl->values_len; ++i) {
676 if ((ds->ds[i].type != DS_TYPE_GAUGE)
677 && (ds->ds[i].type != DS_TYPE_COUNTER)
678 && (ds->ds[i].type != DS_TYPE_DERIVE)
679 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
680 log_err ("c_psql_write: Unknown data source type: %i",
686 if (ds->ds[i].type == DS_TYPE_GAUGE)
687 status = ssnprintf (str_ptr, str_len,
688 ",%f", vl->values[i].gauge);
689 else if (store_rates) {
691 rates = uc_get_rate (ds, vl);
694 log_err ("c_psql_write: Failed to determine rate");
698 status = ssnprintf (str_ptr, str_len,
701 else if (ds->ds[i].type == DS_TYPE_COUNTER)
702 status = ssnprintf (str_ptr, str_len,
703 ",%llu", vl->values[i].counter);
704 else if (ds->ds[i].type == DS_TYPE_DERIVE)
705 status = ssnprintf (str_ptr, str_len,
706 ",%"PRIi64, vl->values[i].derive);
707 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
708 status = ssnprintf (str_ptr, str_len,
709 ",%"PRIu64, vl->values[i].absolute);
715 else if ((size_t)status >= str_len) {
721 str_len -= (size_t)status;
728 log_err ("c_psql_write: Failed to stringify value list");
732 /* overwrite the first comma */
738 } /* values_to_sqlarray */
740 static int c_psql_begin (c_psql_database_t *db)
742 PGresult *r = PQexec (db->conn, "BEGIN");
747 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
748 db->next_commit = cdtime() + db->commit_interval;
752 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
753 PQerrorMessage (db->conn));
759 static int c_psql_commit (c_psql_database_t *db)
761 PGresult *r = PQexec (db->conn, "COMMIT");
766 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
767 db->next_commit = cdtime () + db->commit_interval;
768 log_debug ("Successfully committed transaction.");
772 log_warn ("Failed to commit transaction: %s",
773 PQerrorMessage (db->conn));
777 } /* c_psql_commit */
779 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
782 c_psql_database_t *db;
785 char values_name_str[1024];
786 char values_type_str[1024];
787 char values_str[1024];
789 const char *params[9];
794 if ((ud == NULL) || (ud->data == NULL)) {
795 log_err ("c_psql_write: Invalid user data.");
800 assert (db->database != NULL);
801 assert (db->writers != NULL);
803 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
804 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
808 if (values_name_to_sqlarray (ds,
809 values_name_str, sizeof (values_name_str)) == NULL)
812 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
814 params[0] = time_str;
815 params[1] = vl->host;
816 params[2] = vl->plugin;
817 params[3] = VALUE_OR_NULL(vl->plugin_instance);
818 params[4] = vl->type;
819 params[5] = VALUE_OR_NULL(vl->type_instance);
820 params[6] = values_name_str;
824 pthread_mutex_lock (&db->db_lock);
826 if (0 != c_psql_check_connection (db)) {
827 pthread_mutex_unlock (&db->db_lock);
831 if ((db->commit_interval > 0)
832 && (db->next_commit == 0))
835 for (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,
842 values_type_str, sizeof (values_type_str),
843 writer->store_rates) == NULL) {
844 pthread_mutex_unlock (&db->db_lock);
848 if (values_to_sqlarray (ds, vl,
849 values_str, sizeof (values_str),
850 writer->store_rates) == NULL) {
851 pthread_mutex_unlock (&db->db_lock);
855 params[7] = values_type_str;
856 params[8] = values_str;
858 res = PQexecParams (db->conn, writer->statement,
859 STATIC_ARRAY_SIZE (params), NULL,
860 (const char *const *)params,
861 NULL, NULL, /* return text data */ 0);
863 if ((PGRES_COMMAND_OK != PQresultStatus (res))
864 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
865 if ((CONNECTION_OK != PQstatus (db->conn))
866 && (0 == c_psql_check_connection (db))) {
870 res = PQexecParams (db->conn, writer->statement,
871 STATIC_ARRAY_SIZE (params), NULL,
872 (const char *const *)params,
873 NULL, NULL, /* return text data */ 0);
875 if ((PGRES_COMMAND_OK == PQresultStatus (res))
876 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
882 log_err ("Failed to execute SQL query: %s",
883 PQerrorMessage (db->conn));
884 log_info ("SQL query was: '%s', "
885 "params: %s, %s, %s, %s, %s, %s, %s, %s",
887 params[0], params[1], params[2], params[3],
888 params[4], params[5], params[6], params[7]);
889 pthread_mutex_unlock (&db->db_lock);
895 if ((db->next_commit > 0)
896 && (cdtime () > db->next_commit))
897 if (c_psql_commit (db) == 0)
900 pthread_mutex_unlock (&db->db_lock);
907 static int c_psql_shutdown (void)
909 plugin_unregister_read_group ("postgresql");
911 udb_query_free (queries, queries_num);
920 } /* c_psql_shutdown */
922 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
924 c_psql_user_data_t *data;
925 const char *param_str;
929 data = udb_query_get_user_data (q);
931 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
933 log_err ("Out of memory.");
936 memset (data, 0, sizeof (*data));
940 tmp = (c_psql_param_t *) realloc (data->params,
941 (data->params_num + 1) * sizeof (c_psql_param_t));
943 log_err ("Out of memory.");
948 param_str = ci->values[0].value.string;
949 if (0 == strcasecmp (param_str, "hostname"))
950 data->params[data->params_num] = C_PSQL_PARAM_HOST;
951 else if (0 == strcasecmp (param_str, "database"))
952 data->params[data->params_num] = C_PSQL_PARAM_DB;
953 else if (0 == strcasecmp (param_str, "username"))
954 data->params[data->params_num] = C_PSQL_PARAM_USER;
955 else if (0 == strcasecmp (param_str, "interval"))
956 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
958 log_err ("Invalid parameter \"%s\".", param_str);
963 udb_query_set_user_data (q, data);
966 } /* config_query_param_add */
968 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
970 if (0 == strcasecmp ("Param", ci->key))
971 return config_query_param_add (q, ci);
973 log_err ("Option not allowed within a Query block: `%s'", ci->key);
976 } /* config_query_callback */
978 static int config_add_writer (oconfig_item_t *ci,
979 c_psql_writer_t *src_writers, size_t src_writers_num,
980 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
986 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
989 if ((ci->values_num != 1)
990 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
991 log_err ("`Writer' expects a single string argument.");
995 name = ci->values[0].value.string;
997 for (i = 0; i < src_writers_num; ++i) {
998 c_psql_writer_t **tmp;
1000 if (strcasecmp (name, src_writers[i].name) != 0)
1003 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1004 sizeof (**dst_writers) * (*dst_writers_num + 1));
1006 log_err ("Out of memory.");
1010 tmp[*dst_writers_num] = src_writers + i;
1013 ++(*dst_writers_num);
1017 if (i >= src_writers_num) {
1018 log_err ("No such writer: `%s'", name);
1023 } /* config_add_writer */
1025 static int c_psql_config_writer (oconfig_item_t *ci)
1027 c_psql_writer_t *writer;
1028 c_psql_writer_t *tmp;
1033 if ((ci->values_num != 1)
1034 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1035 log_err ("<Writer> expects a single string argument.");
1039 tmp = (c_psql_writer_t *)realloc (writers,
1040 sizeof (*writers) * (writers_num + 1));
1042 log_err ("Out of memory.");
1047 writer = writers + writers_num;
1050 writer->name = sstrdup (ci->values[0].value.string);
1051 writer->statement = NULL;
1052 writer->store_rates = 1;
1054 for (i = 0; i < ci->children_num; ++i) {
1055 oconfig_item_t *c = ci->children + i;
1057 if (strcasecmp ("Statement", c->key) == 0)
1058 status = cf_util_get_string (c, &writer->statement);
1059 else if (strcasecmp ("StoreRates", c->key) == 0)
1060 status = cf_util_get_boolean (c, &writer->store_rates);
1062 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1066 sfree (writer->statement);
1067 sfree (writer->name);
1073 } /* c_psql_config_writer */
1075 static int c_psql_config_database (oconfig_item_t *ci)
1077 c_psql_database_t *db;
1079 char cb_name[DATA_MAX_NAME_LEN];
1080 struct timespec cb_interval = { 0, 0 };
1085 if ((1 != ci->values_num)
1086 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1087 log_err ("<Database> expects a single string argument.");
1091 memset (&ud, 0, sizeof (ud));
1093 db = c_psql_database_new (ci->values[0].value.string);
1097 for (i = 0; i < ci->children_num; ++i) {
1098 oconfig_item_t *c = ci->children + i;
1100 if (0 == strcasecmp (c->key, "Host"))
1101 cf_util_get_string (c, &db->host);
1102 else if (0 == strcasecmp (c->key, "Port"))
1103 cf_util_get_service (c, &db->port);
1104 else if (0 == strcasecmp (c->key, "User"))
1105 cf_util_get_string (c, &db->user);
1106 else if (0 == strcasecmp (c->key, "Password"))
1107 cf_util_get_string (c, &db->password);
1108 else if (0 == strcasecmp (c->key, "SSLMode"))
1109 cf_util_get_string (c, &db->sslmode);
1110 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1111 cf_util_get_string (c, &db->krbsrvname);
1112 else if (0 == strcasecmp (c->key, "Service"))
1113 cf_util_get_string (c, &db->service);
1114 else if (0 == strcasecmp (c->key, "Query"))
1115 udb_query_pick_from_list (c, queries, queries_num,
1116 &db->queries, &db->queries_num);
1117 else if (0 == strcasecmp (c->key, "Writer"))
1118 config_add_writer (c, writers, writers_num,
1119 &db->writers, &db->writers_num);
1120 else if (0 == strcasecmp (c->key, "Interval"))
1121 cf_util_get_cdtime (c, &db->interval);
1122 else if (strcasecmp ("CommitInterval", c->key) == 0)
1123 cf_util_get_cdtime (c, &db->commit_interval);
1125 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1128 /* If no `Query' options were given, add the default queries.. */
1129 if ((db->queries_num == 0) && (db->writers_num == 0)){
1130 for (i = 0; i < def_queries_num; i++)
1131 udb_query_pick_from_list_by_name (def_queries[i],
1132 queries, queries_num,
1133 &db->queries, &db->queries_num);
1136 if (db->queries_num > 0) {
1137 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1138 db->queries_num, sizeof (*db->q_prep_areas));
1140 if (db->q_prep_areas == NULL) {
1141 log_err ("Out of memory.");
1142 c_psql_database_delete (db);
1147 for (i = 0; (size_t)i < db->queries_num; ++i) {
1148 c_psql_user_data_t *data;
1149 data = udb_query_get_user_data (db->queries[i]);
1150 if ((data != NULL) && (data->params_num > db->max_params_num))
1151 db->max_params_num = data->params_num;
1154 = udb_query_allocate_preparation_area (db->queries[i]);
1156 if (db->q_prep_areas[i] == NULL) {
1157 log_err ("Out of memory.");
1158 c_psql_database_delete (db);
1164 ud.free_func = c_psql_database_delete;
1166 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
1168 if (db->queries_num > 0) {
1169 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1171 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1172 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1175 if (db->writers_num > 0) {
1176 plugin_register_write (cb_name, c_psql_write, &ud);
1178 else if (db->commit_interval > 0) {
1179 log_warn ("Database '%s': You do not have any writers assigned to "
1180 "this database connection. Setting 'CommitInterval' does "
1181 "not have any effect.", db->database);
1184 } /* c_psql_config_database */
1186 static int c_psql_config (oconfig_item_t *ci)
1188 static int have_def_config = 0;
1192 if (0 == have_def_config) {
1195 have_def_config = 1;
1197 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1199 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1203 if (NULL == queries)
1204 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1205 "any queries - please check your installation.");
1208 for (i = 0; i < ci->children_num; ++i) {
1209 oconfig_item_t *c = ci->children + i;
1211 if (0 == strcasecmp (c->key, "Query"))
1212 udb_query_create (&queries, &queries_num, c,
1213 /* callback = */ config_query_callback);
1214 else if (0 == strcasecmp (c->key, "Writer"))
1215 c_psql_config_writer (c);
1216 else if (0 == strcasecmp (c->key, "Database"))
1217 c_psql_config_database (c);
1219 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1222 } /* c_psql_config */
1224 void module_register (void)
1226 plugin_register_complex_config ("postgresql", c_psql_config);
1227 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1228 } /* module_register */
1230 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */