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.
36 #include "configfile.h"
39 #include "utils_cache.h"
40 #include "utils_db_query.h"
41 #include "utils_complain.h"
47 #include <pg_config_manual.h>
50 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
51 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
52 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
53 #define log_debug(...) DEBUG ("postgresql: " __VA_ARGS__)
55 #ifndef C_PSQL_DEFAULT_CONF
56 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
59 /* Appends the (parameter, value) pair to the string
60 * pointed to by 'buf' suitable to be used as argument
61 * for PQconnectdb(). If value equals NULL, the pair
63 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
64 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
65 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
72 /* Returns the tuple (major, minor, patchlevel)
73 * for the given version number. */
74 #define C_PSQL_SERVER_VERSION3(server_version) \
75 (server_version) / 10000, \
76 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
77 (server_version) - (int)((server_version) / 100) * 100
79 /* Returns true if the given host specifies a
80 * UNIX domain socket. */
81 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
82 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
84 /* Returns the tuple (host, delimiter, port) for a
85 * given (host, port) pair. Depending on the value of
86 * 'host' a UNIX domain socket or a TCP socket is
88 #define C_PSQL_SOCKET3(host, port) \
89 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
90 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
94 C_PSQL_PARAM_HOST = 1,
97 C_PSQL_PARAM_INTERVAL,
98 C_PSQL_PARAM_INSTANCE,
101 /* Parameter configuration. Stored as `user data' in the query objects. */
103 c_psql_param_t *params;
105 } c_psql_user_data_t;
115 c_complain_t conn_complaint;
122 /* user configuration */
123 udb_query_preparation_area_t **q_prep_areas;
124 udb_query_t **queries;
127 c_psql_writer_t **writers;
130 /* make sure we don't access the database object in parallel */
131 pthread_mutex_t db_lock;
135 /* writer "caching" settings */
136 cdtime_t commit_interval;
137 cdtime_t next_commit;
138 cdtime_t expire_delay;
157 static char *def_queries[] = {
166 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
168 static c_psql_database_t **databases = NULL;
169 static size_t databases_num = 0;
171 static udb_query_t **queries = NULL;
172 static size_t queries_num = 0;
174 static c_psql_writer_t *writers = NULL;
175 static size_t writers_num = 0;
177 static int c_psql_begin (c_psql_database_t *db)
179 PGresult *r = PQexec (db->conn, "BEGIN");
184 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
185 db->next_commit = cdtime() + db->commit_interval;
189 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
190 PQerrorMessage (db->conn));
196 static int c_psql_commit (c_psql_database_t *db)
198 PGresult *r = PQexec (db->conn, "COMMIT");
203 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
205 log_debug ("Successfully committed transaction.");
209 log_warn ("Failed to commit transaction: %s",
210 PQerrorMessage (db->conn));
214 } /* c_psql_commit */
216 static c_psql_database_t *c_psql_database_new (const char *name)
218 c_psql_database_t **tmp;
219 c_psql_database_t *db;
221 db = (c_psql_database_t *)malloc (sizeof(*db));
223 log_err ("Out of memory.");
227 tmp = (c_psql_database_t **)realloc (databases,
228 (databases_num + 1) * sizeof (*databases));
230 log_err ("Out of memory.");
236 databases[databases_num] = db;
241 C_COMPLAIN_INIT (&db->conn_complaint);
243 db->proto_version = 0;
244 db->server_version = 0;
246 db->max_params_num = 0;
248 db->q_prep_areas = NULL;
255 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
259 db->commit_interval = 0;
261 db->expire_delay = 0;
263 db->database = sstrdup (name);
269 db->instance = sstrdup (name);
273 db->krbsrvname = NULL;
279 } /* c_psql_database_new */
281 static void c_psql_database_delete (void *data)
285 c_psql_database_t *db = data;
288 /* readers and writers may access this database */
292 /* wait for the lock to be released by the last writer */
293 pthread_mutex_lock (&db->db_lock);
295 if (db->next_commit > 0)
301 if (db->q_prep_areas)
302 for (i = 0; i < db->queries_num; ++i)
303 udb_query_delete_preparation_area (db->q_prep_areas[i]);
304 free (db->q_prep_areas);
312 pthread_mutex_unlock (&db->db_lock);
314 pthread_mutex_destroy (&db->db_lock);
316 sfree (db->database);
320 sfree (db->password);
322 sfree (db->instance);
326 sfree (db->krbsrvname);
330 /* don't care about freeing or reordering the 'databases' array
331 * this is done in 'shutdown'; also, don't free the database instance
332 * object just to make sure that in case anybody accesses it before
333 * shutdown won't segfault */
335 } /* c_psql_database_delete */
337 static int c_psql_connect (c_psql_database_t *db)
340 char *buf = conninfo;
341 int buf_len = sizeof (conninfo);
344 if ((! db) || (! db->database))
347 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
353 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
354 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
355 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
356 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
357 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
358 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
359 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
361 db->conn = PQconnectdb (conninfo);
362 db->proto_version = PQprotocolVersion (db->conn);
364 } /* c_psql_connect */
366 static int c_psql_check_connection (c_psql_database_t *db)
373 /* trigger c_release() */
374 if (0 == db->conn_complaint.interval)
375 db->conn_complaint.interval = 1;
380 if (CONNECTION_OK != PQstatus (db->conn)) {
383 /* trigger c_release() */
384 if (0 == db->conn_complaint.interval)
385 db->conn_complaint.interval = 1;
387 if (CONNECTION_OK != PQstatus (db->conn)) {
388 c_complain (LOG_ERR, &db->conn_complaint,
389 "Failed to connect to database %s (%s): %s",
390 db->database, db->instance,
391 PQerrorMessage (db->conn));
395 db->proto_version = PQprotocolVersion (db->conn);
398 db->server_version = PQserverVersion (db->conn);
400 if (c_would_release (&db->conn_complaint)) {
404 server_host = PQhost (db->conn);
405 server_version = PQserverVersion (db->conn);
407 c_do_release (LOG_INFO, &db->conn_complaint,
408 "Successfully %sconnected to database %s (user %s) "
409 "at server %s%s%s (server version: %d.%d.%d, "
410 "protocol version: %d, pid: %d)", init ? "" : "re",
411 PQdb (db->conn), PQuser (db->conn),
412 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
413 C_PSQL_SERVER_VERSION3 (server_version),
414 db->proto_version, PQbackendPID (db->conn));
416 if (3 > db->proto_version)
417 log_warn ("Protocol version %d does not support parameters.",
421 } /* c_psql_check_connection */
423 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
426 return PQexec (db->conn, udb_query_get_statement (q));
427 } /* c_psql_exec_query_noparams */
429 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
430 udb_query_t *q, c_psql_user_data_t *data)
432 char *params[db->max_params_num];
436 if ((data == NULL) || (data->params_num == 0))
437 return (c_psql_exec_query_noparams (db, q));
439 assert (db->max_params_num >= data->params_num);
441 for (i = 0; i < data->params_num; ++i) {
442 switch (data->params[i]) {
443 case C_PSQL_PARAM_HOST:
444 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
445 ? "localhost" : db->host;
447 case C_PSQL_PARAM_DB:
448 params[i] = db->database;
450 case C_PSQL_PARAM_USER:
451 params[i] = db->user;
453 case C_PSQL_PARAM_INTERVAL:
454 ssnprintf (interval, sizeof (interval), "%.3f",
456 ? CDTIME_T_TO_DOUBLE (db->interval)
457 : plugin_get_interval ());
458 params[i] = interval;
460 case C_PSQL_PARAM_INSTANCE:
461 params[i] = db->instance;
468 return PQexecParams (db->conn, udb_query_get_statement (q),
469 data->params_num, NULL,
470 (const char *const *) params,
471 NULL, NULL, /* return text data */ 0);
472 } /* c_psql_exec_query_params */
474 /* db->db_lock must be locked when calling this function */
475 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
476 udb_query_preparation_area_t *prep_area)
480 c_psql_user_data_t *data;
485 char **column_values;
492 /* The user data may hold parameter information, but may be NULL. */
493 data = udb_query_get_user_data (q);
495 /* Versions up to `3' don't know how to handle parameters. */
496 if (3 <= db->proto_version)
497 res = c_psql_exec_query_params (db, q, data);
498 else if ((NULL == data) || (0 == data->params_num))
499 res = c_psql_exec_query_noparams (db, q);
501 log_err ("Connection to database \"%s\" (%s) does not support "
502 "parameters (protocol version %d) - "
503 "cannot execute query \"%s\".",
504 db->database, db->instance, db->proto_version,
505 udb_query_get_name (q));
509 /* give c_psql_write() a chance to acquire the lock if called recursively
510 * through dispatch_values(); this will happen if, both, queries and
511 * writers are configured for a single connection */
512 pthread_mutex_unlock (&db->db_lock);
515 column_values = NULL;
517 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
518 pthread_mutex_lock (&db->db_lock);
520 if ((CONNECTION_OK != PQstatus (db->conn))
521 && (0 == c_psql_check_connection (db))) {
523 return c_psql_exec_query (db, q, prep_area);
526 log_err ("Failed to execute SQL query: %s",
527 PQerrorMessage (db->conn));
528 log_info ("SQL query was: %s",
529 udb_query_get_statement (q));
534 #define BAIL_OUT(status) \
535 sfree (column_names); \
536 sfree (column_values); \
538 pthread_mutex_lock (&db->db_lock); \
541 rows_num = PQntuples (res);
546 column_num = PQnfields (res);
547 column_names = (char **) calloc (column_num, sizeof (char *));
548 if (NULL == column_names) {
549 log_err ("calloc failed.");
553 column_values = (char **) calloc (column_num, sizeof (char *));
554 if (NULL == column_values) {
555 log_err ("calloc failed.");
559 for (col = 0; col < column_num; ++col) {
560 /* Pointers returned by `PQfname' are freed by `PQclear' via
562 column_names[col] = PQfname (res, col);
563 if (NULL == column_names[col]) {
564 log_err ("Failed to resolve name of column %i.", col);
569 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
570 || (0 == strcmp (db->host, "127.0.0.1"))
571 || (0 == strcmp (db->host, "localhost")))
576 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
577 db->instance, column_names, (size_t) column_num, db->interval);
579 log_err ("udb_query_prepare_result failed with status %i.",
584 for (row = 0; row < rows_num; ++row) {
585 for (col = 0; col < column_num; ++col) {
586 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
588 column_values[col] = PQgetvalue (res, row, col);
589 if (NULL == column_values[col]) {
590 log_err ("Failed to get value at (row = %i, col = %i).",
596 /* check for an error */
597 if (col < column_num)
600 status = udb_query_handle_result (q, prep_area, column_values);
602 log_err ("udb_query_handle_result failed with status %i.",
605 } /* for (row = 0; row < rows_num; ++row) */
607 udb_query_finish_result (q, prep_area);
611 } /* c_psql_exec_query */
613 static int c_psql_read (user_data_t *ud)
615 c_psql_database_t *db;
620 if ((ud == NULL) || (ud->data == NULL)) {
621 log_err ("c_psql_read: Invalid user data.");
627 assert (NULL != db->database);
628 assert (NULL != db->instance);
629 assert (NULL != db->queries);
631 pthread_mutex_lock (&db->db_lock);
633 if (0 != c_psql_check_connection (db)) {
634 pthread_mutex_unlock (&db->db_lock);
638 for (i = 0; i < db->queries_num; ++i)
640 udb_query_preparation_area_t *prep_area;
643 prep_area = db->q_prep_areas[i];
646 if ((0 != db->server_version)
647 && (udb_query_check_version (q, db->server_version) <= 0))
650 if (0 == c_psql_exec_query (db, q, prep_area))
654 pthread_mutex_unlock (&db->db_lock);
661 static char *values_name_to_sqlarray (const data_set_t *ds,
662 char *string, size_t string_len)
670 str_len = string_len;
672 for (i = 0; i < ds->ds_num; ++i) {
673 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
677 else if ((size_t)status >= str_len) {
683 str_len -= (size_t)status;
688 log_err ("c_psql_write: Failed to stringify value names");
692 /* overwrite the first comma */
698 } /* values_name_to_sqlarray */
700 static char *values_type_to_sqlarray (const data_set_t *ds,
701 char *string, size_t string_len, _Bool store_rates)
709 str_len = string_len;
711 for (i = 0; i < ds->ds_num; ++i) {
715 status = ssnprintf(str_ptr, str_len, ",'gauge'");
717 status = ssnprintf(str_ptr, str_len, ",'%s'",
718 DS_TYPE_TO_STRING (ds->ds[i].type));
724 else if ((size_t)status >= str_len) {
730 str_len -= (size_t)status;
735 log_err ("c_psql_write: Failed to stringify value types");
739 /* overwrite the first comma */
745 } /* values_type_to_sqlarray */
747 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
748 char *string, size_t string_len, _Bool store_rates)
753 gauge_t *rates = NULL;
758 str_len = string_len;
760 for (i = 0; i < vl->values_len; ++i) {
763 if ((ds->ds[i].type != DS_TYPE_GAUGE)
764 && (ds->ds[i].type != DS_TYPE_COUNTER)
765 && (ds->ds[i].type != DS_TYPE_DERIVE)
766 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
767 log_err ("c_psql_write: Unknown data source type: %i",
773 if (ds->ds[i].type == DS_TYPE_GAUGE)
774 status = ssnprintf (str_ptr, str_len,
775 ",%f", vl->values[i].gauge);
776 else if (store_rates) {
778 rates = uc_get_rate (ds, vl);
781 log_err ("c_psql_write: Failed to determine rate");
785 status = ssnprintf (str_ptr, str_len,
788 else if (ds->ds[i].type == DS_TYPE_COUNTER)
789 status = ssnprintf (str_ptr, str_len,
790 ",%llu", vl->values[i].counter);
791 else if (ds->ds[i].type == DS_TYPE_DERIVE)
792 status = ssnprintf (str_ptr, str_len,
793 ",%"PRIi64, vl->values[i].derive);
794 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
795 status = ssnprintf (str_ptr, str_len,
796 ",%"PRIu64, vl->values[i].absolute);
802 else if ((size_t)status >= str_len) {
808 str_len -= (size_t)status;
815 log_err ("c_psql_write: Failed to stringify value list");
819 /* overwrite the first comma */
825 } /* values_to_sqlarray */
827 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
830 c_psql_database_t *db;
833 char values_name_str[1024];
834 char values_type_str[1024];
835 char values_str[1024];
837 const char *params[9];
842 if ((ud == NULL) || (ud->data == NULL)) {
843 log_err ("c_psql_write: Invalid user data.");
848 assert (db->database != NULL);
849 assert (db->writers != NULL);
851 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
852 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
856 if (values_name_to_sqlarray (ds,
857 values_name_str, sizeof (values_name_str)) == NULL)
860 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
862 params[0] = time_str;
863 params[1] = vl->host;
864 params[2] = vl->plugin;
865 params[3] = VALUE_OR_NULL(vl->plugin_instance);
866 params[4] = vl->type;
867 params[5] = VALUE_OR_NULL(vl->type_instance);
868 params[6] = values_name_str;
872 if( db->expire_delay > 0 && vl->time < (cdtime() - vl->interval - db->expire_delay) ) {
873 log_info ("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
874 params[0], params[1], params[2], params[3], params[4], params[5], params[6] );
878 pthread_mutex_lock (&db->db_lock);
880 if (0 != c_psql_check_connection (db)) {
881 pthread_mutex_unlock (&db->db_lock);
885 if ((db->commit_interval > 0)
886 && (db->next_commit == 0))
889 for (i = 0; i < db->writers_num; ++i) {
890 c_psql_writer_t *writer;
893 writer = db->writers[i];
895 if (values_type_to_sqlarray (ds,
896 values_type_str, sizeof (values_type_str),
897 writer->store_rates) == NULL) {
898 pthread_mutex_unlock (&db->db_lock);
902 if (values_to_sqlarray (ds, vl,
903 values_str, sizeof (values_str),
904 writer->store_rates) == NULL) {
905 pthread_mutex_unlock (&db->db_lock);
909 params[7] = values_type_str;
910 params[8] = values_str;
912 res = PQexecParams (db->conn, writer->statement,
913 STATIC_ARRAY_SIZE (params), NULL,
914 (const char *const *)params,
915 NULL, NULL, /* return text data */ 0);
917 if ((PGRES_COMMAND_OK != PQresultStatus (res))
918 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
921 if ((CONNECTION_OK != PQstatus (db->conn))
922 && (0 == c_psql_check_connection (db))) {
924 res = PQexecParams (db->conn, writer->statement,
925 STATIC_ARRAY_SIZE (params), NULL,
926 (const char *const *)params,
927 NULL, NULL, /* return text data */ 0);
929 if ((PGRES_COMMAND_OK == PQresultStatus (res))
930 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
937 log_err ("Failed to execute SQL query: %s",
938 PQerrorMessage (db->conn));
939 log_info ("SQL query was: '%s', "
940 "params: %s, %s, %s, %s, %s, %s, %s, %s",
942 params[0], params[1], params[2], params[3],
943 params[4], params[5], params[6], params[7]);
945 /* this will abort any current transaction -> restart */
946 if (db->next_commit > 0)
949 pthread_mutex_unlock (&db->db_lock);
957 if ((db->next_commit > 0)
958 && (cdtime () > db->next_commit))
961 pthread_mutex_unlock (&db->db_lock);
968 /* We cannot flush single identifiers as all we do is to commit the currently
969 * running transaction, thus making sure that all written data is actually
970 * visible to everybody. */
971 static int c_psql_flush (cdtime_t timeout,
972 __attribute__((unused)) const char *ident,
975 c_psql_database_t **dbs = databases;
976 size_t dbs_num = databases_num;
979 if ((ud != NULL) && (ud->data != NULL)) {
980 dbs = (void *)&ud->data;
984 for (i = 0; i < dbs_num; ++i) {
985 c_psql_database_t *db = dbs[i];
987 /* don't commit if the timeout is larger than the regular commit
988 * interval as in that case all requested data has already been
990 if ((db->next_commit > 0) && (db->commit_interval > timeout))
996 static int c_psql_shutdown (void)
1000 _Bool had_flush = 0;
1002 plugin_unregister_read_group ("postgresql");
1004 for (i = 0; i < databases_num; ++i) {
1005 c_psql_database_t *db = databases[i];
1007 if (db->writers_num > 0) {
1008 char cb_name[DATA_MAX_NAME_LEN];
1009 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s",
1013 plugin_unregister_flush ("postgresql");
1017 plugin_unregister_flush (cb_name);
1018 plugin_unregister_write (cb_name);
1024 udb_query_free (queries, queries_num);
1037 } /* c_psql_shutdown */
1039 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
1041 c_psql_user_data_t *data;
1042 const char *param_str;
1044 c_psql_param_t *tmp;
1046 data = udb_query_get_user_data (q);
1048 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
1050 log_err ("Out of memory.");
1053 memset (data, 0, sizeof (*data));
1054 data->params = NULL;
1057 tmp = (c_psql_param_t *) realloc (data->params,
1058 (data->params_num + 1) * sizeof (c_psql_param_t));
1060 log_err ("Out of memory.");
1065 param_str = ci->values[0].value.string;
1066 if (0 == strcasecmp (param_str, "hostname"))
1067 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1068 else if (0 == strcasecmp (param_str, "database"))
1069 data->params[data->params_num] = C_PSQL_PARAM_DB;
1070 else if (0 == strcasecmp (param_str, "username"))
1071 data->params[data->params_num] = C_PSQL_PARAM_USER;
1072 else if (0 == strcasecmp (param_str, "interval"))
1073 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1074 else if (0 == strcasecmp (param_str, "instance"))
1075 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1077 log_err ("Invalid parameter \"%s\".", param_str);
1082 udb_query_set_user_data (q, data);
1085 } /* config_query_param_add */
1087 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
1089 if (0 == strcasecmp ("Param", ci->key))
1090 return config_query_param_add (q, ci);
1092 log_err ("Option not allowed within a Query block: `%s'", ci->key);
1095 } /* config_query_callback */
1097 static int config_add_writer (oconfig_item_t *ci,
1098 c_psql_writer_t *src_writers, size_t src_writers_num,
1099 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
1105 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1108 if ((ci->values_num != 1)
1109 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1110 log_err ("`Writer' expects a single string argument.");
1114 name = ci->values[0].value.string;
1116 for (i = 0; i < src_writers_num; ++i) {
1117 c_psql_writer_t **tmp;
1119 if (strcasecmp (name, src_writers[i].name) != 0)
1122 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1123 sizeof (**dst_writers) * (*dst_writers_num + 1));
1125 log_err ("Out of memory.");
1129 tmp[*dst_writers_num] = src_writers + i;
1132 ++(*dst_writers_num);
1136 if (i >= src_writers_num) {
1137 log_err ("No such writer: `%s'", name);
1142 } /* config_add_writer */
1144 static int c_psql_config_writer (oconfig_item_t *ci)
1146 c_psql_writer_t *writer;
1147 c_psql_writer_t *tmp;
1152 if ((ci->values_num != 1)
1153 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1154 log_err ("<Writer> expects a single string argument.");
1158 tmp = (c_psql_writer_t *)realloc (writers,
1159 sizeof (*writers) * (writers_num + 1));
1161 log_err ("Out of memory.");
1166 writer = writers + writers_num;
1169 writer->name = sstrdup (ci->values[0].value.string);
1170 writer->statement = NULL;
1171 writer->store_rates = 1;
1173 for (i = 0; i < ci->children_num; ++i) {
1174 oconfig_item_t *c = ci->children + i;
1176 if (strcasecmp ("Statement", c->key) == 0)
1177 status = cf_util_get_string (c, &writer->statement);
1178 else if (strcasecmp ("StoreRates", c->key) == 0)
1179 status = cf_util_get_boolean (c, &writer->store_rates);
1181 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1185 sfree (writer->statement);
1186 sfree (writer->name);
1192 } /* c_psql_config_writer */
1194 static int c_psql_config_database (oconfig_item_t *ci)
1196 c_psql_database_t *db;
1198 char cb_name[DATA_MAX_NAME_LEN];
1199 struct timespec cb_interval = { 0, 0 };
1202 static _Bool have_flush = 0;
1206 if ((1 != ci->values_num)
1207 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1208 log_err ("<Database> expects a single string argument.");
1212 memset (&ud, 0, sizeof (ud));
1214 db = c_psql_database_new (ci->values[0].value.string);
1218 for (i = 0; i < ci->children_num; ++i) {
1219 oconfig_item_t *c = ci->children + i;
1221 if (0 == strcasecmp (c->key, "Host"))
1222 cf_util_get_string (c, &db->host);
1223 else if (0 == strcasecmp (c->key, "Port"))
1224 cf_util_get_service (c, &db->port);
1225 else if (0 == strcasecmp (c->key, "User"))
1226 cf_util_get_string (c, &db->user);
1227 else if (0 == strcasecmp (c->key, "Password"))
1228 cf_util_get_string (c, &db->password);
1229 else if (0 == strcasecmp (c->key, "Instance"))
1230 cf_util_get_string (c, &db->instance);
1231 else if (0 == strcasecmp (c->key, "SSLMode"))
1232 cf_util_get_string (c, &db->sslmode);
1233 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1234 cf_util_get_string (c, &db->krbsrvname);
1235 else if (0 == strcasecmp (c->key, "Service"))
1236 cf_util_get_string (c, &db->service);
1237 else if (0 == strcasecmp (c->key, "Query"))
1238 udb_query_pick_from_list (c, queries, queries_num,
1239 &db->queries, &db->queries_num);
1240 else if (0 == strcasecmp (c->key, "Writer"))
1241 config_add_writer (c, writers, writers_num,
1242 &db->writers, &db->writers_num);
1243 else if (0 == strcasecmp (c->key, "Interval"))
1244 cf_util_get_cdtime (c, &db->interval);
1245 else if (strcasecmp ("CommitInterval", c->key) == 0)
1246 cf_util_get_cdtime (c, &db->commit_interval);
1247 else if (strcasecmp ("ExpireDelay", c->key) == 0)
1248 cf_util_get_cdtime (c, &db->expire_delay);
1250 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1253 /* If no `Query' options were given, add the default queries.. */
1254 if ((db->queries_num == 0) && (db->writers_num == 0)){
1255 for (i = 0; i < def_queries_num; i++)
1256 udb_query_pick_from_list_by_name (def_queries[i],
1257 queries, queries_num,
1258 &db->queries, &db->queries_num);
1261 if (db->queries_num > 0) {
1262 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1263 db->queries_num, sizeof (*db->q_prep_areas));
1265 if (db->q_prep_areas == NULL) {
1266 log_err ("Out of memory.");
1267 c_psql_database_delete (db);
1272 for (i = 0; (size_t)i < db->queries_num; ++i) {
1273 c_psql_user_data_t *data;
1274 data = udb_query_get_user_data (db->queries[i]);
1275 if ((data != NULL) && (data->params_num > db->max_params_num))
1276 db->max_params_num = data->params_num;
1279 = udb_query_allocate_preparation_area (db->queries[i]);
1281 if (db->q_prep_areas[i] == NULL) {
1282 log_err ("Out of memory.");
1283 c_psql_database_delete (db);
1289 ud.free_func = c_psql_database_delete;
1291 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
1293 if (db->queries_num > 0) {
1294 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1297 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1298 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1301 if (db->writers_num > 0) {
1303 plugin_register_write (cb_name, c_psql_write, &ud);
1307 plugin_register_flush ("postgresql",
1308 c_psql_flush, /* user data = */ NULL);
1312 /* flush this connection only */
1314 plugin_register_flush (cb_name, c_psql_flush, &ud);
1316 else if (db->commit_interval > 0) {
1317 log_warn ("Database '%s': You do not have any writers assigned to "
1318 "this database connection. Setting 'CommitInterval' does "
1319 "not have any effect.", db->database);
1322 } /* c_psql_config_database */
1324 static int c_psql_config (oconfig_item_t *ci)
1326 static int have_def_config = 0;
1330 if (0 == have_def_config) {
1333 have_def_config = 1;
1335 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1337 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1341 if (NULL == queries)
1342 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1343 "any queries - please check your installation.");
1346 for (i = 0; i < ci->children_num; ++i) {
1347 oconfig_item_t *c = ci->children + i;
1349 if (0 == strcasecmp (c->key, "Query"))
1350 udb_query_create (&queries, &queries_num, c,
1351 /* callback = */ config_query_callback);
1352 else if (0 == strcasecmp (c->key, "Writer"))
1353 c_psql_config_writer (c);
1354 else if (0 == strcasecmp (c->key, "Database"))
1355 c_psql_config_database (c);
1357 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1360 } /* c_psql_config */
1362 void module_register (void)
1364 plugin_register_complex_config ("postgresql", c_psql_config);
1365 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1366 } /* module_register */
1368 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */