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_INSTANCE,
105 } c_psql_param_t;
107 /* Parameter configuration. Stored as `user data' in the query objects. */
108 typedef struct {
109 c_psql_param_t *params;
110 int params_num;
111 } c_psql_user_data_t;
113 typedef struct {
114 char *name;
115 char *statement;
116 _Bool store_rates;
117 } c_psql_writer_t;
119 typedef struct {
120 PGconn *conn;
121 c_complain_t conn_complaint;
123 int proto_version;
124 int server_version;
126 int max_params_num;
128 /* user configuration */
129 udb_query_preparation_area_t **q_prep_areas;
130 udb_query_t **queries;
131 size_t queries_num;
133 c_psql_writer_t **writers;
134 size_t writers_num;
136 /* make sure we don't access the database object in parallel */
137 pthread_mutex_t db_lock;
139 cdtime_t interval;
141 /* writer "caching" settings */
142 cdtime_t commit_interval;
143 cdtime_t next_commit;
145 char *host;
146 char *port;
147 char *database;
148 char *user;
149 char *password;
151 char *instance;
153 char *sslmode;
155 char *krbsrvname;
157 char *service;
159 int ref_cnt;
160 } c_psql_database_t;
162 static char *def_queries[] = {
163 "backends",
164 "transactions",
165 "queries",
166 "query_plans",
167 "table_states",
168 "disk_io",
169 "disk_usage"
170 };
171 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
173 static c_psql_database_t **databases = NULL;
174 static size_t databases_num = 0;
176 static udb_query_t **queries = NULL;
177 static size_t queries_num = 0;
179 static c_psql_writer_t *writers = NULL;
180 static size_t writers_num = 0;
182 static int c_psql_begin (c_psql_database_t *db)
183 {
184 PGresult *r = PQexec (db->conn, "BEGIN");
186 int status = 1;
188 if (r != NULL) {
189 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
190 db->next_commit = cdtime() + db->commit_interval;
191 status = 0;
192 }
193 else
194 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
195 PQerrorMessage (db->conn));
196 PQclear (r);
197 }
198 return status;
199 } /* c_psql_begin */
201 static int c_psql_commit (c_psql_database_t *db)
202 {
203 PGresult *r = PQexec (db->conn, "COMMIT");
205 int status = 1;
207 if (r != NULL) {
208 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
209 db->next_commit = 0;
210 log_debug ("Successfully committed transaction.");
211 status = 0;
212 }
213 else
214 log_warn ("Failed to commit transaction: %s",
215 PQerrorMessage (db->conn));
216 PQclear (r);
217 }
218 return status;
219 } /* c_psql_commit */
221 static c_psql_database_t *c_psql_database_new (const char *name)
222 {
223 c_psql_database_t **tmp;
224 c_psql_database_t *db;
226 db = (c_psql_database_t *)malloc (sizeof(*db));
227 if (NULL == db) {
228 log_err ("Out of memory.");
229 return NULL;
230 }
232 tmp = (c_psql_database_t **)realloc (databases,
233 (databases_num + 1) * sizeof (*databases));
234 if (NULL == tmp) {
235 log_err ("Out of memory.");
236 sfree (db);
237 return NULL;
238 }
240 databases = tmp;
241 databases[databases_num] = db;
242 ++databases_num;
244 db->conn = NULL;
246 C_COMPLAIN_INIT (&db->conn_complaint);
248 db->proto_version = 0;
249 db->server_version = 0;
251 db->max_params_num = 0;
253 db->q_prep_areas = NULL;
254 db->queries = NULL;
255 db->queries_num = 0;
257 db->writers = NULL;
258 db->writers_num = 0;
260 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
262 db->interval = 0;
264 db->commit_interval = 0;
265 db->next_commit = 0;
267 db->database = sstrdup (name);
268 db->host = NULL;
269 db->port = NULL;
270 db->user = NULL;
271 db->password = NULL;
273 db->instance = sstrdup (name);
275 db->sslmode = NULL;
277 db->krbsrvname = NULL;
279 db->service = NULL;
281 db->ref_cnt = 0;
282 return db;
283 } /* c_psql_database_new */
285 static void c_psql_database_delete (void *data)
286 {
287 size_t i;
289 c_psql_database_t *db = data;
291 --db->ref_cnt;
292 /* readers and writers may access this database */
293 if (db->ref_cnt > 0)
294 return;
296 /* wait for the lock to be released by the last writer */
297 pthread_mutex_lock (&db->db_lock);
299 if (db->next_commit > 0)
300 c_psql_commit (db);
302 PQfinish (db->conn);
303 db->conn = NULL;
305 if (db->q_prep_areas)
306 for (i = 0; i < db->queries_num; ++i)
307 udb_query_delete_preparation_area (db->q_prep_areas[i]);
308 free (db->q_prep_areas);
310 sfree (db->queries);
311 db->queries_num = 0;
313 sfree (db->writers);
314 db->writers_num = 0;
316 pthread_mutex_unlock (&db->db_lock);
318 pthread_mutex_destroy (&db->db_lock);
320 sfree (db->database);
321 sfree (db->host);
322 sfree (db->port);
323 sfree (db->user);
324 sfree (db->password);
326 sfree (db->instance);
328 sfree (db->sslmode);
330 sfree (db->krbsrvname);
332 sfree (db->service);
334 /* don't care about freeing or reordering the 'databases' array
335 * this is done in 'shutdown'; also, don't free the database instance
336 * object just to make sure that in case anybody accesses it before
337 * shutdown won't segfault */
338 return;
339 } /* c_psql_database_delete */
341 static int c_psql_connect (c_psql_database_t *db)
342 {
343 char conninfo[4096];
344 char *buf = conninfo;
345 int buf_len = sizeof (conninfo);
346 int status;
348 if ((! db) || (! db->database))
349 return -1;
351 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
352 if (0 < status) {
353 buf += status;
354 buf_len -= status;
355 }
357 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
358 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
359 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
360 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
361 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
362 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
363 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
365 db->conn = PQconnectdb (conninfo);
366 db->proto_version = PQprotocolVersion (db->conn);
367 return 0;
368 } /* c_psql_connect */
370 static int c_psql_check_connection (c_psql_database_t *db)
371 {
372 _Bool init = 0;
374 if (! db->conn) {
375 init = 1;
377 /* trigger c_release() */
378 if (0 == db->conn_complaint.interval)
379 db->conn_complaint.interval = 1;
381 c_psql_connect (db);
382 }
384 if (CONNECTION_OK != PQstatus (db->conn)) {
385 PQreset (db->conn);
387 /* trigger c_release() */
388 if (0 == db->conn_complaint.interval)
389 db->conn_complaint.interval = 1;
391 if (CONNECTION_OK != PQstatus (db->conn)) {
392 c_complain (LOG_ERR, &db->conn_complaint,
393 "Failed to connect to database %s (%s): %s",
394 db->database, db->instance,
395 PQerrorMessage (db->conn));
396 return -1;
397 }
399 db->proto_version = PQprotocolVersion (db->conn);
400 }
402 db->server_version = PQserverVersion (db->conn);
404 if (c_would_release (&db->conn_complaint)) {
405 char *server_host;
406 int server_version;
408 server_host = PQhost (db->conn);
409 server_version = PQserverVersion (db->conn);
411 c_do_release (LOG_INFO, &db->conn_complaint,
412 "Successfully %sconnected to database %s (user %s) "
413 "at server %s%s%s (server version: %d.%d.%d, "
414 "protocol version: %d, pid: %d)", init ? "" : "re",
415 PQdb (db->conn), PQuser (db->conn),
416 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
417 C_PSQL_SERVER_VERSION3 (server_version),
418 db->proto_version, PQbackendPID (db->conn));
420 if (3 > db->proto_version)
421 log_warn ("Protocol version %d does not support parameters.",
422 db->proto_version);
423 }
424 return 0;
425 } /* c_psql_check_connection */
427 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
428 udb_query_t *q)
429 {
430 return PQexec (db->conn, udb_query_get_statement (q));
431 } /* c_psql_exec_query_noparams */
433 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
434 udb_query_t *q, c_psql_user_data_t *data)
435 {
436 char *params[db->max_params_num];
437 char interval[64];
438 int i;
440 if ((data == NULL) || (data->params_num == 0))
441 return (c_psql_exec_query_noparams (db, q));
443 assert (db->max_params_num >= data->params_num);
445 for (i = 0; i < data->params_num; ++i) {
446 switch (data->params[i]) {
447 case C_PSQL_PARAM_HOST:
448 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
449 ? "localhost" : db->host;
450 break;
451 case C_PSQL_PARAM_DB:
452 params[i] = db->database;
453 break;
454 case C_PSQL_PARAM_USER:
455 params[i] = db->user;
456 break;
457 case C_PSQL_PARAM_INTERVAL:
458 ssnprintf (interval, sizeof (interval), "%.3f",
459 (db->interval > 0)
460 ? CDTIME_T_TO_DOUBLE (db->interval)
461 : plugin_get_interval ());
462 params[i] = interval;
463 break;
464 case C_PSQL_PARAM_INSTANCE:
465 params[i] = db->instance;
466 break;
467 default:
468 assert (0);
469 }
470 }
472 return PQexecParams (db->conn, udb_query_get_statement (q),
473 data->params_num, NULL,
474 (const char *const *) params,
475 NULL, NULL, /* return text data */ 0);
476 } /* c_psql_exec_query_params */
478 /* db->db_lock must be locked when calling this function */
479 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
480 udb_query_preparation_area_t *prep_area)
481 {
482 PGresult *res;
484 c_psql_user_data_t *data;
486 const char *host;
488 char **column_names;
489 char **column_values;
490 int column_num;
492 int rows_num;
493 int status;
494 int row, col;
496 /* The user data may hold parameter information, but may be NULL. */
497 data = udb_query_get_user_data (q);
499 /* Versions up to `3' don't know how to handle parameters. */
500 if (3 <= db->proto_version)
501 res = c_psql_exec_query_params (db, q, data);
502 else if ((NULL == data) || (0 == data->params_num))
503 res = c_psql_exec_query_noparams (db, q);
504 else {
505 log_err ("Connection to database \"%s\" (%s) does not support "
506 "parameters (protocol version %d) - "
507 "cannot execute query \"%s\".",
508 db->database, db->instance, db->proto_version,
509 udb_query_get_name (q));
510 return -1;
511 }
513 /* give c_psql_write() a chance to acquire the lock if called recursively
514 * through dispatch_values(); this will happen if, both, queries and
515 * writers are configured for a single connection */
516 pthread_mutex_unlock (&db->db_lock);
518 column_names = NULL;
519 column_values = NULL;
521 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
522 pthread_mutex_lock (&db->db_lock);
524 if ((CONNECTION_OK != PQstatus (db->conn))
525 && (0 == c_psql_check_connection (db))) {
526 PQclear (res);
527 return c_psql_exec_query (db, q, prep_area);
528 }
530 log_err ("Failed to execute SQL query: %s",
531 PQerrorMessage (db->conn));
532 log_info ("SQL query was: %s",
533 udb_query_get_statement (q));
534 PQclear (res);
535 return -1;
536 }
538 #define BAIL_OUT(status) \
539 sfree (column_names); \
540 sfree (column_values); \
541 PQclear (res); \
542 pthread_mutex_lock (&db->db_lock); \
543 return status
545 rows_num = PQntuples (res);
546 if (1 > rows_num) {
547 BAIL_OUT (0);
548 }
550 column_num = PQnfields (res);
551 column_names = (char **) calloc (column_num, sizeof (char *));
552 if (NULL == column_names) {
553 log_err ("calloc failed.");
554 BAIL_OUT (-1);
555 }
557 column_values = (char **) calloc (column_num, sizeof (char *));
558 if (NULL == column_values) {
559 log_err ("calloc failed.");
560 BAIL_OUT (-1);
561 }
563 for (col = 0; col < column_num; ++col) {
564 /* Pointers returned by `PQfname' are freed by `PQclear' via
565 * `BAIL_OUT'. */
566 column_names[col] = PQfname (res, col);
567 if (NULL == column_names[col]) {
568 log_err ("Failed to resolve name of column %i.", col);
569 BAIL_OUT (-1);
570 }
571 }
573 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
574 || (0 == strcmp (db->host, "localhost")))
575 host = hostname_g;
576 else
577 host = db->host;
579 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
580 db->instance, column_names, (size_t) column_num, db->interval);
581 if (0 != status) {
582 log_err ("udb_query_prepare_result failed with status %i.",
583 status);
584 BAIL_OUT (-1);
585 }
587 for (row = 0; row < rows_num; ++row) {
588 for (col = 0; col < column_num; ++col) {
589 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
590 * `BAIL_OUT'. */
591 column_values[col] = PQgetvalue (res, row, col);
592 if (NULL == column_values[col]) {
593 log_err ("Failed to get value at (row = %i, col = %i).",
594 row, col);
595 break;
596 }
597 }
599 /* check for an error */
600 if (col < column_num)
601 continue;
603 status = udb_query_handle_result (q, prep_area, column_values);
604 if (status != 0) {
605 log_err ("udb_query_handle_result failed with status %i.",
606 status);
607 }
608 } /* for (row = 0; row < rows_num; ++row) */
610 udb_query_finish_result (q, prep_area);
612 BAIL_OUT (0);
613 #undef BAIL_OUT
614 } /* c_psql_exec_query */
616 static int c_psql_read (user_data_t *ud)
617 {
618 c_psql_database_t *db;
620 int success = 0;
621 int i;
623 if ((ud == NULL) || (ud->data == NULL)) {
624 log_err ("c_psql_read: Invalid user data.");
625 return -1;
626 }
628 db = ud->data;
630 assert (NULL != db->database);
631 assert (NULL != db->instance);
632 assert (NULL != db->queries);
634 pthread_mutex_lock (&db->db_lock);
636 if (0 != c_psql_check_connection (db)) {
637 pthread_mutex_unlock (&db->db_lock);
638 return -1;
639 }
641 for (i = 0; i < db->queries_num; ++i)
642 {
643 udb_query_preparation_area_t *prep_area;
644 udb_query_t *q;
646 prep_area = db->q_prep_areas[i];
647 q = db->queries[i];
649 if ((0 != db->server_version)
650 && (udb_query_check_version (q, db->server_version) <= 0))
651 continue;
653 if (0 == c_psql_exec_query (db, q, prep_area))
654 success = 1;
655 }
657 pthread_mutex_unlock (&db->db_lock);
659 if (! success)
660 return -1;
661 return 0;
662 } /* c_psql_read */
664 static char *values_name_to_sqlarray (const data_set_t *ds,
665 char *string, size_t string_len)
666 {
667 char *str_ptr;
668 size_t str_len;
670 int i;
672 str_ptr = string;
673 str_len = string_len;
675 for (i = 0; i < ds->ds_num; ++i) {
676 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
678 if (status < 1)
679 return NULL;
680 else if ((size_t)status >= str_len) {
681 str_len = 0;
682 break;
683 }
684 else {
685 str_ptr += status;
686 str_len -= (size_t)status;
687 }
688 }
690 if (str_len <= 2) {
691 log_err ("c_psql_write: Failed to stringify value names");
692 return NULL;
693 }
695 /* overwrite the first comma */
696 string[0] = '{';
697 str_ptr[0] = '}';
698 str_ptr[1] = '\0';
700 return string;
701 } /* values_name_to_sqlarray */
703 static char *values_type_to_sqlarray (const data_set_t *ds,
704 char *string, size_t string_len, _Bool store_rates)
705 {
706 char *str_ptr;
707 size_t str_len;
709 int i;
711 str_ptr = string;
712 str_len = string_len;
714 for (i = 0; i < ds->ds_num; ++i) {
715 int status;
717 if (store_rates)
718 status = ssnprintf(str_ptr, str_len, ",'gauge'");
719 else
720 status = ssnprintf(str_ptr, str_len, ",'%s'",
721 DS_TYPE_TO_STRING (ds->ds[i].type));
723 if (status < 1) {
724 str_len = 0;
725 break;
726 }
727 else if ((size_t)status >= str_len) {
728 str_len = 0;
729 break;
730 }
731 else {
732 str_ptr += status;
733 str_len -= (size_t)status;
734 }
735 }
737 if (str_len <= 2) {
738 log_err ("c_psql_write: Failed to stringify value types");
739 return NULL;
740 }
742 /* overwrite the first comma */
743 string[0] = '{';
744 str_ptr[0] = '}';
745 str_ptr[1] = '\0';
747 return string;
748 } /* values_type_to_sqlarray */
750 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
751 char *string, size_t string_len, _Bool store_rates)
752 {
753 char *str_ptr;
754 size_t str_len;
756 gauge_t *rates = NULL;
758 int i;
760 str_ptr = string;
761 str_len = string_len;
763 for (i = 0; i < vl->values_len; ++i) {
764 int status = 0;
766 if ((ds->ds[i].type != DS_TYPE_GAUGE)
767 && (ds->ds[i].type != DS_TYPE_COUNTER)
768 && (ds->ds[i].type != DS_TYPE_DERIVE)
769 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
770 log_err ("c_psql_write: Unknown data source type: %i",
771 ds->ds[i].type);
772 sfree (rates);
773 return NULL;
774 }
776 if (ds->ds[i].type == DS_TYPE_GAUGE)
777 status = ssnprintf (str_ptr, str_len,
778 ",%f", vl->values[i].gauge);
779 else if (store_rates) {
780 if (rates == NULL)
781 rates = uc_get_rate (ds, vl);
783 if (rates == NULL) {
784 log_err ("c_psql_write: Failed to determine rate");
785 return NULL;
786 }
788 status = ssnprintf (str_ptr, str_len,
789 ",%lf", rates[i]);
790 }
791 else if (ds->ds[i].type == DS_TYPE_COUNTER)
792 status = ssnprintf (str_ptr, str_len,
793 ",%llu", vl->values[i].counter);
794 else if (ds->ds[i].type == DS_TYPE_DERIVE)
795 status = ssnprintf (str_ptr, str_len,
796 ",%"PRIi64, vl->values[i].derive);
797 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
798 status = ssnprintf (str_ptr, str_len,
799 ",%"PRIu64, vl->values[i].absolute);
801 if (status < 1) {
802 str_len = 0;
803 break;
804 }
805 else if ((size_t)status >= str_len) {
806 str_len = 0;
807 break;
808 }
809 else {
810 str_ptr += status;
811 str_len -= (size_t)status;
812 }
813 }
815 sfree (rates);
817 if (str_len <= 2) {
818 log_err ("c_psql_write: Failed to stringify value list");
819 return NULL;
820 }
822 /* overwrite the first comma */
823 string[0] = '{';
824 str_ptr[0] = '}';
825 str_ptr[1] = '\0';
827 return string;
828 } /* values_to_sqlarray */
830 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
831 user_data_t *ud)
832 {
833 c_psql_database_t *db;
835 char time_str[32];
836 char values_name_str[1024];
837 char values_type_str[1024];
838 char values_str[1024];
840 const char *params[9];
842 int success = 0;
843 int i;
845 if ((ud == NULL) || (ud->data == NULL)) {
846 log_err ("c_psql_write: Invalid user data.");
847 return -1;
848 }
850 db = ud->data;
851 assert (db->database != NULL);
852 assert (db->writers != NULL);
854 if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
855 log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
856 return -1;
857 }
859 if (values_name_to_sqlarray (ds,
860 values_name_str, sizeof (values_name_str)) == NULL)
861 return -1;
863 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
865 params[0] = time_str;
866 params[1] = vl->host;
867 params[2] = vl->plugin;
868 params[3] = VALUE_OR_NULL(vl->plugin_instance);
869 params[4] = vl->type;
870 params[5] = VALUE_OR_NULL(vl->type_instance);
871 params[6] = values_name_str;
873 #undef VALUE_OR_NULL
875 pthread_mutex_lock (&db->db_lock);
877 if (0 != c_psql_check_connection (db)) {
878 pthread_mutex_unlock (&db->db_lock);
879 return -1;
880 }
882 if ((db->commit_interval > 0)
883 && (db->next_commit == 0))
884 c_psql_begin (db);
886 for (i = 0; i < db->writers_num; ++i) {
887 c_psql_writer_t *writer;
888 PGresult *res;
890 writer = db->writers[i];
892 if (values_type_to_sqlarray (ds,
893 values_type_str, sizeof (values_type_str),
894 writer->store_rates) == NULL) {
895 pthread_mutex_unlock (&db->db_lock);
896 return -1;
897 }
899 if (values_to_sqlarray (ds, vl,
900 values_str, sizeof (values_str),
901 writer->store_rates) == NULL) {
902 pthread_mutex_unlock (&db->db_lock);
903 return -1;
904 }
906 params[7] = values_type_str;
907 params[8] = values_str;
909 res = PQexecParams (db->conn, writer->statement,
910 STATIC_ARRAY_SIZE (params), NULL,
911 (const char *const *)params,
912 NULL, NULL, /* return text data */ 0);
914 if ((PGRES_COMMAND_OK != PQresultStatus (res))
915 && (PGRES_TUPLES_OK != PQresultStatus (res))) {
916 PQclear (res);
918 if ((CONNECTION_OK != PQstatus (db->conn))
919 && (0 == c_psql_check_connection (db))) {
920 /* try again */
921 res = PQexecParams (db->conn, writer->statement,
922 STATIC_ARRAY_SIZE (params), NULL,
923 (const char *const *)params,
924 NULL, NULL, /* return text data */ 0);
926 if ((PGRES_COMMAND_OK == PQresultStatus (res))
927 || (PGRES_TUPLES_OK == PQresultStatus (res))) {
928 PQclear (res);
929 success = 1;
930 continue;
931 }
932 }
934 log_err ("Failed to execute SQL query: %s",
935 PQerrorMessage (db->conn));
936 log_info ("SQL query was: '%s', "
937 "params: %s, %s, %s, %s, %s, %s, %s, %s",
938 writer->statement,
939 params[0], params[1], params[2], params[3],
940 params[4], params[5], params[6], params[7]);
942 /* this will abort any current transaction -> restart */
943 if (db->next_commit > 0)
944 c_psql_commit (db);
946 pthread_mutex_unlock (&db->db_lock);
947 return -1;
948 }
950 PQclear (res);
951 success = 1;
952 }
954 if ((db->next_commit > 0)
955 && (cdtime () > db->next_commit))
956 c_psql_commit (db);
958 pthread_mutex_unlock (&db->db_lock);
960 if (! success)
961 return -1;
962 return 0;
963 } /* c_psql_write */
965 /* We cannot flush single identifiers as all we do is to commit the currently
966 * running transaction, thus making sure that all written data is actually
967 * visible to everybody. */
968 static int c_psql_flush (cdtime_t timeout,
969 __attribute__((unused)) const char *ident,
970 user_data_t *ud)
971 {
972 c_psql_database_t **dbs = databases;
973 size_t dbs_num = databases_num;
974 size_t i;
976 if ((ud != NULL) && (ud->data != NULL)) {
977 dbs = (void *)&ud->data;
978 dbs_num = 1;
979 }
981 for (i = 0; i < dbs_num; ++i) {
982 c_psql_database_t *db = dbs[i];
984 /* don't commit if the timeout is larger than the regular commit
985 * interval as in that case all requested data has already been
986 * committed */
987 if ((db->next_commit > 0) && (db->commit_interval > timeout))
988 c_psql_commit (db);
989 }
990 return 0;
991 } /* c_psql_flush */
993 static int c_psql_shutdown (void)
994 {
995 size_t i = 0;
997 _Bool had_flush = 0;
999 plugin_unregister_read_group ("postgresql");
1001 for (i = 0; i < databases_num; ++i) {
1002 c_psql_database_t *db = databases[i];
1004 if (db->writers_num > 0) {
1005 char cb_name[DATA_MAX_NAME_LEN];
1006 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s",
1007 db->database);
1009 if (! had_flush) {
1010 plugin_unregister_flush ("postgresql");
1011 had_flush = 1;
1012 }
1014 plugin_unregister_flush (cb_name);
1015 plugin_unregister_write (cb_name);
1016 }
1018 sfree (db);
1019 }
1021 udb_query_free (queries, queries_num);
1022 queries = NULL;
1023 queries_num = 0;
1025 sfree (writers);
1026 writers = NULL;
1027 writers_num = 0;
1029 sfree (databases);
1030 databases = NULL;
1031 databases_num = 0;
1033 return 0;
1034 } /* c_psql_shutdown */
1036 static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
1037 {
1038 c_psql_user_data_t *data;
1039 const char *param_str;
1041 c_psql_param_t *tmp;
1043 data = udb_query_get_user_data (q);
1044 if (NULL == data) {
1045 data = (c_psql_user_data_t *) smalloc (sizeof (*data));
1046 if (NULL == data) {
1047 log_err ("Out of memory.");
1048 return -1;
1049 }
1050 memset (data, 0, sizeof (*data));
1051 data->params = NULL;
1052 }
1054 tmp = (c_psql_param_t *) realloc (data->params,
1055 (data->params_num + 1) * sizeof (c_psql_param_t));
1056 if (NULL == tmp) {
1057 log_err ("Out of memory.");
1058 return -1;
1059 }
1060 data->params = tmp;
1062 param_str = ci->values[0].value.string;
1063 if (0 == strcasecmp (param_str, "hostname"))
1064 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1065 else if (0 == strcasecmp (param_str, "database"))
1066 data->params[data->params_num] = C_PSQL_PARAM_DB;
1067 else if (0 == strcasecmp (param_str, "username"))
1068 data->params[data->params_num] = C_PSQL_PARAM_USER;
1069 else if (0 == strcasecmp (param_str, "interval"))
1070 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1071 else if (0 == strcasecmp (param_str, "instance"))
1072 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1073 else {
1074 log_err ("Invalid parameter \"%s\".", param_str);
1075 return 1;
1076 }
1078 data->params_num++;
1079 udb_query_set_user_data (q, data);
1081 return (0);
1082 } /* config_query_param_add */
1084 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
1085 {
1086 if (0 == strcasecmp ("Param", ci->key))
1087 return config_query_param_add (q, ci);
1089 log_err ("Option not allowed within a Query block: `%s'", ci->key);
1091 return (-1);
1092 } /* config_query_callback */
1094 static int config_add_writer (oconfig_item_t *ci,
1095 c_psql_writer_t *src_writers, size_t src_writers_num,
1096 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
1097 {
1098 char *name;
1100 size_t i;
1102 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1103 return -1;
1105 if ((ci->values_num != 1)
1106 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1107 log_err ("`Writer' expects a single string argument.");
1108 return 1;
1109 }
1111 name = ci->values[0].value.string;
1113 for (i = 0; i < src_writers_num; ++i) {
1114 c_psql_writer_t **tmp;
1116 if (strcasecmp (name, src_writers[i].name) != 0)
1117 continue;
1119 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1120 sizeof (**dst_writers) * (*dst_writers_num + 1));
1121 if (tmp == NULL) {
1122 log_err ("Out of memory.");
1123 return -1;
1124 }
1126 tmp[*dst_writers_num] = src_writers + i;
1128 *dst_writers = tmp;
1129 ++(*dst_writers_num);
1130 break;
1131 }
1133 if (i >= src_writers_num) {
1134 log_err ("No such writer: `%s'", name);
1135 return -1;
1136 }
1138 return 0;
1139 } /* config_add_writer */
1141 static int c_psql_config_writer (oconfig_item_t *ci)
1142 {
1143 c_psql_writer_t *writer;
1144 c_psql_writer_t *tmp;
1146 int status = 0;
1147 int i;
1149 if ((ci->values_num != 1)
1150 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1151 log_err ("<Writer> expects a single string argument.");
1152 return 1;
1153 }
1155 tmp = (c_psql_writer_t *)realloc (writers,
1156 sizeof (*writers) * (writers_num + 1));
1157 if (tmp == NULL) {
1158 log_err ("Out of memory.");
1159 return -1;
1160 }
1162 writers = tmp;
1163 writer = writers + writers_num;
1164 ++writers_num;
1166 writer->name = sstrdup (ci->values[0].value.string);
1167 writer->statement = NULL;
1168 writer->store_rates = 1;
1170 for (i = 0; i < ci->children_num; ++i) {
1171 oconfig_item_t *c = ci->children + i;
1173 if (strcasecmp ("Statement", c->key) == 0)
1174 status = cf_util_get_string (c, &writer->statement);
1175 else if (strcasecmp ("StoreRates", c->key) == 0)
1176 status = cf_util_get_boolean (c, &writer->store_rates);
1177 else
1178 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1179 }
1181 if (status != 0) {
1182 sfree (writer->statement);
1183 sfree (writer->name);
1184 sfree (writer);
1185 return status;
1186 }
1188 return 0;
1189 } /* c_psql_config_writer */
1191 static int c_psql_config_database (oconfig_item_t *ci)
1192 {
1193 c_psql_database_t *db;
1195 char cb_name[DATA_MAX_NAME_LEN];
1196 struct timespec cb_interval = { 0, 0 };
1197 user_data_t ud;
1199 static _Bool have_flush = 0;
1201 int i;
1203 if ((1 != ci->values_num)
1204 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1205 log_err ("<Database> expects a single string argument.");
1206 return 1;
1207 }
1209 memset (&ud, 0, sizeof (ud));
1211 db = c_psql_database_new (ci->values[0].value.string);
1212 if (db == NULL)
1213 return -1;
1215 for (i = 0; i < ci->children_num; ++i) {
1216 oconfig_item_t *c = ci->children + i;
1218 if (0 == strcasecmp (c->key, "Host"))
1219 cf_util_get_string (c, &db->host);
1220 else if (0 == strcasecmp (c->key, "Port"))
1221 cf_util_get_service (c, &db->port);
1222 else if (0 == strcasecmp (c->key, "User"))
1223 cf_util_get_string (c, &db->user);
1224 else if (0 == strcasecmp (c->key, "Password"))
1225 cf_util_get_string (c, &db->password);
1226 else if (0 == strcasecmp (c->key, "Instance"))
1227 cf_util_get_string (c, &db->instance);
1228 else if (0 == strcasecmp (c->key, "SSLMode"))
1229 cf_util_get_string (c, &db->sslmode);
1230 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1231 cf_util_get_string (c, &db->krbsrvname);
1232 else if (0 == strcasecmp (c->key, "Service"))
1233 cf_util_get_string (c, &db->service);
1234 else if (0 == strcasecmp (c->key, "Query"))
1235 udb_query_pick_from_list (c, queries, queries_num,
1236 &db->queries, &db->queries_num);
1237 else if (0 == strcasecmp (c->key, "Writer"))
1238 config_add_writer (c, writers, writers_num,
1239 &db->writers, &db->writers_num);
1240 else if (0 == strcasecmp (c->key, "Interval"))
1241 cf_util_get_cdtime (c, &db->interval);
1242 else if (strcasecmp ("CommitInterval", c->key) == 0)
1243 cf_util_get_cdtime (c, &db->commit_interval);
1244 else
1245 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1246 }
1248 /* If no `Query' options were given, add the default queries.. */
1249 if ((db->queries_num == 0) && (db->writers_num == 0)){
1250 for (i = 0; i < def_queries_num; i++)
1251 udb_query_pick_from_list_by_name (def_queries[i],
1252 queries, queries_num,
1253 &db->queries, &db->queries_num);
1254 }
1256 if (db->queries_num > 0) {
1257 db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
1258 db->queries_num, sizeof (*db->q_prep_areas));
1260 if (db->q_prep_areas == NULL) {
1261 log_err ("Out of memory.");
1262 c_psql_database_delete (db);
1263 return -1;
1264 }
1265 }
1267 for (i = 0; (size_t)i < db->queries_num; ++i) {
1268 c_psql_user_data_t *data;
1269 data = udb_query_get_user_data (db->queries[i]);
1270 if ((data != NULL) && (data->params_num > db->max_params_num))
1271 db->max_params_num = data->params_num;
1273 db->q_prep_areas[i]
1274 = udb_query_allocate_preparation_area (db->queries[i]);
1276 if (db->q_prep_areas[i] == NULL) {
1277 log_err ("Out of memory.");
1278 c_psql_database_delete (db);
1279 return -1;
1280 }
1281 }
1283 ud.data = db;
1284 ud.free_func = c_psql_database_delete;
1286 ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
1288 if (db->queries_num > 0) {
1289 CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
1291 ++db->ref_cnt;
1292 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1293 /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
1294 &ud);
1295 }
1296 if (db->writers_num > 0) {
1297 ++db->ref_cnt;
1298 plugin_register_write (cb_name, c_psql_write, &ud);
1300 if (! have_flush) {
1301 /* flush all */
1302 plugin_register_flush ("postgresql",
1303 c_psql_flush, /* user data = */ NULL);
1304 have_flush = 1;
1305 }
1307 /* flush this connection only */
1308 ++db->ref_cnt;
1309 plugin_register_flush (cb_name, c_psql_flush, &ud);
1310 }
1311 else if (db->commit_interval > 0) {
1312 log_warn ("Database '%s': You do not have any writers assigned to "
1313 "this database connection. Setting 'CommitInterval' does "
1314 "not have any effect.", db->database);
1315 }
1316 return 0;
1317 } /* c_psql_config_database */
1319 static int c_psql_config (oconfig_item_t *ci)
1320 {
1321 static int have_def_config = 0;
1323 int i;
1325 if (0 == have_def_config) {
1326 oconfig_item_t *c;
1328 have_def_config = 1;
1330 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1331 if (NULL == c)
1332 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1333 else
1334 c_psql_config (c);
1336 if (NULL == queries)
1337 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1338 "any queries - please check your installation.");
1339 }
1341 for (i = 0; i < ci->children_num; ++i) {
1342 oconfig_item_t *c = ci->children + i;
1344 if (0 == strcasecmp (c->key, "Query"))
1345 udb_query_create (&queries, &queries_num, c,
1346 /* callback = */ config_query_callback);
1347 else if (0 == strcasecmp (c->key, "Writer"))
1348 c_psql_config_writer (c);
1349 else if (0 == strcasecmp (c->key, "Database"))
1350 c_psql_config_database (c);
1351 else
1352 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1353 }
1354 return 0;
1355 } /* c_psql_config */
1357 void module_register (void)
1358 {
1359 plugin_register_complex_config ("postgresql", c_psql_config);
1360 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1361 } /* module_register */
1363 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */