src/configfile.[ch]: Implement "cf_util_get_port_number".
[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 row, col;
291
292         /* The user data may hold parameter information, but may be NULL. */
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 (col = 0; col < column_num; ++col) {
344                 /* Pointers returned by `PQfname' are freed by `PQclear' via
345                  * `BAIL_OUT'. */
346                 column_names[col] = PQfname (res, col);
347                 if (NULL == column_names[col]) {
348                         log_err ("Failed to resolv name of column %i.", col);
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 (row = 0; row < rows_num; ++row) {
368                 for (col = 0; col < column_num; ++col) {
369                         /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
370                          * `BAIL_OUT'. */
371                         column_values[col] = PQgetvalue (res, row, col);
372                         if (NULL == column_values[col]) {
373                                 log_err ("Failed to get value at (row = %i, col = %i).",
374                                                 row, col);
375                                 break;
376                         }
377                 }
378
379                 /* check for an error */
380                 if (col < column_num)
381                         continue;
382
383                 status = udb_query_handle_result (q, column_values);
384                 if (status != 0) {
385                         log_err ("udb_query_handle_result failed with status %i.",
386                                         status);
387                 }
388         } /* for (row = 0; row < rows_num; ++row) */
389
390         BAIL_OUT (0);
391 #undef BAIL_OUT
392 } /* c_psql_exec_query */
393
394 static int c_psql_read (void)
395 {
396         int success = 0;
397         int i;
398
399         for (i = 0; i < databases_num; ++i) {
400                 c_psql_database_t *db = databases + i;
401
402                 int j;
403
404                 assert (NULL != db->database);
405
406                 if (0 != c_psql_check_connection (db))
407                         continue;
408
409                 for (j = 0; j < db->queries_num; ++j)
410                 {
411                         udb_query_t *q;
412
413                         q = db->queries[j];
414
415                         if ((0 != db->server_version)
416                                 && (udb_query_check_version (q, db->server_version) <= 0))
417                                 continue;
418
419                         c_psql_exec_query (db, q);
420                 }
421
422                 ++success;
423         }
424
425         if (! success)
426                 return -1;
427         return 0;
428 } /* c_psql_read */
429
430 static int c_psql_shutdown (void)
431 {
432         int i;
433
434         if ((NULL == databases) || (0 == databases_num))
435                 return 0;
436
437         plugin_unregister_read ("postgresql");
438         plugin_unregister_shutdown ("postgresql");
439
440         for (i = 0; i < databases_num; ++i)
441                 c_psql_database_delete (databases + i);
442
443         sfree (databases);
444         databases_num = 0;
445
446         udb_query_free (queries, queries_num);
447         queries = NULL;
448         queries_num = 0;
449
450         return 0;
451 } /* c_psql_shutdown */
452
453 static int c_psql_init (void)
454 {
455         int i;
456
457         if ((NULL == databases) || (0 == databases_num))
458                 return 0;
459
460         for (i = 0; i < databases_num; ++i) {
461                 c_psql_database_t *db = databases + i;
462
463                 char  conninfo[4096];
464                 char *buf     = conninfo;
465                 int   buf_len = sizeof (conninfo);
466                 int   status;
467
468                 char *server_host;
469                 int   server_version;
470
471                 /* this will happen during reinitialization */
472                 if (NULL != db->conn) {
473                         c_psql_check_connection (db);
474                         continue;
475                 }
476
477                 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
478                 if (0 < status) {
479                         buf     += status;
480                         buf_len -= status;
481                 }
482
483                 C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
484                 C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
485                 C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
486                 C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
487                 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
488                 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
489                 C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
490
491                 db->conn = PQconnectdb (conninfo);
492                 if (0 != c_psql_check_connection (db))
493                         continue;
494
495                 db->proto_version = PQprotocolVersion (db->conn);
496
497                 server_host    = PQhost (db->conn);
498                 server_version = PQserverVersion (db->conn);
499                 log_info ("Sucessfully connected to database %s (user %s) "
500                                 "at server %s%s%s (server version: %d.%d.%d, "
501                                 "protocol version: %d, pid: %d)",
502                                 PQdb (db->conn), PQuser (db->conn),
503                                 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
504                                 C_PSQL_SERVER_VERSION3 (server_version),
505                                 db->proto_version, PQbackendPID (db->conn));
506
507                 if (3 > db->proto_version)
508                         log_warn ("Protocol version %d does not support parameters.",
509                                         db->proto_version);
510         }
511
512         plugin_register_read ("postgresql", c_psql_read);
513         plugin_register_shutdown ("postgresql", c_psql_shutdown);
514         return 0;
515 } /* c_psql_init */
516
517 static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
518 {
519         if ((0 != ci->children_num) || (1 != ci->values_num)
520                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
521                 log_err ("%s expects a single string argument.", name);
522                 return 1;
523         }
524
525         sfree (*var);
526         *var = sstrdup (ci->values[0].value.string);
527         return 0;
528 } /* config_set_s */
529
530 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
531 {
532         c_psql_user_data_t *data;
533         const char *param_str;
534
535         c_psql_param_t *tmp;
536
537         data = udb_query_get_user_data (q);
538         if (NULL == data) {
539                 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
540                 if (NULL == data) {
541                         log_err ("Out of memory.");
542                         return -1;
543                 }
544                 memset (data, 0, sizeof (*data));
545                 data->params = NULL;
546         }
547
548         tmp = (c_psql_param_t *) realloc (data->params,
549                         (data->params_num + 1) * sizeof (c_psql_param_t));
550         if (NULL == tmp) {
551                 log_err ("Out of memory.");
552                 return -1;
553         }
554         data->params = tmp;
555
556         param_str = ci->values[0].value.string;
557         if (0 == strcasecmp (param_str, "hostname"))
558                 data->params[data->params_num] = C_PSQL_PARAM_HOST;
559         else if (0 == strcasecmp (param_str, "database"))
560                 data->params[data->params_num] = C_PSQL_PARAM_DB;
561         else if (0 == strcasecmp (param_str, "username"))
562                 data->params[data->params_num] = C_PSQL_PARAM_USER;
563         else if (0 == strcasecmp (param_str, "interval"))
564                 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
565         else {
566                 log_err ("Invalid parameter \"%s\".", param_str);
567                 return 1;
568         }
569
570         data->params_num++;
571         udb_query_set_user_data (q, data);
572
573         return (0);
574 } /* config_query_param_add */
575
576 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
577 {
578         if (0 == strcasecmp ("Param", ci->key))
579                 return config_query_param_add (q, ci);
580
581         log_err ("Option not allowed within a Query block: `%s'", ci->key);
582
583         return (-1);
584 } /* config_query_callback */
585
586 static int c_psql_config_database (oconfig_item_t *ci)
587 {
588         c_psql_database_t *db;
589
590         int i;
591
592         if ((1 != ci->values_num)
593                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
594                 log_err ("<Database> expects a single string argument.");
595                 return 1;
596         }
597
598         db = c_psql_database_new (ci->values[0].value.string);
599
600         for (i = 0; i < ci->children_num; ++i) {
601                 oconfig_item_t *c = ci->children + i;
602
603                 if (0 == strcasecmp (c->key, "Host"))
604                         config_set_s ("Host", &db->host, c);
605                 else if (0 == strcasecmp (c->key, "Port"))
606                         config_set_s ("Port", &db->port, c);
607                 else if (0 == strcasecmp (c->key, "User"))
608                         config_set_s ("User", &db->user, c);
609                 else if (0 == strcasecmp (c->key, "Password"))
610                         config_set_s ("Password", &db->password, c);
611                 else if (0 == strcasecmp (c->key, "SSLMode"))
612                         config_set_s ("SSLMode", &db->sslmode, c);
613                 else if (0 == strcasecmp (c->key, "KRBSrvName"))
614                         config_set_s ("KRBSrvName", &db->krbsrvname, c);
615                 else if (0 == strcasecmp (c->key, "Service"))
616                         config_set_s ("Service", &db->service, c);
617                 else if (0 == strcasecmp (c->key, "Query"))
618                         udb_query_pick_from_list (c, queries, queries_num,
619                                         &db->queries, &db->queries_num);
620                 else
621                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
622         }
623
624         /* If no `Query' options were given, add the default queries.. */
625         if (db->queries_num == 0)
626         {
627                 for (i = 0; i < def_queries_num; i++)
628                         udb_query_pick_from_list_by_name (def_queries[i],
629                                         queries, queries_num,
630                                         &db->queries, &db->queries_num);
631         }
632
633         for (i = 0; (size_t)i < db->queries_num; ++i) {
634                 c_psql_user_data_t *data;
635                 data = udb_query_get_user_data (db->queries[i]);
636                 if ((data != NULL) && (data->params_num > db->max_params_num))
637                         db->max_params_num = data->params_num;
638         }
639         return 0;
640 } /* c_psql_config_database */
641
642 static int c_psql_config (oconfig_item_t *ci)
643 {
644         static int have_def_config = 0;
645
646         int i;
647
648         if (0 == have_def_config) {
649                 oconfig_item_t *c;
650
651                 have_def_config = 1;
652
653                 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
654                 if (NULL == c)
655                         log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
656                 else
657                         c_psql_config (c);
658
659                 if (NULL == queries)
660                         log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
661                                         "any queries - please check your installation.");
662         }
663
664         for (i = 0; i < ci->children_num; ++i) {
665                 oconfig_item_t *c = ci->children + i;
666
667                 if (0 == strcasecmp (c->key, "Query"))
668                         udb_query_create (&queries, &queries_num, c,
669                                         /* callback = */ config_query_callback,
670                                         /* legacy mode = */ 1);
671                 else if (0 == strcasecmp (c->key, "Database"))
672                         c_psql_config_database (c);
673                 else
674                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
675         }
676         return 0;
677 } /* c_psql_config */
678
679 void module_register (void)
680 {
681         plugin_register_complex_config ("postgresql", c_psql_config);
682         plugin_register_init ("postgresql", c_psql_init);
683 } /* module_register */
684
685 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */