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[] = {
133 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
135 static c_psql_query_t *queries = NULL;
136 static int queries_num = 0;
138 static c_psql_database_t *databases = NULL;
139 static int databases_num = 0;
141 static c_psql_query_t *c_psql_query_new (const char *name)
143 c_psql_query_t *query;
146 if (NULL == (queries = (c_psql_query_t *)realloc (queries,
147 queries_num * sizeof (*queries)))) {
148 log_err ("Out of memory.");
151 query = queries + queries_num - 1;
153 query->name = sstrdup (name);
156 query->params = NULL;
157 query->params_num = 0;
162 } /* c_psql_query_new */
164 static void c_psql_query_delete (c_psql_query_t *query)
169 sfree (query->query);
171 sfree (query->params);
172 query->params_num = 0;
174 for (i = 0; i < query->cols_num; ++i) {
175 sfree (query->cols[i].type);
176 sfree (query->cols[i].type_instance);
181 } /* c_psql_query_delete */
183 static c_psql_query_t *c_psql_query_get (const char *name)
187 for (i = 0; i < queries_num; ++i)
188 if (0 == strcasecmp (name, queries[i].name))
191 } /* c_psql_query_get */
193 static c_psql_database_t *c_psql_database_new (const char *name)
195 c_psql_database_t *db;
198 if (NULL == (databases = (c_psql_database_t *)realloc (databases,
199 databases_num * sizeof (*databases)))) {
200 log_err ("Out of memory.");
204 db = databases + (databases_num - 1);
208 db->conn_complaint.last = 0;
209 db->conn_complaint.interval = 0;
211 db->max_params_num = 0;
216 db->database = sstrdup (name);
224 db->krbsrvname = NULL;
228 } /* c_psql_database_new */
230 static void c_psql_database_delete (c_psql_database_t *db)
237 sfree (db->database);
241 sfree (db->password);
245 sfree (db->krbsrvname);
249 } /* c_psql_database_delete */
251 static void submit (const c_psql_database_t *db,
252 const char *type, const char *type_instance,
253 value_t *values, size_t values_len)
255 value_list_t vl = VALUE_LIST_INIT;
258 vl.values_len = values_len;
259 vl.time = time (NULL);
261 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
262 || (0 == strcmp (db->host, "localhost")))
263 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
265 sstrncpy (vl.host, db->host, sizeof (vl.host));
267 sstrncpy (vl.plugin, "postgresql", sizeof (vl.plugin));
268 sstrncpy (vl.plugin_instance, db->database, sizeof (vl.plugin_instance));
270 sstrncpy (vl.type, type, sizeof (vl.type));
272 if (NULL != type_instance)
273 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
275 plugin_dispatch_values (&vl);
279 static void submit_counter (const c_psql_database_t *db,
280 const char *type, const char *type_instance,
285 if ((NULL == value) || ('\0' == *value))
288 values[0].counter = atoll (value);
289 submit (db, type, type_instance, values, 1);
291 } /* submit_counter */
293 static void submit_gauge (const c_psql_database_t *db,
294 const char *type, const char *type_instance,
299 if ((NULL == value) || ('\0' == *value))
302 values[0].gauge = atof (value);
303 submit (db, type, type_instance, values, 1);
307 static int c_psql_check_connection (c_psql_database_t *db)
310 PQclear (PQexec (db->conn, "SELECT 42;"));
312 if (CONNECTION_OK != PQstatus (db->conn)) {
315 /* trigger c_release() */
316 if (0 == db->conn_complaint.interval)
317 db->conn_complaint.interval = 1;
319 if (CONNECTION_OK != PQstatus (db->conn)) {
320 c_complain (LOG_ERR, &db->conn_complaint,
321 "Failed to connect to database %s: %s",
322 db->database, PQerrorMessage (db->conn));
327 c_release (LOG_INFO, &db->conn_complaint,
328 "Successfully reconnected to database %s", PQdb (db->conn));
330 } /* c_psql_check_connection */
332 static int c_psql_exec_query (c_psql_database_t *db, int idx)
334 c_psql_query_t *query;
337 char *params[db->max_params_num];
342 if (idx >= db->queries_num)
345 query = db->queries[idx];
347 assert (db->max_params_num >= query->params_num);
349 for (i = 0; i < query->params_num; ++i) {
350 switch (query->params[i]) {
351 case C_PSQL_PARAM_HOST:
352 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
353 ? "localhost" : db->host;
355 case C_PSQL_PARAM_DB:
356 params[i] = db->database;
358 case C_PSQL_PARAM_USER:
359 params[i] = db->user;
366 res = PQexecParams (db->conn, query->query, query->params_num, NULL,
367 (const char *const *)((0 == query->params_num) ? NULL : params),
368 NULL, NULL, /* return text data */ 0);
370 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
371 log_err ("Failed to execute SQL query: %s",
372 PQerrorMessage (db->conn));
373 log_info ("SQL query was: %s", query->query);
378 rows = PQntuples (res);
382 cols = PQnfields (res);
383 if (query->cols_num != cols) {
384 log_err ("SQL query returned wrong number of fields "
385 "(expected: %i, got: %i)", query->cols_num, cols);
386 log_info ("SQL query was: %s", query->query);
390 for (i = 0; i < rows; ++i) {
393 for (j = 0; j < cols; ++j) {
394 c_psql_col_t col = query->cols[j];
396 char *value = PQgetvalue (res, i, j);
398 if (col.ds_type == DS_TYPE_COUNTER)
399 submit_counter (db, col.type, col.type_instance, value);
400 else if (col.ds_type == DS_TYPE_GAUGE)
401 submit_gauge (db, col.type, col.type_instance, value);
405 } /* c_psql_exec_query */
407 static int c_psql_read (void)
412 for (i = 0; i < databases_num; ++i) {
413 c_psql_database_t *db = databases + i;
417 assert (NULL != db->database);
419 if (0 != c_psql_check_connection (db))
422 for (j = 0; j < db->queries_num; ++j)
423 c_psql_exec_query (db, j);
433 static int c_psql_shutdown (void)
437 if ((NULL == databases) || (0 == databases_num))
440 plugin_unregister_read ("postgresql");
441 plugin_unregister_shutdown ("postgresql");
443 for (i = 0; i < databases_num; ++i) {
444 c_psql_database_t *db = databases + i;
445 c_psql_database_delete (db);
451 for (i = 0; i < queries_num; ++i) {
452 c_psql_query_t *query = queries + i;
453 c_psql_query_delete (query);
459 } /* c_psql_shutdown */
461 static int c_psql_init (void)
465 if ((NULL == databases) || (0 == databases_num))
468 for (i = 0; i < queries_num; ++i) {
469 c_psql_query_t *query = queries + i;
472 for (j = 0; j < query->cols_num; ++j) {
473 c_psql_col_t *col = query->cols + j;
474 const data_set_t *ds;
476 ds = plugin_get_ds (col->type);
478 log_err ("Column: Unknown type \"%s\".", col->type);
483 if (1 != ds->ds_num) {
484 log_err ("Column: Invalid type \"%s\" - types defining "
485 "one data source are supported only (got: %i).",
486 col->type, ds->ds_num);
491 col->ds_type = ds->ds[0].type;
495 for (i = 0; i < databases_num; ++i) {
496 c_psql_database_t *db = databases + i;
499 char *buf = conninfo;
500 int buf_len = sizeof (conninfo);
506 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
512 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
513 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
514 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
515 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
516 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
517 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
518 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
520 db->conn = PQconnectdb (conninfo);
521 if (0 != c_psql_check_connection (db))
524 server_host = PQhost (db->conn);
525 server_version = PQserverVersion (db->conn);
526 log_info ("Sucessfully connected to database %s (user %s) "
527 "at server %s%s%s (server version: %d.%d.%d, "
528 "protocol version: %d, pid: %d)",
529 PQdb (db->conn), PQuser (db->conn),
530 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
531 C_PSQL_SERVER_VERSION3 (server_version),
532 PQprotocolVersion (db->conn), PQbackendPID (db->conn));
535 plugin_register_read ("postgresql", c_psql_read);
536 plugin_register_shutdown ("postgresql", c_psql_shutdown);
540 static int config_set (char *name, char **var, const oconfig_item_t *ci)
542 if ((0 != ci->children_num) || (1 != ci->values_num)
543 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
544 log_err ("%s expects a single string argument.", name);
549 *var = sstrdup (ci->values[0].value.string);
553 static int config_set_param (c_psql_query_t *query, const oconfig_item_t *ci)
555 c_psql_param_t param;
558 if ((0 != ci->children_num) || (1 != ci->values_num)
559 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
560 log_err ("Param expects a single string argument.");
564 param_str = ci->values[0].value.string;
565 if (0 == strcasecmp (param_str, "hostname"))
566 param = C_PSQL_PARAM_HOST;
567 else if (0 == strcasecmp (param_str, "database"))
568 param = C_PSQL_PARAM_DB;
569 else if (0 == strcasecmp (param_str, "username"))
570 param = C_PSQL_PARAM_USER;
572 log_err ("Invalid parameter \"%s\".", param_str);
577 if (NULL == (query->params = (c_psql_param_t *)realloc (query->params,
578 query->params_num * sizeof (*query->params)))) {
579 log_err ("Out of memory.");
583 query->params[query->params_num - 1] = param;
585 } /* config_set_param */
587 static int config_set_column (c_psql_query_t *query, const oconfig_item_t *ci)
593 if ((0 != ci->children_num)
594 || (1 > ci->values_num) || (2 < ci->values_num)) {
595 log_err ("Column expects either one or two arguments.");
599 for (i = 0; i < ci->values_num; ++i) {
600 if (OCONFIG_TYPE_STRING != ci->values[i].type) {
601 log_err ("Column expects either one or two string arguments.");
607 if (NULL == (query->cols = (c_psql_col_t *)realloc (query->cols,
608 query->cols_num * sizeof (*query->cols)))) {
609 log_err ("Out of memory.");
613 col = query->cols + query->cols_num - 1;
617 col->type = sstrdup (ci->values[0].value.string);
618 col->type_instance = (2 == ci->values_num)
619 ? sstrdup (ci->values[1].value.string) : NULL;
621 } /* config_set_column */
623 static int config_set_query (c_psql_database_t *db, const oconfig_item_t *ci)
625 c_psql_query_t *query;
627 if ((0 != ci->children_num) || (1 != ci->values_num)
628 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
629 log_err ("Query expects a single string argument.");
633 query = c_psql_query_get (ci->values[0].value.string);
635 log_err ("Query \"%s\" not found - please check your configuration.",
636 ci->values[0].value.string);
641 if (NULL == (db->queries = (c_psql_query_t **)realloc (db->queries,
642 db->queries_num * sizeof (*db->queries)))) {
643 log_err ("Out of memory.");
647 if (query->params_num > db->max_params_num)
648 db->max_params_num = query->params_num;
650 db->queries[db->queries_num - 1] = query;
652 } /* config_set_query */
654 static int c_psql_config_query (oconfig_item_t *ci)
656 c_psql_query_t *query;
660 if ((1 != ci->values_num)
661 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
662 log_err ("<Query> expects a single string argument.");
666 query = c_psql_query_new (ci->values[0].value.string);
668 for (i = 0; i < ci->children_num; ++i) {
669 oconfig_item_t *c = ci->children + i;
671 if (0 == strcasecmp (c->key, "Query"))
672 config_set ("Query", &query->query, c);
673 else if (0 == strcasecmp (c->key, "Param"))
674 config_set_param (query, c);
675 else if (0 == strcasecmp (c->key, "Column"))
676 config_set_column (query, c);
678 log_warn ("Ignoring unknown config key \"%s\".", c->key);
681 } /* c_psql_config_query */
683 static int c_psql_config_database (oconfig_item_t *ci)
685 c_psql_database_t *db;
689 if ((1 != ci->values_num)
690 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
691 log_err ("<Database> expects a single string argument.");
695 db = c_psql_database_new (ci->values[0].value.string);
697 for (i = 0; i < ci->children_num; ++i) {
698 oconfig_item_t *c = ci->children + i;
700 if (0 == strcasecmp (c->key, "Host"))
701 config_set ("Host", &db->host, c);
702 else if (0 == strcasecmp (c->key, "Port"))
703 config_set ("Port", &db->port, c);
704 else if (0 == strcasecmp (c->key, "User"))
705 config_set ("User", &db->user, c);
706 else if (0 == strcasecmp (c->key, "Password"))
707 config_set ("Password", &db->password, c);
708 else if (0 == strcasecmp (c->key, "SSLMode"))
709 config_set ("SSLMode", &db->sslmode, c);
710 else if (0 == strcasecmp (c->key, "KRBSrvName"))
711 config_set ("KRBSrvName", &db->krbsrvname, c);
712 else if (0 == strcasecmp (c->key, "Service"))
713 config_set ("Service", &db->service, c);
714 else if (0 == strcasecmp (c->key, "Query"))
715 config_set_query (db, c);
717 log_warn ("Ignoring unknown config key \"%s\".", c->key);
720 if (NULL == db->queries) {
721 db->queries = (c_psql_query_t **)malloc (def_queries_num
722 * sizeof (*db->queries));
724 for (i = 0; i < def_queries_num; ++i) {
725 db->queries[i] = c_psql_query_get (def_queries[i]);
726 if (NULL == db->queries[i])
727 log_err ("Query \"%s\" not found - "
728 "please check your installation.",
737 static int c_psql_config (oconfig_item_t *ci)
739 static int have_def_config = 0;
743 if (0 == have_def_config) {
748 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
750 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
755 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
756 "any queries - please check your installation.");
759 for (i = 0; i < ci->children_num; ++i) {
760 oconfig_item_t *c = ci->children + i;
762 if (0 == strcasecmp (c->key, "Query"))
763 c_psql_config_query (c);
764 else if (0 == strcasecmp (c->key, "Database"))
765 c_psql_config_database (c);
767 log_warn ("Ignoring unknown config key \"%s\".", c->key);
770 } /* c_psql_config */
772 void module_register (void)
774 plugin_register_complex_config ("postgresql", c_psql_config);
775 plugin_register_init ("postgresql", c_psql_init);
776 } /* module_register */
778 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */