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[] = {
134 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
136 static c_psql_query_t *queries = NULL;
137 static int queries_num = 0;
139 static c_psql_database_t *databases = NULL;
140 static int databases_num = 0;
142 static c_psql_query_t *c_psql_query_new (const char *name)
144 c_psql_query_t *query;
147 if (NULL == (queries = (c_psql_query_t *)realloc (queries,
148 queries_num * sizeof (*queries)))) {
149 log_err ("Out of memory.");
152 query = queries + queries_num - 1;
154 query->name = sstrdup (name);
157 query->params = NULL;
158 query->params_num = 0;
163 } /* c_psql_query_new */
165 static void c_psql_query_delete (c_psql_query_t *query)
170 sfree (query->query);
172 sfree (query->params);
173 query->params_num = 0;
175 for (i = 0; i < query->cols_num; ++i) {
176 sfree (query->cols[i].type);
177 sfree (query->cols[i].type_instance);
182 } /* c_psql_query_delete */
184 static c_psql_query_t *c_psql_query_get (const char *name)
188 for (i = 0; i < queries_num; ++i)
189 if (0 == strcasecmp (name, queries[i].name))
192 } /* c_psql_query_get */
194 static c_psql_database_t *c_psql_database_new (const char *name)
196 c_psql_database_t *db;
199 if (NULL == (databases = (c_psql_database_t *)realloc (databases,
200 databases_num * sizeof (*databases)))) {
201 log_err ("Out of memory.");
205 db = databases + (databases_num - 1);
209 db->conn_complaint.last = 0;
210 db->conn_complaint.interval = 0;
212 db->max_params_num = 0;
217 db->database = sstrdup (name);
225 db->krbsrvname = NULL;
229 } /* c_psql_database_new */
231 static void c_psql_database_delete (c_psql_database_t *db)
238 sfree (db->database);
242 sfree (db->password);
246 sfree (db->krbsrvname);
250 } /* c_psql_database_delete */
252 static void submit (const c_psql_database_t *db,
253 const char *type, const char *type_instance,
254 value_t *values, size_t values_len)
256 value_list_t vl = VALUE_LIST_INIT;
259 vl.values_len = values_len;
260 vl.time = time (NULL);
262 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
263 || (0 == strcmp (db->host, "localhost")))
264 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
266 sstrncpy (vl.host, db->host, sizeof (vl.host));
268 sstrncpy (vl.plugin, "postgresql", sizeof (vl.plugin));
269 sstrncpy (vl.plugin_instance, db->database, sizeof (vl.plugin_instance));
271 sstrncpy (vl.type, type, sizeof (vl.type));
273 if (NULL != type_instance)
274 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
276 plugin_dispatch_values (&vl);
280 static void submit_counter (const c_psql_database_t *db,
281 const char *type, const char *type_instance,
286 if ((NULL == value) || ('\0' == *value))
289 values[0].counter = atoll (value);
290 submit (db, type, type_instance, values, 1);
292 } /* submit_counter */
294 static void submit_gauge (const c_psql_database_t *db,
295 const char *type, const char *type_instance,
300 if ((NULL == value) || ('\0' == *value))
303 values[0].gauge = atof (value);
304 submit (db, type, type_instance, values, 1);
308 static int c_psql_check_connection (c_psql_database_t *db)
311 PQclear (PQexec (db->conn, "SELECT 42;"));
313 if (CONNECTION_OK != PQstatus (db->conn)) {
316 /* trigger c_release() */
317 if (0 == db->conn_complaint.interval)
318 db->conn_complaint.interval = 1;
320 if (CONNECTION_OK != PQstatus (db->conn)) {
321 c_complain (LOG_ERR, &db->conn_complaint,
322 "Failed to connect to database %s: %s",
323 db->database, PQerrorMessage (db->conn));
328 c_release (LOG_INFO, &db->conn_complaint,
329 "Successfully reconnected to database %s", PQdb (db->conn));
331 } /* c_psql_check_connection */
333 static int c_psql_exec_query (c_psql_database_t *db, int idx)
335 c_psql_query_t *query;
338 char *params[db->max_params_num];
343 if (idx >= db->queries_num)
346 query = db->queries[idx];
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 res = 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);
371 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
372 log_err ("Failed to execute SQL query: %s",
373 PQerrorMessage (db->conn));
374 log_info ("SQL query was: %s", query->query);
379 rows = PQntuples (res);
383 cols = PQnfields (res);
384 if (query->cols_num != cols) {
385 log_err ("SQL query returned wrong number of fields "
386 "(expected: %i, got: %i)", query->cols_num, cols);
387 log_info ("SQL query was: %s", query->query);
391 for (i = 0; i < rows; ++i) {
394 for (j = 0; j < cols; ++j) {
395 c_psql_col_t col = query->cols[j];
397 char *value = PQgetvalue (res, i, j);
399 if (col.ds_type == DS_TYPE_COUNTER)
400 submit_counter (db, col.type, col.type_instance, value);
401 else if (col.ds_type == DS_TYPE_GAUGE)
402 submit_gauge (db, col.type, col.type_instance, value);
406 } /* c_psql_exec_query */
408 static int c_psql_read (void)
413 for (i = 0; i < databases_num; ++i) {
414 c_psql_database_t *db = databases + i;
418 assert (NULL != db->database);
420 if (0 != c_psql_check_connection (db))
423 for (j = 0; j < db->queries_num; ++j)
424 c_psql_exec_query (db, j);
434 static int c_psql_shutdown (void)
438 if ((NULL == databases) || (0 == databases_num))
441 plugin_unregister_read ("postgresql");
442 plugin_unregister_shutdown ("postgresql");
444 for (i = 0; i < databases_num; ++i) {
445 c_psql_database_t *db = databases + i;
446 c_psql_database_delete (db);
452 for (i = 0; i < queries_num; ++i) {
453 c_psql_query_t *query = queries + i;
454 c_psql_query_delete (query);
460 } /* c_psql_shutdown */
462 static int c_psql_init (void)
466 if ((NULL == databases) || (0 == databases_num))
469 for (i = 0; i < queries_num; ++i) {
470 c_psql_query_t *query = queries + i;
473 for (j = 0; j < query->cols_num; ++j) {
474 c_psql_col_t *col = query->cols + j;
475 const data_set_t *ds;
477 ds = plugin_get_ds (col->type);
479 log_err ("Column: Unknown type \"%s\".", col->type);
484 if (1 != ds->ds_num) {
485 log_err ("Column: Invalid type \"%s\" - types defining "
486 "one data source are supported only (got: %i).",
487 col->type, ds->ds_num);
492 col->ds_type = ds->ds[0].type;
496 for (i = 0; i < databases_num; ++i) {
497 c_psql_database_t *db = databases + i;
500 char *buf = conninfo;
501 int buf_len = sizeof (conninfo);
507 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
513 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
514 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
515 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
516 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
517 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
518 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
519 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
521 db->conn = PQconnectdb (conninfo);
522 if (0 != c_psql_check_connection (db))
525 server_host = PQhost (db->conn);
526 server_version = PQserverVersion (db->conn);
527 log_info ("Sucessfully connected to database %s (user %s) "
528 "at server %s%s%s (server version: %d.%d.%d, "
529 "protocol version: %d, pid: %d)",
530 PQdb (db->conn), PQuser (db->conn),
531 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
532 C_PSQL_SERVER_VERSION3 (server_version),
533 PQprotocolVersion (db->conn), PQbackendPID (db->conn));
536 plugin_register_read ("postgresql", c_psql_read);
537 plugin_register_shutdown ("postgresql", c_psql_shutdown);
541 static int config_set (char *name, char **var, const oconfig_item_t *ci)
543 if ((0 != ci->children_num) || (1 != ci->values_num)
544 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
545 log_err ("%s expects a single string argument.", name);
550 *var = sstrdup (ci->values[0].value.string);
554 static int config_set_param (c_psql_query_t *query, const oconfig_item_t *ci)
556 c_psql_param_t param;
559 if ((0 != ci->children_num) || (1 != ci->values_num)
560 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
561 log_err ("Param expects a single string argument.");
565 param_str = ci->values[0].value.string;
566 if (0 == strcasecmp (param_str, "hostname"))
567 param = C_PSQL_PARAM_HOST;
568 else if (0 == strcasecmp (param_str, "database"))
569 param = C_PSQL_PARAM_DB;
570 else if (0 == strcasecmp (param_str, "username"))
571 param = C_PSQL_PARAM_USER;
573 log_err ("Invalid parameter \"%s\".", param_str);
578 if (NULL == (query->params = (c_psql_param_t *)realloc (query->params,
579 query->params_num * sizeof (*query->params)))) {
580 log_err ("Out of memory.");
584 query->params[query->params_num - 1] = param;
586 } /* config_set_param */
588 static int config_set_column (c_psql_query_t *query, const oconfig_item_t *ci)
594 if ((0 != ci->children_num)
595 || (1 > ci->values_num) || (2 < ci->values_num)) {
596 log_err ("Column expects either one or two arguments.");
600 for (i = 0; i < ci->values_num; ++i) {
601 if (OCONFIG_TYPE_STRING != ci->values[i].type) {
602 log_err ("Column expects either one or two string arguments.");
608 if (NULL == (query->cols = (c_psql_col_t *)realloc (query->cols,
609 query->cols_num * sizeof (*query->cols)))) {
610 log_err ("Out of memory.");
614 col = query->cols + query->cols_num - 1;
618 col->type = sstrdup (ci->values[0].value.string);
619 col->type_instance = (2 == ci->values_num)
620 ? sstrdup (ci->values[1].value.string) : NULL;
622 } /* config_set_column */
624 static int config_set_query (c_psql_database_t *db, const oconfig_item_t *ci)
626 c_psql_query_t *query;
628 if ((0 != ci->children_num) || (1 != ci->values_num)
629 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
630 log_err ("Query expects a single string argument.");
634 query = c_psql_query_get (ci->values[0].value.string);
636 log_err ("Query \"%s\" not found - please check your configuration.",
637 ci->values[0].value.string);
642 if (NULL == (db->queries = (c_psql_query_t **)realloc (db->queries,
643 db->queries_num * sizeof (*db->queries)))) {
644 log_err ("Out of memory.");
648 if (query->params_num > db->max_params_num)
649 db->max_params_num = query->params_num;
651 db->queries[db->queries_num - 1] = query;
653 } /* config_set_query */
655 static int c_psql_config_query (oconfig_item_t *ci)
657 c_psql_query_t *query;
661 if ((1 != ci->values_num)
662 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
663 log_err ("<Query> expects a single string argument.");
667 query = c_psql_query_new (ci->values[0].value.string);
669 for (i = 0; i < ci->children_num; ++i) {
670 oconfig_item_t *c = ci->children + i;
672 if (0 == strcasecmp (c->key, "Query"))
673 config_set ("Query", &query->query, c);
674 else if (0 == strcasecmp (c->key, "Param"))
675 config_set_param (query, c);
676 else if (0 == strcasecmp (c->key, "Column"))
677 config_set_column (query, c);
679 log_warn ("Ignoring unknown config key \"%s\".", c->key);
682 } /* c_psql_config_query */
684 static int c_psql_config_database (oconfig_item_t *ci)
686 c_psql_database_t *db;
690 if ((1 != ci->values_num)
691 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
692 log_err ("<Database> expects a single string argument.");
696 db = c_psql_database_new (ci->values[0].value.string);
698 for (i = 0; i < ci->children_num; ++i) {
699 oconfig_item_t *c = ci->children + i;
701 if (0 == strcasecmp (c->key, "Host"))
702 config_set ("Host", &db->host, c);
703 else if (0 == strcasecmp (c->key, "Port"))
704 config_set ("Port", &db->port, c);
705 else if (0 == strcasecmp (c->key, "User"))
706 config_set ("User", &db->user, c);
707 else if (0 == strcasecmp (c->key, "Password"))
708 config_set ("Password", &db->password, c);
709 else if (0 == strcasecmp (c->key, "SSLMode"))
710 config_set ("SSLMode", &db->sslmode, c);
711 else if (0 == strcasecmp (c->key, "KRBSrvName"))
712 config_set ("KRBSrvName", &db->krbsrvname, c);
713 else if (0 == strcasecmp (c->key, "Service"))
714 config_set ("Service", &db->service, c);
715 else if (0 == strcasecmp (c->key, "Query"))
716 config_set_query (db, c);
718 log_warn ("Ignoring unknown config key \"%s\".", c->key);
721 if (NULL == db->queries) {
722 db->queries = (c_psql_query_t **)malloc (def_queries_num
723 * sizeof (*db->queries));
725 for (i = 0; i < def_queries_num; ++i) {
726 db->queries[i] = c_psql_query_get (def_queries[i]);
727 if (NULL == db->queries[i])
728 log_err ("Query \"%s\" not found - "
729 "please check your installation.",
738 static int c_psql_config (oconfig_item_t *ci)
740 static int have_def_config = 0;
744 if (0 == have_def_config) {
749 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
751 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
756 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
757 "any queries - please check your installation.");
760 for (i = 0; i < ci->children_num; ++i) {
761 oconfig_item_t *c = ci->children + i;
763 if (0 == strcasecmp (c->key, "Query"))
764 c_psql_config_query (c);
765 else if (0 == strcasecmp (c->key, "Database"))
766 c_psql_config_database (c);
768 log_warn ("Ignoring unknown config key \"%s\".", c->key);
771 } /* c_psql_config */
773 void module_register (void)
775 plugin_register_complex_config ("postgresql", c_psql_config);
776 plugin_register_init ("postgresql", c_psql_init);
777 } /* module_register */
779 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */