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)
669 str_len = string_len;
671 for (i = 0; i < ds->ds_num; ++i) {
672 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
676 else if ((size_t)status >= str_len) {
682 str_len -= (size_t)status;
687 log_err ("c_psql_write: Failed to stringify value names");
691 /* overwrite the first comma */
697 } /* values_name_to_sqlarray */
699 static char *values_type_to_sqlarray (const data_set_t *ds,
700 char *string, size_t string_len, _Bool store_rates)
707 str_len = string_len;
709 for (i = 0; i < ds->ds_num; ++i) {
713 status = ssnprintf(str_ptr, str_len, ",'gauge'");
715 status = ssnprintf(str_ptr, str_len, ",'%s'",
716 DS_TYPE_TO_STRING (ds->ds[i].type));
722 else if ((size_t)status >= str_len) {
728 str_len -= (size_t)status;
733 log_err ("c_psql_write: Failed to stringify value types");
737 /* overwrite the first comma */
743 } /* values_type_to_sqlarray */
745 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
746 char *string, size_t string_len, _Bool store_rates)
751 gauge_t *rates = NULL;
755 str_len = string_len;
757 for (i = 0; i < vl->values_len; ++i) {
760 if ((ds->ds[i].type != DS_TYPE_GAUGE)
761 && (ds->ds[i].type != DS_TYPE_COUNTER)
762 && (ds->ds[i].type != DS_TYPE_DERIVE)
763 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
764 log_err ("c_psql_write: Unknown data source type: %i",
770 if (ds->ds[i].type == DS_TYPE_GAUGE)
771 status = ssnprintf (str_ptr, str_len,
772 ","GAUGE_FORMAT, vl->values[i].gauge);
773 else if (store_rates) {
775 rates = uc_get_rate (ds, vl);
778 log_err ("c_psql_write: Failed to determine rate");
782 status = ssnprintf (str_ptr, str_len,
785 else if (ds->ds[i].type == DS_TYPE_COUNTER)
786 status = ssnprintf (str_ptr, str_len,
787 ",%llu", vl->values[i].counter);
788 else if (ds->ds[i].type == DS_TYPE_DERIVE)
789 status = ssnprintf (str_ptr, str_len,
790 ",%"PRIi64, vl->values[i].derive);
791 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
792 status = ssnprintf (str_ptr, str_len,
793 ",%"PRIu64, vl->values[i].absolute);
799 else if ((size_t)status >= str_len) {
805 str_len -= (size_t)status;
812 log_err ("c_psql_write: Failed to stringify value list");
816 /* overwrite the first comma */
822 } /* values_to_sqlarray */
824 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
827 c_psql_database_t *db;
830 char values_name_str[1024];
831 char values_type_str[1024];
832 char values_str[1024];
834 const char *params[9];
839 if ((ud == NULL) || (ud->data == NULL)) {
840 log_err ("c_psql_write: Invalid user data.");
845 assert (db->database != NULL);
846 assert (db->writers != NULL);
848 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
849 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
853 if (values_name_to_sqlarray (ds,
854 values_name_str, sizeof (values_name_str)) == NULL)
857 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
859 params[0] = time_str;
860 params[1] = vl->host;
861 params[2] = vl->plugin;
862 params[3] = VALUE_OR_NULL(vl->plugin_instance);
863 params[4] = vl->type;
864 params[5] = VALUE_OR_NULL(vl->type_instance);
865 params[6] = values_name_str;
869 if( db->expire_delay > 0 && vl->time < (cdtime() - vl->interval - db->expire_delay) ) {
870 log_info ("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
871 params[0], params[1], params[2], params[3], params[4], params[5], params[6] );
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];
1198 static _Bool have_flush = 0;
1202 if ((1 != ci->values_num)
1203 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1204 log_err ("<Database> expects a single string argument.");
1208 memset (&ud, 0, sizeof (ud));
1210 db = c_psql_database_new (ci->values[0].value.string);
1214 for (i = 0; i < ci->children_num; ++i) {
1215 oconfig_item_t *c = ci->children + i;
1217 if (0 == strcasecmp (c->key, "Host"))
1218 cf_util_get_string (c, &db->host);
1219 else if (0 == strcasecmp (c->key, "Port"))
1220 cf_util_get_service (c, &db->port);
1221 else if (0 == strcasecmp (c->key, "User"))
1222 cf_util_get_string (c, &db->user);
1223 else if (0 == strcasecmp (c->key, "Password"))
1224 cf_util_get_string (c, &db->password);
1225 else if (0 == strcasecmp (c->key, "Instance"))
1226 cf_util_get_string (c, &db->instance);
1227 else if (0 == strcasecmp (c->key, "SSLMode"))
1228 cf_util_get_string (c, &db->sslmode);
1229 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1230 cf_util_get_string (c, &db->krbsrvname);
1231 else if (0 == strcasecmp (c->key, "Service"))
1232 cf_util_get_string (c, &db->service);
1233 else if (0 == strcasecmp (c->key, "Query"))
1234 udb_query_pick_from_list (c, queries, queries_num,
1235 &db->queries, &db->queries_num);
1236 else if (0 == strcasecmp (c->key, "Writer"))
1237 config_add_writer (c, writers, writers_num,
1238 &db->writers, &db->writers_num);
1239 else if (0 == strcasecmp (c->key, "Interval"))
1240 cf_util_get_cdtime (c, &db->interval);
1241 else if (strcasecmp ("CommitInterval", c->key) == 0)
1242 cf_util_get_cdtime (c, &db->commit_interval);
1243 else if (strcasecmp ("ExpireDelay", c->key) == 0)
1244 cf_util_get_cdtime (c, &db->expire_delay);
1246 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1249 /* If no `Query' options were given, add the default queries.. */
1250 if ((db->queries_num == 0) && (db->writers_num == 0)){
1251 for (i = 0; i < def_queries_num; i++)
1252 udb_query_pick_from_list_by_name (def_queries[i],
1253 queries, queries_num,
1254 &db->queries, &db->queries_num);
1257 if (db->queries_num > 0) {
1258 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1259 db->queries_num, sizeof (*db->q_prep_areas));
1261 if (db->q_prep_areas == NULL) {
1262 log_err ("Out of memory.");
1263 c_psql_database_delete (db);
1268 for (i = 0; (size_t)i < db->queries_num; ++i) {
1269 c_psql_user_data_t *data;
1270 data = udb_query_get_user_data (db->queries[i]);
1271 if ((data != NULL) && (data->params_num > db->max_params_num))
1272 db->max_params_num = data->params_num;
1275 = udb_query_allocate_preparation_area (db->queries[i]);
1277 if (db->q_prep_areas[i] == NULL) {
1278 log_err ("Out of memory.");
1279 c_psql_database_delete (db);
1285 ud.free_func = c_psql_database_delete;
1287 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
1289 if (db->queries_num > 0) {
1291 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1292 /* interval = */ db->interval, &ud);
1294 if (db->writers_num > 0) {
1296 plugin_register_write (cb_name, c_psql_write, &ud);
1300 plugin_register_flush ("postgresql",
1301 c_psql_flush, /* user data = */ NULL);
1305 /* flush this connection only */
1307 plugin_register_flush (cb_name, c_psql_flush, &ud);
1309 else if (db->commit_interval > 0) {
1310 log_warn ("Database '%s': You do not have any writers assigned to "
1311 "this database connection. Setting 'CommitInterval' does "
1312 "not have any effect.", db->database);
1315 } /* c_psql_config_database */
1317 static int c_psql_config (oconfig_item_t *ci)
1319 static int have_def_config = 0;
1323 if (0 == have_def_config) {
1326 have_def_config = 1;
1328 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1330 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1334 if (NULL == queries)
1335 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1336 "any queries - please check your installation.");
1339 for (i = 0; i < ci->children_num; ++i) {
1340 oconfig_item_t *c = ci->children + i;
1342 if (0 == strcasecmp (c->key, "Query"))
1343 udb_query_create (&queries, &queries_num, c,
1344 /* callback = */ config_query_callback);
1345 else if (0 == strcasecmp (c->key, "Writer"))
1346 c_psql_config_writer (c);
1347 else if (0 == strcasecmp (c->key, "Database"))
1348 c_psql_config_database (c);
1350 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1353 } /* c_psql_config */
1355 void module_register (void)
1357 plugin_register_complex_config ("postgresql", c_psql_config);
1358 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1359 } /* module_register */
1361 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */