2 * collectd - src/postgresql.c
3 * Copyright (C) 2008, 2009 Sebastian Harl
4 * Copyright (C) 2009 Florian Forster
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; only version 2 of the License is applicable.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * Sebastian Harl <sh at tokkee.org>
21 * Florian Forster <octo at verplant.org>
25 * This module collects PostgreSQL database statistics.
31 #include "configfile.h"
34 #include "utils_db_query.h"
35 #include "utils_complain.h"
37 #include <pg_config_manual.h>
40 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
41 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
42 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
44 #ifndef C_PSQL_DEFAULT_CONF
45 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
48 /* Appends the (parameter, value) pair to the string
49 * pointed to by 'buf' suitable to be used as argument
50 * for PQconnectdb(). If value equals NULL, the pair
52 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
53 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
54 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
61 /* Returns the tuple (major, minor, patchlevel)
62 * for the given version number. */
63 #define C_PSQL_SERVER_VERSION3(server_version) \
64 (server_version) / 10000, \
65 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
66 (server_version) - (int)((server_version) / 100) * 100
68 /* Returns true if the given host specifies a
69 * UNIX domain socket. */
70 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
71 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
73 /* Returns the tuple (host, delimiter, port) for a
74 * given (host, port) pair. Depending on the value of
75 * 'host' a UNIX domain socket or a TCP socket is
77 #define C_PSQL_SOCKET3(host, port) \
78 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
79 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
83 C_PSQL_PARAM_HOST = 1,
86 C_PSQL_PARAM_INTERVAL,
89 /* Parameter configuration. Stored as `user data' in the query objects. */
91 c_psql_param_t *params;
97 c_complain_t conn_complaint;
104 /* user configuration */
105 udb_query_t **queries;
121 static char *def_queries[] = {
130 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
132 static udb_query_t **queries = NULL;
133 static size_t queries_num = 0;
135 static c_psql_database_t *databases = NULL;
136 static int databases_num = 0;
138 static c_psql_database_t *c_psql_database_new (const char *name)
140 c_psql_database_t *db;
143 if (NULL == (databases = (c_psql_database_t *)realloc (databases,
144 databases_num * sizeof (*databases)))) {
145 log_err ("Out of memory.");
149 db = databases + (databases_num - 1);
153 C_COMPLAIN_INIT (&db->conn_complaint);
155 db->proto_version = 0;
156 db->server_version = 0;
158 db->max_params_num = 0;
163 db->database = sstrdup (name);
171 db->krbsrvname = NULL;
175 } /* c_psql_database_new */
177 static void c_psql_database_delete (c_psql_database_t *db)
185 sfree (db->database);
189 sfree (db->password);
193 sfree (db->krbsrvname);
197 } /* c_psql_database_delete */
199 static int c_psql_check_connection (c_psql_database_t *db)
202 PQclear (PQexec (db->conn, "SELECT 42;"));
204 if (CONNECTION_OK != PQstatus (db->conn)) {
207 /* trigger c_release() */
208 if (0 == db->conn_complaint.interval)
209 db->conn_complaint.interval = 1;
211 if (CONNECTION_OK != PQstatus (db->conn)) {
212 c_complain (LOG_ERR, &db->conn_complaint,
213 "Failed to connect to database %s: %s",
214 db->database, PQerrorMessage (db->conn));
218 db->proto_version = PQprotocolVersion (db->conn);
219 if (3 > db->proto_version)
220 log_warn ("Protocol version %d does not support parameters.",
224 db->server_version = PQserverVersion (db->conn);
226 c_release (LOG_INFO, &db->conn_complaint,
227 "Successfully reconnected to database %s", PQdb (db->conn));
229 } /* c_psql_check_connection */
231 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
234 return PQexec (db->conn, udb_query_get_statement (q));
235 } /* c_psql_exec_query_noparams */
237 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
238 udb_query_t *q, c_psql_user_data_t *data)
240 char *params[db->max_params_num];
244 if ((data == NULL) || (data->params_num == 0))
245 return (c_psql_exec_query_noparams (db, q));
247 assert (db->max_params_num >= data->params_num);
249 for (i = 0; i < data->params_num; ++i) {
250 switch (data->params[i]) {
251 case C_PSQL_PARAM_HOST:
252 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
253 ? "localhost" : db->host;
255 case C_PSQL_PARAM_DB:
256 params[i] = db->database;
258 case C_PSQL_PARAM_USER:
259 params[i] = db->user;
261 case C_PSQL_PARAM_INTERVAL:
262 ssnprintf (interval, sizeof (interval), "%i", interval_g);
263 params[i] = interval;
270 return PQexecParams (db->conn, udb_query_get_statement (q),
271 data->params_num, NULL,
272 (const char *const *) params,
273 NULL, NULL, /* return text data */ 0);
274 } /* c_psql_exec_query_params */
276 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q)
280 c_psql_user_data_t *data;
285 char **column_values;
292 /* The user data may hold parameter information, but may be NULL. */
293 data = udb_query_get_user_data (q);
295 /* Versions up to `3' don't know how to handle parameters. */
296 if (3 <= db->proto_version)
297 res = c_psql_exec_query_params (db, q, data);
298 else if ((NULL == data) || (0 == data->params_num))
299 res = c_psql_exec_query_noparams (db, q);
301 log_err ("Connection to database \"%s\" does not support parameters "
302 "(protocol version %d) - cannot execute query \"%s\".",
303 db->database, db->proto_version,
304 udb_query_get_name (q));
309 column_values = NULL;
311 #define BAIL_OUT(status) \
312 sfree (column_names); \
313 sfree (column_values); \
317 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
318 log_err ("Failed to execute SQL query: %s",
319 PQerrorMessage (db->conn));
320 log_info ("SQL query was: %s",
321 udb_query_get_statement (q));
325 rows_num = PQntuples (res);
330 column_num = PQnfields (res);
331 column_names = (char **) calloc (column_num, sizeof (char *));
332 if (NULL == column_names) {
333 log_err ("calloc failed.");
337 column_values = (char **) calloc (column_num, sizeof (char *));
338 if (NULL == column_values) {
339 log_err ("calloc failed.");
343 for (col = 0; col < column_num; ++col) {
344 /* Pointers returned by `PQfname' are freed by `PQclear' via
346 column_names[col] = PQfname (res, col);
347 if (NULL == column_names[col]) {
348 log_err ("Failed to resolv name of column %i.", col);
353 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
354 || (0 == strcmp (db->host, "localhost")))
359 status = udb_query_prepare_result (q, host, "postgresql",
360 db->database, column_names, (size_t) column_num);
362 log_err ("udb_query_prepare_result failed with status %i.",
367 for (row = 0; row < rows_num; ++row) {
368 for (col = 0; col < column_num; ++col) {
369 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
371 column_values[col] = PQgetvalue (res, row, col);
372 if (NULL == column_values[col]) {
373 log_err ("Failed to get value at (row = %i, col = %i).",
379 /* check for an error */
380 if (col < column_num)
383 status = udb_query_handle_result (q, column_values);
385 log_err ("udb_query_handle_result failed with status %i.",
388 } /* for (row = 0; row < rows_num; ++row) */
392 } /* c_psql_exec_query */
394 static int c_psql_read (void)
399 for (i = 0; i < databases_num; ++i) {
400 c_psql_database_t *db = databases + i;
404 assert (NULL != db->database);
406 if (0 != c_psql_check_connection (db))
409 for (j = 0; j < db->queries_num; ++j)
415 if ((0 != db->server_version)
416 && (udb_query_check_version (q, db->server_version) <= 0))
419 c_psql_exec_query (db, q);
430 static int c_psql_shutdown (void)
434 if ((NULL == databases) || (0 == databases_num))
437 plugin_unregister_read ("postgresql");
438 plugin_unregister_shutdown ("postgresql");
440 for (i = 0; i < databases_num; ++i)
441 c_psql_database_delete (databases + i);
446 udb_query_free (queries, queries_num);
451 } /* c_psql_shutdown */
453 static int c_psql_init (void)
457 if ((NULL == databases) || (0 == databases_num))
460 for (i = 0; i < databases_num; ++i) {
461 c_psql_database_t *db = databases + i;
464 char *buf = conninfo;
465 int buf_len = sizeof (conninfo);
471 /* this will happen during reinitialization */
472 if (NULL != db->conn) {
473 c_psql_check_connection (db);
477 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
483 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
484 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
485 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
486 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
487 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
488 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
489 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
491 db->conn = PQconnectdb (conninfo);
492 if (0 != c_psql_check_connection (db))
495 db->proto_version = PQprotocolVersion (db->conn);
497 server_host = PQhost (db->conn);
498 server_version = PQserverVersion (db->conn);
499 log_info ("Sucessfully connected to database %s (user %s) "
500 "at server %s%s%s (server version: %d.%d.%d, "
501 "protocol version: %d, pid: %d)",
502 PQdb (db->conn), PQuser (db->conn),
503 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
504 C_PSQL_SERVER_VERSION3 (server_version),
505 db->proto_version, PQbackendPID (db->conn));
507 if (3 > db->proto_version)
508 log_warn ("Protocol version %d does not support parameters.",
512 plugin_register_read ("postgresql", c_psql_read);
513 plugin_register_shutdown ("postgresql", c_psql_shutdown);
517 static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
519 if ((0 != ci->children_num) || (1 != ci->values_num)
520 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
521 log_err ("%s expects a single string argument.", name);
526 *var = sstrdup (ci->values[0].value.string);
530 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
532 c_psql_user_data_t *data;
533 const char *param_str;
537 data = udb_query_get_user_data (q);
539 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
541 log_err ("Out of memory.");
544 memset (data, 0, sizeof (*data));
548 tmp = (c_psql_param_t *) realloc (data->params,
549 (data->params_num + 1) * sizeof (c_psql_param_t));
551 log_err ("Out of memory.");
556 param_str = ci->values[0].value.string;
557 if (0 == strcasecmp (param_str, "hostname"))
558 data->params[data->params_num] = C_PSQL_PARAM_HOST;
559 else if (0 == strcasecmp (param_str, "database"))
560 data->params[data->params_num] = C_PSQL_PARAM_DB;
561 else if (0 == strcasecmp (param_str, "username"))
562 data->params[data->params_num] = C_PSQL_PARAM_USER;
563 else if (0 == strcasecmp (param_str, "interval"))
564 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
566 log_err ("Invalid parameter \"%s\".", param_str);
571 udb_query_set_user_data (q, data);
574 } /* config_query_param_add */
576 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
578 if (0 == strcasecmp ("Param", ci->key))
579 return config_query_param_add (q, ci);
581 log_err ("Option not allowed within a Query block: `%s'", ci->key);
584 } /* config_query_callback */
586 static int c_psql_config_database (oconfig_item_t *ci)
588 c_psql_database_t *db;
592 if ((1 != ci->values_num)
593 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
594 log_err ("<Database> expects a single string argument.");
598 db = c_psql_database_new (ci->values[0].value.string);
600 for (i = 0; i < ci->children_num; ++i) {
601 oconfig_item_t *c = ci->children + i;
603 if (0 == strcasecmp (c->key, "Host"))
604 config_set_s ("Host", &db->host, c);
605 else if (0 == strcasecmp (c->key, "Port"))
606 config_set_s ("Port", &db->port, c);
607 else if (0 == strcasecmp (c->key, "User"))
608 config_set_s ("User", &db->user, c);
609 else if (0 == strcasecmp (c->key, "Password"))
610 config_set_s ("Password", &db->password, c);
611 else if (0 == strcasecmp (c->key, "SSLMode"))
612 config_set_s ("SSLMode", &db->sslmode, c);
613 else if (0 == strcasecmp (c->key, "KRBSrvName"))
614 config_set_s ("KRBSrvName", &db->krbsrvname, c);
615 else if (0 == strcasecmp (c->key, "Service"))
616 config_set_s ("Service", &db->service, c);
617 else if (0 == strcasecmp (c->key, "Query"))
618 udb_query_pick_from_list (c, queries, queries_num,
619 &db->queries, &db->queries_num);
621 log_warn ("Ignoring unknown config key \"%s\".", c->key);
624 /* If no `Query' options were given, add the default queries.. */
625 if (db->queries_num == 0)
627 for (i = 0; i < def_queries_num; i++)
628 udb_query_pick_from_list_by_name (def_queries[i],
629 queries, queries_num,
630 &db->queries, &db->queries_num);
633 for (i = 0; (size_t)i < db->queries_num; ++i) {
634 c_psql_user_data_t *data;
635 data = udb_query_get_user_data (db->queries[i]);
636 if ((data != NULL) && (data->params_num > db->max_params_num))
637 db->max_params_num = data->params_num;
640 } /* c_psql_config_database */
642 static int c_psql_config (oconfig_item_t *ci)
644 static int have_def_config = 0;
648 if (0 == have_def_config) {
653 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
655 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
660 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
661 "any queries - please check your installation.");
664 for (i = 0; i < ci->children_num; ++i) {
665 oconfig_item_t *c = ci->children + i;
667 if (0 == strcasecmp (c->key, "Query"))
668 udb_query_create (&queries, &queries_num, c,
669 /* callback = */ config_query_callback,
670 /* legacy mode = */ 1);
671 else if (0 == strcasecmp (c->key, "Database"))
672 c_psql_config_database (c);
674 log_warn ("Ignoring unknown config key \"%s\".", c->key);
677 } /* c_psql_config */
679 void module_register (void)
681 plugin_register_complex_config ("postgresql", c_psql_config);
682 plugin_register_init ("postgresql", c_psql_init);
683 } /* module_register */
685 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */