4e1c1e0c8127bebb693d71fc0b60116a84f1ad35
[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  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Sebastian Harl <sh at tokkee.org>
21  *   Florian Forster <octo at verplant.org>
22  **/
23
24 /*
25  * This module collects PostgreSQL database statistics.
26  */
27
28 #include "collectd.h"
29 #include "common.h"
30
31 #include "configfile.h"
32 #include "plugin.h"
33
34 #include "utils_db_query.h"
35 #include "utils_complain.h"
36
37 #include <pg_config_manual.h>
38 #include <libpq-fe.h>
39
40 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
41 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
42 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
43
44 #ifndef C_PSQL_DEFAULT_CONF
45 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
46 #endif
47
48 /* Appends the (parameter, value) pair to the string
49  * pointed to by 'buf' suitable to be used as argument
50  * for PQconnectdb(). If value equals NULL, the pair
51  * is ignored. */
52 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
53         if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
54                 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
55                 if (0 < s) { \
56                         buf     += s; \
57                         buf_len -= s; \
58                 } \
59         }
60
61 /* Returns the tuple (major, minor, patchlevel)
62  * for the given version number. */
63 #define C_PSQL_SERVER_VERSION3(server_version) \
64         (server_version) / 10000, \
65         (server_version) / 100 - (int)((server_version) / 10000) * 100, \
66         (server_version) - (int)((server_version) / 100) * 100
67
68 /* Returns true if the given host specifies a
69  * UNIX domain socket. */
70 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
71         ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
72
73 /* Returns the tuple (host, delimiter, port) for a
74  * given (host, port) pair. Depending on the value of
75  * 'host' a UNIX domain socket or a TCP socket is
76  * assumed. */
77 #define C_PSQL_SOCKET3(host, port) \
78         ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
79         C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
80         port
81
82 typedef enum {
83         C_PSQL_PARAM_HOST = 1,
84         C_PSQL_PARAM_DB,
85         C_PSQL_PARAM_USER,
86         C_PSQL_PARAM_INTERVAL,
87 } c_psql_param_t;
88
89 /* Parameter configuration. Stored as `user data' in the query objects. */
90 typedef struct {
91         c_psql_param_t *params;
92         int             params_num;
93 } c_psql_user_data_t;
94
95 typedef struct {
96         PGconn      *conn;
97         c_complain_t conn_complaint;
98
99         int proto_version;
100         int server_version;
101
102         int max_params_num;
103
104         /* user configuration */
105         udb_query_t    **queries;
106         size_t           queries_num;
107
108         char *host;
109         char *port;
110         char *database;
111         char *user;
112         char *password;
113
114         char *sslmode;
115
116         char *krbsrvname;
117
118         char *service;
119 } c_psql_database_t;
120
121 static char *def_queries[] = {
122         "backends",
123         "transactions",
124         "queries",
125         "query_plans",
126         "table_states",
127         "disk_io",
128         "disk_usage"
129 };
130 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
131
132 static udb_query_t      **queries       = NULL;
133 static size_t             queries_num   = 0;
134
135 static c_psql_database_t *databases     = NULL;
136 static int                databases_num = 0;
137
138 static c_psql_database_t *c_psql_database_new (const char *name)
139 {
140         c_psql_database_t *db;
141
142         ++databases_num;
143         if (NULL == (databases = (c_psql_database_t *)realloc (databases,
144                                 databases_num * sizeof (*databases)))) {
145                 log_err ("Out of memory.");
146                 exit (5);
147         }
148
149         db = databases + (databases_num - 1);
150
151         db->conn = NULL;
152
153         C_COMPLAIN_INIT (&db->conn_complaint);
154
155         db->proto_version = 0;
156         db->server_version = 0;
157
158         db->max_params_num = 0;
159
160         db->queries        = NULL;
161         db->queries_num    = 0;
162
163         db->database   = sstrdup (name);
164         db->host       = NULL;
165         db->port       = NULL;
166         db->user       = NULL;
167         db->password   = NULL;
168
169         db->sslmode    = NULL;
170
171         db->krbsrvname = NULL;
172
173         db->service    = NULL;
174         return db;
175 } /* c_psql_database_new */
176
177 static void c_psql_database_delete (c_psql_database_t *db)
178 {
179         PQfinish (db->conn);
180         db->conn = NULL;
181
182         sfree (db->queries);
183         db->queries_num = 0;
184
185         sfree (db->database);
186         sfree (db->host);
187         sfree (db->port);
188         sfree (db->user);
189         sfree (db->password);
190
191         sfree (db->sslmode);
192
193         sfree (db->krbsrvname);
194
195         sfree (db->service);
196         return;
197 } /* c_psql_database_delete */
198
199 static int c_psql_check_connection (c_psql_database_t *db)
200 {
201         /* "ping" */
202         PQclear (PQexec (db->conn, "SELECT 42;"));
203
204         if (CONNECTION_OK != PQstatus (db->conn)) {
205                 PQreset (db->conn);
206
207                 /* trigger c_release() */
208                 if (0 == db->conn_complaint.interval)
209                         db->conn_complaint.interval = 1;
210
211                 if (CONNECTION_OK != PQstatus (db->conn)) {
212                         c_complain (LOG_ERR, &db->conn_complaint,
213                                         "Failed to connect to database %s: %s",
214                                         db->database, PQerrorMessage (db->conn));
215                         return -1;
216                 }
217
218                 db->proto_version = PQprotocolVersion (db->conn);
219                 if (3 > db->proto_version)
220                         log_warn ("Protocol version %d does not support parameters.",
221                                         db->proto_version);
222         }
223
224         db->server_version = PQserverVersion (db->conn);
225
226         c_release (LOG_INFO, &db->conn_complaint,
227                         "Successfully reconnected to database %s", PQdb (db->conn));
228         return 0;
229 } /* c_psql_check_connection */
230
231 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
232                 udb_query_t *q)
233 {
234         return PQexec (db->conn, udb_query_get_statement (q));
235 } /* c_psql_exec_query_noparams */
236
237 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
238                 udb_query_t *q, c_psql_user_data_t *data)
239 {
240         char *params[db->max_params_num];
241         char  interval[64];
242         int   i;
243
244         if ((data == NULL) || (data->params_num == 0))
245                 return (c_psql_exec_query_noparams (db, q));
246
247         assert (db->max_params_num >= data->params_num);
248
249         for (i = 0; i < data->params_num; ++i) {
250                 switch (data->params[i]) {
251                         case C_PSQL_PARAM_HOST:
252                                 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
253                                         ? "localhost" : db->host;
254                                 break;
255                         case C_PSQL_PARAM_DB:
256                                 params[i] = db->database;
257                                 break;
258                         case C_PSQL_PARAM_USER:
259                                 params[i] = db->user;
260                                 break;
261                         case C_PSQL_PARAM_INTERVAL:
262                                 ssnprintf (interval, sizeof (interval), "%i", interval_g);
263                                 params[i] = interval;
264                                 break;
265                         default:
266                                 assert (0);
267                 }
268         }
269
270         return PQexecParams (db->conn, udb_query_get_statement (q),
271                         data->params_num, NULL,
272                         (const char *const *) params,
273                         NULL, NULL, /* return text data */ 0);
274 } /* c_psql_exec_query_params */
275
276 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q)
277 {
278         PGresult *res;
279
280         c_psql_user_data_t *data;
281
282         const char *host;
283
284         char **column_names;
285         char **column_values;
286         int    column_num;
287
288         int rows_num;
289         int status;
290         int i;
291
292         /* The user data may hold parameter information */
293         data = udb_query_get_user_data (q);
294
295         /* Versions up to `3' don't know how to handle parameters. */
296         if (3 <= db->proto_version)
297                 res = c_psql_exec_query_params (db, q, data);
298         else if ((NULL == data) || (0 == data->params_num))
299                 res = c_psql_exec_query_noparams (db, q);
300         else {
301                 log_err ("Connection to database \"%s\" does not support parameters "
302                                 "(protocol version %d) - cannot execute query \"%s\".",
303                                 db->database, db->proto_version,
304                                 udb_query_get_name (q));
305                 return -1;
306         }
307
308         column_names = NULL;
309         column_values = NULL;
310
311 #define BAIL_OUT(status) \
312         sfree (column_names); \
313         sfree (column_values); \
314         PQclear (res); \
315         return status
316
317         if (PGRES_TUPLES_OK != PQresultStatus (res)) {
318                 log_err ("Failed to execute SQL query: %s",
319                                 PQerrorMessage (db->conn));
320                 log_info ("SQL query was: %s",
321                                 udb_query_get_statement (q));
322                 BAIL_OUT (-1);
323         }
324
325         rows_num = PQntuples (res);
326         if (1 > rows_num) {
327                 BAIL_OUT (0);
328         }
329
330         column_num = PQnfields (res);
331         column_names = (char **) calloc (column_num, sizeof (char *));
332         if (NULL == column_names) {
333                 log_err ("calloc failed.");
334                 BAIL_OUT (-1);
335         }
336
337         column_values = (char **) calloc (column_num, sizeof (char *));
338         if (NULL == column_values) {
339                 log_err ("calloc failed.");
340                 BAIL_OUT (-1);
341         }
342         
343         for (i = 0; i < column_num; i++) {
344                 /* Pointers returned by `PQfname' are freed by `PQclear' via
345                  * `BAIL_OUT'. */
346                 column_names[i] = PQfname (res, i);
347                 if (NULL == column_names[i]) {
348                         log_err ("PQfname (%i) failed.", i);
349                         BAIL_OUT (-1);
350                 }
351         }
352
353         if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
354                         || (0 == strcmp (db->host, "localhost")))
355                 host = hostname_g;
356         else
357                 host = db->host;
358
359         status = udb_query_prepare_result (q, host, "postgresql",
360                         db->database, column_names, (size_t) column_num);
361         if (0 != status) {
362                 log_err ("udb_query_prepare_result failed with status %i.",
363                                 status);
364                 BAIL_OUT (-1);
365         }
366
367         for (i = 0; i < rows_num; ++i) {
368                 int j;
369
370                 for (j = 0; j < column_num; j++) {
371                         /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
372                          * `BAIL_OUT'. */
373                         column_values[j] = PQgetvalue (res, /* row = */ i, /* col = */ j);
374                         if (NULL == column_values[j]) {
375                                 log_err ("PQgetvalue (%i, %i) failed.", i, j);
376                                 break;
377                         }
378                 }
379
380                 /* check for an error */
381                 if (j < column_num)
382                         continue;
383
384                 status = udb_query_handle_result (q, column_values);
385                 if (status != 0) {
386                         log_err ("udb_query_handle_result failed with status %i.",
387                                         status);
388                 }
389         } /* for (i = 0; i < rows_num; ++i) */
390
391         BAIL_OUT (0);
392 #undef BAIL_OUT
393 } /* c_psql_exec_query */
394
395 static int c_psql_read (void)
396 {
397         int success = 0;
398         int i;
399
400         for (i = 0; i < databases_num; ++i) {
401                 c_psql_database_t *db = databases + i;
402
403                 int j;
404
405                 assert (NULL != db->database);
406
407                 if (0 != c_psql_check_connection (db))
408                         continue;
409
410                 for (j = 0; j < db->queries_num; ++j)
411                 {
412                         udb_query_t *q;
413
414                         q = db->queries[j];
415
416                         if ((0 != db->server_version)
417                                 && (udb_query_check_version (q, db->server_version) <= 0))
418                                 continue;
419
420                         c_psql_exec_query (db, q);
421                 }
422
423                 ++success;
424         }
425
426         if (! success)
427                 return -1;
428         return 0;
429 } /* c_psql_read */
430
431 static int c_psql_shutdown (void)
432 {
433         int i;
434
435         if ((NULL == databases) || (0 == databases_num))
436                 return 0;
437
438         plugin_unregister_read ("postgresql");
439         plugin_unregister_shutdown ("postgresql");
440
441         for (i = 0; i < databases_num; ++i)
442                 c_psql_database_delete (databases + i);
443
444         sfree (databases);
445         databases_num = 0;
446
447         udb_query_free (queries, queries_num);
448         queries = NULL;
449         queries_num = 0;
450
451         return 0;
452 } /* c_psql_shutdown */
453
454 static int c_psql_init (void)
455 {
456         int i;
457
458         if ((NULL == databases) || (0 == databases_num))
459                 return 0;
460
461         for (i = 0; i < databases_num; ++i) {
462                 c_psql_database_t *db = databases + i;
463
464                 char  conninfo[4096];
465                 char *buf     = conninfo;
466                 int   buf_len = sizeof (conninfo);
467                 int   status;
468
469                 char *server_host;
470                 int   server_version;
471
472                 /* this will happen during reinitialization */
473                 if (NULL != db->conn) {
474                         c_psql_check_connection (db);
475                         continue;
476                 }
477
478                 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
479                 if (0 < status) {
480                         buf     += status;
481                         buf_len -= status;
482                 }
483
484                 C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
485                 C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
486                 C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
487                 C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
488                 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
489                 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
490                 C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
491
492                 db->conn = PQconnectdb (conninfo);
493                 if (0 != c_psql_check_connection (db))
494                         continue;
495
496                 db->proto_version = PQprotocolVersion (db->conn);
497
498                 server_host    = PQhost (db->conn);
499                 server_version = PQserverVersion (db->conn);
500                 log_info ("Sucessfully connected to database %s (user %s) "
501                                 "at server %s%s%s (server version: %d.%d.%d, "
502                                 "protocol version: %d, pid: %d)",
503                                 PQdb (db->conn), PQuser (db->conn),
504                                 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
505                                 C_PSQL_SERVER_VERSION3 (server_version),
506                                 db->proto_version, PQbackendPID (db->conn));
507
508                 if (3 > db->proto_version)
509                         log_warn ("Protocol version %d does not support parameters.",
510                                         db->proto_version);
511         }
512
513         plugin_register_read ("postgresql", c_psql_read);
514         plugin_register_shutdown ("postgresql", c_psql_shutdown);
515         return 0;
516 } /* c_psql_init */
517
518 static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
519 {
520         if ((0 != ci->children_num) || (1 != ci->values_num)
521                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
522                 log_err ("%s expects a single string argument.", name);
523                 return 1;
524         }
525
526         sfree (*var);
527         *var = sstrdup (ci->values[0].value.string);
528         return 0;
529 } /* config_set_s */
530
531 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
532 {
533         c_psql_user_data_t *data;
534         const char *param_str;
535
536         c_psql_param_t *tmp;
537
538         data = udb_query_get_user_data (q);
539         if (NULL == data) {
540                 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
541                 if (NULL == data) {
542                         log_err ("Out of memory.");
543                         return -1;
544                 }
545                 memset (data, 0, sizeof (*data));
546                 data->params = NULL;
547         }
548
549         tmp = (c_psql_param_t *) realloc (data->params,
550                         (data->params_num + 1) * sizeof (c_psql_param_t));
551         if (NULL == tmp) {
552                 log_err ("Out of memory.");
553                 return -1;
554         }
555         data->params = tmp;
556
557         param_str = ci->values[0].value.string;
558         if (0 == strcasecmp (param_str, "hostname"))
559                 data->params[data->params_num] = C_PSQL_PARAM_HOST;
560         else if (0 == strcasecmp (param_str, "database"))
561                 data->params[data->params_num] = C_PSQL_PARAM_DB;
562         else if (0 == strcasecmp (param_str, "username"))
563                 data->params[data->params_num] = C_PSQL_PARAM_USER;
564         else if (0 == strcasecmp (param_str, "interval"))
565                 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
566         else {
567                 log_err ("Invalid parameter \"%s\".", param_str);
568                 return 1;
569         }
570
571         data->params_num++;
572         udb_query_set_user_data (q, data);
573
574         return (0);
575 } /* config_query_param_add */
576
577 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
578 {
579         if (0 == strcasecmp ("Param", ci->key))
580                 return config_query_param_add (q, ci);
581
582         log_err ("Option not allowed within a Query block: `%s'", ci->key);
583
584         return (-1);
585 } /* config_query_callback */
586
587 static int c_psql_config_database (oconfig_item_t *ci)
588 {
589         c_psql_database_t *db;
590
591         int i;
592
593         if ((1 != ci->values_num)
594                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
595                 log_err ("<Database> expects a single string argument.");
596                 return 1;
597         }
598
599         db = c_psql_database_new (ci->values[0].value.string);
600
601         for (i = 0; i < ci->children_num; ++i) {
602                 oconfig_item_t *c = ci->children + i;
603
604                 if (0 == strcasecmp (c->key, "Host"))
605                         config_set_s ("Host", &db->host, c);
606                 else if (0 == strcasecmp (c->key, "Port"))
607                         config_set_s ("Port", &db->port, c);
608                 else if (0 == strcasecmp (c->key, "User"))
609                         config_set_s ("User", &db->user, c);
610                 else if (0 == strcasecmp (c->key, "Password"))
611                         config_set_s ("Password", &db->password, c);
612                 else if (0 == strcasecmp (c->key, "SSLMode"))
613                         config_set_s ("SSLMode", &db->sslmode, c);
614                 else if (0 == strcasecmp (c->key, "KRBSrvName"))
615                         config_set_s ("KRBSrvName", &db->krbsrvname, c);
616                 else if (0 == strcasecmp (c->key, "Service"))
617                         config_set_s ("Service", &db->service, c);
618                 else if (0 == strcasecmp (c->key, "Query"))
619                         udb_query_pick_from_list (c, queries, queries_num,
620                                         &db->queries, &db->queries_num);
621                 else
622                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
623         }
624
625         /* If no `Query' options were given, add the default queries.. */
626         if (db->queries_num == 0)
627         {
628                 for (i = 0; i < def_queries_num; i++)
629                         udb_query_pick_from_list_by_name (def_queries[i],
630                                         queries, queries_num,
631                                         &db->queries, &db->queries_num);
632         }
633
634         return 0;
635 } /* c_psql_config_database */
636
637 static int c_psql_config (oconfig_item_t *ci)
638 {
639         static int have_def_config = 0;
640
641         int i;
642
643         if (0 == have_def_config) {
644                 oconfig_item_t *c;
645
646                 have_def_config = 1;
647
648                 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
649                 if (NULL == c)
650                         log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
651                 else
652                         c_psql_config (c);
653
654                 if (NULL == queries)
655                         log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
656                                         "any queries - please check your installation.");
657         }
658
659         for (i = 0; i < ci->children_num; ++i) {
660                 oconfig_item_t *c = ci->children + i;
661
662                 if (0 == strcasecmp (c->key, "Query"))
663                         udb_query_create (&queries, &queries_num, c,
664                                         /* callback = */ config_query_callback,
665                                         /* legacy mode = */ 1);
666                 else if (0 == strcasecmp (c->key, "Database"))
667                         c_psql_config_database (c);
668                 else
669                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
670         }
671         return 0;
672 } /* c_psql_config */
673
674 void module_register (void)
675 {
676         plugin_register_complex_config ("postgresql", c_psql_config);
677         plugin_register_init ("postgresql", c_psql_init);
678 } /* module_register */
679
680 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */