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_INSTANCE,
99 } c_psql_param_t;
101 /* Parameter configuration. Stored as `user data' in the query objects. */
102 typedef struct {
103 c_psql_param_t *params;
104 int params_num;
105 } c_psql_user_data_t;
107 typedef struct {
108 PGconn *conn;
109 c_complain_t conn_complaint;
111 int proto_version;
112 int server_version;
114 int max_params_num;
116 /* user configuration */
117 udb_query_preparation_area_t **q_prep_areas;
118 udb_query_t **queries;
119 size_t queries_num;
121 cdtime_t interval;
123 char *host;
124 char *port;
125 char *database;
126 char *user;
127 char *password;
129 char *instance;
131 char *sslmode;
133 char *krbsrvname;
135 char *service;
136 } c_psql_database_t;
138 static char *def_queries[] = {
139 "backends",
140 "transactions",
141 "queries",
142 "query_plans",
143 "table_states",
144 "disk_io",
145 "disk_usage"
146 };
147 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
149 static udb_query_t **queries = NULL;
150 static size_t queries_num = 0;
152 static c_psql_database_t *c_psql_database_new (const char *name)
153 {
154 c_psql_database_t *db;
156 db = (c_psql_database_t *)malloc (sizeof (*db));
157 if (NULL == db) {
158 log_err ("Out of memory.");
159 return NULL;
160 }
162 db->conn = NULL;
164 C_COMPLAIN_INIT (&db->conn_complaint);
166 db->proto_version = 0;
167 db->server_version = 0;
169 db->max_params_num = 0;
171 db->q_prep_areas = NULL;
172 db->queries = NULL;
173 db->queries_num = 0;
175 db->interval = 0;
177 db->database = sstrdup (name);
178 db->host = NULL;
179 db->port = NULL;
180 db->user = NULL;
181 db->password = NULL;
183 db->instance = sstrdup (name);
185 db->sslmode = NULL;
187 db->krbsrvname = NULL;
189 db->service = NULL;
190 return db;
191 } /* c_psql_database_new */
193 static void c_psql_database_delete (void *data)
194 {
195 size_t i;
197 c_psql_database_t *db = data;
199 PQfinish (db->conn);
200 db->conn = NULL;
202 if (db->q_prep_areas)
203 for (i = 0; i < db->queries_num; ++i)
204 udb_query_delete_preparation_area (db->q_prep_areas[i]);
205 free (db->q_prep_areas);
207 sfree (db->queries);
208 db->queries_num = 0;
210 sfree (db->database);
211 sfree (db->host);
212 sfree (db->port);
213 sfree (db->user);
214 sfree (db->password);
216 sfree (db->instance);
218 sfree (db->sslmode);
220 sfree (db->krbsrvname);
222 sfree (db->service);
223 return;
224 } /* c_psql_database_delete */
226 static int c_psql_connect (c_psql_database_t *db)
227 {
228 char conninfo[4096];
229 char *buf = conninfo;
230 int buf_len = sizeof (conninfo);
231 int status;
233 if (! db)
234 return -1;
236 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
237 if (0 < status) {
238 buf += status;
239 buf_len -= status;
240 }
242 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
243 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
244 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
245 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
246 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
247 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
248 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
250 db->conn = PQconnectdb (conninfo);
251 db->proto_version = PQprotocolVersion (db->conn);
252 return 0;
253 } /* c_psql_connect */
255 static int c_psql_check_connection (c_psql_database_t *db)
256 {
257 _Bool init = 0;
259 if (! db->conn) {
260 init = 1;
262 /* trigger c_release() */
263 if (0 == db->conn_complaint.interval)
264 db->conn_complaint.interval = 1;
266 c_psql_connect (db);
267 }
269 /* "ping" */
270 PQclear (PQexec (db->conn, "SELECT 42;"));
272 if (CONNECTION_OK != PQstatus (db->conn)) {
273 PQreset (db->conn);
275 /* trigger c_release() */
276 if (0 == db->conn_complaint.interval)
277 db->conn_complaint.interval = 1;
279 if (CONNECTION_OK != PQstatus (db->conn)) {
280 c_complain (LOG_ERR, &db->conn_complaint,
281 "Failed to connect to database %s (%s): %s",
282 db->database, db->instance,
283 PQerrorMessage (db->conn));
284 return -1;
285 }
287 db->proto_version = PQprotocolVersion (db->conn);
288 }
290 db->server_version = PQserverVersion (db->conn);
292 if (c_would_release (&db->conn_complaint)) {
293 char *server_host;
294 int server_version;
296 server_host = PQhost (db->conn);
297 server_version = PQserverVersion (db->conn);
299 c_do_release (LOG_INFO, &db->conn_complaint,
300 "Successfully %sconnected to database %s (user %s) "
301 "at server %s%s%s (server version: %d.%d.%d, "
302 "protocol version: %d, pid: %d)", init ? "" : "re",
303 PQdb (db->conn), PQuser (db->conn),
304 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
305 C_PSQL_SERVER_VERSION3 (server_version),
306 db->proto_version, PQbackendPID (db->conn));
308 if (3 > db->proto_version)
309 log_warn ("Protocol version %d does not support parameters.",
310 db->proto_version);
311 }
312 return 0;
313 } /* c_psql_check_connection */
315 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
316 udb_query_t *q)
317 {
318 return PQexec (db->conn, udb_query_get_statement (q));
319 } /* c_psql_exec_query_noparams */
321 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
322 udb_query_t *q, c_psql_user_data_t *data)
323 {
324 char *params[db->max_params_num];
325 char interval[64];
326 int i;
328 if ((data == NULL) || (data->params_num == 0))
329 return (c_psql_exec_query_noparams (db, q));
331 assert (db->max_params_num >= data->params_num);
333 for (i = 0; i < data->params_num; ++i) {
334 switch (data->params[i]) {
335 case C_PSQL_PARAM_HOST:
336 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
337 ? "localhost" : db->host;
338 break;
339 case C_PSQL_PARAM_DB:
340 params[i] = db->database;
341 break;
342 case C_PSQL_PARAM_USER:
343 params[i] = db->user;
344 break;
345 case C_PSQL_PARAM_INTERVAL:
346 ssnprintf (interval, sizeof (interval), "%.3f",
347 (db->interval > 0)
348 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
349 params[i] = interval;
350 break;
351 case C_PSQL_PARAM_INSTANCE:
352 params[i] = db->instance;
353 break;
354 default:
355 assert (0);
356 }
357 }
359 return PQexecParams (db->conn, udb_query_get_statement (q),
360 data->params_num, NULL,
361 (const char *const *) params,
362 NULL, NULL, /* return text data */ 0);
363 } /* c_psql_exec_query_params */
365 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
366 udb_query_preparation_area_t *prep_area)
367 {
368 PGresult *res;
370 c_psql_user_data_t *data;
372 const char *host;
374 char **column_names;
375 char **column_values;
376 int column_num;
378 int rows_num;
379 int status;
380 int row, col;
382 /* The user data may hold parameter information, but may be NULL. */
383 data = udb_query_get_user_data (q);
385 /* Versions up to `3' don't know how to handle parameters. */
386 if (3 <= db->proto_version)
387 res = c_psql_exec_query_params (db, q, data);
388 else if ((NULL == data) || (0 == data->params_num))
389 res = c_psql_exec_query_noparams (db, q);
390 else {
391 log_err ("Connection to database \"%s\" (%s) does not support "
392 "parameters (protocol version %d) - "
393 "cannot execute query \"%s\".",
394 db->database, db->instance, db->proto_version,
395 udb_query_get_name (q));
396 return -1;
397 }
399 column_names = NULL;
400 column_values = NULL;
402 #define BAIL_OUT(status) \
403 sfree (column_names); \
404 sfree (column_values); \
405 PQclear (res); \
406 return status
408 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
409 log_err ("Failed to execute SQL query: %s",
410 PQerrorMessage (db->conn));
411 log_info ("SQL query was: %s",
412 udb_query_get_statement (q));
413 BAIL_OUT (-1);
414 }
416 rows_num = PQntuples (res);
417 if (1 > rows_num) {
418 BAIL_OUT (0);
419 }
421 column_num = PQnfields (res);
422 column_names = (char **) calloc (column_num, sizeof (char *));
423 if (NULL == column_names) {
424 log_err ("calloc failed.");
425 BAIL_OUT (-1);
426 }
428 column_values = (char **) calloc (column_num, sizeof (char *));
429 if (NULL == column_values) {
430 log_err ("calloc failed.");
431 BAIL_OUT (-1);
432 }
434 for (col = 0; col < column_num; ++col) {
435 /* Pointers returned by `PQfname' are freed by `PQclear' via
436 * `BAIL_OUT'. */
437 column_names[col] = PQfname (res, col);
438 if (NULL == column_names[col]) {
439 log_err ("Failed to resolve name of column %i.", col);
440 BAIL_OUT (-1);
441 }
442 }
444 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
445 || (0 == strcmp (db->host, "localhost")))
446 host = hostname_g;
447 else
448 host = db->host;
450 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
451 db->instance, column_names, (size_t) column_num, db->interval);
452 if (0 != status) {
453 log_err ("udb_query_prepare_result failed with status %i.",
454 status);
455 BAIL_OUT (-1);
456 }
458 for (row = 0; row < rows_num; ++row) {
459 for (col = 0; col < column_num; ++col) {
460 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
461 * `BAIL_OUT'. */
462 column_values[col] = PQgetvalue (res, row, col);
463 if (NULL == column_values[col]) {
464 log_err ("Failed to get value at (row = %i, col = %i).",
465 row, col);
466 break;
467 }
468 }
470 /* check for an error */
471 if (col < column_num)
472 continue;
474 status = udb_query_handle_result (q, prep_area, column_values);
475 if (status != 0) {
476 log_err ("udb_query_handle_result failed with status %i.",
477 status);
478 }
479 } /* for (row = 0; row < rows_num; ++row) */
481 udb_query_finish_result (q, prep_area);
483 BAIL_OUT (0);
484 #undef BAIL_OUT
485 } /* c_psql_exec_query */
487 static int c_psql_read (user_data_t *ud)
488 {
489 c_psql_database_t *db;
491 int success = 0;
492 int i;
494 if ((ud == NULL) || (ud->data == NULL)) {
495 log_err ("c_psql_read: Invalid user data.");
496 return -1;
497 }
499 db = ud->data;
501 assert (NULL != db->database);
502 assert (NULL != db->instance);
504 if (0 != c_psql_check_connection (db))
505 return -1;
507 for (i = 0; i < db->queries_num; ++i)
508 {
509 udb_query_preparation_area_t *prep_area;
510 udb_query_t *q;
512 prep_area = db->q_prep_areas[i];
513 q = db->queries[i];
515 if ((0 != db->server_version)
516 && (udb_query_check_version (q, db->server_version) <= 0))
517 continue;
519 if (0 == c_psql_exec_query (db, q, prep_area))
520 success = 1;
521 }
523 if (! success)
524 return -1;
525 return 0;
526 } /* c_psql_read */
528 static int c_psql_shutdown (void)
529 {
530 plugin_unregister_read_group ("postgresql");
532 udb_query_free (queries, queries_num);
533 queries = NULL;
534 queries_num = 0;
536 return 0;
537 } /* c_psql_shutdown */
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 if (0 == strcasecmp (param_str, "instance"))
575 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
576 else {
577 log_err ("Invalid parameter \"%s\".", param_str);
578 return 1;
579 }
581 data->params_num++;
582 udb_query_set_user_data (q, data);
584 return (0);
585 } /* config_query_param_add */
587 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
588 {
589 if (0 == strcasecmp ("Param", ci->key))
590 return config_query_param_add (q, ci);
592 log_err ("Option not allowed within a Query block: `%s'", ci->key);
594 return (-1);
595 } /* config_query_callback */
597 static int c_psql_config_database (oconfig_item_t *ci)
598 {
599 c_psql_database_t *db;
601 char cb_name[DATA_MAX_NAME_LEN];
602 struct timespec cb_interval = { 0, 0 };
603 user_data_t ud;
605 int i;
607 if ((1 != ci->values_num)
608 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
609 log_err ("<Database> expects a single string argument.");
610 return 1;
611 }
613 memset (&ud, 0, sizeof (ud));
615 db = c_psql_database_new (ci->values[0].value.string);
616 if (db == NULL)
617 return -1;
619 for (i = 0; i < ci->children_num; ++i) {
620 oconfig_item_t *c = ci->children + i;
622 if (0 == strcasecmp (c->key, "Host"))
623 cf_util_get_string (c, &db->host);
624 else if (0 == strcasecmp (c->key, "Port"))
625 cf_util_get_service (c, &db->port);
626 else if (0 == strcasecmp (c->key, "User"))
627 cf_util_get_string (c, &db->user);
628 else if (0 == strcasecmp (c->key, "Password"))
629 cf_util_get_string (c, &db->password);
630 else if (0 == strcasecmp (c->key, "Instance"))
631 cf_util_get_string (c, &db->instance);
632 else if (0 == strcasecmp (c->key, "SSLMode"))
633 cf_util_get_string (c, &db->sslmode);
634 else if (0 == strcasecmp (c->key, "KRBSrvName"))
635 cf_util_get_string (c, &db->krbsrvname);
636 else if (0 == strcasecmp (c->key, "Service"))
637 cf_util_get_string (c, &db->service);
638 else if (0 == strcasecmp (c->key, "Query"))
639 udb_query_pick_from_list (c, queries, queries_num,
640 &db->queries, &db->queries_num);
641 else if (0 == strcasecmp (c->key, "Interval"))
642 cf_util_get_cdtime (c, &db->interval);
643 else
644 log_warn ("Ignoring unknown config key \"%s\".", c->key);
645 }
647 /* If no `Query' options were given, add the default queries.. */
648 if (db->queries_num == 0) {
649 for (i = 0; i < def_queries_num; i++)
650 udb_query_pick_from_list_by_name (def_queries[i],
651 queries, queries_num,
652 &db->queries, &db->queries_num);
653 }
655 if (db->queries_num > 0) {
656 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
657 db->queries_num, sizeof (*db->q_prep_areas));
659 if (db->q_prep_areas == NULL) {
660 log_err ("Out of memory.");
661 c_psql_database_delete (db);
662 return -1;
663 }
664 }
666 for (i = 0; (size_t)i < db->queries_num; ++i) {
667 c_psql_user_data_t *data;
668 data = udb_query_get_user_data (db->queries[i]);
669 if ((data != NULL) && (data->params_num > db->max_params_num))
670 db->max_params_num = data->params_num;
672 db->q_prep_areas[i]
673 = udb_query_allocate_preparation_area (db->queries[i]);
675 if (db->q_prep_areas[i] == NULL) {
676 log_err ("Out of memory.");
677 c_psql_database_delete (db);
678 return -1;
679 }
680 }
682 ud.data = db;
683 ud.free_func = c_psql_database_delete;
685 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
687 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
689 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
690 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
691 &ud);
692 return 0;
693 } /* c_psql_config_database */
695 static int c_psql_config (oconfig_item_t *ci)
696 {
697 static int have_def_config = 0;
699 int i;
701 if (0 == have_def_config) {
702 oconfig_item_t *c;
704 have_def_config = 1;
706 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
707 if (NULL == c)
708 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
709 else
710 c_psql_config (c);
712 if (NULL == queries)
713 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
714 "any queries - please check your installation.");
715 }
717 for (i = 0; i < ci->children_num; ++i) {
718 oconfig_item_t *c = ci->children + i;
720 if (0 == strcasecmp (c->key, "Query"))
721 udb_query_create (&queries, &queries_num, c,
722 /* callback = */ config_query_callback);
723 else if (0 == strcasecmp (c->key, "Database"))
724 c_psql_config_database (c);
725 else
726 log_warn ("Ignoring unknown config key \"%s\".", c->key);
727 }
728 return 0;
729 } /* c_psql_config */
731 void module_register (void)
732 {
733 plugin_register_complex_config ("postgresql", c_psql_config);
734 plugin_register_shutdown ("postgresql", c_psql_shutdown);
735 } /* module_register */
737 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */