1 /**
2 * collectd - src/postgresql.c
3 * Copyright (C) 2008, 2009 Sebastian Harl
4 * Copyright (C) 2009 Florian Forster
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 *
14 * - Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 *
30 * Authors:
31 * Sebastian Harl <sh at tokkee.org>
32 * Florian Forster <octo at verplant.org>
33 **/
35 /*
36 * This module collects PostgreSQL database statistics.
37 */
39 #include "collectd.h"
40 #include "common.h"
42 #include "configfile.h"
43 #include "plugin.h"
45 #include "utils_db_query.h"
46 #include "utils_complain.h"
48 #include <pg_config_manual.h>
49 #include <libpq-fe.h>
51 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
52 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
53 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
55 #ifndef C_PSQL_DEFAULT_CONF
56 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
57 #endif
59 /* Appends the (parameter, value) pair to the string
60 * pointed to by 'buf' suitable to be used as argument
61 * for PQconnectdb(). If value equals NULL, the pair
62 * is ignored. */
63 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
64 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
65 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
66 if (0 < s) { \
67 buf += s; \
68 buf_len -= s; \
69 } \
70 }
72 /* Returns the tuple (major, minor, patchlevel)
73 * for the given version number. */
74 #define C_PSQL_SERVER_VERSION3(server_version) \
75 (server_version) / 10000, \
76 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
77 (server_version) - (int)((server_version) / 100) * 100
79 /* Returns true if the given host specifies a
80 * UNIX domain socket. */
81 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
82 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
84 /* Returns the tuple (host, delimiter, port) for a
85 * given (host, port) pair. Depending on the value of
86 * 'host' a UNIX domain socket or a TCP socket is
87 * assumed. */
88 #define C_PSQL_SOCKET3(host, port) \
89 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
90 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
91 port
93 typedef enum {
94 C_PSQL_PARAM_HOST = 1,
95 C_PSQL_PARAM_DB,
96 C_PSQL_PARAM_USER,
97 C_PSQL_PARAM_INTERVAL,
98 } c_psql_param_t;
100 /* Parameter configuration. Stored as `user data' in the query objects. */
101 typedef struct {
102 c_psql_param_t *params;
103 int params_num;
104 } c_psql_user_data_t;
106 typedef struct {
107 PGconn *conn;
108 c_complain_t conn_complaint;
110 int proto_version;
111 int server_version;
113 int max_params_num;
115 /* user configuration */
116 udb_query_preparation_area_t **q_prep_areas;
117 udb_query_t **queries;
118 size_t queries_num;
120 cdtime_t interval;
122 char *host;
123 char *port;
124 char *database;
125 char *user;
126 char *password;
128 char *sslmode;
130 char *krbsrvname;
132 char *service;
133 } c_psql_database_t;
135 static char *def_queries[] = {
136 "backends",
137 "transactions",
138 "queries",
139 "query_plans",
140 "table_states",
141 "disk_io",
142 "disk_usage"
143 };
144 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
146 static udb_query_t **queries = NULL;
147 static size_t queries_num = 0;
149 static c_psql_database_t *c_psql_database_new (const char *name)
150 {
151 c_psql_database_t *db;
153 db = (c_psql_database_t *)malloc (sizeof (*db));
154 if (NULL == db) {
155 log_err ("Out of memory.");
156 return NULL;
157 }
159 db->conn = NULL;
161 C_COMPLAIN_INIT (&db->conn_complaint);
163 db->proto_version = 0;
164 db->server_version = 0;
166 db->max_params_num = 0;
168 db->q_prep_areas = NULL;
169 db->queries = NULL;
170 db->queries_num = 0;
172 db->interval = 0;
174 db->database = sstrdup (name);
175 db->host = NULL;
176 db->port = NULL;
177 db->user = NULL;
178 db->password = NULL;
180 db->sslmode = NULL;
182 db->krbsrvname = NULL;
184 db->service = NULL;
185 return db;
186 } /* c_psql_database_new */
188 static void c_psql_database_delete (void *data)
189 {
190 size_t i;
192 c_psql_database_t *db = data;
194 PQfinish (db->conn);
195 db->conn = NULL;
197 if (db->q_prep_areas)
198 for (i = 0; i < db->queries_num; ++i)
199 udb_query_delete_preparation_area (db->q_prep_areas[i]);
200 free (db->q_prep_areas);
202 sfree (db->queries);
203 db->queries_num = 0;
205 sfree (db->database);
206 sfree (db->host);
207 sfree (db->port);
208 sfree (db->user);
209 sfree (db->password);
211 sfree (db->sslmode);
213 sfree (db->krbsrvname);
215 sfree (db->service);
216 return;
217 } /* c_psql_database_delete */
219 static int c_psql_connect (c_psql_database_t *db)
220 {
221 char conninfo[4096];
222 char *buf = conninfo;
223 int buf_len = sizeof (conninfo);
224 int status;
226 if (! db)
227 return -1;
229 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
230 if (0 < status) {
231 buf += status;
232 buf_len -= status;
233 }
235 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
236 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
237 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
238 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
239 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
240 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
241 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
243 db->conn = PQconnectdb (conninfo);
244 db->proto_version = PQprotocolVersion (db->conn);
245 return 0;
246 } /* c_psql_connect */
248 static int c_psql_check_connection (c_psql_database_t *db)
249 {
250 _Bool init = 0;
252 if (! db->conn) {
253 init = 1;
255 /* trigger c_release() */
256 if (0 == db->conn_complaint.interval)
257 db->conn_complaint.interval = 1;
259 c_psql_connect (db);
260 }
262 /* "ping" */
263 PQclear (PQexec (db->conn, "SELECT 42;"));
265 if (CONNECTION_OK != PQstatus (db->conn)) {
266 PQreset (db->conn);
268 /* trigger c_release() */
269 if (0 == db->conn_complaint.interval)
270 db->conn_complaint.interval = 1;
272 if (CONNECTION_OK != PQstatus (db->conn)) {
273 c_complain (LOG_ERR, &db->conn_complaint,
274 "Failed to connect to database %s: %s",
275 db->database, PQerrorMessage (db->conn));
276 return -1;
277 }
279 db->proto_version = PQprotocolVersion (db->conn);
280 }
282 db->server_version = PQserverVersion (db->conn);
284 if (c_would_release (&db->conn_complaint)) {
285 char *server_host;
286 int server_version;
288 server_host = PQhost (db->conn);
289 server_version = PQserverVersion (db->conn);
291 c_do_release (LOG_INFO, &db->conn_complaint,
292 "Successfully %sconnected to database %s (user %s) "
293 "at server %s%s%s (server version: %d.%d.%d, "
294 "protocol version: %d, pid: %d)", init ? "" : "re",
295 PQdb (db->conn), PQuser (db->conn),
296 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
297 C_PSQL_SERVER_VERSION3 (server_version),
298 db->proto_version, PQbackendPID (db->conn));
300 if (3 > db->proto_version)
301 log_warn ("Protocol version %d does not support parameters.",
302 db->proto_version);
303 }
304 return 0;
305 } /* c_psql_check_connection */
307 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
308 udb_query_t *q)
309 {
310 return PQexec (db->conn, udb_query_get_statement (q));
311 } /* c_psql_exec_query_noparams */
313 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
314 udb_query_t *q, c_psql_user_data_t *data)
315 {
316 char *params[db->max_params_num];
317 char interval[64];
318 int i;
320 if ((data == NULL) || (data->params_num == 0))
321 return (c_psql_exec_query_noparams (db, q));
323 assert (db->max_params_num >= data->params_num);
325 for (i = 0; i < data->params_num; ++i) {
326 switch (data->params[i]) {
327 case C_PSQL_PARAM_HOST:
328 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
329 ? "localhost" : db->host;
330 break;
331 case C_PSQL_PARAM_DB:
332 params[i] = db->database;
333 break;
334 case C_PSQL_PARAM_USER:
335 params[i] = db->user;
336 break;
337 case C_PSQL_PARAM_INTERVAL:
338 ssnprintf (interval, sizeof (interval), "%.3f",
339 (db->interval > 0)
340 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
341 params[i] = interval;
342 break;
343 default:
344 assert (0);
345 }
346 }
348 return PQexecParams (db->conn, udb_query_get_statement (q),
349 data->params_num, NULL,
350 (const char *const *) params,
351 NULL, NULL, /* return text data */ 0);
352 } /* c_psql_exec_query_params */
354 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
355 udb_query_preparation_area_t *prep_area)
356 {
357 PGresult *res;
359 c_psql_user_data_t *data;
361 const char *host;
363 char **column_names;
364 char **column_values;
365 int column_num;
367 int rows_num;
368 int status;
369 int row, col;
371 /* The user data may hold parameter information, but may be NULL. */
372 data = udb_query_get_user_data (q);
374 /* Versions up to `3' don't know how to handle parameters. */
375 if (3 <= db->proto_version)
376 res = c_psql_exec_query_params (db, q, data);
377 else if ((NULL == data) || (0 == data->params_num))
378 res = c_psql_exec_query_noparams (db, q);
379 else {
380 log_err ("Connection to database \"%s\" does not support parameters "
381 "(protocol version %d) - cannot execute query \"%s\".",
382 db->database, db->proto_version,
383 udb_query_get_name (q));
384 return -1;
385 }
387 column_names = NULL;
388 column_values = NULL;
390 #define BAIL_OUT(status) \
391 sfree (column_names); \
392 sfree (column_values); \
393 PQclear (res); \
394 return status
396 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
397 log_err ("Failed to execute SQL query: %s",
398 PQerrorMessage (db->conn));
399 log_info ("SQL query was: %s",
400 udb_query_get_statement (q));
401 BAIL_OUT (-1);
402 }
404 rows_num = PQntuples (res);
405 if (1 > rows_num) {
406 BAIL_OUT (0);
407 }
409 column_num = PQnfields (res);
410 column_names = (char **) calloc (column_num, sizeof (char *));
411 if (NULL == column_names) {
412 log_err ("calloc failed.");
413 BAIL_OUT (-1);
414 }
416 column_values = (char **) calloc (column_num, sizeof (char *));
417 if (NULL == column_values) {
418 log_err ("calloc failed.");
419 BAIL_OUT (-1);
420 }
422 for (col = 0; col < column_num; ++col) {
423 /* Pointers returned by `PQfname' are freed by `PQclear' via
424 * `BAIL_OUT'. */
425 column_names[col] = PQfname (res, col);
426 if (NULL == column_names[col]) {
427 log_err ("Failed to resolve name of column %i.", col);
428 BAIL_OUT (-1);
429 }
430 }
432 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
433 || (0 == strcmp (db->host, "localhost")))
434 host = hostname_g;
435 else
436 host = db->host;
438 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
439 db->database, column_names, (size_t) column_num, db->interval);
440 if (0 != status) {
441 log_err ("udb_query_prepare_result failed with status %i.",
442 status);
443 BAIL_OUT (-1);
444 }
446 for (row = 0; row < rows_num; ++row) {
447 for (col = 0; col < column_num; ++col) {
448 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
449 * `BAIL_OUT'. */
450 column_values[col] = PQgetvalue (res, row, col);
451 if (NULL == column_values[col]) {
452 log_err ("Failed to get value at (row = %i, col = %i).",
453 row, col);
454 break;
455 }
456 }
458 /* check for an error */
459 if (col < column_num)
460 continue;
462 status = udb_query_handle_result (q, prep_area, column_values);
463 if (status != 0) {
464 log_err ("udb_query_handle_result failed with status %i.",
465 status);
466 }
467 } /* for (row = 0; row < rows_num; ++row) */
469 udb_query_finish_result (q, prep_area);
471 BAIL_OUT (0);
472 #undef BAIL_OUT
473 } /* c_psql_exec_query */
475 static int c_psql_read (user_data_t *ud)
476 {
477 c_psql_database_t *db;
479 int success = 0;
480 int i;
482 if ((ud == NULL) || (ud->data == NULL)) {
483 log_err ("c_psql_read: Invalid user data.");
484 return -1;
485 }
487 db = ud->data;
489 assert (NULL != db->database);
491 if (0 != c_psql_check_connection (db))
492 return -1;
494 for (i = 0; i < db->queries_num; ++i)
495 {
496 udb_query_preparation_area_t *prep_area;
497 udb_query_t *q;
499 prep_area = db->q_prep_areas[i];
500 q = db->queries[i];
502 if ((0 != db->server_version)
503 && (udb_query_check_version (q, db->server_version) <= 0))
504 continue;
506 if (0 == c_psql_exec_query (db, q, prep_area))
507 success = 1;
508 }
510 if (! success)
511 return -1;
512 return 0;
513 } /* c_psql_read */
515 static int c_psql_shutdown (void)
516 {
517 plugin_unregister_read_group ("postgresql");
519 udb_query_free (queries, queries_num);
520 queries = NULL;
521 queries_num = 0;
523 return 0;
524 } /* c_psql_shutdown */
526 static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
527 {
528 if ((0 != ci->children_num) || (1 != ci->values_num)
529 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
530 log_err ("%s expects a single string argument.", name);
531 return 1;
532 }
534 sfree (*var);
535 *var = sstrdup (ci->values[0].value.string);
536 return 0;
537 } /* config_set_s */
539 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
540 {
541 c_psql_user_data_t *data;
542 const char *param_str;
544 c_psql_param_t *tmp;
546 data = udb_query_get_user_data (q);
547 if (NULL == data) {
548 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
549 if (NULL == data) {
550 log_err ("Out of memory.");
551 return -1;
552 }
553 memset (data, 0, sizeof (*data));
554 data->params = NULL;
555 }
557 tmp = (c_psql_param_t *) realloc (data->params,
558 (data->params_num + 1) * sizeof (c_psql_param_t));
559 if (NULL == tmp) {
560 log_err ("Out of memory.");
561 return -1;
562 }
563 data->params = tmp;
565 param_str = ci->values[0].value.string;
566 if (0 == strcasecmp (param_str, "hostname"))
567 data->params[data->params_num] = C_PSQL_PARAM_HOST;
568 else if (0 == strcasecmp (param_str, "database"))
569 data->params[data->params_num] = C_PSQL_PARAM_DB;
570 else if (0 == strcasecmp (param_str, "username"))
571 data->params[data->params_num] = C_PSQL_PARAM_USER;
572 else if (0 == strcasecmp (param_str, "interval"))
573 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
574 else {
575 log_err ("Invalid parameter \"%s\".", param_str);
576 return 1;
577 }
579 data->params_num++;
580 udb_query_set_user_data (q, data);
582 return (0);
583 } /* config_query_param_add */
585 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
586 {
587 if (0 == strcasecmp ("Param", ci->key))
588 return config_query_param_add (q, ci);
590 log_err ("Option not allowed within a Query block: `%s'", ci->key);
592 return (-1);
593 } /* config_query_callback */
595 static int c_psql_config_database (oconfig_item_t *ci)
596 {
597 c_psql_database_t *db;
599 char cb_name[DATA_MAX_NAME_LEN];
600 struct timespec cb_interval = { 0, 0 };
601 user_data_t ud;
603 int i;
605 if ((1 != ci->values_num)
606 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
607 log_err ("<Database> expects a single string argument.");
608 return 1;
609 }
611 memset (&ud, 0, sizeof (ud));
613 db = c_psql_database_new (ci->values[0].value.string);
614 if (db == NULL)
615 return -1;
617 for (i = 0; i < ci->children_num; ++i) {
618 oconfig_item_t *c = ci->children + i;
620 if (0 == strcasecmp (c->key, "Host"))
621 config_set_s ("Host", &db->host, c);
622 else if (0 == strcasecmp (c->key, "Port"))
623 config_set_s ("Port", &db->port, c);
624 else if (0 == strcasecmp (c->key, "User"))
625 config_set_s ("User", &db->user, c);
626 else if (0 == strcasecmp (c->key, "Password"))
627 config_set_s ("Password", &db->password, c);
628 else if (0 == strcasecmp (c->key, "SSLMode"))
629 config_set_s ("SSLMode", &db->sslmode, c);
630 else if (0 == strcasecmp (c->key, "KRBSrvName"))
631 config_set_s ("KRBSrvName", &db->krbsrvname, c);
632 else if (0 == strcasecmp (c->key, "Service"))
633 config_set_s ("Service", &db->service, c);
634 else if (0 == strcasecmp (c->key, "Query"))
635 udb_query_pick_from_list (c, queries, queries_num,
636 &db->queries, &db->queries_num);
637 else if (0 == strcasecmp (c->key, "Interval"))
638 cf_util_get_cdtime (c, &db->interval);
639 else
640 log_warn ("Ignoring unknown config key \"%s\".", c->key);
641 }
643 /* If no `Query' options were given, add the default queries.. */
644 if (db->queries_num == 0) {
645 for (i = 0; i < def_queries_num; i++)
646 udb_query_pick_from_list_by_name (def_queries[i],
647 queries, queries_num,
648 &db->queries, &db->queries_num);
649 }
651 if (db->queries_num > 0) {
652 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
653 db->queries_num, sizeof (*db->q_prep_areas));
655 if (db->q_prep_areas == NULL) {
656 log_err ("Out of memory.");
657 c_psql_database_delete (db);
658 return -1;
659 }
660 }
662 for (i = 0; (size_t)i < db->queries_num; ++i) {
663 c_psql_user_data_t *data;
664 data = udb_query_get_user_data (db->queries[i]);
665 if ((data != NULL) && (data->params_num > db->max_params_num))
666 db->max_params_num = data->params_num;
668 db->q_prep_areas[i]
669 = udb_query_allocate_preparation_area (db->queries[i]);
671 if (db->q_prep_areas[i] == NULL) {
672 log_err ("Out of memory.");
673 c_psql_database_delete (db);
674 return -1;
675 }
676 }
678 ud.data = db;
679 ud.free_func = c_psql_database_delete;
681 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
683 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
685 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
686 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
687 &ud);
688 return 0;
689 } /* c_psql_config_database */
691 static int c_psql_config (oconfig_item_t *ci)
692 {
693 static int have_def_config = 0;
695 int i;
697 if (0 == have_def_config) {
698 oconfig_item_t *c;
700 have_def_config = 1;
702 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
703 if (NULL == c)
704 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
705 else
706 c_psql_config (c);
708 if (NULL == queries)
709 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
710 "any queries - please check your installation.");
711 }
713 for (i = 0; i < ci->children_num; ++i) {
714 oconfig_item_t *c = ci->children + i;
716 if (0 == strcasecmp (c->key, "Query"))
717 udb_query_create (&queries, &queries_num, c,
718 /* callback = */ config_query_callback);
719 else if (0 == strcasecmp (c->key, "Database"))
720 c_psql_config_database (c);
721 else
722 log_warn ("Ignoring unknown config key \"%s\".", c->key);
723 }
724 return 0;
725 } /* c_psql_config */
727 void module_register (void)
728 {
729 plugin_register_complex_config ("postgresql", c_psql_config);
730 plugin_register_shutdown ("postgresql", c_psql_shutdown);
731 } /* module_register */
733 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */