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 int 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), "%i",
339 db->interval > 0 ? db->interval : interval_g);
340 params[i] = interval;
341 break;
342 default:
343 assert (0);
344 }
345 }
347 return PQexecParams (db->conn, udb_query_get_statement (q),
348 data->params_num, NULL,
349 (const char *const *) params,
350 NULL, NULL, /* return text data */ 0);
351 } /* c_psql_exec_query_params */
353 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
354 udb_query_preparation_area_t *prep_area)
355 {
356 PGresult *res;
358 c_psql_user_data_t *data;
360 const char *host;
362 char **column_names;
363 char **column_values;
364 int column_num;
366 int rows_num;
367 int status;
368 int row, col;
370 /* The user data may hold parameter information, but may be NULL. */
371 data = udb_query_get_user_data (q);
373 /* Versions up to `3' don't know how to handle parameters. */
374 if (3 <= db->proto_version)
375 res = c_psql_exec_query_params (db, q, data);
376 else if ((NULL == data) || (0 == data->params_num))
377 res = c_psql_exec_query_noparams (db, q);
378 else {
379 log_err ("Connection to database \"%s\" does not support parameters "
380 "(protocol version %d) - cannot execute query \"%s\".",
381 db->database, db->proto_version,
382 udb_query_get_name (q));
383 return -1;
384 }
386 column_names = NULL;
387 column_values = NULL;
389 #define BAIL_OUT(status) \
390 sfree (column_names); \
391 sfree (column_values); \
392 PQclear (res); \
393 return status
395 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
396 log_err ("Failed to execute SQL query: %s",
397 PQerrorMessage (db->conn));
398 log_info ("SQL query was: %s",
399 udb_query_get_statement (q));
400 BAIL_OUT (-1);
401 }
403 rows_num = PQntuples (res);
404 if (1 > rows_num) {
405 BAIL_OUT (0);
406 }
408 column_num = PQnfields (res);
409 column_names = (char **) calloc (column_num, sizeof (char *));
410 if (NULL == column_names) {
411 log_err ("calloc failed.");
412 BAIL_OUT (-1);
413 }
415 column_values = (char **) calloc (column_num, sizeof (char *));
416 if (NULL == column_values) {
417 log_err ("calloc failed.");
418 BAIL_OUT (-1);
419 }
421 for (col = 0; col < column_num; ++col) {
422 /* Pointers returned by `PQfname' are freed by `PQclear' via
423 * `BAIL_OUT'. */
424 column_names[col] = PQfname (res, col);
425 if (NULL == column_names[col]) {
426 log_err ("Failed to resolve name of column %i.", col);
427 BAIL_OUT (-1);
428 }
429 }
431 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
432 || (0 == strcmp (db->host, "localhost")))
433 host = hostname_g;
434 else
435 host = db->host;
437 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
438 db->database, column_names, (size_t) column_num, db->interval);
439 if (0 != status) {
440 log_err ("udb_query_prepare_result failed with status %i.",
441 status);
442 BAIL_OUT (-1);
443 }
445 for (row = 0; row < rows_num; ++row) {
446 for (col = 0; col < column_num; ++col) {
447 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
448 * `BAIL_OUT'. */
449 column_values[col] = PQgetvalue (res, row, col);
450 if (NULL == column_values[col]) {
451 log_err ("Failed to get value at (row = %i, col = %i).",
452 row, col);
453 break;
454 }
455 }
457 /* check for an error */
458 if (col < column_num)
459 continue;
461 status = udb_query_handle_result (q, prep_area, column_values);
462 if (status != 0) {
463 log_err ("udb_query_handle_result failed with status %i.",
464 status);
465 }
466 } /* for (row = 0; row < rows_num; ++row) */
468 udb_query_finish_result (q, prep_area);
470 BAIL_OUT (0);
471 #undef BAIL_OUT
472 } /* c_psql_exec_query */
474 static int c_psql_read (user_data_t *ud)
475 {
476 c_psql_database_t *db;
478 int success = 0;
479 int i;
481 if ((ud == NULL) || (ud->data == NULL)) {
482 log_err ("c_psql_read: Invalid user data.");
483 return -1;
484 }
486 db = ud->data;
488 assert (NULL != db->database);
490 if (0 != c_psql_check_connection (db))
491 return -1;
493 for (i = 0; i < db->queries_num; ++i)
494 {
495 udb_query_preparation_area_t *prep_area;
496 udb_query_t *q;
498 prep_area = db->q_prep_areas[i];
499 q = db->queries[i];
501 if ((0 != db->server_version)
502 && (udb_query_check_version (q, db->server_version) <= 0))
503 continue;
505 if (0 == c_psql_exec_query (db, q, prep_area))
506 success = 1;
507 }
509 if (! success)
510 return -1;
511 return 0;
512 } /* c_psql_read */
514 static int c_psql_shutdown (void)
515 {
516 plugin_unregister_read_group ("postgresql");
518 udb_query_free (queries, queries_num);
519 queries = NULL;
520 queries_num = 0;
522 return 0;
523 } /* c_psql_shutdown */
525 static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
526 {
527 if ((0 != ci->children_num) || (1 != ci->values_num)
528 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
529 log_err ("%s expects a single string argument.", name);
530 return 1;
531 }
533 sfree (*var);
534 *var = sstrdup (ci->values[0].value.string);
535 return 0;
536 } /* config_set_s */
538 static int config_set_i (char *name, int *var,
539 const oconfig_item_t *ci, int min)
540 {
541 int value;
543 if ((0 != ci->children_num) || (1 != ci->values_num)
544 || (OCONFIG_TYPE_NUMBER != ci->values[0].type)) {
545 log_err ("%s expects a single number argument.", name);
546 return 1;
547 }
549 value = (int)ci->values[0].value.number;
551 if (value < min) {
552 log_err ("%s expects a number greater or equal to %i.", name, min);
553 return 1;
554 }
556 *var = value;
557 return 0;
558 } /* config_set_s */
560 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
561 {
562 c_psql_user_data_t *data;
563 const char *param_str;
565 c_psql_param_t *tmp;
567 data = udb_query_get_user_data (q);
568 if (NULL == data) {
569 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
570 if (NULL == data) {
571 log_err ("Out of memory.");
572 return -1;
573 }
574 memset (data, 0, sizeof (*data));
575 data->params = NULL;
576 }
578 tmp = (c_psql_param_t *) realloc (data->params,
579 (data->params_num + 1) * sizeof (c_psql_param_t));
580 if (NULL == tmp) {
581 log_err ("Out of memory.");
582 return -1;
583 }
584 data->params = tmp;
586 param_str = ci->values[0].value.string;
587 if (0 == strcasecmp (param_str, "hostname"))
588 data->params[data->params_num] = C_PSQL_PARAM_HOST;
589 else if (0 == strcasecmp (param_str, "database"))
590 data->params[data->params_num] = C_PSQL_PARAM_DB;
591 else if (0 == strcasecmp (param_str, "username"))
592 data->params[data->params_num] = C_PSQL_PARAM_USER;
593 else if (0 == strcasecmp (param_str, "interval"))
594 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
595 else {
596 log_err ("Invalid parameter \"%s\".", param_str);
597 return 1;
598 }
600 data->params_num++;
601 udb_query_set_user_data (q, data);
603 return (0);
604 } /* config_query_param_add */
606 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
607 {
608 if (0 == strcasecmp ("Param", ci->key))
609 return config_query_param_add (q, ci);
611 log_err ("Option not allowed within a Query block: `%s'", ci->key);
613 return (-1);
614 } /* config_query_callback */
616 static int c_psql_config_database (oconfig_item_t *ci)
617 {
618 c_psql_database_t *db;
620 char cb_name[DATA_MAX_NAME_LEN];
621 struct timespec cb_interval;
622 user_data_t ud;
624 int i;
626 if ((1 != ci->values_num)
627 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
628 log_err ("<Database> expects a single string argument.");
629 return 1;
630 }
632 memset (&ud, 0, sizeof (ud));
634 db = c_psql_database_new (ci->values[0].value.string);
635 if (db == NULL)
636 return -1;
638 for (i = 0; i < ci->children_num; ++i) {
639 oconfig_item_t *c = ci->children + i;
641 if (0 == strcasecmp (c->key, "Host"))
642 config_set_s ("Host", &db->host, c);
643 else if (0 == strcasecmp (c->key, "Port"))
644 config_set_s ("Port", &db->port, c);
645 else if (0 == strcasecmp (c->key, "User"))
646 config_set_s ("User", &db->user, c);
647 else if (0 == strcasecmp (c->key, "Password"))
648 config_set_s ("Password", &db->password, c);
649 else if (0 == strcasecmp (c->key, "SSLMode"))
650 config_set_s ("SSLMode", &db->sslmode, c);
651 else if (0 == strcasecmp (c->key, "KRBSrvName"))
652 config_set_s ("KRBSrvName", &db->krbsrvname, c);
653 else if (0 == strcasecmp (c->key, "Service"))
654 config_set_s ("Service", &db->service, c);
655 else if (0 == strcasecmp (c->key, "Query"))
656 udb_query_pick_from_list (c, queries, queries_num,
657 &db->queries, &db->queries_num);
658 else if (0 == strcasecmp (c->key, "Interval"))
659 config_set_i ("Interval", &db->interval, c, /* min = */ 1);
660 else
661 log_warn ("Ignoring unknown config key \"%s\".", c->key);
662 }
664 /* If no `Query' options were given, add the default queries.. */
665 if (db->queries_num == 0) {
666 for (i = 0; i < def_queries_num; i++)
667 udb_query_pick_from_list_by_name (def_queries[i],
668 queries, queries_num,
669 &db->queries, &db->queries_num);
670 }
672 if (db->queries_num > 0) {
673 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
674 db->queries_num, sizeof (*db->q_prep_areas));
676 if (db->q_prep_areas == NULL) {
677 log_err ("Out of memory.");
678 c_psql_database_delete (db);
679 return -1;
680 }
681 }
683 for (i = 0; (size_t)i < db->queries_num; ++i) {
684 c_psql_user_data_t *data;
685 data = udb_query_get_user_data (db->queries[i]);
686 if ((data != NULL) && (data->params_num > db->max_params_num))
687 db->max_params_num = data->params_num;
689 db->q_prep_areas[i]
690 = udb_query_allocate_preparation_area (db->queries[i]);
692 if (db->q_prep_areas[i] == NULL) {
693 log_err ("Out of memory.");
694 c_psql_database_delete (db);
695 return -1;
696 }
697 }
699 ud.data = db;
700 ud.free_func = c_psql_database_delete;
702 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
704 memset (&cb_interval, 0, sizeof (cb_interval));
705 if (db->interval > 0)
706 cb_interval.tv_sec = (time_t)db->interval;
708 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
709 /* interval = */ &cb_interval, &ud);
710 return 0;
711 } /* c_psql_config_database */
713 static int c_psql_config (oconfig_item_t *ci)
714 {
715 static int have_def_config = 0;
717 int i;
719 if (0 == have_def_config) {
720 oconfig_item_t *c;
722 have_def_config = 1;
724 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
725 if (NULL == c)
726 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
727 else
728 c_psql_config (c);
730 if (NULL == queries)
731 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
732 "any queries - please check your installation.");
733 }
735 for (i = 0; i < ci->children_num; ++i) {
736 oconfig_item_t *c = ci->children + i;
738 if (0 == strcasecmp (c->key, "Query"))
739 udb_query_create (&queries, &queries_num, c,
740 /* callback = */ config_query_callback,
741 /* legacy mode = */ 1);
742 else if (0 == strcasecmp (c->key, "Database"))
743 c_psql_config_database (c);
744 else
745 log_warn ("Ignoring unknown config key \"%s\".", c->key);
746 }
747 return 0;
748 } /* c_psql_config */
750 void module_register (void)
751 {
752 plugin_register_complex_config ("postgresql", c_psql_config);
753 plugin_register_shutdown ("postgresql", c_psql_shutdown);
754 } /* module_register */
756 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */