postgresql plugin: Connect to the database in the read function.
[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_connect (c_psql_database_t *db)
200 {
201         char  conninfo[4096];
202         char *buf     = conninfo;
203         int   buf_len = sizeof (conninfo);
204         int   status;
205
206         if (! db)
207                 return -1;
208
209         status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
210         if (0 < status) {
211                 buf     += status;
212                 buf_len -= status;
213         }
214
215         C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
216         C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
217         C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
218         C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
219         C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
220         C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
221         C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
222
223         db->conn = PQconnectdb (conninfo);
224         db->proto_version = PQprotocolVersion (db->conn);
225         return 0;
226 } /* c_psql_connect */
227
228 static int c_psql_check_connection (c_psql_database_t *db)
229 {
230         _Bool init = 0;
231
232         if (! db->conn) {
233                 init = 1;
234
235                 /* trigger c_release() */
236                 if (0 == db->conn_complaint.interval)
237                         db->conn_complaint.interval = 1;
238
239                 c_psql_connect (db);
240         }
241
242         /* "ping" */
243         PQclear (PQexec (db->conn, "SELECT 42;"));
244
245         if (CONNECTION_OK != PQstatus (db->conn)) {
246                 PQreset (db->conn);
247
248                 /* trigger c_release() */
249                 if (0 == db->conn_complaint.interval)
250                         db->conn_complaint.interval = 1;
251
252                 if (CONNECTION_OK != PQstatus (db->conn)) {
253                         c_complain (LOG_ERR, &db->conn_complaint,
254                                         "Failed to connect to database %s: %s",
255                                         db->database, PQerrorMessage (db->conn));
256                         return -1;
257                 }
258
259                 db->proto_version = PQprotocolVersion (db->conn);
260         }
261
262         db->server_version = PQserverVersion (db->conn);
263
264         if (c_would_release (&db->conn_complaint)) {
265                 char *server_host;
266                 int   server_version;
267
268                 server_host    = PQhost (db->conn);
269                 server_version = PQserverVersion (db->conn);
270
271                 c_do_release (LOG_INFO, &db->conn_complaint,
272                                 "Successfully %sconnected to database %s (user %s) "
273                                 "at server %s%s%s (server version: %d.%d.%d, "
274                                 "protocol version: %d, pid: %d)", init ? "" : "re",
275                                 PQdb (db->conn), PQuser (db->conn),
276                                 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
277                                 C_PSQL_SERVER_VERSION3 (server_version),
278                                 db->proto_version, PQbackendPID (db->conn));
279
280                 if (3 > db->proto_version)
281                         log_warn ("Protocol version %d does not support parameters.",
282                                         db->proto_version);
283         }
284         return 0;
285 } /* c_psql_check_connection */
286
287 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
288                 udb_query_t *q)
289 {
290         return PQexec (db->conn, udb_query_get_statement (q));
291 } /* c_psql_exec_query_noparams */
292
293 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
294                 udb_query_t *q, c_psql_user_data_t *data)
295 {
296         char *params[db->max_params_num];
297         char  interval[64];
298         int   i;
299
300         if ((data == NULL) || (data->params_num == 0))
301                 return (c_psql_exec_query_noparams (db, q));
302
303         assert (db->max_params_num >= data->params_num);
304
305         for (i = 0; i < data->params_num; ++i) {
306                 switch (data->params[i]) {
307                         case C_PSQL_PARAM_HOST:
308                                 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
309                                         ? "localhost" : db->host;
310                                 break;
311                         case C_PSQL_PARAM_DB:
312                                 params[i] = db->database;
313                                 break;
314                         case C_PSQL_PARAM_USER:
315                                 params[i] = db->user;
316                                 break;
317                         case C_PSQL_PARAM_INTERVAL:
318                                 ssnprintf (interval, sizeof (interval), "%i", interval_g);
319                                 params[i] = interval;
320                                 break;
321                         default:
322                                 assert (0);
323                 }
324         }
325
326         return PQexecParams (db->conn, udb_query_get_statement (q),
327                         data->params_num, NULL,
328                         (const char *const *) params,
329                         NULL, NULL, /* return text data */ 0);
330 } /* c_psql_exec_query_params */
331
332 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q)
333 {
334         PGresult *res;
335
336         c_psql_user_data_t *data;
337
338         const char *host;
339
340         char **column_names;
341         char **column_values;
342         int    column_num;
343
344         int rows_num;
345         int status;
346         int row, col;
347
348         /* The user data may hold parameter information, but may be NULL. */
349         data = udb_query_get_user_data (q);
350
351         /* Versions up to `3' don't know how to handle parameters. */
352         if (3 <= db->proto_version)
353                 res = c_psql_exec_query_params (db, q, data);
354         else if ((NULL == data) || (0 == data->params_num))
355                 res = c_psql_exec_query_noparams (db, q);
356         else {
357                 log_err ("Connection to database \"%s\" does not support parameters "
358                                 "(protocol version %d) - cannot execute query \"%s\".",
359                                 db->database, db->proto_version,
360                                 udb_query_get_name (q));
361                 return -1;
362         }
363
364         column_names = NULL;
365         column_values = NULL;
366
367 #define BAIL_OUT(status) \
368         sfree (column_names); \
369         sfree (column_values); \
370         PQclear (res); \
371         return status
372
373         if (PGRES_TUPLES_OK != PQresultStatus (res)) {
374                 log_err ("Failed to execute SQL query: %s",
375                                 PQerrorMessage (db->conn));
376                 log_info ("SQL query was: %s",
377                                 udb_query_get_statement (q));
378                 BAIL_OUT (-1);
379         }
380
381         rows_num = PQntuples (res);
382         if (1 > rows_num) {
383                 BAIL_OUT (0);
384         }
385
386         column_num = PQnfields (res);
387         column_names = (char **) calloc (column_num, sizeof (char *));
388         if (NULL == column_names) {
389                 log_err ("calloc failed.");
390                 BAIL_OUT (-1);
391         }
392
393         column_values = (char **) calloc (column_num, sizeof (char *));
394         if (NULL == column_values) {
395                 log_err ("calloc failed.");
396                 BAIL_OUT (-1);
397         }
398         
399         for (col = 0; col < column_num; ++col) {
400                 /* Pointers returned by `PQfname' are freed by `PQclear' via
401                  * `BAIL_OUT'. */
402                 column_names[col] = PQfname (res, col);
403                 if (NULL == column_names[col]) {
404                         log_err ("Failed to resolve name of column %i.", col);
405                         BAIL_OUT (-1);
406                 }
407         }
408
409         if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
410                         || (0 == strcmp (db->host, "localhost")))
411                 host = hostname_g;
412         else
413                 host = db->host;
414
415         status = udb_query_prepare_result (q, host, "postgresql",
416                         db->database, column_names, (size_t) column_num);
417         if (0 != status) {
418                 log_err ("udb_query_prepare_result failed with status %i.",
419                                 status);
420                 BAIL_OUT (-1);
421         }
422
423         for (row = 0; row < rows_num; ++row) {
424                 for (col = 0; col < column_num; ++col) {
425                         /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
426                          * `BAIL_OUT'. */
427                         column_values[col] = PQgetvalue (res, row, col);
428                         if (NULL == column_values[col]) {
429                                 log_err ("Failed to get value at (row = %i, col = %i).",
430                                                 row, col);
431                                 break;
432                         }
433                 }
434
435                 /* check for an error */
436                 if (col < column_num)
437                         continue;
438
439                 status = udb_query_handle_result (q, column_values);
440                 if (status != 0) {
441                         log_err ("udb_query_handle_result failed with status %i.",
442                                         status);
443                 }
444         } /* for (row = 0; row < rows_num; ++row) */
445
446         BAIL_OUT (0);
447 #undef BAIL_OUT
448 } /* c_psql_exec_query */
449
450 static int c_psql_read (void)
451 {
452         int success = 0;
453         int i;
454
455         for (i = 0; i < databases_num; ++i) {
456                 c_psql_database_t *db = databases + i;
457
458                 int j;
459
460                 assert (NULL != db->database);
461
462                 if (0 != c_psql_check_connection (db))
463                         continue;
464
465                 for (j = 0; j < db->queries_num; ++j)
466                 {
467                         udb_query_t *q;
468
469                         q = db->queries[j];
470
471                         if ((0 != db->server_version)
472                                 && (udb_query_check_version (q, db->server_version) <= 0))
473                                 continue;
474
475                         c_psql_exec_query (db, q);
476                 }
477
478                 ++success;
479         }
480
481         if (! success)
482                 return -1;
483         return 0;
484 } /* c_psql_read */
485
486 static int c_psql_shutdown (void)
487 {
488         int i;
489
490         if ((NULL == databases) || (0 == databases_num))
491                 return 0;
492
493         plugin_unregister_read ("postgresql");
494         plugin_unregister_shutdown ("postgresql");
495
496         for (i = 0; i < databases_num; ++i)
497                 c_psql_database_delete (databases + i);
498
499         sfree (databases);
500         databases_num = 0;
501
502         udb_query_free (queries, queries_num);
503         queries = NULL;
504         queries_num = 0;
505
506         return 0;
507 } /* c_psql_shutdown */
508
509 static int c_psql_init (void)
510 {
511         if ((NULL == databases) || (0 == databases_num))
512                 return 0;
513
514         plugin_register_read ("postgresql", c_psql_read);
515         plugin_register_shutdown ("postgresql", c_psql_shutdown);
516         return 0;
517 } /* c_psql_init */
518
519 static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
520 {
521         if ((0 != ci->children_num) || (1 != ci->values_num)
522                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
523                 log_err ("%s expects a single string argument.", name);
524                 return 1;
525         }
526
527         sfree (*var);
528         *var = sstrdup (ci->values[0].value.string);
529         return 0;
530 } /* config_set_s */
531
532 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
533 {
534         c_psql_user_data_t *data;
535         const char *param_str;
536
537         c_psql_param_t *tmp;
538
539         data = udb_query_get_user_data (q);
540         if (NULL == data) {
541                 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
542                 if (NULL == data) {
543                         log_err ("Out of memory.");
544                         return -1;
545                 }
546                 memset (data, 0, sizeof (*data));
547                 data->params = NULL;
548         }
549
550         tmp = (c_psql_param_t *) realloc (data->params,
551                         (data->params_num + 1) * sizeof (c_psql_param_t));
552         if (NULL == tmp) {
553                 log_err ("Out of memory.");
554                 return -1;
555         }
556         data->params = tmp;
557
558         param_str = ci->values[0].value.string;
559         if (0 == strcasecmp (param_str, "hostname"))
560                 data->params[data->params_num] = C_PSQL_PARAM_HOST;
561         else if (0 == strcasecmp (param_str, "database"))
562                 data->params[data->params_num] = C_PSQL_PARAM_DB;
563         else if (0 == strcasecmp (param_str, "username"))
564                 data->params[data->params_num] = C_PSQL_PARAM_USER;
565         else if (0 == strcasecmp (param_str, "interval"))
566                 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
567         else {
568                 log_err ("Invalid parameter \"%s\".", param_str);
569                 return 1;
570         }
571
572         data->params_num++;
573         udb_query_set_user_data (q, data);
574
575         return (0);
576 } /* config_query_param_add */
577
578 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
579 {
580         if (0 == strcasecmp ("Param", ci->key))
581                 return config_query_param_add (q, ci);
582
583         log_err ("Option not allowed within a Query block: `%s'", ci->key);
584
585         return (-1);
586 } /* config_query_callback */
587
588 static int c_psql_config_database (oconfig_item_t *ci)
589 {
590         c_psql_database_t *db;
591
592         int i;
593
594         if ((1 != ci->values_num)
595                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
596                 log_err ("<Database> expects a single string argument.");
597                 return 1;
598         }
599
600         db = c_psql_database_new (ci->values[0].value.string);
601
602         for (i = 0; i < ci->children_num; ++i) {
603                 oconfig_item_t *c = ci->children + i;
604
605                 if (0 == strcasecmp (c->key, "Host"))
606                         config_set_s ("Host", &db->host, c);
607                 else if (0 == strcasecmp (c->key, "Port"))
608                         config_set_s ("Port", &db->port, c);
609                 else if (0 == strcasecmp (c->key, "User"))
610                         config_set_s ("User", &db->user, c);
611                 else if (0 == strcasecmp (c->key, "Password"))
612                         config_set_s ("Password", &db->password, c);
613                 else if (0 == strcasecmp (c->key, "SSLMode"))
614                         config_set_s ("SSLMode", &db->sslmode, c);
615                 else if (0 == strcasecmp (c->key, "KRBSrvName"))
616                         config_set_s ("KRBSrvName", &db->krbsrvname, c);
617                 else if (0 == strcasecmp (c->key, "Service"))
618                         config_set_s ("Service", &db->service, c);
619                 else if (0 == strcasecmp (c->key, "Query"))
620                         udb_query_pick_from_list (c, queries, queries_num,
621                                         &db->queries, &db->queries_num);
622                 else
623                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
624         }
625
626         /* If no `Query' options were given, add the default queries.. */
627         if (db->queries_num == 0)
628         {
629                 for (i = 0; i < def_queries_num; i++)
630                         udb_query_pick_from_list_by_name (def_queries[i],
631                                         queries, queries_num,
632                                         &db->queries, &db->queries_num);
633         }
634
635         for (i = 0; (size_t)i < db->queries_num; ++i) {
636                 c_psql_user_data_t *data;
637                 data = udb_query_get_user_data (db->queries[i]);
638                 if ((data != NULL) && (data->params_num > db->max_params_num))
639                         db->max_params_num = data->params_num;
640         }
641         return 0;
642 } /* c_psql_config_database */
643
644 static int c_psql_config (oconfig_item_t *ci)
645 {
646         static int have_def_config = 0;
647
648         int i;
649
650         if (0 == have_def_config) {
651                 oconfig_item_t *c;
652
653                 have_def_config = 1;
654
655                 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
656                 if (NULL == c)
657                         log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
658                 else
659                         c_psql_config (c);
660
661                 if (NULL == queries)
662                         log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
663                                         "any queries - please check your installation.");
664         }
665
666         for (i = 0; i < ci->children_num; ++i) {
667                 oconfig_item_t *c = ci->children + i;
668
669                 if (0 == strcasecmp (c->key, "Query"))
670                         udb_query_create (&queries, &queries_num, c,
671                                         /* callback = */ config_query_callback,
672                                         /* legacy mode = */ 1);
673                 else if (0 == strcasecmp (c->key, "Database"))
674                         c_psql_config_database (c);
675                 else
676                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
677         }
678         return 0;
679 } /* c_psql_config */
680
681 void module_register (void)
682 {
683         plugin_register_complex_config ("postgresql", c_psql_config);
684         plugin_register_init ("postgresql", c_psql_init);
685 } /* module_register */
686
687 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */