2 * collectd - src/postgresql.c
3 * Copyright (C) 2008 Sebastian Harl
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Sebastian Harl <sh at tokkee.org>
23 * This module collects PostgreSQL database statistics.
29 #include "configfile.h"
32 #include "utils_complain.h"
34 #include <pg_config_manual.h>
37 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
38 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
39 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
41 #ifndef C_PSQL_DEFAULT_CONF
42 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
45 /* Appends the (parameter, value) pair to the string
46 * pointed to by 'buf' suitable to be used as argument
47 * for PQconnectdb(). If value equals NULL, the pair
49 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
50 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
51 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
58 /* Returns the tuple (major, minor, patchlevel)
59 * for the given version number. */
60 #define C_PSQL_SERVER_VERSION3(server_version) \
61 (server_version) / 10000, \
62 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
63 (server_version) - (int)((server_version) / 100) * 100
65 /* Returns true if the given host specifies a
66 * UNIX domain socket. */
67 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
68 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
70 /* Returns the tuple (host, delimiter, port) for a
71 * given (host, port) pair. Depending on the value of
72 * 'host' a UNIX domain socket or a TCP socket is
74 #define C_PSQL_SOCKET3(host, port) \
75 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
76 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
80 C_PSQL_PARAM_HOST = 1,
95 c_psql_param_t *params;
104 c_complain_t conn_complaint;
108 /* user configuration */
109 c_psql_query_t **queries;
125 static char *def_queries[] = {
129 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
131 static c_psql_query_t *queries = NULL;
132 static int queries_num = 0;
134 static c_psql_database_t *databases = NULL;
135 static int databases_num = 0;
137 static c_psql_query_t *c_psql_query_new (const char *name)
139 c_psql_query_t *query;
142 if (NULL == (queries = (c_psql_query_t *)realloc (queries,
143 queries_num * sizeof (*queries)))) {
144 log_err ("Out of memory.");
147 query = queries + queries_num - 1;
149 query->name = sstrdup (name);
152 query->params = NULL;
153 query->params_num = 0;
158 } /* c_psql_query_new */
160 static void c_psql_query_delete (c_psql_query_t *query)
165 sfree (query->query);
167 sfree (query->params);
168 query->params_num = 0;
170 for (i = 0; i < query->cols_num; ++i) {
171 sfree (query->cols[i].type);
172 sfree (query->cols[i].type_instance);
177 } /* c_psql_query_delete */
179 static c_psql_query_t *c_psql_query_get (const char *name)
183 for (i = 0; i < queries_num; ++i)
184 if (0 == strcasecmp (name, queries[i].name))
187 } /* c_psql_query_get */
189 static c_psql_database_t *c_psql_database_new (const char *name)
191 c_psql_database_t *db;
194 if (NULL == (databases = (c_psql_database_t *)realloc (databases,
195 databases_num * sizeof (*databases)))) {
196 log_err ("Out of memory.");
200 db = databases + (databases_num - 1);
204 db->conn_complaint.last = 0;
205 db->conn_complaint.interval = 0;
207 db->max_params_num = 0;
212 db->database = sstrdup (name);
220 db->krbsrvname = NULL;
224 } /* c_psql_database_new */
226 static void c_psql_database_delete (c_psql_database_t *db)
233 sfree (db->database);
237 sfree (db->password);
241 sfree (db->krbsrvname);
245 } /* c_psql_database_delete */
247 static void submit (const c_psql_database_t *db,
248 const char *type, const char *type_instance,
249 value_t *values, size_t values_len)
251 value_list_t vl = VALUE_LIST_INIT;
254 vl.values_len = values_len;
255 vl.time = time (NULL);
257 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
258 || (0 == strcmp (db->host, "localhost")))
259 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
261 sstrncpy (vl.host, db->host, sizeof (vl.host));
263 sstrncpy (vl.plugin, "postgresql", sizeof (vl.plugin));
264 sstrncpy (vl.plugin_instance, db->database, sizeof (vl.plugin_instance));
266 sstrncpy (vl.type, type, sizeof (vl.type));
268 if (NULL != type_instance)
269 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
271 plugin_dispatch_values (&vl);
275 static void submit_counter (const c_psql_database_t *db,
276 const char *type, const char *type_instance,
281 if ((NULL == value) || ('\0' == *value))
284 values[0].counter = atoll (value);
285 submit (db, type, type_instance, values, 1);
287 } /* submit_counter */
289 static void submit_gauge (const c_psql_database_t *db,
290 const char *type, const char *type_instance,
295 if ((NULL == value) || ('\0' == *value))
298 values[0].gauge = atof (value);
299 submit (db, type, type_instance, values, 1);
303 static int c_psql_check_connection (c_psql_database_t *db)
306 PQclear (PQexec (db->conn, "SELECT 42;"));
308 if (CONNECTION_OK != PQstatus (db->conn)) {
311 /* trigger c_release() */
312 if (0 == db->conn_complaint.interval)
313 db->conn_complaint.interval = 1;
315 if (CONNECTION_OK != PQstatus (db->conn)) {
316 c_complain (LOG_ERR, &db->conn_complaint,
317 "Failed to connect to database %s: %s",
318 db->database, PQerrorMessage (db->conn));
323 c_release (LOG_INFO, &db->conn_complaint,
324 "Successfully reconnected to database %s", PQdb (db->conn));
326 } /* c_psql_check_connection */
328 static int c_psql_exec_query (c_psql_database_t *db, int idx)
330 c_psql_query_t *query;
333 char *params[db->max_params_num];
338 if (idx >= db->queries_num)
341 query = db->queries[idx];
343 assert (db->max_params_num >= query->params_num);
345 for (i = 0; i < query->params_num; ++i) {
346 switch (query->params[i]) {
347 case C_PSQL_PARAM_HOST:
348 params[i] = (NULL == db->host) ? "localhost" : db->host;
350 case C_PSQL_PARAM_DB:
351 params[i] = db->database;
353 case C_PSQL_PARAM_USER:
354 params[i] = db->user;
361 res = PQexecParams (db->conn, query->query, query->params_num, NULL,
362 (const char *const *)((0 == query->params_num) ? NULL : params),
363 NULL, NULL, /* return text data */ 0);
365 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
366 log_err ("Failed to execute SQL query: %s",
367 PQerrorMessage (db->conn));
368 log_info ("SQL query was: %s", query->query);
373 rows = PQntuples (res);
377 cols = PQnfields (res);
378 if (query->cols_num != cols) {
379 log_err ("SQL query returned wrong number of fields "
380 "(expected: %i, got: %i)", query->cols_num, cols);
381 log_info ("SQL query was: %s", query->query);
385 for (i = 0; i < rows; ++i) {
388 for (j = 0; j < cols; ++j) {
389 c_psql_col_t col = query->cols[j];
391 char *value = PQgetvalue (res, i, j);
393 if (col.ds_type == DS_TYPE_COUNTER)
394 submit_counter (db, col.type, col.type_instance, value);
395 else if (col.ds_type == DS_TYPE_GAUGE)
396 submit_gauge (db, col.type, col.type_instance, value);
400 } /* c_psql_exec_query */
402 static int c_psql_stat_database (c_psql_database_t *db)
404 const char *const query =
405 "SELECT numbackends, xact_commit, xact_rollback "
406 "FROM pg_stat_database "
407 "WHERE datname = $1;";
413 res = PQexecParams (db->conn, query, /* number of parameters */ 1,
414 NULL, (const char *const *)&db->database, NULL, NULL,
415 /* return text data */ 0);
417 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
418 log_err ("Failed to execute SQL query: %s",
419 PQerrorMessage (db->conn));
420 log_info ("SQL query was: %s", query);
427 log_warn ("pg_stat_database has more than one entry "
428 "for database %s - ignoring additional results.",
432 log_err ("pg_stat_database has no entry for database %s",
438 submit_gauge (db, "pg_numbackends", NULL, PQgetvalue (res, 0, 0));
440 submit_counter (db, "pg_xact", "commit", PQgetvalue (res, 0, 1));
441 submit_counter (db, "pg_xact", "rollback", PQgetvalue (res, 0, 2));
445 } /* c_psql_stat_database */
447 static int c_psql_read (void)
452 for (i = 0; i < databases_num; ++i) {
453 c_psql_database_t *db = databases + i;
457 assert (NULL != db->database);
459 if (0 != c_psql_check_connection (db))
462 c_psql_stat_database (db);
464 for (j = 0; j < db->queries_num; ++j)
465 c_psql_exec_query (db, j);
475 static int c_psql_shutdown (void)
479 if ((NULL == databases) || (0 == databases_num))
482 plugin_unregister_read ("postgresql");
483 plugin_unregister_shutdown ("postgresql");
485 for (i = 0; i < databases_num; ++i) {
486 c_psql_database_t *db = databases + i;
487 c_psql_database_delete (db);
493 for (i = 0; i < queries_num; ++i) {
494 c_psql_query_t *query = queries + i;
495 c_psql_query_delete (query);
501 } /* c_psql_shutdown */
503 static int c_psql_init (void)
507 if ((NULL == databases) || (0 == databases_num))
510 for (i = 0; i < queries_num; ++i) {
511 c_psql_query_t *query = queries + i;
514 for (j = 0; j < query->cols_num; ++j) {
515 c_psql_col_t *col = query->cols + j;
516 const data_set_t *ds;
518 ds = plugin_get_ds (col->type);
520 log_err ("Column: Unknown type \"%s\".", col->type);
525 if (1 != ds->ds_num) {
526 log_err ("Column: Invalid type \"%s\" - types defining "
527 "one data source are supported only (got: %i).",
528 col->type, ds->ds_num);
533 col->ds_type = ds->ds[0].type;
537 for (i = 0; i < databases_num; ++i) {
538 c_psql_database_t *db = databases + i;
541 char *buf = conninfo;
542 int buf_len = sizeof (conninfo);
548 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
554 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
555 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
556 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
557 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
558 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
559 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
560 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
562 db->conn = PQconnectdb (conninfo);
563 if (0 != c_psql_check_connection (db))
566 server_host = PQhost (db->conn);
567 server_version = PQserverVersion (db->conn);
568 log_info ("Sucessfully connected to database %s (user %s) "
569 "at server %s%s%s (server version: %d.%d.%d, "
570 "protocol version: %d, pid: %d)",
571 PQdb (db->conn), PQuser (db->conn),
572 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
573 C_PSQL_SERVER_VERSION3 (server_version),
574 PQprotocolVersion (db->conn), PQbackendPID (db->conn));
577 plugin_register_read ("postgresql", c_psql_read);
578 plugin_register_shutdown ("postgresql", c_psql_shutdown);
582 static int config_set (char *name, char **var, const oconfig_item_t *ci)
584 if ((0 != ci->children_num) || (1 != ci->values_num)
585 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
586 log_err ("%s expects a single string argument.", name);
591 *var = sstrdup (ci->values[0].value.string);
595 static int config_set_param (c_psql_query_t *query, const oconfig_item_t *ci)
597 c_psql_param_t param;
600 if ((0 != ci->children_num) || (1 != ci->values_num)
601 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
602 log_err ("Param expects a single string argument.");
606 param_str = ci->values[0].value.string;
607 if (0 == strcasecmp (param_str, "hostname"))
608 param = C_PSQL_PARAM_HOST;
609 else if (0 == strcasecmp (param_str, "database"))
610 param = C_PSQL_PARAM_DB;
611 else if (0 == strcasecmp (param_str, "username"))
612 param = C_PSQL_PARAM_USER;
614 log_err ("Invalid parameter \"%s\".", param_str);
619 if (NULL == (query->params = (c_psql_param_t *)realloc (query->params,
620 query->params_num * sizeof (*query->params)))) {
621 log_err ("Out of memory.");
625 query->params[query->params_num - 1] = param;
627 } /* config_set_param */
629 static int config_set_column (c_psql_query_t *query, const oconfig_item_t *ci)
635 if ((0 != ci->children_num)
636 || (1 > ci->values_num) || (2 < ci->values_num)) {
637 log_err ("Column expects either one or two arguments.");
641 for (i = 0; i < ci->values_num; ++i) {
642 if (OCONFIG_TYPE_STRING != ci->values[i].type) {
643 log_err ("Column expects either one or two string arguments.");
649 if (NULL == (query->cols = (c_psql_col_t *)realloc (query->cols,
650 query->cols_num * sizeof (*query->cols)))) {
651 log_err ("Out of memory.");
655 col = query->cols + query->cols_num - 1;
659 col->type = sstrdup (ci->values[0].value.string);
660 col->type_instance = (2 == ci->values_num)
661 ? sstrdup (ci->values[1].value.string) : NULL;
663 } /* config_set_column */
665 static int config_set_query (c_psql_database_t *db, const oconfig_item_t *ci)
667 c_psql_query_t *query;
669 if ((0 != ci->children_num) || (1 != ci->values_num)
670 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
671 log_err ("Query expects a single string argument.");
675 query = c_psql_query_get (ci->values[0].value.string);
677 log_err ("Query \"%s\" not found - please check your configuration.",
678 ci->values[0].value.string);
683 if (NULL == (db->queries = (c_psql_query_t **)realloc (db->queries,
684 db->queries_num * sizeof (*db->queries)))) {
685 log_err ("Out of memory.");
689 if (query->params_num > db->max_params_num)
690 db->max_params_num = query->params_num;
692 db->queries[db->queries_num - 1] = query;
694 } /* config_set_query */
696 static int c_psql_config_query (oconfig_item_t *ci)
698 c_psql_query_t *query;
702 if ((1 != ci->values_num)
703 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
704 log_err ("<Query> expects a single string argument.");
708 query = c_psql_query_new (ci->values[0].value.string);
710 for (i = 0; i < ci->children_num; ++i) {
711 oconfig_item_t *c = ci->children + i;
713 if (0 == strcasecmp (c->key, "Query"))
714 config_set ("Query", &query->query, c);
715 else if (0 == strcasecmp (c->key, "Param"))
716 config_set_param (query, c);
717 else if (0 == strcasecmp (c->key, "Column"))
718 config_set_column (query, c);
720 log_warn ("Ignoring unknown config key \"%s\".", c->key);
723 } /* c_psql_config_query */
725 static int c_psql_config_database (oconfig_item_t *ci)
727 c_psql_database_t *db;
731 if ((1 != ci->values_num)
732 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
733 log_err ("<Database> expects a single string argument.");
737 db = c_psql_database_new (ci->values[0].value.string);
739 for (i = 0; i < ci->children_num; ++i) {
740 oconfig_item_t *c = ci->children + i;
742 if (0 == strcasecmp (c->key, "Host"))
743 config_set ("Host", &db->host, c);
744 else if (0 == strcasecmp (c->key, "Port"))
745 config_set ("Port", &db->port, c);
746 else if (0 == strcasecmp (c->key, "User"))
747 config_set ("User", &db->user, c);
748 else if (0 == strcasecmp (c->key, "Password"))
749 config_set ("Password", &db->password, c);
750 else if (0 == strcasecmp (c->key, "SSLMode"))
751 config_set ("SSLMode", &db->sslmode, c);
752 else if (0 == strcasecmp (c->key, "KRBSrvName"))
753 config_set ("KRBSrvName", &db->krbsrvname, c);
754 else if (0 == strcasecmp (c->key, "Service"))
755 config_set ("Service", &db->service, c);
756 else if (0 == strcasecmp (c->key, "Query"))
757 config_set_query (db, c);
759 log_warn ("Ignoring unknown config key \"%s\".", c->key);
762 if (NULL == db->queries) {
763 db->queries = (c_psql_query_t **)malloc (def_queries_num
764 * sizeof (*db->queries));
766 for (i = 0; i < def_queries_num; ++i) {
767 db->queries[i] = c_psql_query_get (def_queries[i]);
768 if (NULL == db->queries[i])
769 log_err ("Query \"%s\" not found - "
770 "please check your installation.",
779 static int c_psql_config (oconfig_item_t *ci)
781 static int have_def_config = 0;
785 if (0 == have_def_config) {
790 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
792 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
797 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
798 "any queries - please check your installation.");
801 for (i = 0; i < ci->children_num; ++i) {
802 oconfig_item_t *c = ci->children + i;
804 if (0 == strcasecmp (c->key, "Query"))
805 c_psql_config_query (c);
806 else if (0 == strcasecmp (c->key, "Database"))
807 c_psql_config_database (c);
809 log_warn ("Ignoring unknown config key \"%s\".", c->key);
812 } /* c_psql_config */
814 void module_register (void)
816 plugin_register_complex_config ("postgresql", c_psql_config);
817 plugin_register_init ("postgresql", c_psql_init);
818 } /* module_register */
820 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */