1 /**
2 * collectd - src/postgresql.c
3 * Copyright (C) 2008-2012 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_cache.h"
46 #include "utils_db_query.h"
47 #include "utils_complain.h"
49 #if HAVE_PTHREAD_H
50 # include <pthread.h>
51 #endif
53 #include <pg_config_manual.h>
54 #include <libpq-fe.h>
56 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
57 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
58 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
59 #define log_debug(...) DEBUG ("postgresql: " __VA_ARGS__)
61 #ifndef C_PSQL_DEFAULT_CONF
62 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
63 #endif
65 /* Appends the (parameter, value) pair to the string
66 * pointed to by 'buf' suitable to be used as argument
67 * for PQconnectdb(). If value equals NULL, the pair
68 * is ignored. */
69 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
70 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
71 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
72 if (0 < s) { \
73 buf += s; \
74 buf_len -= s; \
75 } \
76 }
78 /* Returns the tuple (major, minor, patchlevel)
79 * for the given version number. */
80 #define C_PSQL_SERVER_VERSION3(server_version) \
81 (server_version) / 10000, \
82 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
83 (server_version) - (int)((server_version) / 100) * 100
85 /* Returns true if the given host specifies a
86 * UNIX domain socket. */
87 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
88 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
90 /* Returns the tuple (host, delimiter, port) for a
91 * given (host, port) pair. Depending on the value of
92 * 'host' a UNIX domain socket or a TCP socket is
93 * assumed. */
94 #define C_PSQL_SOCKET3(host, port) \
95 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
96 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
97 port
99 typedef enum {
100 C_PSQL_PARAM_HOST = 1,
101 C_PSQL_PARAM_DB,
102 C_PSQL_PARAM_USER,
103 C_PSQL_PARAM_INTERVAL,
104 } c_psql_param_t;
106 /* Parameter configuration. Stored as `user data' in the query objects. */
107 typedef struct {
108 c_psql_param_t *params;
109 int params_num;
110 } c_psql_user_data_t;
112 typedef struct {
113 char *name;
114 char *statement;
115 _Bool store_rates;
116 } c_psql_writer_t;
118 typedef struct {
119 PGconn *conn;
120 c_complain_t conn_complaint;
122 int proto_version;
123 int server_version;
125 int max_params_num;
127 /* user configuration */
128 udb_query_preparation_area_t **q_prep_areas;
129 udb_query_t **queries;
130 size_t queries_num;
132 c_psql_writer_t **writers;
133 size_t writers_num;
135 /* make sure we don't access the database object in parallel */
136 pthread_mutex_t db_lock;
138 cdtime_t interval;
140 /* writer "caching" settings */
141 cdtime_t commit_interval;
142 cdtime_t next_commit;
144 char *host;
145 char *port;
146 char *database;
147 char *user;
148 char *password;
150 char *sslmode;
152 char *krbsrvname;
154 char *service;
155 } c_psql_database_t;
157 static char *def_queries[] = {
158 "backends",
159 "transactions",
160 "queries",
161 "query_plans",
162 "table_states",
163 "disk_io",
164 "disk_usage"
165 };
166 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
168 static udb_query_t **queries = NULL;
169 static size_t queries_num = 0;
171 static c_psql_writer_t *writers = NULL;
172 static size_t writers_num = 0;
174 static c_psql_database_t *c_psql_database_new (const char *name)
175 {
176 c_psql_database_t *db;
178 db = (c_psql_database_t *)malloc (sizeof (*db));
179 if (NULL == db) {
180 log_err ("Out of memory.");
181 return NULL;
182 }
184 db->conn = NULL;
186 C_COMPLAIN_INIT (&db->conn_complaint);
188 db->proto_version = 0;
189 db->server_version = 0;
191 db->max_params_num = 0;
193 db->q_prep_areas = NULL;
194 db->queries = NULL;
195 db->queries_num = 0;
197 db->writers = NULL;
198 db->writers_num = 0;
200 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
202 db->interval = 0;
204 db->commit_interval = 0;
205 db->next_commit = 0;
207 db->database = sstrdup (name);
208 db->host = NULL;
209 db->port = NULL;
210 db->user = NULL;
211 db->password = NULL;
213 db->sslmode = NULL;
215 db->krbsrvname = NULL;
217 db->service = NULL;
218 return db;
219 } /* c_psql_database_new */
221 static void c_psql_database_delete (void *data)
222 {
223 size_t i;
225 c_psql_database_t *db = data;
227 PQfinish (db->conn);
228 db->conn = NULL;
230 if (db->q_prep_areas)
231 for (i = 0; i < db->queries_num; ++i)
232 udb_query_delete_preparation_area (db->q_prep_areas[i]);
233 free (db->q_prep_areas);
235 sfree (db->queries);
236 db->queries_num = 0;
238 sfree (db->writers);
239 db->writers_num = 0;
241 /* wait for the lock to be released by the last writer */
242 pthread_mutex_lock (&db->db_lock);
243 pthread_mutex_unlock (&db->db_lock);
245 pthread_mutex_destroy (&db->db_lock);
247 sfree (db->database);
248 sfree (db->host);
249 sfree (db->port);
250 sfree (db->user);
251 sfree (db->password);
253 sfree (db->sslmode);
255 sfree (db->krbsrvname);
257 sfree (db->service);
258 return;
259 } /* c_psql_database_delete */
261 static int c_psql_connect (c_psql_database_t *db)
262 {
263 char conninfo[4096];
264 char *buf = conninfo;
265 int buf_len = sizeof (conninfo);
266 int status;
268 if (! db)
269 return -1;
271 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
272 if (0 < status) {
273 buf += status;
274 buf_len -= status;
275 }
277 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
278 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
279 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
280 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
281 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
282 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
283 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
285 db->conn = PQconnectdb (conninfo);
286 db->proto_version = PQprotocolVersion (db->conn);
287 return 0;
288 } /* c_psql_connect */
290 static int c_psql_check_connection (c_psql_database_t *db)
291 {
292 _Bool init = 0;
294 if (! db->conn) {
295 init = 1;
297 /* trigger c_release() */
298 if (0 == db->conn_complaint.interval)
299 db->conn_complaint.interval = 1;
301 c_psql_connect (db);
302 }
304 /* "ping" */
305 PQclear (PQexec (db->conn, "SELECT 42;"));
307 if (CONNECTION_OK != PQstatus (db->conn)) {
308 PQreset (db->conn);
310 /* trigger c_release() */
311 if (0 == db->conn_complaint.interval)
312 db->conn_complaint.interval = 1;
314 if (CONNECTION_OK != PQstatus (db->conn)) {
315 c_complain (LOG_ERR, &db->conn_complaint,
316 "Failed to connect to database %s: %s",
317 db->database, PQerrorMessage (db->conn));
318 return -1;
319 }
321 db->proto_version = PQprotocolVersion (db->conn);
322 }
324 db->server_version = PQserverVersion (db->conn);
326 if (c_would_release (&db->conn_complaint)) {
327 char *server_host;
328 int server_version;
330 server_host = PQhost (db->conn);
331 server_version = PQserverVersion (db->conn);
333 c_do_release (LOG_INFO, &db->conn_complaint,
334 "Successfully %sconnected to database %s (user %s) "
335 "at server %s%s%s (server version: %d.%d.%d, "
336 "protocol version: %d, pid: %d)", init ? "" : "re",
337 PQdb (db->conn), PQuser (db->conn),
338 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
339 C_PSQL_SERVER_VERSION3 (server_version),
340 db->proto_version, PQbackendPID (db->conn));
342 if (3 > db->proto_version)
343 log_warn ("Protocol version %d does not support parameters.",
344 db->proto_version);
345 }
346 return 0;
347 } /* c_psql_check_connection */
349 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
350 udb_query_t *q)
351 {
352 return PQexec (db->conn, udb_query_get_statement (q));
353 } /* c_psql_exec_query_noparams */
355 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
356 udb_query_t *q, c_psql_user_data_t *data)
357 {
358 char *params[db->max_params_num];
359 char interval[64];
360 int i;
362 if ((data == NULL) || (data->params_num == 0))
363 return (c_psql_exec_query_noparams (db, q));
365 assert (db->max_params_num >= data->params_num);
367 for (i = 0; i < data->params_num; ++i) {
368 switch (data->params[i]) {
369 case C_PSQL_PARAM_HOST:
370 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
371 ? "localhost" : db->host;
372 break;
373 case C_PSQL_PARAM_DB:
374 params[i] = db->database;
375 break;
376 case C_PSQL_PARAM_USER:
377 params[i] = db->user;
378 break;
379 case C_PSQL_PARAM_INTERVAL:
380 ssnprintf (interval, sizeof (interval), "%.3f",
381 (db->interval > 0)
382 ? CDTIME_T_TO_DOUBLE (db->interval) : interval_g);
383 params[i] = interval;
384 break;
385 default:
386 assert (0);
387 }
388 }
390 return PQexecParams (db->conn, udb_query_get_statement (q),
391 data->params_num, NULL,
392 (const char *const *) params,
393 NULL, NULL, /* return text data */ 0);
394 } /* c_psql_exec_query_params */
396 /* db->db_lock must be locked when calling this function */
397 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
398 udb_query_preparation_area_t *prep_area)
399 {
400 PGresult *res;
402 c_psql_user_data_t *data;
404 const char *host;
406 char **column_names;
407 char **column_values;
408 int column_num;
410 int rows_num;
411 int status;
412 int row, col;
414 /* The user data may hold parameter information, but may be NULL. */
415 data = udb_query_get_user_data (q);
417 /* Versions up to `3' don't know how to handle parameters. */
418 if (3 <= db->proto_version)
419 res = c_psql_exec_query_params (db, q, data);
420 else if ((NULL == data) || (0 == data->params_num))
421 res = c_psql_exec_query_noparams (db, q);
422 else {
423 log_err ("Connection to database \"%s\" does not support parameters "
424 "(protocol version %d) - cannot execute query \"%s\".",
425 db->database, db->proto_version,
426 udb_query_get_name (q));
427 return -1;
428 }
430 /* give c_psql_write() a chance to acquire the lock if called recursively
431 * through dispatch_values(); this will happen if, both, queries and
432 * writers are configured for a single connection */
433 pthread_mutex_unlock (&db->db_lock);
435 column_names = NULL;
436 column_values = NULL;
438 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
439 pthread_mutex_lock (&db->db_lock);
441 log_err ("Failed to execute SQL query: %s",
442 PQerrorMessage (db->conn));
443 log_info ("SQL query was: %s",
444 udb_query_get_statement (q));
445 PQclear (res);
446 return -1;
447 }
449 #define BAIL_OUT(status) \
450 sfree (column_names); \
451 sfree (column_values); \
452 PQclear (res); \
453 pthread_mutex_lock (&db->db_lock); \
454 return status
456 rows_num = PQntuples (res);
457 if (1 > rows_num) {
458 BAIL_OUT (0);
459 }
461 column_num = PQnfields (res);
462 column_names = (char **) calloc (column_num, sizeof (char *));
463 if (NULL == column_names) {
464 log_err ("calloc failed.");
465 BAIL_OUT (-1);
466 }
468 column_values = (char **) calloc (column_num, sizeof (char *));
469 if (NULL == column_values) {
470 log_err ("calloc failed.");
471 BAIL_OUT (-1);
472 }
474 for (col = 0; col < column_num; ++col) {
475 /* Pointers returned by `PQfname' are freed by `PQclear' via
476 * `BAIL_OUT'. */
477 column_names[col] = PQfname (res, col);
478 if (NULL == column_names[col]) {
479 log_err ("Failed to resolve name of column %i.", col);
480 BAIL_OUT (-1);
481 }
482 }
484 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
485 || (0 == strcmp (db->host, "localhost")))
486 host = hostname_g;
487 else
488 host = db->host;
490 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
491 db->database, column_names, (size_t) column_num, db->interval);
492 if (0 != status) {
493 log_err ("udb_query_prepare_result failed with status %i.",
494 status);
495 BAIL_OUT (-1);
496 }
498 for (row = 0; row < rows_num; ++row) {
499 for (col = 0; col < column_num; ++col) {
500 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
501 * `BAIL_OUT'. */
502 column_values[col] = PQgetvalue (res, row, col);
503 if (NULL == column_values[col]) {
504 log_err ("Failed to get value at (row = %i, col = %i).",
505 row, col);
506 break;
507 }
508 }
510 /* check for an error */
511 if (col < column_num)
512 continue;
514 status = udb_query_handle_result (q, prep_area, column_values);
515 if (status != 0) {
516 log_err ("udb_query_handle_result failed with status %i.",
517 status);
518 }
519 } /* for (row = 0; row < rows_num; ++row) */
521 udb_query_finish_result (q, prep_area);
523 BAIL_OUT (0);
524 #undef BAIL_OUT
525 } /* c_psql_exec_query */
527 static int c_psql_read (user_data_t *ud)
528 {
529 c_psql_database_t *db;
531 int success = 0;
532 int i;
534 if ((ud == NULL) || (ud->data == NULL)) {
535 log_err ("c_psql_read: Invalid user data.");
536 return -1;
537 }
539 db = ud->data;
541 assert (NULL != db->database);
542 assert (NULL != db->queries);
544 pthread_mutex_lock (&db->db_lock);
546 if (0 != c_psql_check_connection (db)) {
547 pthread_mutex_unlock (&db->db_lock);
548 return -1;
549 }
551 for (i = 0; i < db->queries_num; ++i)
552 {
553 udb_query_preparation_area_t *prep_area;
554 udb_query_t *q;
556 prep_area = db->q_prep_areas[i];
557 q = db->queries[i];
559 if ((0 != db->server_version)
560 && (udb_query_check_version (q, db->server_version) <= 0))
561 continue;
563 if (0 == c_psql_exec_query (db, q, prep_area))
564 success = 1;
565 }
567 pthread_mutex_unlock (&db->db_lock);
569 if (! success)
570 return -1;
571 return 0;
572 } /* c_psql_read */
574 static char *values_name_to_sqlarray (const data_set_t *ds,
575 char *string, size_t string_len)
576 {
577 char *str_ptr;
578 size_t str_len;
580 int i;
582 str_ptr = string;
583 str_len = string_len;
585 for (i = 0; i < ds->ds_num; ++i) {
586 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
588 if (status < 1)
589 return NULL;
590 else if ((size_t)status >= str_len) {
591 str_len = 0;
592 break;
593 }
594 else {
595 str_ptr += status;
596 str_len -= (size_t)status;
597 }
598 }
600 if (str_len <= 2) {
601 log_err ("c_psql_write: Failed to stringify value names");
602 return NULL;
603 }
605 /* overwrite the first comma */
606 string[0] = '{';
607 str_ptr[0] = '}';
608 str_ptr[1] = '\0';
610 return string;
611 } /* values_name_to_sqlarray */
613 static char *values_type_to_sqlarray (const data_set_t *ds,
614 char *string, size_t string_len, _Bool store_rates)
615 {
616 char *str_ptr;
617 size_t str_len;
619 int i;
621 str_ptr = string;
622 str_len = string_len;
624 for (i = 0; i < ds->ds_num; ++i) {
625 int status;
627 if (store_rates)
628 status = ssnprintf(str_ptr, str_len, ",'gauge'");
629 else
630 status = ssnprintf(str_ptr, str_len, ",'%s'",
631 DS_TYPE_TO_STRING (ds->ds[i].type));
633 if (status < 1) {
634 str_len = 0;
635 break;
636 }
637 else if ((size_t)status >= str_len) {
638 str_len = 0;
639 break;
640 }
641 else {
642 str_ptr += status;
643 str_len -= (size_t)status;
644 }
645 }
647 if (str_len <= 2) {
648 log_err ("c_psql_write: Failed to stringify value types");
649 return NULL;
650 }
652 /* overwrite the first comma */
653 string[0] = '{';
654 str_ptr[0] = '}';
655 str_ptr[1] = '\0';
657 return string;
658 } /* values_type_to_sqlarray */
660 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
661 char *string, size_t string_len, _Bool store_rates)
662 {
663 char *str_ptr;
664 size_t str_len;
666 gauge_t *rates = NULL;
668 int i;
670 str_ptr = string;
671 str_len = string_len;
673 for (i = 0; i < vl->values_len; ++i) {
674 int status = 0;
676 if ((ds->ds[i].type != DS_TYPE_GAUGE)
677 && (ds->ds[i].type != DS_TYPE_COUNTER)
678 && (ds->ds[i].type != DS_TYPE_DERIVE)
679 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
680 log_err ("c_psql_write: Unknown data source type: %i",
681 ds->ds[i].type);
682 sfree (rates);
683 return NULL;
684 }
686 if (ds->ds[i].type == DS_TYPE_GAUGE)
687 status = ssnprintf (str_ptr, str_len,
688 ",%f", vl->values[i].gauge);
689 else if (store_rates) {
690 if (rates == NULL)
691 rates = uc_get_rate (ds, vl);
693 if (rates == NULL) {
694 log_err ("c_psql_write: Failed to determine rate");
695 return NULL;
696 }
698 status = ssnprintf (str_ptr, str_len,
699 ",%lf", rates[i]);
700 }
701 else if (ds->ds[i].type == DS_TYPE_COUNTER)
702 status = ssnprintf (str_ptr, str_len,
703 ",%llu", vl->values[i].counter);
704 else if (ds->ds[i].type == DS_TYPE_DERIVE)
705 status = ssnprintf (str_ptr, str_len,
706 ",%"PRIi64, vl->values[i].derive);
707 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
708 status = ssnprintf (str_ptr, str_len,
709 ",%"PRIu64, vl->values[i].absolute);
711 if (status < 1) {
712 str_len = 0;
713 break;
714 }
715 else if ((size_t)status >= str_len) {
716 str_len = 0;
717 break;
718 }
719 else {
720 str_ptr += status;
721 str_len -= (size_t)status;
722 }
723 }
725 sfree (rates);
727 if (str_len <= 2) {
728 log_err ("c_psql_write: Failed to stringify value list");
729 return NULL;
730 }
732 /* overwrite the first comma */
733 string[0] = '{';
734 str_ptr[0] = '}';
735 str_ptr[1] = '\0';
737 return string;
738 } /* values_to_sqlarray */
740 static int c_psql_begin (c_psql_database_t *db)
741 {
742 PGresult *r = PQexec (db->conn, "BEGIN");
744 int status = 1;
746 if (r != NULL) {
747 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
748 db->next_commit = cdtime() + db->commit_interval;
749 status = 0;
750 }
751 else
752 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
753 PQerrorMessage (db->conn));
754 PQclear (r);
755 }
756 return status;
757 } /* c_psql_begin */
759 static int c_psql_commit (c_psql_database_t *db)
760 {
761 PGresult *r = PQexec (db->conn, "COMMIT");
763 int status = 1;
765 if (r != NULL) {
766 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
767 db->next_commit = cdtime () + db->commit_interval;
768 log_debug ("Successfully committed transaction.");
769 status = 0;
770 }
771 else
772 log_warn ("Failed to commit transaction: %s",
773 PQerrorMessage (db->conn));
774 PQclear (r);
775 }
776 return status;
777 } /* c_psql_commit */
779 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
780 user_data_t *ud)
781 {
782 c_psql_database_t *db;
784 char time_str[32];
785 char values_name_str[1024];
786 char values_type_str[1024];
787 char values_str[1024];
789 const char *params[9];
791 int success = 0;
792 int i;
794 if ((ud == NULL) || (ud->data == NULL)) {
795 log_err ("c_psql_write: Invalid user data.");
796 return -1;
797 }
799 db = ud->data;
800 assert (db->database != NULL);
801 assert (db->writers != NULL);
803 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
804 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
805 return -1;
806 }
808 if (values_name_to_sqlarray (ds,
809 values_name_str, sizeof (values_name_str)) == NULL)
810 return -1;
812 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
814 params[0] = time_str;
815 params[1] = vl->host;
816 params[2] = vl->plugin;
817 params[3] = VALUE_OR_NULL(vl->plugin_instance);
818 params[4] = vl->type;
819 params[5] = VALUE_OR_NULL(vl->type_instance);
820 params[6] = values_name_str;
822 #undef VALUE_OR_NULL
824 pthread_mutex_lock (&db->db_lock);
826 if (0 != c_psql_check_connection (db)) {
827 pthread_mutex_unlock (&db->db_lock);
828 return -1;
829 }
831 if ((db->commit_interval > 0)
832 && (db->next_commit == 0))
833 c_psql_begin (db);
835 for (i = 0; i < db->writers_num; ++i) {
836 c_psql_writer_t *writer;
837 PGresult *res;
839 writer = db->writers[i];
841 if (values_type_to_sqlarray (ds,
842 values_type_str, sizeof (values_type_str),
843 writer->store_rates) == NULL) {
844 pthread_mutex_unlock (&db->db_lock);
845 return -1;
846 }
848 if (values_to_sqlarray (ds, vl,
849 values_str, sizeof (values_str),
850 writer->store_rates) == NULL) {
851 pthread_mutex_unlock (&db->db_lock);
852 return -1;
853 }
855 params[7] = values_type_str;
856 params[8] = values_str;
858 res = PQexecParams (db->conn, writer->statement,
859 STATIC_ARRAY_SIZE (params), NULL,
860 (const char *const *)params,
861 NULL, NULL, /* return text data */ 0);
863 if ((PGRES_COMMAND_OK != PQresultStatus (res))
864 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
865 if ((CONNECTION_OK != PQstatus (db->conn))
866 && (0 == c_psql_check_connection (db))) {
867 PQclear (res);
869 /* try again */
870 res = PQexecParams (db->conn, writer->statement,
871 STATIC_ARRAY_SIZE (params), NULL,
872 (const char *const *)params,
873 NULL, NULL, /* return text data */ 0);
875 if ((PGRES_COMMAND_OK == PQresultStatus (res))
876 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
877 success = 1;
878 continue;
879 }
880 }
882 log_err ("Failed to execute SQL query: %s",
883 PQerrorMessage (db->conn));
884 log_info ("SQL query was: '%s', "
885 "params: %s, %s, %s, %s, %s, %s, %s, %s",
886 writer->statement,
887 params[0], params[1], params[2], params[3],
888 params[4], params[5], params[6], params[7]);
890 /* this will abort any current transaction -> restart */
891 if (db->next_commit > 0)
892 if (c_psql_commit (db) == 0)
893 c_psql_begin (db);
895 pthread_mutex_unlock (&db->db_lock);
896 return -1;
897 }
898 success = 1;
899 }
901 if ((db->next_commit > 0)
902 && (cdtime () > db->next_commit))
903 if (c_psql_commit (db) == 0)
904 c_psql_begin (db);
906 pthread_mutex_unlock (&db->db_lock);
908 if (! success)
909 return -1;
910 return 0;
911 } /* c_psql_write */
913 static int c_psql_shutdown (void)
914 {
915 plugin_unregister_read_group ("postgresql");
917 udb_query_free (queries, queries_num);
918 queries = NULL;
919 queries_num = 0;
921 sfree (writers);
922 writers = NULL;
923 writers_num = 0;
925 return 0;
926 } /* c_psql_shutdown */
928 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
929 {
930 c_psql_user_data_t *data;
931 const char *param_str;
933 c_psql_param_t *tmp;
935 data = udb_query_get_user_data (q);
936 if (NULL == data) {
937 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
938 if (NULL == data) {
939 log_err ("Out of memory.");
940 return -1;
941 }
942 memset (data, 0, sizeof (*data));
943 data->params = NULL;
944 }
946 tmp = (c_psql_param_t *) realloc (data->params,
947 (data->params_num + 1) * sizeof (c_psql_param_t));
948 if (NULL == tmp) {
949 log_err ("Out of memory.");
950 return -1;
951 }
952 data->params = tmp;
954 param_str = ci->values[0].value.string;
955 if (0 == strcasecmp (param_str, "hostname"))
956 data->params[data->params_num] = C_PSQL_PARAM_HOST;
957 else if (0 == strcasecmp (param_str, "database"))
958 data->params[data->params_num] = C_PSQL_PARAM_DB;
959 else if (0 == strcasecmp (param_str, "username"))
960 data->params[data->params_num] = C_PSQL_PARAM_USER;
961 else if (0 == strcasecmp (param_str, "interval"))
962 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
963 else {
964 log_err ("Invalid parameter \"%s\".", param_str);
965 return 1;
966 }
968 data->params_num++;
969 udb_query_set_user_data (q, data);
971 return (0);
972 } /* config_query_param_add */
974 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
975 {
976 if (0 == strcasecmp ("Param", ci->key))
977 return config_query_param_add (q, ci);
979 log_err ("Option not allowed within a Query block: `%s'", ci->key);
981 return (-1);
982 } /* config_query_callback */
984 static int config_add_writer (oconfig_item_t *ci,
985 c_psql_writer_t *src_writers, size_t src_writers_num,
986 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
987 {
988 char *name;
990 size_t i;
992 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
993 return -1;
995 if ((ci->values_num != 1)
996 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
997 log_err ("`Writer' expects a single string argument.");
998 return 1;
999 }
1001 name = ci->values[0].value.string;
1003 for (i = 0; i < src_writers_num; ++i) {
1004 c_psql_writer_t **tmp;
1006 if (strcasecmp (name, src_writers[i].name) != 0)
1007 continue;
1009 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1010 sizeof (**dst_writers) * (*dst_writers_num + 1));
1011 if (tmp == NULL) {
1012 log_err ("Out of memory.");
1013 return -1;
1014 }
1016 tmp[*dst_writers_num] = src_writers + i;
1018 *dst_writers = tmp;
1019 ++(*dst_writers_num);
1020 break;
1021 }
1023 if (i >= src_writers_num) {
1024 log_err ("No such writer: `%s'", name);
1025 return -1;
1026 }
1028 return 0;
1029 } /* config_add_writer */
1031 static int c_psql_config_writer (oconfig_item_t *ci)
1032 {
1033 c_psql_writer_t *writer;
1034 c_psql_writer_t *tmp;
1036 int status = 0;
1037 int i;
1039 if ((ci->values_num != 1)
1040 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1041 log_err ("<Writer> expects a single string argument.");
1042 return 1;
1043 }
1045 tmp = (c_psql_writer_t *)realloc (writers,
1046 sizeof (*writers) * (writers_num + 1));
1047 if (tmp == NULL) {
1048 log_err ("Out of memory.");
1049 return -1;
1050 }
1052 writers = tmp;
1053 writer = writers + writers_num;
1054 ++writers_num;
1056 writer->name = sstrdup (ci->values[0].value.string);
1057 writer->statement = NULL;
1058 writer->store_rates = 1;
1060 for (i = 0; i < ci->children_num; ++i) {
1061 oconfig_item_t *c = ci->children + i;
1063 if (strcasecmp ("Statement", c->key) == 0)
1064 status = cf_util_get_string (c, &writer->statement);
1065 else if (strcasecmp ("StoreRates", c->key) == 0)
1066 status = cf_util_get_boolean (c, &writer->store_rates);
1067 else
1068 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1069 }
1071 if (status != 0) {
1072 sfree (writer->statement);
1073 sfree (writer->name);
1074 sfree (writer);
1075 return status;
1076 }
1078 return 0;
1079 } /* c_psql_config_writer */
1081 static int c_psql_config_database (oconfig_item_t *ci)
1082 {
1083 c_psql_database_t *db;
1085 char cb_name[DATA_MAX_NAME_LEN];
1086 struct timespec cb_interval = { 0, 0 };
1087 user_data_t ud;
1089 int i;
1091 if ((1 != ci->values_num)
1092 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1093 log_err ("<Database> expects a single string argument.");
1094 return 1;
1095 }
1097 memset (&ud, 0, sizeof (ud));
1099 db = c_psql_database_new (ci->values[0].value.string);
1100 if (db == NULL)
1101 return -1;
1103 for (i = 0; i < ci->children_num; ++i) {
1104 oconfig_item_t *c = ci->children + i;
1106 if (0 == strcasecmp (c->key, "Host"))
1107 cf_util_get_string (c, &db->host);
1108 else if (0 == strcasecmp (c->key, "Port"))
1109 cf_util_get_service (c, &db->port);
1110 else if (0 == strcasecmp (c->key, "User"))
1111 cf_util_get_string (c, &db->user);
1112 else if (0 == strcasecmp (c->key, "Password"))
1113 cf_util_get_string (c, &db->password);
1114 else if (0 == strcasecmp (c->key, "SSLMode"))
1115 cf_util_get_string (c, &db->sslmode);
1116 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1117 cf_util_get_string (c, &db->krbsrvname);
1118 else if (0 == strcasecmp (c->key, "Service"))
1119 cf_util_get_string (c, &db->service);
1120 else if (0 == strcasecmp (c->key, "Query"))
1121 udb_query_pick_from_list (c, queries, queries_num,
1122 &db->queries, &db->queries_num);
1123 else if (0 == strcasecmp (c->key, "Writer"))
1124 config_add_writer (c, writers, writers_num,
1125 &db->writers, &db->writers_num);
1126 else if (0 == strcasecmp (c->key, "Interval"))
1127 cf_util_get_cdtime (c, &db->interval);
1128 else if (strcasecmp ("CommitInterval", c->key) == 0)
1129 cf_util_get_cdtime (c, &db->commit_interval);
1130 else
1131 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1132 }
1134 /* If no `Query' options were given, add the default queries.. */
1135 if ((db->queries_num == 0) && (db->writers_num == 0)){
1136 for (i = 0; i < def_queries_num; i++)
1137 udb_query_pick_from_list_by_name (def_queries[i],
1138 queries, queries_num,
1139 &db->queries, &db->queries_num);
1140 }
1142 if (db->queries_num > 0) {
1143 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1144 db->queries_num, sizeof (*db->q_prep_areas));
1146 if (db->q_prep_areas == NULL) {
1147 log_err ("Out of memory.");
1148 c_psql_database_delete (db);
1149 return -1;
1150 }
1151 }
1153 for (i = 0; (size_t)i < db->queries_num; ++i) {
1154 c_psql_user_data_t *data;
1155 data = udb_query_get_user_data (db->queries[i]);
1156 if ((data != NULL) && (data->params_num > db->max_params_num))
1157 db->max_params_num = data->params_num;
1159 db->q_prep_areas[i]
1160 = udb_query_allocate_preparation_area (db->queries[i]);
1162 if (db->q_prep_areas[i] == NULL) {
1163 log_err ("Out of memory.");
1164 c_psql_database_delete (db);
1165 return -1;
1166 }
1167 }
1169 ud.data = db;
1170 ud.free_func = c_psql_database_delete;
1172 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->database);
1174 if (db->queries_num > 0) {
1175 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1177 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1178 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1179 &ud);
1180 }
1181 if (db->writers_num > 0) {
1182 plugin_register_write (cb_name, c_psql_write, &ud);
1183 }
1184 else if (db->commit_interval > 0) {
1185 log_warn ("Database '%s': You do not have any writers assigned to "
1186 "this database connection. Setting 'CommitInterval' does "
1187 "not have any effect.", db->database);
1188 }
1189 return 0;
1190 } /* c_psql_config_database */
1192 static int c_psql_config (oconfig_item_t *ci)
1193 {
1194 static int have_def_config = 0;
1196 int i;
1198 if (0 == have_def_config) {
1199 oconfig_item_t *c;
1201 have_def_config = 1;
1203 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1204 if (NULL == c)
1205 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1206 else
1207 c_psql_config (c);
1209 if (NULL == queries)
1210 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1211 "any queries - please check your installation.");
1212 }
1214 for (i = 0; i < ci->children_num; ++i) {
1215 oconfig_item_t *c = ci->children + i;
1217 if (0 == strcasecmp (c->key, "Query"))
1218 udb_query_create (&queries, &queries_num, c,
1219 /* callback = */ config_query_callback);
1220 else if (0 == strcasecmp (c->key, "Writer"))
1221 c_psql_config_writer (c);
1222 else if (0 == strcasecmp (c->key, "Database"))
1223 c_psql_config_database (c);
1224 else
1225 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1226 }
1227 return 0;
1228 } /* c_psql_config */
1230 void module_register (void)
1231 {
1232 plugin_register_complex_config ("postgresql", c_psql_config);
1233 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1234 } /* module_register */
1236 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */