2 * collectd - src/postgresql.c
3 * Copyright (C) 2008, 2009 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_db_query.h"
46 #include "utils_complain.h"
48 #include <pg_config_manual.h>
51 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
52 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
53 #define log_info(...) INFO ("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;
109 c_complain_t conn_complaint;
116 /* user configuration */
117 udb_query_preparation_area_t **q_prep_areas;
118 udb_query_t **queries;
138 static char *def_queries[] = {
147 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
149 static udb_query_t **queries = NULL;
150 static size_t queries_num = 0;
152 static c_psql_database_t *c_psql_database_new (const char *name)
154 c_psql_database_t *db;
156 db = (c_psql_database_t *)malloc (sizeof (*db));
158 log_err ("Out of memory.");
164 C_COMPLAIN_INIT (&db->conn_complaint);
166 db->proto_version = 0;
167 db->server_version = 0;
169 db->max_params_num = 0;
171 db->q_prep_areas = NULL;
177 db->database = sstrdup (name);
183 db->instance = sstrdup (name);
187 db->krbsrvname = NULL;
191 } /* c_psql_database_new */
193 static void c_psql_database_delete (void *data)
197 c_psql_database_t *db = data;
202 if (db->q_prep_areas)
203 for (i = 0; i < db->queries_num; ++i)
204 udb_query_delete_preparation_area (db->q_prep_areas[i]);
205 free (db->q_prep_areas);
210 sfree (db->database);
214 sfree (db->password);
216 sfree (db->instance);
220 sfree (db->krbsrvname);
224 } /* c_psql_database_delete */
226 static int c_psql_connect (c_psql_database_t *db)
229 char *buf = conninfo;
230 int buf_len = sizeof (conninfo);
236 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
242 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
243 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
244 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
245 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
246 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
247 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
248 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
250 db->conn = PQconnectdb (conninfo);
251 db->proto_version = PQprotocolVersion (db->conn);
253 } /* c_psql_connect */
255 static int c_psql_check_connection (c_psql_database_t *db)
262 /* trigger c_release() */
263 if (0 == db->conn_complaint.interval)
264 db->conn_complaint.interval = 1;
270 PQclear (PQexec (db->conn, "SELECT 42;"));
272 if (CONNECTION_OK != PQstatus (db->conn)) {
275 /* trigger c_release() */
276 if (0 == db->conn_complaint.interval)
277 db->conn_complaint.interval = 1;
279 if (CONNECTION_OK != PQstatus (db->conn)) {
280 c_complain (LOG_ERR, &db->conn_complaint,
281 "Failed to connect to database %s (%s): %s",
282 db->database, db->instance,
283 PQerrorMessage (db->conn));
287 db->proto_version = PQprotocolVersion (db->conn);
290 db->server_version = PQserverVersion (db->conn);
292 if (c_would_release (&db->conn_complaint)) {
296 server_host = PQhost (db->conn);
297 server_version = PQserverVersion (db->conn);
299 c_do_release (LOG_INFO, &db->conn_complaint,
300 "Successfully %sconnected to database %s (user %s) "
301 "at server %s%s%s (server version: %d.%d.%d, "
302 "protocol version: %d, pid: %d)", init ? "" : "re",
303 PQdb (db->conn), PQuser (db->conn),
304 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
305 C_PSQL_SERVER_VERSION3 (server_version),
306 db->proto_version, PQbackendPID (db->conn));
308 if (3 > db->proto_version)
309 log_warn ("Protocol version %d does not support parameters.",
313 } /* c_psql_check_connection */
315 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
318 return PQexec (db->conn, udb_query_get_statement (q));
319 } /* c_psql_exec_query_noparams */
321 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
322 udb_query_t *q, c_psql_user_data_t *data)
324 char *params[db->max_params_num];
328 if ((data == NULL) || (data->params_num == 0))
329 return (c_psql_exec_query_noparams (db, q));
331 assert (db->max_params_num >= data->params_num);
333 for (i = 0; i < data->params_num; ++i) {
334 switch (data->params[i]) {
335 case C_PSQL_PARAM_HOST:
336 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
337 ? "localhost" : db->host;
339 case C_PSQL_PARAM_DB:
340 params[i] = db->database;
342 case C_PSQL_PARAM_USER:
343 params[i] = db->user;
345 case C_PSQL_PARAM_INTERVAL:
346 ssnprintf (interval, sizeof (interval), "%.3f",
348 ? CDTIME_T_TO_DOUBLE (db->interval)
349 : plugin_get_interval ());
350 params[i] = interval;
352 case C_PSQL_PARAM_INSTANCE:
353 params[i] = db->instance;
360 return PQexecParams (db->conn, udb_query_get_statement (q),
361 data->params_num, NULL,
362 (const char *const *) params,
363 NULL, NULL, /* return text data */ 0);
364 } /* c_psql_exec_query_params */
366 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
367 udb_query_preparation_area_t *prep_area)
371 c_psql_user_data_t *data;
376 char **column_values;
383 /* The user data may hold parameter information, but may be NULL. */
384 data = udb_query_get_user_data (q);
386 /* Versions up to `3' don't know how to handle parameters. */
387 if (3 <= db->proto_version)
388 res = c_psql_exec_query_params (db, q, data);
389 else if ((NULL == data) || (0 == data->params_num))
390 res = c_psql_exec_query_noparams (db, q);
392 log_err ("Connection to database \"%s\" (%s) does not support "
393 "parameters (protocol version %d) - "
394 "cannot execute query \"%s\".",
395 db->database, db->instance, db->proto_version,
396 udb_query_get_name (q));
401 column_values = NULL;
403 #define BAIL_OUT(status) \
404 sfree (column_names); \
405 sfree (column_values); \
409 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
410 log_err ("Failed to execute SQL query: %s",
411 PQerrorMessage (db->conn));
412 log_info ("SQL query was: %s",
413 udb_query_get_statement (q));
417 rows_num = PQntuples (res);
422 column_num = PQnfields (res);
423 column_names = (char **) calloc (column_num, sizeof (char *));
424 if (NULL == column_names) {
425 log_err ("calloc failed.");
429 column_values = (char **) calloc (column_num, sizeof (char *));
430 if (NULL == column_values) {
431 log_err ("calloc failed.");
435 for (col = 0; col < column_num; ++col) {
436 /* Pointers returned by `PQfname' are freed by `PQclear' via
438 column_names[col] = PQfname (res, col);
439 if (NULL == column_names[col]) {
440 log_err ("Failed to resolve name of column %i.", col);
445 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
446 || (0 == strcmp (db->host, "localhost")))
451 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
452 db->instance, column_names, (size_t) column_num, db->interval);
454 log_err ("udb_query_prepare_result failed with status %i.",
459 for (row = 0; row < rows_num; ++row) {
460 for (col = 0; col < column_num; ++col) {
461 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
463 column_values[col] = PQgetvalue (res, row, col);
464 if (NULL == column_values[col]) {
465 log_err ("Failed to get value at (row = %i, col = %i).",
471 /* check for an error */
472 if (col < column_num)
475 status = udb_query_handle_result (q, prep_area, column_values);
477 log_err ("udb_query_handle_result failed with status %i.",
480 } /* for (row = 0; row < rows_num; ++row) */
482 udb_query_finish_result (q, prep_area);
486 } /* c_psql_exec_query */
488 static int c_psql_read (user_data_t *ud)
490 c_psql_database_t *db;
495 if ((ud == NULL) || (ud->data == NULL)) {
496 log_err ("c_psql_read: Invalid user data.");
502 assert (NULL != db->database);
503 assert (NULL != db->instance);
505 if (0 != c_psql_check_connection (db))
508 for (i = 0; i < db->queries_num; ++i)
510 udb_query_preparation_area_t *prep_area;
513 prep_area = db->q_prep_areas[i];
516 if ((0 != db->server_version)
517 && (udb_query_check_version (q, db->server_version) <= 0))
520 if (0 == c_psql_exec_query (db, q, prep_area))
529 static int c_psql_shutdown (void)
531 plugin_unregister_read_group ("postgresql");
533 udb_query_free (queries, queries_num);
538 } /* c_psql_shutdown */
540 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
542 c_psql_user_data_t *data;
543 const char *param_str;
547 data = udb_query_get_user_data (q);
549 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
551 log_err ("Out of memory.");
554 memset (data, 0, sizeof (*data));
558 tmp = (c_psql_param_t *) realloc (data->params,
559 (data->params_num + 1) * sizeof (c_psql_param_t));
561 log_err ("Out of memory.");
566 param_str = ci->values[0].value.string;
567 if (0 == strcasecmp (param_str, "hostname"))
568 data->params[data->params_num] = C_PSQL_PARAM_HOST;
569 else if (0 == strcasecmp (param_str, "database"))
570 data->params[data->params_num] = C_PSQL_PARAM_DB;
571 else if (0 == strcasecmp (param_str, "username"))
572 data->params[data->params_num] = C_PSQL_PARAM_USER;
573 else if (0 == strcasecmp (param_str, "interval"))
574 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
575 else if (0 == strcasecmp (param_str, "instance"))
576 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
578 log_err ("Invalid parameter \"%s\".", param_str);
583 udb_query_set_user_data (q, data);
586 } /* config_query_param_add */
588 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
590 if (0 == strcasecmp ("Param", ci->key))
591 return config_query_param_add (q, ci);
593 log_err ("Option not allowed within a Query block: `%s'", ci->key);
596 } /* config_query_callback */
598 static int c_psql_config_database (oconfig_item_t *ci)
600 c_psql_database_t *db;
602 char cb_name[DATA_MAX_NAME_LEN];
603 struct timespec cb_interval = { 0, 0 };
608 if ((1 != ci->values_num)
609 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
610 log_err ("<Database> expects a single string argument.");
614 memset (&ud, 0, sizeof (ud));
616 db = c_psql_database_new (ci->values[0].value.string);
620 for (i = 0; i < ci->children_num; ++i) {
621 oconfig_item_t *c = ci->children + i;
623 if (0 == strcasecmp (c->key, "Host"))
624 cf_util_get_string (c, &db->host);
625 else if (0 == strcasecmp (c->key, "Port"))
626 cf_util_get_service (c, &db->port);
627 else if (0 == strcasecmp (c->key, "User"))
628 cf_util_get_string (c, &db->user);
629 else if (0 == strcasecmp (c->key, "Password"))
630 cf_util_get_string (c, &db->password);
631 else if (0 == strcasecmp (c->key, "Instance"))
632 cf_util_get_string (c, &db->instance);
633 else if (0 == strcasecmp (c->key, "SSLMode"))
634 cf_util_get_string (c, &db->sslmode);
635 else if (0 == strcasecmp (c->key, "KRBSrvName"))
636 cf_util_get_string (c, &db->krbsrvname);
637 else if (0 == strcasecmp (c->key, "Service"))
638 cf_util_get_string (c, &db->service);
639 else if (0 == strcasecmp (c->key, "Query"))
640 udb_query_pick_from_list (c, queries, queries_num,
641 &db->queries, &db->queries_num);
642 else if (0 == strcasecmp (c->key, "Interval"))
643 cf_util_get_cdtime (c, &db->interval);
645 log_warn ("Ignoring unknown config key \"%s\".", c->key);
648 /* If no `Query' options were given, add the default queries.. */
649 if (db->queries_num == 0) {
650 for (i = 0; i < def_queries_num; i++)
651 udb_query_pick_from_list_by_name (def_queries[i],
652 queries, queries_num,
653 &db->queries, &db->queries_num);
656 if (db->queries_num > 0) {
657 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
658 db->queries_num, sizeof (*db->q_prep_areas));
660 if (db->q_prep_areas == NULL) {
661 log_err ("Out of memory.");
662 c_psql_database_delete (db);
667 for (i = 0; (size_t)i < db->queries_num; ++i) {
668 c_psql_user_data_t *data;
669 data = udb_query_get_user_data (db->queries[i]);
670 if ((data != NULL) && (data->params_num > db->max_params_num))
671 db->max_params_num = data->params_num;
674 = udb_query_allocate_preparation_area (db->queries[i]);
676 if (db->q_prep_areas[i] == NULL) {
677 log_err ("Out of memory.");
678 c_psql_database_delete (db);
684 ud.free_func = c_psql_database_delete;
686 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
688 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
690 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
691 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
694 } /* c_psql_config_database */
696 static int c_psql_config (oconfig_item_t *ci)
698 static int have_def_config = 0;
702 if (0 == have_def_config) {
707 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
709 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
714 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
715 "any queries - please check your installation.");
718 for (i = 0; i < ci->children_num; ++i) {
719 oconfig_item_t *c = ci->children + i;
721 if (0 == strcasecmp (c->key, "Query"))
722 udb_query_create (&queries, &queries_num, c,
723 /* callback = */ config_query_callback);
724 else if (0 == strcasecmp (c->key, "Database"))
725 c_psql_config_database (c);
727 log_warn ("Ignoring unknown config key \"%s\".", c->key);
730 } /* c_psql_config */
732 void module_register (void)
734 plugin_register_complex_config ("postgresql", c_psql_config);
735 plugin_register_shutdown ("postgresql", c_psql_shutdown);
736 } /* module_register */
738 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */