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;
110 /* user configuration */
111 c_psql_query_t **queries;
127 static char *def_queries[] = {
136 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
138 static c_psql_query_t *queries = NULL;
139 static int queries_num = 0;
141 static c_psql_database_t *databases = NULL;
142 static int databases_num = 0;
144 static c_psql_query_t *c_psql_query_new (const char *name)
146 c_psql_query_t *query;
149 if (NULL == (queries = (c_psql_query_t *)realloc (queries,
150 queries_num * sizeof (*queries)))) {
151 log_err ("Out of memory.");
154 query = queries + queries_num - 1;
156 query->name = sstrdup (name);
159 query->params = NULL;
160 query->params_num = 0;
165 } /* c_psql_query_new */
167 static void c_psql_query_delete (c_psql_query_t *query)
172 sfree (query->query);
174 sfree (query->params);
175 query->params_num = 0;
177 for (i = 0; i < query->cols_num; ++i) {
178 sfree (query->cols[i].type);
179 sfree (query->cols[i].type_instance);
184 } /* c_psql_query_delete */
186 static c_psql_query_t *c_psql_query_get (const char *name)
190 for (i = 0; i < queries_num; ++i)
191 if (0 == strcasecmp (name, queries[i].name))
194 } /* c_psql_query_get */
196 static c_psql_database_t *c_psql_database_new (const char *name)
198 c_psql_database_t *db;
201 if (NULL == (databases = (c_psql_database_t *)realloc (databases,
202 databases_num * sizeof (*databases)))) {
203 log_err ("Out of memory.");
207 db = databases + (databases_num - 1);
211 db->conn_complaint.last = 0;
212 db->conn_complaint.interval = 0;
214 db->proto_version = 0;
216 db->max_params_num = 0;
221 db->database = sstrdup (name);
229 db->krbsrvname = NULL;
233 } /* c_psql_database_new */
235 static void c_psql_database_delete (c_psql_database_t *db)
242 sfree (db->database);
246 sfree (db->password);
250 sfree (db->krbsrvname);
254 } /* c_psql_database_delete */
256 static void submit (const c_psql_database_t *db,
257 const char *type, const char *type_instance,
258 value_t *values, size_t values_len)
260 value_list_t vl = VALUE_LIST_INIT;
263 vl.values_len = values_len;
264 vl.time = time (NULL);
266 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
267 || (0 == strcmp (db->host, "localhost")))
268 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
270 sstrncpy (vl.host, db->host, sizeof (vl.host));
272 sstrncpy (vl.plugin, "postgresql", sizeof (vl.plugin));
273 sstrncpy (vl.plugin_instance, db->database, sizeof (vl.plugin_instance));
275 sstrncpy (vl.type, type, sizeof (vl.type));
277 if (NULL != type_instance)
278 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
280 plugin_dispatch_values (&vl);
284 static void submit_counter (const c_psql_database_t *db,
285 const char *type, const char *type_instance,
290 if ((NULL == value) || ('\0' == *value))
293 values[0].counter = atoll (value);
294 submit (db, type, type_instance, values, 1);
296 } /* submit_counter */
298 static void submit_gauge (const c_psql_database_t *db,
299 const char *type, const char *type_instance,
304 if ((NULL == value) || ('\0' == *value))
307 values[0].gauge = atof (value);
308 submit (db, type, type_instance, values, 1);
312 static int c_psql_check_connection (c_psql_database_t *db)
315 PQclear (PQexec (db->conn, "SELECT 42;"));
317 if (CONNECTION_OK != PQstatus (db->conn)) {
320 /* trigger c_release() */
321 if (0 == db->conn_complaint.interval)
322 db->conn_complaint.interval = 1;
324 if (CONNECTION_OK != PQstatus (db->conn)) {
325 c_complain (LOG_ERR, &db->conn_complaint,
326 "Failed to connect to database %s: %s",
327 db->database, PQerrorMessage (db->conn));
331 db->proto_version = PQprotocolVersion (db->conn);
332 if (3 > db->proto_version)
333 log_warn ("Protocol version %d does not support parameters.",
337 c_release (LOG_INFO, &db->conn_complaint,
338 "Successfully reconnected to database %s", PQdb (db->conn));
340 } /* c_psql_check_connection */
342 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
343 c_psql_query_t *query)
345 char *params[db->max_params_num];
348 assert (db->max_params_num >= query->params_num);
350 for (i = 0; i < query->params_num; ++i) {
351 switch (query->params[i]) {
352 case C_PSQL_PARAM_HOST:
353 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
354 ? "localhost" : db->host;
356 case C_PSQL_PARAM_DB:
357 params[i] = db->database;
359 case C_PSQL_PARAM_USER:
360 params[i] = db->user;
367 return PQexecParams (db->conn, query->query, query->params_num, NULL,
368 (const char *const *)((0 == query->params_num) ? NULL : params),
369 NULL, NULL, /* return text data */ 0);
370 } /* c_psql_exec_query_params */
372 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
373 c_psql_query_t *query)
375 return PQexec (db->conn, query->query);
376 } /* c_psql_exec_query_noparams */
378 static int c_psql_exec_query (c_psql_database_t *db, int idx)
380 c_psql_query_t *query;
386 if (idx >= db->queries_num)
389 query = db->queries[idx];
391 if (3 <= db->proto_version)
392 res = c_psql_exec_query_params (db, query);
393 else if (0 == query->params_num)
394 res = c_psql_exec_query_noparams (db, query);
396 log_err ("Connection to database \"%s\" does not support parameters "
397 "(protocol version %d) - cannot execute query \"%s\".",
398 db->database, db->proto_version, query->name);
402 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
403 log_err ("Failed to execute SQL query: %s",
404 PQerrorMessage (db->conn));
405 log_info ("SQL query was: %s", query->query);
410 rows = PQntuples (res);
414 cols = PQnfields (res);
415 if (query->cols_num != cols) {
416 log_err ("SQL query returned wrong number of fields "
417 "(expected: %i, got: %i)", query->cols_num, cols);
418 log_info ("SQL query was: %s", query->query);
422 for (i = 0; i < rows; ++i) {
425 for (j = 0; j < cols; ++j) {
426 c_psql_col_t col = query->cols[j];
428 char *value = PQgetvalue (res, i, j);
430 if (col.ds_type == DS_TYPE_COUNTER)
431 submit_counter (db, col.type, col.type_instance, value);
432 else if (col.ds_type == DS_TYPE_GAUGE)
433 submit_gauge (db, col.type, col.type_instance, value);
437 } /* c_psql_exec_query */
439 static int c_psql_read (void)
444 for (i = 0; i < databases_num; ++i) {
445 c_psql_database_t *db = databases + i;
449 assert (NULL != db->database);
451 if (0 != c_psql_check_connection (db))
454 for (j = 0; j < db->queries_num; ++j)
455 c_psql_exec_query (db, j);
465 static int c_psql_shutdown (void)
469 if ((NULL == databases) || (0 == databases_num))
472 plugin_unregister_read ("postgresql");
473 plugin_unregister_shutdown ("postgresql");
475 for (i = 0; i < databases_num; ++i) {
476 c_psql_database_t *db = databases + i;
477 c_psql_database_delete (db);
483 for (i = 0; i < queries_num; ++i) {
484 c_psql_query_t *query = queries + i;
485 c_psql_query_delete (query);
491 } /* c_psql_shutdown */
493 static int c_psql_init (void)
497 if ((NULL == databases) || (0 == databases_num))
500 for (i = 0; i < queries_num; ++i) {
501 c_psql_query_t *query = queries + i;
504 for (j = 0; j < query->cols_num; ++j) {
505 c_psql_col_t *col = query->cols + j;
506 const data_set_t *ds;
508 ds = plugin_get_ds (col->type);
510 log_err ("Column: Unknown type \"%s\".", col->type);
515 if (1 != ds->ds_num) {
516 log_err ("Column: Invalid type \"%s\" - types defining "
517 "one data source are supported only (got: %i).",
518 col->type, ds->ds_num);
523 col->ds_type = ds->ds[0].type;
527 for (i = 0; i < databases_num; ++i) {
528 c_psql_database_t *db = databases + i;
531 char *buf = conninfo;
532 int buf_len = sizeof (conninfo);
538 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
544 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
545 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
546 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
547 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
548 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
549 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
550 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
552 db->conn = PQconnectdb (conninfo);
553 if (0 != c_psql_check_connection (db))
556 db->proto_version = PQprotocolVersion (db->conn);
558 server_host = PQhost (db->conn);
559 server_version = PQserverVersion (db->conn);
560 log_info ("Sucessfully connected to database %s (user %s) "
561 "at server %s%s%s (server version: %d.%d.%d, "
562 "protocol version: %d, pid: %d)",
563 PQdb (db->conn), PQuser (db->conn),
564 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
565 C_PSQL_SERVER_VERSION3 (server_version),
566 db->proto_version, PQbackendPID (db->conn));
568 if (3 > db->proto_version)
569 log_warn ("Protocol version %d does not support parameters.",
573 plugin_register_read ("postgresql", c_psql_read);
574 plugin_register_shutdown ("postgresql", c_psql_shutdown);
578 static int config_set (char *name, char **var, const oconfig_item_t *ci)
580 if ((0 != ci->children_num) || (1 != ci->values_num)
581 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
582 log_err ("%s expects a single string argument.", name);
587 *var = sstrdup (ci->values[0].value.string);
591 static int config_set_param (c_psql_query_t *query, const oconfig_item_t *ci)
593 c_psql_param_t param;
596 if ((0 != ci->children_num) || (1 != ci->values_num)
597 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
598 log_err ("Param expects a single string argument.");
602 param_str = ci->values[0].value.string;
603 if (0 == strcasecmp (param_str, "hostname"))
604 param = C_PSQL_PARAM_HOST;
605 else if (0 == strcasecmp (param_str, "database"))
606 param = C_PSQL_PARAM_DB;
607 else if (0 == strcasecmp (param_str, "username"))
608 param = C_PSQL_PARAM_USER;
610 log_err ("Invalid parameter \"%s\".", param_str);
615 if (NULL == (query->params = (c_psql_param_t *)realloc (query->params,
616 query->params_num * sizeof (*query->params)))) {
617 log_err ("Out of memory.");
621 query->params[query->params_num - 1] = param;
623 } /* config_set_param */
625 static int config_set_column (c_psql_query_t *query, const oconfig_item_t *ci)
631 if ((0 != ci->children_num)
632 || (1 > ci->values_num) || (2 < ci->values_num)) {
633 log_err ("Column expects either one or two arguments.");
637 for (i = 0; i < ci->values_num; ++i) {
638 if (OCONFIG_TYPE_STRING != ci->values[i].type) {
639 log_err ("Column expects either one or two string arguments.");
645 if (NULL == (query->cols = (c_psql_col_t *)realloc (query->cols,
646 query->cols_num * sizeof (*query->cols)))) {
647 log_err ("Out of memory.");
651 col = query->cols + query->cols_num - 1;
655 col->type = sstrdup (ci->values[0].value.string);
656 col->type_instance = (2 == ci->values_num)
657 ? sstrdup (ci->values[1].value.string) : NULL;
659 } /* config_set_column */
661 static int set_query (c_psql_database_t *db, const char *name)
663 c_psql_query_t *query;
665 query = c_psql_query_get (name);
667 log_err ("Query \"%s\" not found - please check your configuration.",
673 if (NULL == (db->queries = (c_psql_query_t **)realloc (db->queries,
674 db->queries_num * sizeof (*db->queries)))) {
675 log_err ("Out of memory.");
679 if (query->params_num > db->max_params_num)
680 db->max_params_num = query->params_num;
682 db->queries[db->queries_num - 1] = query;
686 static int config_set_query (c_psql_database_t *db, const oconfig_item_t *ci)
688 if ((0 != ci->children_num) || (1 != ci->values_num)
689 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
690 log_err ("Query expects a single string argument.");
693 return set_query (db, ci->values[0].value.string);
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 for (i = 0; i < def_queries_num; ++i)
764 set_query (db, def_queries[i]);
769 static int c_psql_config (oconfig_item_t *ci)
771 static int have_def_config = 0;
775 if (0 == have_def_config) {
780 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
782 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
787 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
788 "any queries - please check your installation.");
791 for (i = 0; i < ci->children_num; ++i) {
792 oconfig_item_t *c = ci->children + i;
794 if (0 == strcasecmp (c->key, "Query"))
795 c_psql_config_query (c);
796 else if (0 == strcasecmp (c->key, "Database"))
797 c_psql_config_database (c);
799 log_warn ("Ignoring unknown config key \"%s\".", c->key);
802 } /* c_psql_config */
804 void module_register (void)
806 plugin_register_complex_config ("postgresql", c_psql_config);
807 plugin_register_init ("postgresql", c_psql_init);
808 } /* module_register */
810 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */