Code

postgresql plugin: Added "Instance" option to <Database> config block.
[collectd.git] / src / postgresql.c
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 *instance;
130         char *sslmode;
132         char *krbsrvname;
134         char *service;
135 } c_psql_database_t;
137 static char *def_queries[] = {
138         "backends",
139         "transactions",
140         "queries",
141         "query_plans",
142         "table_states",
143         "disk_io",
144         "disk_usage"
145 };
146 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
148 static udb_query_t      **queries       = NULL;
149 static size_t             queries_num   = 0;
151 static c_psql_database_t *c_psql_database_new (const char *name)
153         c_psql_database_t *db;
155         db = (c_psql_database_t *)malloc (sizeof (*db));
156         if (NULL == db) {
157                 log_err ("Out of memory.");
158                 return NULL;
159         }
161         db->conn = NULL;
163         C_COMPLAIN_INIT (&db->conn_complaint);
165         db->proto_version = 0;
166         db->server_version = 0;
168         db->max_params_num = 0;
170         db->q_prep_areas   = NULL;
171         db->queries        = NULL;
172         db->queries_num    = 0;
174         db->interval   = 0;
176         db->database   = sstrdup (name);
177         db->host       = NULL;
178         db->port       = NULL;
179         db->user       = NULL;
180         db->password   = NULL;
182         db->instance   = sstrdup (name);
184         db->sslmode    = NULL;
186         db->krbsrvname = NULL;
188         db->service    = NULL;
189         return db;
190 } /* c_psql_database_new */
192 static void c_psql_database_delete (void *data)
194         size_t i;
196         c_psql_database_t *db = data;
198         PQfinish (db->conn);
199         db->conn = NULL;
201         if (db->q_prep_areas)
202                 for (i = 0; i < db->queries_num; ++i)
203                         udb_query_delete_preparation_area (db->q_prep_areas[i]);
204         free (db->q_prep_areas);
206         sfree (db->queries);
207         db->queries_num = 0;
209         sfree (db->database);
210         sfree (db->host);
211         sfree (db->port);
212         sfree (db->user);
213         sfree (db->password);
215         sfree (db->instance);
217         sfree (db->sslmode);
219         sfree (db->krbsrvname);
221         sfree (db->service);
222         return;
223 } /* c_psql_database_delete */
225 static int c_psql_connect (c_psql_database_t *db)
227         char  conninfo[4096];
228         char *buf     = conninfo;
229         int   buf_len = sizeof (conninfo);
230         int   status;
232         if (! db)
233                 return -1;
235         status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
236         if (0 < status) {
237                 buf     += status;
238                 buf_len -= status;
239         }
241         C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
242         C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
243         C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
244         C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
245         C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
246         C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
247         C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
249         db->conn = PQconnectdb (conninfo);
250         db->proto_version = PQprotocolVersion (db->conn);
251         return 0;
252 } /* c_psql_connect */
254 static int c_psql_check_connection (c_psql_database_t *db)
256         _Bool init = 0;
258         if (! db->conn) {
259                 init = 1;
261                 /* trigger c_release() */
262                 if (0 == db->conn_complaint.interval)
263                         db->conn_complaint.interval = 1;
265                 c_psql_connect (db);
266         }
268         /* "ping" */
269         PQclear (PQexec (db->conn, "SELECT 42;"));
271         if (CONNECTION_OK != PQstatus (db->conn)) {
272                 PQreset (db->conn);
274                 /* trigger c_release() */
275                 if (0 == db->conn_complaint.interval)
276                         db->conn_complaint.interval = 1;
278                 if (CONNECTION_OK != PQstatus (db->conn)) {
279                         c_complain (LOG_ERR, &db->conn_complaint,
280                                         "Failed to connect to database %s (%s): %s",
281                                         db->database, db->instance,
282                                         PQerrorMessage (db->conn));
283                         return -1;
284                 }
286                 db->proto_version = PQprotocolVersion (db->conn);
287         }
289         db->server_version = PQserverVersion (db->conn);
291         if (c_would_release (&db->conn_complaint)) {
292                 char *server_host;
293                 int   server_version;
295                 server_host    = PQhost (db->conn);
296                 server_version = PQserverVersion (db->conn);
298                 c_do_release (LOG_INFO, &db->conn_complaint,
299                                 "Successfully %sconnected to database %s (user %s) "
300                                 "at server %s%s%s (server version: %d.%d.%d, "
301                                 "protocol version: %d, pid: %d)", init ? "" : "re",
302                                 PQdb (db->conn), PQuser (db->conn),
303                                 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
304                                 C_PSQL_SERVER_VERSION3 (server_version),
305                                 db->proto_version, PQbackendPID (db->conn));
307                 if (3 > db->proto_version)
308                         log_warn ("Protocol version %d does not support parameters.",
309                                         db->proto_version);
310         }
311         return 0;
312 } /* c_psql_check_connection */
314 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
315                 udb_query_t *q)
317         return PQexec (db->conn, udb_query_get_statement (q));
318 } /* c_psql_exec_query_noparams */
320 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
321                 udb_query_t *q, c_psql_user_data_t *data)
323         char *params[db->max_params_num];
324         char  interval[64];
325         int   i;
327         if ((data == NULL) || (data->params_num == 0))
328                 return (c_psql_exec_query_noparams (db, q));
330         assert (db->max_params_num >= data->params_num);
332         for (i = 0; i < data->params_num; ++i) {
333                 switch (data->params[i]) {
334                         case C_PSQL_PARAM_HOST:
335                                 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
336                                         ? "localhost" : db->host;
337                                 break;
338                         case C_PSQL_PARAM_DB:
339                                 params[i] = db->database;
340                                 break;
341                         case C_PSQL_PARAM_USER:
342                                 params[i] = db->user;
343                                 break;
344                         case C_PSQL_PARAM_INTERVAL:
345                                 ssnprintf (interval, sizeof (interval), "%.3f",
346                                                 (db->interval > 0)
347                                                 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
348                                 params[i] = interval;
349                                 break;
350                         default:
351                                 assert (0);
352                 }
353         }
355         return PQexecParams (db->conn, udb_query_get_statement (q),
356                         data->params_num, NULL,
357                         (const char *const *) params,
358                         NULL, NULL, /* return text data */ 0);
359 } /* c_psql_exec_query_params */
361 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
362                 udb_query_preparation_area_t *prep_area)
364         PGresult *res;
366         c_psql_user_data_t *data;
368         const char *host;
370         char **column_names;
371         char **column_values;
372         int    column_num;
374         int rows_num;
375         int status;
376         int row, col;
378         /* The user data may hold parameter information, but may be NULL. */
379         data = udb_query_get_user_data (q);
381         /* Versions up to `3' don't know how to handle parameters. */
382         if (3 <= db->proto_version)
383                 res = c_psql_exec_query_params (db, q, data);
384         else if ((NULL == data) || (0 == data->params_num))
385                 res = c_psql_exec_query_noparams (db, q);
386         else {
387                 log_err ("Connection to database \"%s\" (%s) does not support "
388                                 "parameters (protocol version %d) - "
389                                 "cannot execute query \"%s\".",
390                                 db->database, db->instance, db->proto_version,
391                                 udb_query_get_name (q));
392                 return -1;
393         }
395         column_names = NULL;
396         column_values = NULL;
398 #define BAIL_OUT(status) \
399         sfree (column_names); \
400         sfree (column_values); \
401         PQclear (res); \
402         return status
404         if (PGRES_TUPLES_OK != PQresultStatus (res)) {
405                 log_err ("Failed to execute SQL query: %s",
406                                 PQerrorMessage (db->conn));
407                 log_info ("SQL query was: %s",
408                                 udb_query_get_statement (q));
409                 BAIL_OUT (-1);
410         }
412         rows_num = PQntuples (res);
413         if (1 > rows_num) {
414                 BAIL_OUT (0);
415         }
417         column_num = PQnfields (res);
418         column_names = (char **) calloc (column_num, sizeof (char *));
419         if (NULL == column_names) {
420                 log_err ("calloc failed.");
421                 BAIL_OUT (-1);
422         }
424         column_values = (char **) calloc (column_num, sizeof (char *));
425         if (NULL == column_values) {
426                 log_err ("calloc failed.");
427                 BAIL_OUT (-1);
428         }
429         
430         for (col = 0; col < column_num; ++col) {
431                 /* Pointers returned by `PQfname' are freed by `PQclear' via
432                  * `BAIL_OUT'. */
433                 column_names[col] = PQfname (res, col);
434                 if (NULL == column_names[col]) {
435                         log_err ("Failed to resolve name of column %i.", col);
436                         BAIL_OUT (-1);
437                 }
438         }
440         if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
441                         || (0 == strcmp (db->host, "localhost")))
442                 host = hostname_g;
443         else
444                 host = db->host;
446         status = udb_query_prepare_result (q, prep_area, host, "postgresql",
447                         db->instance, column_names, (size_t) column_num, db->interval);
448         if (0 != status) {
449                 log_err ("udb_query_prepare_result failed with status %i.",
450                                 status);
451                 BAIL_OUT (-1);
452         }
454         for (row = 0; row < rows_num; ++row) {
455                 for (col = 0; col < column_num; ++col) {
456                         /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
457                          * `BAIL_OUT'. */
458                         column_values[col] = PQgetvalue (res, row, col);
459                         if (NULL == column_values[col]) {
460                                 log_err ("Failed to get value at (row = %i, col = %i).",
461                                                 row, col);
462                                 break;
463                         }
464                 }
466                 /* check for an error */
467                 if (col < column_num)
468                         continue;
470                 status = udb_query_handle_result (q, prep_area, column_values);
471                 if (status != 0) {
472                         log_err ("udb_query_handle_result failed with status %i.",
473                                         status);
474                 }
475         } /* for (row = 0; row < rows_num; ++row) */
477         udb_query_finish_result (q, prep_area);
479         BAIL_OUT (0);
480 #undef BAIL_OUT
481 } /* c_psql_exec_query */
483 static int c_psql_read (user_data_t *ud)
485         c_psql_database_t *db;
487         int success = 0;
488         int i;
490         if ((ud == NULL) || (ud->data == NULL)) {
491                 log_err ("c_psql_read: Invalid user data.");
492                 return -1;
493         }
495         db = ud->data;
497         assert (NULL != db->database);
498         assert (NULL != db->instance);
500         if (0 != c_psql_check_connection (db))
501                 return -1;
503         for (i = 0; i < db->queries_num; ++i)
504         {
505                 udb_query_preparation_area_t *prep_area;
506                 udb_query_t *q;
508                 prep_area = db->q_prep_areas[i];
509                 q = db->queries[i];
511                 if ((0 != db->server_version)
512                                 && (udb_query_check_version (q, db->server_version) <= 0))
513                         continue;
515                 if (0 == c_psql_exec_query (db, q, prep_area))
516                         success = 1;
517         }
519         if (! success)
520                 return -1;
521         return 0;
522 } /* c_psql_read */
524 static int c_psql_shutdown (void)
526         plugin_unregister_read_group ("postgresql");
528         udb_query_free (queries, queries_num);
529         queries = NULL;
530         queries_num = 0;
532         return 0;
533 } /* c_psql_shutdown */
535 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
537         c_psql_user_data_t *data;
538         const char *param_str;
540         c_psql_param_t *tmp;
542         data = udb_query_get_user_data (q);
543         if (NULL == data) {
544                 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
545                 if (NULL == data) {
546                         log_err ("Out of memory.");
547                         return -1;
548                 }
549                 memset (data, 0, sizeof (*data));
550                 data->params = NULL;
551         }
553         tmp = (c_psql_param_t *) realloc (data->params,
554                         (data->params_num + 1) * sizeof (c_psql_param_t));
555         if (NULL == tmp) {
556                 log_err ("Out of memory.");
557                 return -1;
558         }
559         data->params = tmp;
561         param_str = ci->values[0].value.string;
562         if (0 == strcasecmp (param_str, "hostname"))
563                 data->params[data->params_num] = C_PSQL_PARAM_HOST;
564         else if (0 == strcasecmp (param_str, "database"))
565                 data->params[data->params_num] = C_PSQL_PARAM_DB;
566         else if (0 == strcasecmp (param_str, "username"))
567                 data->params[data->params_num] = C_PSQL_PARAM_USER;
568         else if (0 == strcasecmp (param_str, "interval"))
569                 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
570         else {
571                 log_err ("Invalid parameter \"%s\".", param_str);
572                 return 1;
573         }
575         data->params_num++;
576         udb_query_set_user_data (q, data);
578         return (0);
579 } /* config_query_param_add */
581 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
583         if (0 == strcasecmp ("Param", ci->key))
584                 return config_query_param_add (q, ci);
586         log_err ("Option not allowed within a Query block: `%s'", ci->key);
588         return (-1);
589 } /* config_query_callback */
591 static int c_psql_config_database (oconfig_item_t *ci)
593         c_psql_database_t *db;
595         char cb_name[DATA_MAX_NAME_LEN];
596         struct timespec cb_interval = { 0, 0 };
597         user_data_t ud;
599         int i;
601         if ((1 != ci->values_num)
602                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
603                 log_err ("<Database> expects a single string argument.");
604                 return 1;
605         }
607         memset (&ud, 0, sizeof (ud));
609         db = c_psql_database_new (ci->values[0].value.string);
610         if (db == NULL)
611                 return -1;
613         for (i = 0; i < ci->children_num; ++i) {
614                 oconfig_item_t *c = ci->children + i;
616                 if (0 == strcasecmp (c->key, "Host"))
617                         cf_util_get_string (c, &db->host);
618                 else if (0 == strcasecmp (c->key, "Port"))
619                         cf_util_get_service (c, &db->port);
620                 else if (0 == strcasecmp (c->key, "User"))
621                         cf_util_get_string (c, &db->user);
622                 else if (0 == strcasecmp (c->key, "Password"))
623                         cf_util_get_string (c, &db->password);
624                 else if (0 == strcasecmp (c->key, "Instance"))
625                         cf_util_get_string (c, &db->instance);
626                 else if (0 == strcasecmp (c->key, "SSLMode"))
627                         cf_util_get_string (c, &db->sslmode);
628                 else if (0 == strcasecmp (c->key, "KRBSrvName"))
629                         cf_util_get_string (c, &db->krbsrvname);
630                 else if (0 == strcasecmp (c->key, "Service"))
631                         cf_util_get_string (c, &db->service);
632                 else if (0 == strcasecmp (c->key, "Query"))
633                         udb_query_pick_from_list (c, queries, queries_num,
634                                         &db->queries, &db->queries_num);
635                 else if (0 == strcasecmp (c->key, "Interval"))
636                         cf_util_get_cdtime (c, &db->interval);
637                 else
638                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
639         }
641         /* If no `Query' options were given, add the default queries.. */
642         if (db->queries_num == 0) {
643                 for (i = 0; i < def_queries_num; i++)
644                         udb_query_pick_from_list_by_name (def_queries[i],
645                                         queries, queries_num,
646                                         &db->queries, &db->queries_num);
647         }
649         if (db->queries_num > 0) {
650                 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
651                                 db->queries_num, sizeof (*db->q_prep_areas));
653                 if (db->q_prep_areas == NULL) {
654                         log_err ("Out of memory.");
655                         c_psql_database_delete (db);
656                         return -1;
657                 }
658         }
660         for (i = 0; (size_t)i < db->queries_num; ++i) {
661                 c_psql_user_data_t *data;
662                 data = udb_query_get_user_data (db->queries[i]);
663                 if ((data != NULL) && (data->params_num > db->max_params_num))
664                         db->max_params_num = data->params_num;
666                 db->q_prep_areas[i]
667                         = udb_query_allocate_preparation_area (db->queries[i]);
669                 if (db->q_prep_areas[i] == NULL) {
670                         log_err ("Out of memory.");
671                         c_psql_database_delete (db);
672                         return -1;
673                 }
674         }
676         ud.data = db;
677         ud.free_func = c_psql_database_delete;
679         ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
681         CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
683         plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
684                         /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
685                         &ud);
686         return 0;
687 } /* c_psql_config_database */
689 static int c_psql_config (oconfig_item_t *ci)
691         static int have_def_config = 0;
693         int i;
695         if (0 == have_def_config) {
696                 oconfig_item_t *c;
698                 have_def_config = 1;
700                 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
701                 if (NULL == c)
702                         log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
703                 else
704                         c_psql_config (c);
706                 if (NULL == queries)
707                         log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
708                                         "any queries - please check your installation.");
709         }
711         for (i = 0; i < ci->children_num; ++i) {
712                 oconfig_item_t *c = ci->children + i;
714                 if (0 == strcasecmp (c->key, "Query"))
715                         udb_query_create (&queries, &queries_num, c,
716                                         /* callback = */ config_query_callback);
717                 else if (0 == strcasecmp (c->key, "Database"))
718                         c_psql_config_database (c);
719                 else
720                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
721         }
722         return 0;
723 } /* c_psql_config */
725 void module_register (void)
727         plugin_register_complex_config ("postgresql", c_psql_config);
728         plugin_register_shutdown ("postgresql", c_psql_shutdown);
729 } /* module_register */
731 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */