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 #if HAVE_PTHREAD_H
49 # include <pthread.h>
50 #endif
52 #include <pg_config_manual.h>
53 #include <libpq-fe.h>
55 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
56 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
57 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
59 #ifndef C_PSQL_DEFAULT_CONF
60 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
61 #endif
63 /* Appends the (parameter, value) pair to the string
64 * pointed to by 'buf' suitable to be used as argument
65 * for PQconnectdb(). If value equals NULL, the pair
66 * is ignored. */
67 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
68 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
69 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
70 if (0 < s) { \
71 buf += s; \
72 buf_len -= s; \
73 } \
74 }
76 /* Returns the tuple (major, minor, patchlevel)
77 * for the given version number. */
78 #define C_PSQL_SERVER_VERSION3(server_version) \
79 (server_version) / 10000, \
80 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
81 (server_version) - (int)((server_version) / 100) * 100
83 /* Returns true if the given host specifies a
84 * UNIX domain socket. */
85 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
86 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
88 /* Returns the tuple (host, delimiter, port) for a
89 * given (host, port) pair. Depending on the value of
90 * 'host' a UNIX domain socket or a TCP socket is
91 * assumed. */
92 #define C_PSQL_SOCKET3(host, port) \
93 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
94 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
95 port
97 typedef enum {
98 C_PSQL_PARAM_HOST = 1,
99 C_PSQL_PARAM_DB,
100 C_PSQL_PARAM_USER,
101 C_PSQL_PARAM_INTERVAL,
102 } c_psql_param_t;
104 /* Parameter configuration. Stored as `user data' in the query objects. */
105 typedef struct {
106 c_psql_param_t *params;
107 int params_num;
108 } c_psql_user_data_t;
110 typedef struct {
111 char *name;
112 char *statement;
113 } c_psql_writer_t;
115 typedef struct {
116 PGconn *conn;
117 c_complain_t conn_complaint;
119 int proto_version;
120 int server_version;
122 int max_params_num;
124 /* user configuration */
125 udb_query_preparation_area_t **q_prep_areas;
126 udb_query_t **queries;
127 size_t queries_num;
129 c_psql_writer_t **writers;
130 size_t writers_num;
132 /* make sure we don't access the database object in parallel */
133 pthread_mutex_t db_lock;
135 cdtime_t interval;
137 char *host;
138 char *port;
139 char *database;
140 char *user;
141 char *password;
143 char *sslmode;
145 char *krbsrvname;
147 char *service;
148 } c_psql_database_t;
150 static char *def_queries[] = {
151 "backends",
152 "transactions",
153 "queries",
154 "query_plans",
155 "table_states",
156 "disk_io",
157 "disk_usage"
158 };
159 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
161 static udb_query_t **queries = NULL;
162 static size_t queries_num = 0;
164 static c_psql_writer_t *writers = NULL;
165 static size_t writers_num = 0;
167 static c_psql_database_t *c_psql_database_new (const char *name)
168 {
169 c_psql_database_t *db;
171 db = (c_psql_database_t *)malloc (sizeof (*db));
172 if (NULL == db) {
173 log_err ("Out of memory.");
174 return NULL;
175 }
177 db->conn = NULL;
179 C_COMPLAIN_INIT (&db->conn_complaint);
181 db->proto_version = 0;
182 db->server_version = 0;
184 db->max_params_num = 0;
186 db->q_prep_areas = NULL;
187 db->queries = NULL;
188 db->queries_num = 0;
190 db->writers = NULL;
191 db->writers_num = 0;
193 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
195 db->interval = 0;
197 db->database = sstrdup (name);
198 db->host = NULL;
199 db->port = NULL;
200 db->user = NULL;
201 db->password = NULL;
203 db->sslmode = NULL;
205 db->krbsrvname = NULL;
207 db->service = NULL;
208 return db;
209 } /* c_psql_database_new */
211 static void c_psql_database_delete (void *data)
212 {
213 size_t i;
215 c_psql_database_t *db = data;
217 PQfinish (db->conn);
218 db->conn = NULL;
220 if (db->q_prep_areas)
221 for (i = 0; i < db->queries_num; ++i)
222 udb_query_delete_preparation_area (db->q_prep_areas[i]);
223 free (db->q_prep_areas);
225 sfree (db->queries);
226 db->queries_num = 0;
228 sfree (db->writers);
229 db->writers_num = 0;
231 pthread_mutex_destroy (&db->db_lock);
233 sfree (db->database);
234 sfree (db->host);
235 sfree (db->port);
236 sfree (db->user);
237 sfree (db->password);
239 sfree (db->sslmode);
241 sfree (db->krbsrvname);
243 sfree (db->service);
244 return;
245 } /* c_psql_database_delete */
247 static int c_psql_connect (c_psql_database_t *db)
248 {
249 char conninfo[4096];
250 char *buf = conninfo;
251 int buf_len = sizeof (conninfo);
252 int status;
254 if (! db)
255 return -1;
257 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
258 if (0 < status) {
259 buf += status;
260 buf_len -= status;
261 }
263 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
264 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
265 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
266 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
267 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
268 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
269 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
271 db->conn = PQconnectdb (conninfo);
272 db->proto_version = PQprotocolVersion (db->conn);
273 return 0;
274 } /* c_psql_connect */
276 static int c_psql_check_connection (c_psql_database_t *db)
277 {
278 _Bool init = 0;
280 if (! db->conn) {
281 init = 1;
283 /* trigger c_release() */
284 if (0 == db->conn_complaint.interval)
285 db->conn_complaint.interval = 1;
287 c_psql_connect (db);
288 }
290 /* "ping" */
291 PQclear (PQexec (db->conn, "SELECT 42;"));
293 if (CONNECTION_OK != PQstatus (db->conn)) {
294 PQreset (db->conn);
296 /* trigger c_release() */
297 if (0 == db->conn_complaint.interval)
298 db->conn_complaint.interval = 1;
300 if (CONNECTION_OK != PQstatus (db->conn)) {
301 c_complain (LOG_ERR, &db->conn_complaint,
302 "Failed to connect to database %s: %s",
303 db->database, PQerrorMessage (db->conn));
304 return -1;
305 }
307 db->proto_version = PQprotocolVersion (db->conn);
308 }
310 db->server_version = PQserverVersion (db->conn);
312 if (c_would_release (&db->conn_complaint)) {
313 char *server_host;
314 int server_version;
316 server_host = PQhost (db->conn);
317 server_version = PQserverVersion (db->conn);
319 c_do_release (LOG_INFO, &db->conn_complaint,
320 "Successfully %sconnected to database %s (user %s) "
321 "at server %s%s%s (server version: %d.%d.%d, "
322 "protocol version: %d, pid: %d)", init ? "" : "re",
323 PQdb (db->conn), PQuser (db->conn),
324 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
325 C_PSQL_SERVER_VERSION3 (server_version),
326 db->proto_version, PQbackendPID (db->conn));
328 if (3 > db->proto_version)
329 log_warn ("Protocol version %d does not support parameters.",
330 db->proto_version);
331 }
332 return 0;
333 } /* c_psql_check_connection */
335 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
336 udb_query_t *q)
337 {
338 return PQexec (db->conn, udb_query_get_statement (q));
339 } /* c_psql_exec_query_noparams */
341 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
342 udb_query_t *q, c_psql_user_data_t *data)
343 {
344 char *params[db->max_params_num];
345 char interval[64];
346 int i;
348 if ((data == NULL) || (data->params_num == 0))
349 return (c_psql_exec_query_noparams (db, q));
351 assert (db->max_params_num >= data->params_num);
353 for (i = 0; i < data->params_num; ++i) {
354 switch (data->params[i]) {
355 case C_PSQL_PARAM_HOST:
356 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
357 ? "localhost" : db->host;
358 break;
359 case C_PSQL_PARAM_DB:
360 params[i] = db->database;
361 break;
362 case C_PSQL_PARAM_USER:
363 params[i] = db->user;
364 break;
365 case C_PSQL_PARAM_INTERVAL:
366 ssnprintf (interval, sizeof (interval), "%.3f",
367 (db->interval > 0)
368 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
369 params[i] = interval;
370 break;
371 default:
372 assert (0);
373 }
374 }
376 return PQexecParams (db->conn, udb_query_get_statement (q),
377 data->params_num, NULL,
378 (const char *const *) params,
379 NULL, NULL, /* return text data */ 0);
380 } /* c_psql_exec_query_params */
382 /* db->db_lock must be locked when calling this function */
383 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
384 udb_query_preparation_area_t *prep_area)
385 {
386 PGresult *res;
388 c_psql_user_data_t *data;
390 const char *host;
392 char **column_names;
393 char **column_values;
394 int column_num;
396 int rows_num;
397 int status;
398 int row, col;
400 /* The user data may hold parameter information, but may be NULL. */
401 data = udb_query_get_user_data (q);
403 /* Versions up to `3' don't know how to handle parameters. */
404 if (3 <= db->proto_version)
405 res = c_psql_exec_query_params (db, q, data);
406 else if ((NULL == data) || (0 == data->params_num))
407 res = c_psql_exec_query_noparams (db, q);
408 else {
409 log_err ("Connection to database \"%s\" does not support parameters "
410 "(protocol version %d) - cannot execute query \"%s\".",
411 db->database, db->proto_version,
412 udb_query_get_name (q));
413 return -1;
414 }
416 /* give c_psql_write() a chance to acquire the lock if called recursively
417 * through dispatch_values(); this will happen if, both, queries and
418 * writers are configured for a single connection */
419 pthread_mutex_unlock (&db->db_lock);
421 column_names = NULL;
422 column_values = NULL;
424 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
425 pthread_mutex_lock (&db->db_lock);
427 log_err ("Failed to execute SQL query: %s",
428 PQerrorMessage (db->conn));
429 log_info ("SQL query was: %s",
430 udb_query_get_statement (q));
431 PQclear (res);
432 return -1;
433 }
435 #define BAIL_OUT(status) \
436 sfree (column_names); \
437 sfree (column_values); \
438 PQclear (res); \
439 pthread_mutex_lock (&db->db_lock); \
440 return status
442 rows_num = PQntuples (res);
443 if (1 > rows_num) {
444 BAIL_OUT (0);
445 }
447 column_num = PQnfields (res);
448 column_names = (char **) calloc (column_num, sizeof (char *));
449 if (NULL == column_names) {
450 log_err ("calloc failed.");
451 BAIL_OUT (-1);
452 }
454 column_values = (char **) calloc (column_num, sizeof (char *));
455 if (NULL == column_values) {
456 log_err ("calloc failed.");
457 BAIL_OUT (-1);
458 }
460 for (col = 0; col < column_num; ++col) {
461 /* Pointers returned by `PQfname' are freed by `PQclear' via
462 * `BAIL_OUT'. */
463 column_names[col] = PQfname (res, col);
464 if (NULL == column_names[col]) {
465 log_err ("Failed to resolve name of column %i.", col);
466 BAIL_OUT (-1);
467 }
468 }
470 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
471 || (0 == strcmp (db->host, "localhost")))
472 host = hostname_g;
473 else
474 host = db->host;
476 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
477 db->database, column_names, (size_t) column_num, db->interval);
478 if (0 != status) {
479 log_err ("udb_query_prepare_result failed with status %i.",
480 status);
481 BAIL_OUT (-1);
482 }
484 for (row = 0; row < rows_num; ++row) {
485 for (col = 0; col < column_num; ++col) {
486 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
487 * `BAIL_OUT'. */
488 column_values[col] = PQgetvalue (res, row, col);
489 if (NULL == column_values[col]) {
490 log_err ("Failed to get value at (row = %i, col = %i).",
491 row, col);
492 break;
493 }
494 }
496 /* check for an error */
497 if (col < column_num)
498 continue;
500 status = udb_query_handle_result (q, prep_area, column_values);
501 if (status != 0) {
502 log_err ("udb_query_handle_result failed with status %i.",
503 status);
504 }
505 } /* for (row = 0; row < rows_num; ++row) */
507 udb_query_finish_result (q, prep_area);
509 BAIL_OUT (0);
510 #undef BAIL_OUT
511 } /* c_psql_exec_query */
513 static int c_psql_read (user_data_t *ud)
514 {
515 c_psql_database_t *db;
517 int success = 0;
518 int i;
520 if ((ud == NULL) || (ud->data == NULL)) {
521 log_err ("c_psql_read: Invalid user data.");
522 return -1;
523 }
525 db = ud->data;
527 assert (NULL != db->database);
528 assert (NULL != db->queries);
530 pthread_mutex_lock (&db->db_lock);
532 if (0 != c_psql_check_connection (db)) {
533 pthread_mutex_unlock (&db->db_lock);
534 return -1;
535 }
537 for (i = 0; i < db->queries_num; ++i)
538 {
539 udb_query_preparation_area_t *prep_area;
540 udb_query_t *q;
542 prep_area = db->q_prep_areas[i];
543 q = db->queries[i];
545 if ((0 != db->server_version)
546 && (udb_query_check_version (q, db->server_version) <= 0))
547 continue;
549 if (0 == c_psql_exec_query (db, q, prep_area))
550 success = 1;
551 }
553 pthread_mutex_unlock (&db->db_lock);
555 if (! success)
556 return -1;
557 return 0;
558 } /* c_psql_read */
560 static char *values_name_to_sqlarray (const data_set_t *ds,
561 char *string, size_t string_len)
562 {
563 char *str_ptr;
564 size_t str_len;
566 int i;
568 str_ptr = string;
569 str_len = string_len;
571 for (i = 0; i < ds->ds_num; ++i) {
572 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
574 if (status < 1)
575 return NULL;
576 else if ((size_t)status >= str_len) {
577 str_len = 0;
578 break;
579 }
580 else {
581 str_ptr += status;
582 str_len -= (size_t)status;
583 }
584 }
586 if (str_len <= 2) {
587 log_err ("c_psql_write: Failed to stringify value names");
588 return NULL;
589 }
591 /* overwrite the first comma */
592 string[0] = '{';
593 str_ptr[0] = '}';
594 str_ptr[1] = '\0';
596 return string;
597 } /* values_name_to_sqlarray */
599 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
600 char *string, size_t string_len)
601 {
602 char *str_ptr;
603 size_t str_len;
605 int i;
607 str_ptr = string;
608 str_len = string_len;
610 for (i = 0; i < vl->values_len; ++i) {
611 int status;
613 if (ds->ds[i].type == DS_TYPE_GAUGE)
614 status = ssnprintf (str_ptr, str_len,
615 ",%f", vl->values[i].gauge);
616 else if (ds->ds[i].type == DS_TYPE_COUNTER)
617 status = ssnprintf (str_ptr, str_len,
618 ",%llu", vl->values[i].counter);
619 else if (ds->ds[i].type == DS_TYPE_DERIVE)
620 status = ssnprintf (str_ptr, str_len,
621 ",%"PRIi64, vl->values[i].derive);
622 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
623 status = ssnprintf (str_ptr, str_len,
624 ",%"PRIu64, vl->values[i].absolute);
625 else {
626 log_err ("c_psql_write: Unknown data source type: %i",
627 ds->ds[i].type);
628 return NULL;
629 }
631 if (status < 1)
632 return NULL;
633 else if ((size_t)status >= str_len) {
634 str_len = 0;
635 break;
636 }
637 else {
638 str_ptr += status;
639 str_len -= (size_t)status;
640 }
641 }
643 if (str_len <= 2) {
644 log_err ("c_psql_write: Failed to stringify value list");
645 return NULL;
646 }
648 /* overwrite the first comma */
649 string[0] = '{';
650 str_ptr[0] = '}';
651 str_ptr[1] = '\0';
653 return string;
654 } /* values_to_sqlarray */
656 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
657 user_data_t *ud)
658 {
659 c_psql_database_t *db;
661 char time_str[1024];
662 char values_name_str[1024];
663 char values_str[1024];
665 const char *params[8];
667 int success = 0;
668 int i;
670 if ((ud == NULL) || (ud->data == NULL)) {
671 log_err ("c_psql_write: Invalid user data.");
672 return -1;
673 }
675 db = ud->data;
676 assert (db->database != NULL);
677 assert (db->writers != NULL);
679 ssnprintf (time_str, sizeof (time_str),
680 "%f", CDTIME_T_TO_DOUBLE (vl->time));
682 if (values_name_to_sqlarray (ds,
683 values_name_str, sizeof (values_name_str)) == NULL)
684 return -1;
686 if (values_to_sqlarray (ds, vl, values_str, sizeof (values_str)) == NULL)
687 return -1;
689 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
691 params[0] = time_str;
692 params[1] = vl->host;
693 params[2] = vl->plugin;
694 params[3] = VALUE_OR_NULL(vl->plugin_instance);
695 params[4] = vl->type;
696 params[5] = VALUE_OR_NULL(vl->type_instance);
697 params[6] = values_name_str;
698 params[7] = values_str;
700 #undef VALUE_OR_NULL
702 pthread_mutex_lock (&db->db_lock);
704 if (0 != c_psql_check_connection (db)) {
705 pthread_mutex_unlock (&db->db_lock);
706 return -1;
707 }
709 for (i = 0; i < db->writers_num; ++i) {
710 c_psql_writer_t *writer;
711 PGresult *res;
713 writer = db->writers[i];
715 res = PQexecParams (db->conn, writer->statement,
716 STATIC_ARRAY_SIZE (params), NULL,
717 (const char *const *)params,
718 NULL, NULL, /* return text data */ 0);
720 if ((PGRES_COMMAND_OK != PQresultStatus (res))
721 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
722 if ((CONNECTION_OK != PQstatus (db->conn))
723 && (0 == c_psql_check_connection (db))) {
724 PQclear (res);
726 /* try again */
727 res = PQexecParams (db->conn, writer->statement,
728 STATIC_ARRAY_SIZE (params), NULL,
729 (const char *const *)params,
730 NULL, NULL, /* return text data */ 0);
732 if ((PGRES_COMMAND_OK == PQresultStatus (res))
733 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
734 success = 1;
735 continue;
736 }
737 }
739 log_err ("Failed to execute SQL query: %s",
740 PQerrorMessage (db->conn));
741 log_info ("SQL query was: '%s', "
742 "params: %s, %s, %s, %s, %s, %s, %s, %s",
743 writer->statement,
744 params[0], params[1], params[2], params[3],
745 params[4], params[5], params[6], params[7]);
746 pthread_mutex_unlock (&db->db_lock);
747 return -1;
748 }
749 success = 1;
750 }
752 pthread_mutex_unlock (&db->db_lock);
754 if (! success)
755 return -1;
756 return 0;
757 } /* c_psql_write */
759 static int c_psql_shutdown (void)
760 {
761 plugin_unregister_read_group ("postgresql");
763 udb_query_free (queries, queries_num);
764 queries = NULL;
765 queries_num = 0;
767 sfree (writers);
768 writers = NULL;
769 writers_num = 0;
771 return 0;
772 } /* c_psql_shutdown */
774 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
775 {
776 c_psql_user_data_t *data;
777 const char *param_str;
779 c_psql_param_t *tmp;
781 data = udb_query_get_user_data (q);
782 if (NULL == data) {
783 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
784 if (NULL == data) {
785 log_err ("Out of memory.");
786 return -1;
787 }
788 memset (data, 0, sizeof (*data));
789 data->params = NULL;
790 }
792 tmp = (c_psql_param_t *) realloc (data->params,
793 (data->params_num + 1) * sizeof (c_psql_param_t));
794 if (NULL == tmp) {
795 log_err ("Out of memory.");
796 return -1;
797 }
798 data->params = tmp;
800 param_str = ci->values[0].value.string;
801 if (0 == strcasecmp (param_str, "hostname"))
802 data->params[data->params_num] = C_PSQL_PARAM_HOST;
803 else if (0 == strcasecmp (param_str, "database"))
804 data->params[data->params_num] = C_PSQL_PARAM_DB;
805 else if (0 == strcasecmp (param_str, "username"))
806 data->params[data->params_num] = C_PSQL_PARAM_USER;
807 else if (0 == strcasecmp (param_str, "interval"))
808 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
809 else {
810 log_err ("Invalid parameter \"%s\".", param_str);
811 return 1;
812 }
814 data->params_num++;
815 udb_query_set_user_data (q, data);
817 return (0);
818 } /* config_query_param_add */
820 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
821 {
822 if (0 == strcasecmp ("Param", ci->key))
823 return config_query_param_add (q, ci);
825 log_err ("Option not allowed within a Query block: `%s'", ci->key);
827 return (-1);
828 } /* config_query_callback */
830 static int config_add_writer (oconfig_item_t *ci,
831 c_psql_writer_t *src_writers, size_t src_writers_num,
832 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
833 {
834 char *name;
836 size_t i;
838 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
839 return -1;
841 if ((ci->values_num != 1)
842 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
843 log_err ("`Writer' expects a single string argument.");
844 return 1;
845 }
847 name = ci->values[0].value.string;
849 for (i = 0; i < src_writers_num; ++i) {
850 c_psql_writer_t **tmp;
852 if (strcasecmp (name, src_writers[i].name) != 0)
853 continue;
855 tmp = (c_psql_writer_t **)realloc (*dst_writers,
856 sizeof (**dst_writers) * (*dst_writers_num + 1));
857 if (tmp == NULL) {
858 log_err ("Out of memory.");
859 return -1;
860 }
862 tmp[*dst_writers_num] = src_writers + i;
864 *dst_writers = tmp;
865 ++(*dst_writers_num);
866 break;
867 }
869 if (i >= src_writers_num) {
870 log_err ("No such writer: `%s'", name);
871 return -1;
872 }
874 return 0;
875 } /* config_add_writer */
877 static int c_psql_config_writer (oconfig_item_t *ci)
878 {
879 c_psql_writer_t *writer;
880 c_psql_writer_t *tmp;
882 int status = 0;
883 int i;
885 if ((ci->values_num != 1)
886 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
887 log_err ("<Writer> expects a single string argument.");
888 return 1;
889 }
891 tmp = (c_psql_writer_t *)realloc (writers,
892 sizeof (*writers) * (writers_num + 1));
893 if (tmp == NULL) {
894 log_err ("Out of memory.");
895 return -1;
896 }
898 writers = tmp;
899 writer = writers + writers_num;
900 ++writers_num;
902 writer->name = sstrdup (ci->values[0].value.string);
903 writer->statement = NULL;
905 for (i = 0; i < ci->children_num; ++i) {
906 oconfig_item_t *c = ci->children + i;
908 if (strcasecmp ("Statement", c->key) == 0)
909 status = cf_util_get_string (c, &writer->statement);
910 else
911 log_warn ("Ignoring unknown config key \"%s\".", c->key);
912 }
914 if (status != 0) {
915 sfree (writer->statement);
916 sfree (writer->name);
917 sfree (writer);
918 return status;
919 }
921 return 0;
922 } /* c_psql_config_writer */
924 static int c_psql_config_database (oconfig_item_t *ci)
925 {
926 c_psql_database_t *db;
928 char cb_name[DATA_MAX_NAME_LEN];
929 struct timespec cb_interval = { 0, 0 };
930 user_data_t ud;
932 int i;
934 if ((1 != ci->values_num)
935 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
936 log_err ("<Database> expects a single string argument.");
937 return 1;
938 }
940 memset (&ud, 0, sizeof (ud));
942 db = c_psql_database_new (ci->values[0].value.string);
943 if (db == NULL)
944 return -1;
946 for (i = 0; i < ci->children_num; ++i) {
947 oconfig_item_t *c = ci->children + i;
949 if (0 == strcasecmp (c->key, "Host"))
950 cf_util_get_string (c, &db->host);
951 else if (0 == strcasecmp (c->key, "Port"))
952 cf_util_get_service (c, &db->port);
953 else if (0 == strcasecmp (c->key, "User"))
954 cf_util_get_string (c, &db->user);
955 else if (0 == strcasecmp (c->key, "Password"))
956 cf_util_get_string (c, &db->password);
957 else if (0 == strcasecmp (c->key, "SSLMode"))
958 cf_util_get_string (c, &db->sslmode);
959 else if (0 == strcasecmp (c->key, "KRBSrvName"))
960 cf_util_get_string (c, &db->krbsrvname);
961 else if (0 == strcasecmp (c->key, "Service"))
962 cf_util_get_string (c, &db->service);
963 else if (0 == strcasecmp (c->key, "Query"))
964 udb_query_pick_from_list (c, queries, queries_num,
965 &db->queries, &db->queries_num);
966 else if (0 == strcasecmp (c->key, "Writer"))
967 config_add_writer (c, writers, writers_num,
968 &db->writers, &db->writers_num);
969 else if (0 == strcasecmp (c->key, "Interval"))
970 cf_util_get_cdtime (c, &db->interval);
971 else
972 log_warn ("Ignoring unknown config key \"%s\".", c->key);
973 }
975 /* If no `Query' options were given, add the default queries.. */
976 if ((db->queries_num == 0) && (db->writers_num == 0)){
977 for (i = 0; i < def_queries_num; i++)
978 udb_query_pick_from_list_by_name (def_queries[i],
979 queries, queries_num,
980 &db->queries, &db->queries_num);
981 }
983 if (db->queries_num > 0) {
984 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
985 db->queries_num, sizeof (*db->q_prep_areas));
987 if (db->q_prep_areas == NULL) {
988 log_err ("Out of memory.");
989 c_psql_database_delete (db);
990 return -1;
991 }
992 }
994 for (i = 0; (size_t)i < db->queries_num; ++i) {
995 c_psql_user_data_t *data;
996 data = udb_query_get_user_data (db->queries[i]);
997 if ((data != NULL) && (data->params_num > db->max_params_num))
998 db->max_params_num = data->params_num;
1000 db->q_prep_areas[i]
1001 = udb_query_allocate_preparation_area (db->queries[i]);
1003 if (db->q_prep_areas[i] == NULL) {
1004 log_err ("Out of memory.");
1005 c_psql_database_delete (db);
1006 return -1;
1007 }
1008 }
1010 ud.data = db;
1011 ud.free_func = c_psql_database_delete;
1013 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
1015 if (db->queries_num > 0) {
1016 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1018 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1019 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1020 &ud);
1021 }
1022 if (db->writers_num > 0) {
1023 plugin_register_write (cb_name, c_psql_write, &ud);
1024 }
1025 return 0;
1026 } /* c_psql_config_database */
1028 static int c_psql_config (oconfig_item_t *ci)
1029 {
1030 static int have_def_config = 0;
1032 int i;
1034 if (0 == have_def_config) {
1035 oconfig_item_t *c;
1037 have_def_config = 1;
1039 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1040 if (NULL == c)
1041 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1042 else
1043 c_psql_config (c);
1045 if (NULL == queries)
1046 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1047 "any queries - please check your installation.");
1048 }
1050 for (i = 0; i < ci->children_num; ++i) {
1051 oconfig_item_t *c = ci->children + i;
1053 if (0 == strcasecmp (c->key, "Query"))
1054 udb_query_create (&queries, &queries_num, c,
1055 /* callback = */ config_query_callback);
1056 else if (0 == strcasecmp (c->key, "Writer"))
1057 c_psql_config_writer (c);
1058 else if (0 == strcasecmp (c->key, "Database"))
1059 c_psql_config_database (c);
1060 else
1061 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1062 }
1063 return 0;
1064 } /* c_psql_config */
1066 void module_register (void)
1067 {
1068 plugin_register_complex_config ("postgresql", c_psql_config);
1069 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1070 } /* module_register */
1072 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */