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;
159 static char *def_queries[] = {
168 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
170 static c_psql_database_t *databases = NULL;
171 static size_t databases_num = 0;
173 static udb_query_t **queries = NULL;
174 static size_t queries_num = 0;
176 static c_psql_writer_t *writers = NULL;
177 static size_t writers_num = 0;
179 static int c_psql_begin (c_psql_database_t *db)
181 PGresult *r = PQexec (db->conn, "BEGIN");
186 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
187 db->next_commit = cdtime() + db->commit_interval;
191 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
192 PQerrorMessage (db->conn));
198 static int c_psql_commit (c_psql_database_t *db)
200 PGresult *r = PQexec (db->conn, "COMMIT");
205 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
206 db->next_commit = cdtime () + db->commit_interval;
207 log_debug ("Successfully committed transaction.");
211 log_warn ("Failed to commit transaction: %s",
212 PQerrorMessage (db->conn));
216 } /* c_psql_commit */
218 static c_psql_database_t *c_psql_database_new (const char *name)
220 c_psql_database_t *db;
222 db = (c_psql_database_t *)realloc (databases,
223 (databases_num + 1) * sizeof (*db));
225 log_err ("Out of memory.");
230 db = databases + databases_num;
235 C_COMPLAIN_INIT (&db->conn_complaint);
237 db->proto_version = 0;
238 db->server_version = 0;
240 db->max_params_num = 0;
242 db->q_prep_areas = NULL;
249 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
253 db->commit_interval = 0;
256 db->database = sstrdup (name);
264 db->krbsrvname = NULL;
270 } /* c_psql_database_new */
272 static void c_psql_database_delete (void *data)
276 c_psql_database_t *db = data;
279 /* readers and writers may access this database */
283 /* wait for the lock to be released by the last writer */
284 pthread_mutex_lock (&db->db_lock);
286 if (db->next_commit > 0)
292 if (db->q_prep_areas)
293 for (i = 0; i < db->queries_num; ++i)
294 udb_query_delete_preparation_area (db->q_prep_areas[i]);
295 free (db->q_prep_areas);
303 pthread_mutex_unlock (&db->db_lock);
305 pthread_mutex_destroy (&db->db_lock);
307 sfree (db->database);
311 sfree (db->password);
315 sfree (db->krbsrvname);
319 /* don't care about freeing or reordering the 'databases' array
320 * this is done in 'shutdown' */
322 } /* c_psql_database_delete */
324 static int c_psql_connect (c_psql_database_t *db)
327 char *buf = conninfo;
328 int buf_len = sizeof (conninfo);
331 if ((! db) || (! db->database))
334 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
340 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
341 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
342 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
343 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
344 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
345 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
346 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
348 db->conn = PQconnectdb (conninfo);
349 db->proto_version = PQprotocolVersion (db->conn);
351 } /* c_psql_connect */
353 static int c_psql_check_connection (c_psql_database_t *db)
360 /* trigger c_release() */
361 if (0 == db->conn_complaint.interval)
362 db->conn_complaint.interval = 1;
368 PQclear (PQexec (db->conn, "SELECT 42;"));
370 if (CONNECTION_OK != PQstatus (db->conn)) {
373 /* trigger c_release() */
374 if (0 == db->conn_complaint.interval)
375 db->conn_complaint.interval = 1;
377 if (CONNECTION_OK != PQstatus (db->conn)) {
378 c_complain (LOG_ERR, &db->conn_complaint,
379 "Failed to connect to database %s: %s",
380 db->database, PQerrorMessage (db->conn));
384 db->proto_version = PQprotocolVersion (db->conn);
387 db->server_version = PQserverVersion (db->conn);
389 if (c_would_release (&db->conn_complaint)) {
393 server_host = PQhost (db->conn);
394 server_version = PQserverVersion (db->conn);
396 c_do_release (LOG_INFO, &db->conn_complaint,
397 "Successfully %sconnected to database %s (user %s) "
398 "at server %s%s%s (server version: %d.%d.%d, "
399 "protocol version: %d, pid: %d)", init ? "" : "re",
400 PQdb (db->conn), PQuser (db->conn),
401 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
402 C_PSQL_SERVER_VERSION3 (server_version),
403 db->proto_version, PQbackendPID (db->conn));
405 if (3 > db->proto_version)
406 log_warn ("Protocol version %d does not support parameters.",
410 } /* c_psql_check_connection */
412 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
415 return PQexec (db->conn, udb_query_get_statement (q));
416 } /* c_psql_exec_query_noparams */
418 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
419 udb_query_t *q, c_psql_user_data_t *data)
421 char *params[db->max_params_num];
425 if ((data == NULL) || (data->params_num == 0))
426 return (c_psql_exec_query_noparams (db, q));
428 assert (db->max_params_num >= data->params_num);
430 for (i = 0; i < data->params_num; ++i) {
431 switch (data->params[i]) {
432 case C_PSQL_PARAM_HOST:
433 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
434 ? "localhost" : db->host;
436 case C_PSQL_PARAM_DB:
437 params[i] = db->database;
439 case C_PSQL_PARAM_USER:
440 params[i] = db->user;
442 case C_PSQL_PARAM_INTERVAL:
443 ssnprintf (interval, sizeof (interval), "%.3f",
445 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
446 params[i] = interval;
453 return PQexecParams (db->conn, udb_query_get_statement (q),
454 data->params_num, NULL,
455 (const char *const *) params,
456 NULL, NULL, /* return text data */ 0);
457 } /* c_psql_exec_query_params */
459 /* db->db_lock must be locked when calling this function */
460 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
461 udb_query_preparation_area_t *prep_area)
465 c_psql_user_data_t *data;
470 char **column_values;
477 /* The user data may hold parameter information, but may be NULL. */
478 data = udb_query_get_user_data (q);
480 /* Versions up to `3' don't know how to handle parameters. */
481 if (3 <= db->proto_version)
482 res = c_psql_exec_query_params (db, q, data);
483 else if ((NULL == data) || (0 == data->params_num))
484 res = c_psql_exec_query_noparams (db, q);
486 log_err ("Connection to database \"%s\" does not support parameters "
487 "(protocol version %d) - cannot execute query \"%s\".",
488 db->database, db->proto_version,
489 udb_query_get_name (q));
493 /* give c_psql_write() a chance to acquire the lock if called recursively
494 * through dispatch_values(); this will happen if, both, queries and
495 * writers are configured for a single connection */
496 pthread_mutex_unlock (&db->db_lock);
499 column_values = NULL;
501 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
502 pthread_mutex_lock (&db->db_lock);
504 log_err ("Failed to execute SQL query: %s",
505 PQerrorMessage (db->conn));
506 log_info ("SQL query was: %s",
507 udb_query_get_statement (q));
512 #define BAIL_OUT(status) \
513 sfree (column_names); \
514 sfree (column_values); \
516 pthread_mutex_lock (&db->db_lock); \
519 rows_num = PQntuples (res);
524 column_num = PQnfields (res);
525 column_names = (char **) calloc (column_num, sizeof (char *));
526 if (NULL == column_names) {
527 log_err ("calloc failed.");
531 column_values = (char **) calloc (column_num, sizeof (char *));
532 if (NULL == column_values) {
533 log_err ("calloc failed.");
537 for (col = 0; col < column_num; ++col) {
538 /* Pointers returned by `PQfname' are freed by `PQclear' via
540 column_names[col] = PQfname (res, col);
541 if (NULL == column_names[col]) {
542 log_err ("Failed to resolve name of column %i.", col);
547 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
548 || (0 == strcmp (db->host, "localhost")))
553 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
554 db->database, column_names, (size_t) column_num, db->interval);
556 log_err ("udb_query_prepare_result failed with status %i.",
561 for (row = 0; row < rows_num; ++row) {
562 for (col = 0; col < column_num; ++col) {
563 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
565 column_values[col] = PQgetvalue (res, row, col);
566 if (NULL == column_values[col]) {
567 log_err ("Failed to get value at (row = %i, col = %i).",
573 /* check for an error */
574 if (col < column_num)
577 status = udb_query_handle_result (q, prep_area, column_values);
579 log_err ("udb_query_handle_result failed with status %i.",
582 } /* for (row = 0; row < rows_num; ++row) */
584 udb_query_finish_result (q, prep_area);
588 } /* c_psql_exec_query */
590 static int c_psql_read (user_data_t *ud)
592 c_psql_database_t *db;
597 if ((ud == NULL) || (ud->data == NULL)) {
598 log_err ("c_psql_read: Invalid user data.");
604 assert (NULL != db->database);
605 assert (NULL != db->queries);
607 pthread_mutex_lock (&db->db_lock);
609 if (0 != c_psql_check_connection (db)) {
610 pthread_mutex_unlock (&db->db_lock);
614 for (i = 0; i < db->queries_num; ++i)
616 udb_query_preparation_area_t *prep_area;
619 prep_area = db->q_prep_areas[i];
622 if ((0 != db->server_version)
623 && (udb_query_check_version (q, db->server_version) <= 0))
626 if (0 == c_psql_exec_query (db, q, prep_area))
630 pthread_mutex_unlock (&db->db_lock);
637 static char *values_name_to_sqlarray (const data_set_t *ds,
638 char *string, size_t string_len)
646 str_len = string_len;
648 for (i = 0; i < ds->ds_num; ++i) {
649 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
653 else if ((size_t)status >= str_len) {
659 str_len -= (size_t)status;
664 log_err ("c_psql_write: Failed to stringify value names");
668 /* overwrite the first comma */
674 } /* values_name_to_sqlarray */
676 static char *values_type_to_sqlarray (const data_set_t *ds,
677 char *string, size_t string_len, _Bool store_rates)
685 str_len = string_len;
687 for (i = 0; i < ds->ds_num; ++i) {
691 status = ssnprintf(str_ptr, str_len, ",'gauge'");
693 status = ssnprintf(str_ptr, str_len, ",'%s'",
694 DS_TYPE_TO_STRING (ds->ds[i].type));
700 else if ((size_t)status >= str_len) {
706 str_len -= (size_t)status;
711 log_err ("c_psql_write: Failed to stringify value types");
715 /* overwrite the first comma */
721 } /* values_type_to_sqlarray */
723 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
724 char *string, size_t string_len, _Bool store_rates)
729 gauge_t *rates = NULL;
734 str_len = string_len;
736 for (i = 0; i < vl->values_len; ++i) {
739 if ((ds->ds[i].type != DS_TYPE_GAUGE)
740 && (ds->ds[i].type != DS_TYPE_COUNTER)
741 && (ds->ds[i].type != DS_TYPE_DERIVE)
742 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
743 log_err ("c_psql_write: Unknown data source type: %i",
749 if (ds->ds[i].type == DS_TYPE_GAUGE)
750 status = ssnprintf (str_ptr, str_len,
751 ",%f", vl->values[i].gauge);
752 else if (store_rates) {
754 rates = uc_get_rate (ds, vl);
757 log_err ("c_psql_write: Failed to determine rate");
761 status = ssnprintf (str_ptr, str_len,
764 else if (ds->ds[i].type == DS_TYPE_COUNTER)
765 status = ssnprintf (str_ptr, str_len,
766 ",%llu", vl->values[i].counter);
767 else if (ds->ds[i].type == DS_TYPE_DERIVE)
768 status = ssnprintf (str_ptr, str_len,
769 ",%"PRIi64, vl->values[i].derive);
770 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
771 status = ssnprintf (str_ptr, str_len,
772 ",%"PRIu64, vl->values[i].absolute);
778 else if ((size_t)status >= str_len) {
784 str_len -= (size_t)status;
791 log_err ("c_psql_write: Failed to stringify value list");
795 /* overwrite the first comma */
801 } /* values_to_sqlarray */
803 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
806 c_psql_database_t *db;
809 char values_name_str[1024];
810 char values_type_str[1024];
811 char values_str[1024];
813 const char *params[9];
818 if ((ud == NULL) || (ud->data == NULL)) {
819 log_err ("c_psql_write: Invalid user data.");
824 assert (db->database != NULL);
825 assert (db->writers != NULL);
827 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
828 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
832 if (values_name_to_sqlarray (ds,
833 values_name_str, sizeof (values_name_str)) == NULL)
836 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
838 params[0] = time_str;
839 params[1] = vl->host;
840 params[2] = vl->plugin;
841 params[3] = VALUE_OR_NULL(vl->plugin_instance);
842 params[4] = vl->type;
843 params[5] = VALUE_OR_NULL(vl->type_instance);
844 params[6] = values_name_str;
848 pthread_mutex_lock (&db->db_lock);
850 if (0 != c_psql_check_connection (db)) {
851 pthread_mutex_unlock (&db->db_lock);
855 if ((db->commit_interval > 0)
856 && (db->next_commit == 0))
859 for (i = 0; i < db->writers_num; ++i) {
860 c_psql_writer_t *writer;
863 writer = db->writers[i];
865 if (values_type_to_sqlarray (ds,
866 values_type_str, sizeof (values_type_str),
867 writer->store_rates) == NULL) {
868 pthread_mutex_unlock (&db->db_lock);
872 if (values_to_sqlarray (ds, vl,
873 values_str, sizeof (values_str),
874 writer->store_rates) == NULL) {
875 pthread_mutex_unlock (&db->db_lock);
879 params[7] = values_type_str;
880 params[8] = values_str;
882 res = PQexecParams (db->conn, writer->statement,
883 STATIC_ARRAY_SIZE (params), NULL,
884 (const char *const *)params,
885 NULL, NULL, /* return text data */ 0);
887 if ((PGRES_COMMAND_OK != PQresultStatus (res))
888 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
889 if ((CONNECTION_OK != PQstatus (db->conn))
890 && (0 == c_psql_check_connection (db))) {
894 res = PQexecParams (db->conn, writer->statement,
895 STATIC_ARRAY_SIZE (params), NULL,
896 (const char *const *)params,
897 NULL, NULL, /* return text data */ 0);
899 if ((PGRES_COMMAND_OK == PQresultStatus (res))
900 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
906 log_err ("Failed to execute SQL query: %s",
907 PQerrorMessage (db->conn));
908 log_info ("SQL query was: '%s', "
909 "params: %s, %s, %s, %s, %s, %s, %s, %s",
911 params[0], params[1], params[2], params[3],
912 params[4], params[5], params[6], params[7]);
914 /* this will abort any current transaction -> restart */
915 if (db->next_commit > 0)
916 if (c_psql_commit (db) == 0)
919 pthread_mutex_unlock (&db->db_lock);
925 if ((db->next_commit > 0)
926 && (cdtime () > db->next_commit))
927 if (c_psql_commit (db) == 0)
930 pthread_mutex_unlock (&db->db_lock);
937 static int c_psql_shutdown (void)
941 plugin_unregister_read_group ("postgresql");
943 for (i = 0; i < databases_num; ++i) {
944 c_psql_database_t *db = databases + i;
947 for (j = 0; j < db->writers_num; ++j) {
948 char cb_name[DATA_MAX_NAME_LEN];
950 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s",
952 plugin_unregister_write (cb_name);
956 udb_query_free (queries, queries_num);
969 } /* c_psql_shutdown */
971 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 = (c_psql_user_data_t *) smalloc (sizeof (*data));
982 log_err ("Out of memory.");
985 memset (data, 0, sizeof (*data));
989 tmp = (c_psql_param_t *) realloc (data->params,
990 (data->params_num + 1) * sizeof (c_psql_param_t));
992 log_err ("Out of memory.");
997 param_str = ci->values[0].value.string;
998 if (0 == strcasecmp (param_str, "hostname"))
999 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1000 else if (0 == strcasecmp (param_str, "database"))
1001 data->params[data->params_num] = C_PSQL_PARAM_DB;
1002 else if (0 == strcasecmp (param_str, "username"))
1003 data->params[data->params_num] = C_PSQL_PARAM_USER;
1004 else if (0 == strcasecmp (param_str, "interval"))
1005 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1007 log_err ("Invalid parameter \"%s\".", param_str);
1012 udb_query_set_user_data (q, data);
1015 } /* config_query_param_add */
1017 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,
1028 c_psql_writer_t *src_writers, size_t src_writers_num,
1029 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
1035 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1038 if ((ci->values_num != 1)
1039 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1040 log_err ("`Writer' expects a single string argument.");
1044 name = ci->values[0].value.string;
1046 for (i = 0; i < src_writers_num; ++i) {
1047 c_psql_writer_t **tmp;
1049 if (strcasecmp (name, src_writers[i].name) != 0)
1052 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1053 sizeof (**dst_writers) * (*dst_writers_num + 1));
1055 log_err ("Out of memory.");
1059 tmp[*dst_writers_num] = src_writers + i;
1062 ++(*dst_writers_num);
1066 if (i >= src_writers_num) {
1067 log_err ("No such writer: `%s'", name);
1072 } /* config_add_writer */
1074 static int c_psql_config_writer (oconfig_item_t *ci)
1076 c_psql_writer_t *writer;
1077 c_psql_writer_t *tmp;
1082 if ((ci->values_num != 1)
1083 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1084 log_err ("<Writer> expects a single string argument.");
1088 tmp = (c_psql_writer_t *)realloc (writers,
1089 sizeof (*writers) * (writers_num + 1));
1091 log_err ("Out of memory.");
1096 writer = writers + writers_num;
1099 writer->name = sstrdup (ci->values[0].value.string);
1100 writer->statement = NULL;
1101 writer->store_rates = 1;
1103 for (i = 0; i < ci->children_num; ++i) {
1104 oconfig_item_t *c = ci->children + i;
1106 if (strcasecmp ("Statement", c->key) == 0)
1107 status = cf_util_get_string (c, &writer->statement);
1108 else if (strcasecmp ("StoreRates", c->key) == 0)
1109 status = cf_util_get_boolean (c, &writer->store_rates);
1111 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1115 sfree (writer->statement);
1116 sfree (writer->name);
1122 } /* c_psql_config_writer */
1124 static int c_psql_config_database (oconfig_item_t *ci)
1126 c_psql_database_t *db;
1128 char cb_name[DATA_MAX_NAME_LEN];
1129 struct timespec cb_interval = { 0, 0 };
1134 if ((1 != ci->values_num)
1135 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1136 log_err ("<Database> expects a single string argument.");
1140 memset (&ud, 0, sizeof (ud));
1142 db = c_psql_database_new (ci->values[0].value.string);
1146 for (i = 0; i < ci->children_num; ++i) {
1147 oconfig_item_t *c = ci->children + i;
1149 if (0 == strcasecmp (c->key, "Host"))
1150 cf_util_get_string (c, &db->host);
1151 else if (0 == strcasecmp (c->key, "Port"))
1152 cf_util_get_service (c, &db->port);
1153 else if (0 == strcasecmp (c->key, "User"))
1154 cf_util_get_string (c, &db->user);
1155 else if (0 == strcasecmp (c->key, "Password"))
1156 cf_util_get_string (c, &db->password);
1157 else if (0 == strcasecmp (c->key, "SSLMode"))
1158 cf_util_get_string (c, &db->sslmode);
1159 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1160 cf_util_get_string (c, &db->krbsrvname);
1161 else if (0 == strcasecmp (c->key, "Service"))
1162 cf_util_get_string (c, &db->service);
1163 else if (0 == strcasecmp (c->key, "Query"))
1164 udb_query_pick_from_list (c, queries, queries_num,
1165 &db->queries, &db->queries_num);
1166 else if (0 == strcasecmp (c->key, "Writer"))
1167 config_add_writer (c, writers, writers_num,
1168 &db->writers, &db->writers_num);
1169 else if (0 == strcasecmp (c->key, "Interval"))
1170 cf_util_get_cdtime (c, &db->interval);
1171 else if (strcasecmp ("CommitInterval", c->key) == 0)
1172 cf_util_get_cdtime (c, &db->commit_interval);
1174 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1177 /* If no `Query' options were given, add the default queries.. */
1178 if ((db->queries_num == 0) && (db->writers_num == 0)){
1179 for (i = 0; i < def_queries_num; i++)
1180 udb_query_pick_from_list_by_name (def_queries[i],
1181 queries, queries_num,
1182 &db->queries, &db->queries_num);
1185 if (db->queries_num > 0) {
1186 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1187 db->queries_num, sizeof (*db->q_prep_areas));
1189 if (db->q_prep_areas == NULL) {
1190 log_err ("Out of memory.");
1191 c_psql_database_delete (db);
1196 for (i = 0; (size_t)i < db->queries_num; ++i) {
1197 c_psql_user_data_t *data;
1198 data = udb_query_get_user_data (db->queries[i]);
1199 if ((data != NULL) && (data->params_num > db->max_params_num))
1200 db->max_params_num = data->params_num;
1203 = udb_query_allocate_preparation_area (db->queries[i]);
1205 if (db->q_prep_areas[i] == NULL) {
1206 log_err ("Out of memory.");
1207 c_psql_database_delete (db);
1213 ud.free_func = c_psql_database_delete;
1215 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
1217 if (db->queries_num > 0) {
1218 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1221 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1222 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1225 if (db->writers_num > 0) {
1227 plugin_register_write (cb_name, c_psql_write, &ud);
1229 else if (db->commit_interval > 0) {
1230 log_warn ("Database '%s': You do not have any writers assigned to "
1231 "this database connection. Setting 'CommitInterval' does "
1232 "not have any effect.", db->database);
1235 } /* c_psql_config_database */
1237 static int c_psql_config (oconfig_item_t *ci)
1239 static int have_def_config = 0;
1243 if (0 == have_def_config) {
1246 have_def_config = 1;
1248 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1250 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1254 if (NULL == queries)
1255 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1256 "any queries - please check your installation.");
1259 for (i = 0; i < ci->children_num; ++i) {
1260 oconfig_item_t *c = ci->children + i;
1262 if (0 == strcasecmp (c->key, "Query"))
1263 udb_query_create (&queries, &queries_num, c,
1264 /* callback = */ config_query_callback);
1265 else if (0 == strcasecmp (c->key, "Writer"))
1266 c_psql_config_writer (c);
1267 else if (0 == strcasecmp (c->key, "Database"))
1268 c_psql_config_database (c);
1270 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1273 } /* c_psql_config */
1275 void module_register (void)
1277 plugin_register_complex_config ("postgresql", c_psql_config);
1278 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1279 } /* module_register */
1281 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */