1 /**
2 * collectd - src/postgresql.c
3 * Copyright (C) 2008-2012 Sebastian Harl
4 * Copyright (C) 2009 Florian Forster
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *
24 * Authors:
25 * Sebastian Harl <sh at tokkee.org>
26 * Florian Forster <octo at collectd.org>
27 **/
29 /*
30 * This module collects PostgreSQL database statistics.
31 */
33 #include "collectd.h"
34 #include "common.h"
36 #include "configfile.h"
37 #include "plugin.h"
39 #include "utils_cache.h"
40 #include "utils_db_query.h"
41 #include "utils_complain.h"
43 #if HAVE_PTHREAD_H
44 # include <pthread.h>
45 #endif
47 #include <pg_config_manual.h>
48 #include <libpq-fe.h>
50 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
51 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
52 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
53 #define log_debug(...) DEBUG ("postgresql: " __VA_ARGS__)
55 #ifndef C_PSQL_DEFAULT_CONF
56 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
57 #endif
59 /* Appends the (parameter, value) pair to the string
60 * pointed to by 'buf' suitable to be used as argument
61 * for PQconnectdb(). If value equals NULL, the pair
62 * is ignored. */
63 #define C_PSQL_PAR_APPEND(buf, buf_len, parameter, value) \
64 if ((0 < (buf_len)) && (NULL != (value)) && ('\0' != *(value))) { \
65 int s = ssnprintf (buf, buf_len, " %s = '%s'", parameter, value); \
66 if (0 < s) { \
67 buf += s; \
68 buf_len -= s; \
69 } \
70 }
72 /* Returns the tuple (major, minor, patchlevel)
73 * for the given version number. */
74 #define C_PSQL_SERVER_VERSION3(server_version) \
75 (server_version) / 10000, \
76 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
77 (server_version) - (int)((server_version) / 100) * 100
79 /* Returns true if the given host specifies a
80 * UNIX domain socket. */
81 #define C_PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
82 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
84 /* Returns the tuple (host, delimiter, port) for a
85 * given (host, port) pair. Depending on the value of
86 * 'host' a UNIX domain socket or a TCP socket is
87 * assumed. */
88 #define C_PSQL_SOCKET3(host, port) \
89 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
90 C_PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
91 port
93 typedef enum {
94 C_PSQL_PARAM_HOST = 1,
95 C_PSQL_PARAM_DB,
96 C_PSQL_PARAM_USER,
97 C_PSQL_PARAM_INTERVAL,
98 C_PSQL_PARAM_INSTANCE,
99 } c_psql_param_t;
101 /* Parameter configuration. Stored as `user data' in the query objects. */
102 typedef struct {
103 c_psql_param_t *params;
104 int params_num;
105 } c_psql_user_data_t;
107 typedef struct {
108 char *name;
109 char *statement;
110 _Bool store_rates;
111 } c_psql_writer_t;
113 typedef struct {
114 PGconn *conn;
115 c_complain_t conn_complaint;
117 int proto_version;
118 int server_version;
120 int max_params_num;
122 /* user configuration */
123 udb_query_preparation_area_t **q_prep_areas;
124 udb_query_t **queries;
125 size_t queries_num;
127 c_psql_writer_t **writers;
128 size_t writers_num;
130 /* make sure we don't access the database object in parallel */
131 pthread_mutex_t db_lock;
133 cdtime_t interval;
135 /* writer "caching" settings */
136 cdtime_t commit_interval;
137 cdtime_t next_commit;
138 cdtime_t expire_delay;
140 char *host;
141 char *port;
142 char *database;
143 char *user;
144 char *password;
146 char *instance;
148 char *sslmode;
150 char *krbsrvname;
152 char *service;
154 int ref_cnt;
155 } c_psql_database_t;
157 static const char *const 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 c_psql_database_t **databases = NULL;
169 static size_t databases_num = 0;
171 static udb_query_t **queries = NULL;
172 static size_t queries_num = 0;
174 static c_psql_writer_t *writers = NULL;
175 static size_t writers_num = 0;
177 static int c_psql_begin (c_psql_database_t *db)
178 {
179 PGresult *r = PQexec (db->conn, "BEGIN");
181 int status = 1;
183 if (r != NULL) {
184 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
185 db->next_commit = cdtime() + db->commit_interval;
186 status = 0;
187 }
188 else
189 log_warn ("Failed to initiate ('BEGIN') transaction: %s",
190 PQerrorMessage (db->conn));
191 PQclear (r);
192 }
193 return status;
194 } /* c_psql_begin */
196 static int c_psql_commit (c_psql_database_t *db)
197 {
198 PGresult *r = PQexec (db->conn, "COMMIT");
200 int status = 1;
202 if (r != NULL) {
203 if (PGRES_COMMAND_OK == PQresultStatus (r)) {
204 db->next_commit = 0;
205 log_debug ("Successfully committed transaction.");
206 status = 0;
207 }
208 else
209 log_warn ("Failed to commit transaction: %s",
210 PQerrorMessage (db->conn));
211 PQclear (r);
212 }
213 return status;
214 } /* c_psql_commit */
216 static c_psql_database_t *c_psql_database_new (const char *name)
217 {
218 c_psql_database_t **tmp;
219 c_psql_database_t *db;
221 db = malloc (sizeof(*db));
222 if (NULL == db) {
223 log_err ("Out of memory.");
224 return NULL;
225 }
227 tmp = (c_psql_database_t **)realloc (databases,
228 (databases_num + 1) * sizeof (*databases));
229 if (NULL == tmp) {
230 log_err ("Out of memory.");
231 sfree (db);
232 return NULL;
233 }
235 databases = tmp;
236 databases[databases_num] = db;
237 ++databases_num;
239 db->conn = NULL;
241 C_COMPLAIN_INIT (&db->conn_complaint);
243 db->proto_version = 0;
244 db->server_version = 0;
246 db->max_params_num = 0;
248 db->q_prep_areas = NULL;
249 db->queries = NULL;
250 db->queries_num = 0;
252 db->writers = NULL;
253 db->writers_num = 0;
255 pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
257 db->interval = 0;
259 db->commit_interval = 0;
260 db->next_commit = 0;
261 db->expire_delay = 0;
263 db->database = sstrdup (name);
264 db->host = NULL;
265 db->port = NULL;
266 db->user = NULL;
267 db->password = NULL;
269 db->instance = sstrdup (name);
271 db->sslmode = NULL;
273 db->krbsrvname = NULL;
275 db->service = NULL;
277 db->ref_cnt = 0;
278 return db;
279 } /* c_psql_database_new */
281 static void c_psql_database_delete (void *data)
282 {
283 size_t i;
285 c_psql_database_t *db = data;
287 --db->ref_cnt;
288 /* readers and writers may access this database */
289 if (db->ref_cnt > 0)
290 return;
292 /* wait for the lock to be released by the last writer */
293 pthread_mutex_lock (&db->db_lock);
295 if (db->next_commit > 0)
296 c_psql_commit (db);
298 PQfinish (db->conn);
299 db->conn = NULL;
301 if (db->q_prep_areas)
302 for (i = 0; i < db->queries_num; ++i)
303 udb_query_delete_preparation_area (db->q_prep_areas[i]);
304 free (db->q_prep_areas);
306 sfree (db->queries);
307 db->queries_num = 0;
309 sfree (db->writers);
310 db->writers_num = 0;
312 pthread_mutex_unlock (&db->db_lock);
314 pthread_mutex_destroy (&db->db_lock);
316 sfree (db->database);
317 sfree (db->host);
318 sfree (db->port);
319 sfree (db->user);
320 sfree (db->password);
322 sfree (db->instance);
324 sfree (db->sslmode);
326 sfree (db->krbsrvname);
328 sfree (db->service);
330 /* don't care about freeing or reordering the 'databases' array
331 * this is done in 'shutdown'; also, don't free the database instance
332 * object just to make sure that in case anybody accesses it before
333 * shutdown won't segfault */
334 return;
335 } /* c_psql_database_delete */
337 static int c_psql_connect (c_psql_database_t *db)
338 {
339 char conninfo[4096];
340 char *buf = conninfo;
341 int buf_len = sizeof (conninfo);
342 int status;
344 if ((! db) || (! db->database))
345 return -1;
347 status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
348 if (0 < status) {
349 buf += status;
350 buf_len -= status;
351 }
353 C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host);
354 C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port);
355 C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user);
356 C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password);
357 C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode);
358 C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
359 C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service);
361 db->conn = PQconnectdb (conninfo);
362 db->proto_version = PQprotocolVersion (db->conn);
363 return 0;
364 } /* c_psql_connect */
366 static int c_psql_check_connection (c_psql_database_t *db)
367 {
368 _Bool init = 0;
370 if (! db->conn) {
371 init = 1;
373 /* trigger c_release() */
374 if (0 == db->conn_complaint.interval)
375 db->conn_complaint.interval = 1;
377 c_psql_connect (db);
378 }
380 if (CONNECTION_OK != PQstatus (db->conn)) {
381 PQreset (db->conn);
383 /* trigger c_release() */
384 if (0 == db->conn_complaint.interval)
385 db->conn_complaint.interval = 1;
387 if (CONNECTION_OK != PQstatus (db->conn)) {
388 c_complain (LOG_ERR, &db->conn_complaint,
389 "Failed to connect to database %s (%s): %s",
390 db->database, db->instance,
391 PQerrorMessage (db->conn));
392 return -1;
393 }
395 db->proto_version = PQprotocolVersion (db->conn);
396 }
398 db->server_version = PQserverVersion (db->conn);
400 if (c_would_release (&db->conn_complaint)) {
401 char *server_host;
402 int server_version;
404 server_host = PQhost (db->conn);
405 server_version = PQserverVersion (db->conn);
407 c_do_release (LOG_INFO, &db->conn_complaint,
408 "Successfully %sconnected to database %s (user %s) "
409 "at server %s%s%s (server version: %d.%d.%d, "
410 "protocol version: %d, pid: %d)", init ? "" : "re",
411 PQdb (db->conn), PQuser (db->conn),
412 C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
413 C_PSQL_SERVER_VERSION3 (server_version),
414 db->proto_version, PQbackendPID (db->conn));
416 if (3 > db->proto_version)
417 log_warn ("Protocol version %d does not support parameters.",
418 db->proto_version);
419 }
420 return 0;
421 } /* c_psql_check_connection */
423 static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
424 udb_query_t *q)
425 {
426 return PQexec (db->conn, udb_query_get_statement (q));
427 } /* c_psql_exec_query_noparams */
429 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
430 udb_query_t *q, c_psql_user_data_t *data)
431 {
432 const char *params[db->max_params_num];
433 char interval[64];
434 int i;
436 if ((data == NULL) || (data->params_num == 0))
437 return (c_psql_exec_query_noparams (db, q));
439 assert (db->max_params_num >= data->params_num);
441 for (i = 0; i < data->params_num; ++i) {
442 switch (data->params[i]) {
443 case C_PSQL_PARAM_HOST:
444 params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
445 ? "localhost" : db->host;
446 break;
447 case C_PSQL_PARAM_DB:
448 params[i] = db->database;
449 break;
450 case C_PSQL_PARAM_USER:
451 params[i] = db->user;
452 break;
453 case C_PSQL_PARAM_INTERVAL:
454 ssnprintf (interval, sizeof (interval), "%.3f",
455 (db->interval > 0)
456 ? CDTIME_T_TO_DOUBLE (db->interval)
457 : plugin_get_interval ());
458 params[i] = interval;
459 break;
460 case C_PSQL_PARAM_INSTANCE:
461 params[i] = db->instance;
462 break;
463 default:
464 assert (0);
465 }
466 }
468 return PQexecParams (db->conn, udb_query_get_statement (q),
469 data->params_num, NULL,
470 (const char *const *) params,
471 NULL, NULL, /* return text data */ 0);
472 } /* c_psql_exec_query_params */
474 /* db->db_lock must be locked when calling this function */
475 static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
476 udb_query_preparation_area_t *prep_area)
477 {
478 PGresult *res;
480 c_psql_user_data_t *data;
482 const char *host;
484 char **column_names;
485 char **column_values;
486 int column_num;
488 int rows_num;
489 int status;
490 int row, col;
492 /* The user data may hold parameter information, but may be NULL. */
493 data = udb_query_get_user_data (q);
495 /* Versions up to `3' don't know how to handle parameters. */
496 if (3 <= db->proto_version)
497 res = c_psql_exec_query_params (db, q, data);
498 else if ((NULL == data) || (0 == data->params_num))
499 res = c_psql_exec_query_noparams (db, q);
500 else {
501 log_err ("Connection to database \"%s\" (%s) does not support "
502 "parameters (protocol version %d) - "
503 "cannot execute query \"%s\".",
504 db->database, db->instance, db->proto_version,
505 udb_query_get_name (q));
506 return -1;
507 }
509 /* give c_psql_write() a chance to acquire the lock if called recursively
510 * through dispatch_values(); this will happen if, both, queries and
511 * writers are configured for a single connection */
512 pthread_mutex_unlock (&db->db_lock);
514 column_names = NULL;
515 column_values = NULL;
517 if (PGRES_TUPLES_OK != PQresultStatus (res)) {
518 pthread_mutex_lock (&db->db_lock);
520 if ((CONNECTION_OK != PQstatus (db->conn))
521 && (0 == c_psql_check_connection (db))) {
522 PQclear (res);
523 return c_psql_exec_query (db, q, prep_area);
524 }
526 log_err ("Failed to execute SQL query: %s",
527 PQerrorMessage (db->conn));
528 log_info ("SQL query was: %s",
529 udb_query_get_statement (q));
530 PQclear (res);
531 return -1;
532 }
534 #define BAIL_OUT(status) \
535 sfree (column_names); \
536 sfree (column_values); \
537 PQclear (res); \
538 pthread_mutex_lock (&db->db_lock); \
539 return status
541 rows_num = PQntuples (res);
542 if (1 > rows_num) {
543 BAIL_OUT (0);
544 }
546 column_num = PQnfields (res);
547 column_names = (char **) calloc (column_num, sizeof (char *));
548 if (NULL == column_names) {
549 log_err ("calloc failed.");
550 BAIL_OUT (-1);
551 }
553 column_values = (char **) calloc (column_num, sizeof (char *));
554 if (NULL == column_values) {
555 log_err ("calloc failed.");
556 BAIL_OUT (-1);
557 }
559 for (col = 0; col < column_num; ++col) {
560 /* Pointers returned by `PQfname' are freed by `PQclear' via
561 * `BAIL_OUT'. */
562 column_names[col] = PQfname (res, col);
563 if (NULL == column_names[col]) {
564 log_err ("Failed to resolve name of column %i.", col);
565 BAIL_OUT (-1);
566 }
567 }
569 if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
570 || (0 == strcmp (db->host, "127.0.0.1"))
571 || (0 == strcmp (db->host, "localhost")))
572 host = hostname_g;
573 else
574 host = db->host;
576 status = udb_query_prepare_result (q, prep_area, host, "postgresql",
577 db->instance, column_names, (size_t) column_num, db->interval);
578 if (0 != status) {
579 log_err ("udb_query_prepare_result failed with status %i.",
580 status);
581 BAIL_OUT (-1);
582 }
584 for (row = 0; row < rows_num; ++row) {
585 for (col = 0; col < column_num; ++col) {
586 /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
587 * `BAIL_OUT'. */
588 column_values[col] = PQgetvalue (res, row, col);
589 if (NULL == column_values[col]) {
590 log_err ("Failed to get value at (row = %i, col = %i).",
591 row, col);
592 break;
593 }
594 }
596 /* check for an error */
597 if (col < column_num)
598 continue;
600 status = udb_query_handle_result (q, prep_area, column_values);
601 if (status != 0) {
602 log_err ("udb_query_handle_result failed with status %i.",
603 status);
604 }
605 } /* for (row = 0; row < rows_num; ++row) */
607 udb_query_finish_result (q, prep_area);
609 BAIL_OUT (0);
610 #undef BAIL_OUT
611 } /* c_psql_exec_query */
613 static int c_psql_read (user_data_t *ud)
614 {
615 c_psql_database_t *db;
617 int success = 0;
618 size_t i;
620 if ((ud == NULL) || (ud->data == NULL)) {
621 log_err ("c_psql_read: Invalid user data.");
622 return -1;
623 }
625 db = ud->data;
627 assert (NULL != db->database);
628 assert (NULL != db->instance);
629 assert (NULL != db->queries);
631 pthread_mutex_lock (&db->db_lock);
633 if (0 != c_psql_check_connection (db)) {
634 pthread_mutex_unlock (&db->db_lock);
635 return -1;
636 }
638 for (i = 0; i < db->queries_num; ++i)
639 {
640 udb_query_preparation_area_t *prep_area;
641 udb_query_t *q;
643 prep_area = db->q_prep_areas[i];
644 q = db->queries[i];
646 if ((0 != db->server_version)
647 && (udb_query_check_version (q, db->server_version) <= 0))
648 continue;
650 if (0 == c_psql_exec_query (db, q, prep_area))
651 success = 1;
652 }
654 pthread_mutex_unlock (&db->db_lock);
656 if (! success)
657 return -1;
658 return 0;
659 } /* c_psql_read */
661 static char *values_name_to_sqlarray (const data_set_t *ds,
662 char *string, size_t string_len)
663 {
664 char *str_ptr;
665 size_t str_len;
666 size_t i;
668 str_ptr = string;
669 str_len = string_len;
671 for (i = 0; i < ds->ds_num; ++i) {
672 int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
674 if (status < 1)
675 return NULL;
676 else if ((size_t)status >= str_len) {
677 str_len = 0;
678 break;
679 }
680 else {
681 str_ptr += status;
682 str_len -= (size_t)status;
683 }
684 }
686 if (str_len <= 2) {
687 log_err ("c_psql_write: Failed to stringify value names");
688 return NULL;
689 }
691 /* overwrite the first comma */
692 string[0] = '{';
693 str_ptr[0] = '}';
694 str_ptr[1] = '\0';
696 return string;
697 } /* values_name_to_sqlarray */
699 static char *values_type_to_sqlarray (const data_set_t *ds,
700 char *string, size_t string_len, _Bool store_rates)
701 {
702 char *str_ptr;
703 size_t str_len;
704 size_t i;
706 str_ptr = string;
707 str_len = string_len;
709 for (i = 0; i < ds->ds_num; ++i) {
710 int status;
712 if (store_rates)
713 status = ssnprintf(str_ptr, str_len, ",'gauge'");
714 else
715 status = ssnprintf(str_ptr, str_len, ",'%s'",
716 DS_TYPE_TO_STRING (ds->ds[i].type));
718 if (status < 1) {
719 str_len = 0;
720 break;
721 }
722 else if ((size_t)status >= str_len) {
723 str_len = 0;
724 break;
725 }
726 else {
727 str_ptr += status;
728 str_len -= (size_t)status;
729 }
730 }
732 if (str_len <= 2) {
733 log_err ("c_psql_write: Failed to stringify value types");
734 return NULL;
735 }
737 /* overwrite the first comma */
738 string[0] = '{';
739 str_ptr[0] = '}';
740 str_ptr[1] = '\0';
742 return string;
743 } /* values_type_to_sqlarray */
745 static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
746 char *string, size_t string_len, _Bool store_rates)
747 {
748 char *str_ptr;
749 size_t str_len;
751 gauge_t *rates = NULL;
752 size_t i;
754 str_ptr = string;
755 str_len = string_len;
757 for (i = 0; i < vl->values_len; ++i) {
758 int status = 0;
760 if ((ds->ds[i].type != DS_TYPE_GAUGE)
761 && (ds->ds[i].type != DS_TYPE_COUNTER)
762 && (ds->ds[i].type != DS_TYPE_DERIVE)
763 && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
764 log_err ("c_psql_write: Unknown data source type: %i",
765 ds->ds[i].type);
766 sfree (rates);
767 return NULL;
768 }
770 if (ds->ds[i].type == DS_TYPE_GAUGE)
771 status = ssnprintf (str_ptr, str_len,
772 ","GAUGE_FORMAT, vl->values[i].gauge);
773 else if (store_rates) {
774 if (rates == NULL)
775 rates = uc_get_rate (ds, vl);
777 if (rates == NULL) {
778 log_err ("c_psql_write: Failed to determine rate");
779 return NULL;
780 }
782 status = ssnprintf (str_ptr, str_len,
783 ",%lf", rates[i]);
784 }
785 else if (ds->ds[i].type == DS_TYPE_COUNTER)
786 status = ssnprintf (str_ptr, str_len,
787 ",%llu", vl->values[i].counter);
788 else if (ds->ds[i].type == DS_TYPE_DERIVE)
789 status = ssnprintf (str_ptr, str_len,
790 ",%"PRIi64, vl->values[i].derive);
791 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
792 status = ssnprintf (str_ptr, str_len,
793 ",%"PRIu64, vl->values[i].absolute);
795 if (status < 1) {
796 str_len = 0;
797 break;
798 }
799 else if ((size_t)status >= str_len) {
800 str_len = 0;
801 break;
802 }
803 else {
804 str_ptr += status;
805 str_len -= (size_t)status;
806 }
807 }
809 sfree (rates);
811 if (str_len <= 2) {
812 log_err ("c_psql_write: Failed to stringify value list");
813 return NULL;
814 }
816 /* overwrite the first comma */
817 string[0] = '{';
818 str_ptr[0] = '}';
819 str_ptr[1] = '\0';
821 return string;
822 } /* values_to_sqlarray */
824 static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
825 user_data_t *ud)
826 {
827 c_psql_database_t *db;
829 char time_str[RFC3339NANO_SIZE];
830 char values_name_str[1024];
831 char values_type_str[1024];
832 char values_str[1024];
834 const char *params[9];
836 int success = 0;
837 size_t i;
839 if ((ud == NULL) || (ud->data == NULL)) {
840 log_err ("c_psql_write: Invalid user data.");
841 return -1;
842 }
844 db = ud->data;
845 assert (db->database != NULL);
846 assert (db->writers != NULL);
848 if (rfc3339nano (time_str, sizeof (time_str), vl->time) != 0) {
849 log_err ("c_psql_write: Failed to convert time to RFC 3339 format");
850 return -1;
851 }
853 if (values_name_to_sqlarray (ds,
854 values_name_str, sizeof (values_name_str)) == NULL)
855 return -1;
857 #define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
859 params[0] = time_str;
860 params[1] = vl->host;
861 params[2] = vl->plugin;
862 params[3] = VALUE_OR_NULL(vl->plugin_instance);
863 params[4] = vl->type;
864 params[5] = VALUE_OR_NULL(vl->type_instance);
865 params[6] = values_name_str;
867 #undef VALUE_OR_NULL
869 if( db->expire_delay > 0 && vl->time < (cdtime() - vl->interval - db->expire_delay) ) {
870 log_info ("c_psql_write: Skipped expired value @ %s - %s/%s-%s/%s-%s/%s",
871 params[0], params[1], params[2], params[3], params[4], params[5], params[6] );
872 return 0;
873 }
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 = calloc (1, sizeof (*data));
1046 if (NULL == data) {
1047 log_err ("Out of memory.");
1048 return -1;
1049 }
1050 data->params = NULL;
1051 data->params_num = 0;
1053 udb_query_set_user_data (q, data);
1054 }
1056 tmp = realloc (data->params, (data->params_num + 1) * sizeof (*data->params));
1057 if (NULL == tmp) {
1058 log_err ("Out of memory.");
1059 return -1;
1060 }
1061 data->params = tmp;
1063 param_str = ci->values[0].value.string;
1064 if (0 == strcasecmp (param_str, "hostname"))
1065 data->params[data->params_num] = C_PSQL_PARAM_HOST;
1066 else if (0 == strcasecmp (param_str, "database"))
1067 data->params[data->params_num] = C_PSQL_PARAM_DB;
1068 else if (0 == strcasecmp (param_str, "username"))
1069 data->params[data->params_num] = C_PSQL_PARAM_USER;
1070 else if (0 == strcasecmp (param_str, "interval"))
1071 data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
1072 else if (0 == strcasecmp (param_str, "instance"))
1073 data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
1074 else {
1075 log_err ("Invalid parameter \"%s\".", param_str);
1076 return 1;
1077 }
1079 data->params_num++;
1080 return (0);
1081 } /* config_query_param_add */
1083 static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
1084 {
1085 if (0 == strcasecmp ("Param", ci->key))
1086 return config_query_param_add (q, ci);
1088 log_err ("Option not allowed within a Query block: `%s'", ci->key);
1090 return (-1);
1091 } /* config_query_callback */
1093 static int config_add_writer (oconfig_item_t *ci,
1094 c_psql_writer_t *src_writers, size_t src_writers_num,
1095 c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
1096 {
1097 char *name;
1099 size_t i;
1101 if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
1102 return -1;
1104 if ((ci->values_num != 1)
1105 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1106 log_err ("`Writer' expects a single string argument.");
1107 return 1;
1108 }
1110 name = ci->values[0].value.string;
1112 for (i = 0; i < src_writers_num; ++i) {
1113 c_psql_writer_t **tmp;
1115 if (strcasecmp (name, src_writers[i].name) != 0)
1116 continue;
1118 tmp = (c_psql_writer_t **)realloc (*dst_writers,
1119 sizeof (**dst_writers) * (*dst_writers_num + 1));
1120 if (tmp == NULL) {
1121 log_err ("Out of memory.");
1122 return -1;
1123 }
1125 tmp[*dst_writers_num] = src_writers + i;
1127 *dst_writers = tmp;
1128 ++(*dst_writers_num);
1129 break;
1130 }
1132 if (i >= src_writers_num) {
1133 log_err ("No such writer: `%s'", name);
1134 return -1;
1135 }
1137 return 0;
1138 } /* config_add_writer */
1140 static int c_psql_config_writer (oconfig_item_t *ci)
1141 {
1142 c_psql_writer_t *writer;
1143 c_psql_writer_t *tmp;
1145 int status = 0;
1146 int i;
1148 if ((ci->values_num != 1)
1149 || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1150 log_err ("<Writer> expects a single string argument.");
1151 return 1;
1152 }
1154 tmp = (c_psql_writer_t *)realloc (writers,
1155 sizeof (*writers) * (writers_num + 1));
1156 if (tmp == NULL) {
1157 log_err ("Out of memory.");
1158 return -1;
1159 }
1161 writers = tmp;
1162 writer = writers + writers_num;
1163 memset (writer, 0, sizeof (*writer));
1165 writer->name = sstrdup (ci->values[0].value.string);
1166 writer->statement = NULL;
1167 writer->store_rates = 1;
1169 for (i = 0; i < ci->children_num; ++i) {
1170 oconfig_item_t *c = ci->children + i;
1172 if (strcasecmp ("Statement", c->key) == 0)
1173 status = cf_util_get_string (c, &writer->statement);
1174 else if (strcasecmp ("StoreRates", c->key) == 0)
1175 status = cf_util_get_boolean (c, &writer->store_rates);
1176 else
1177 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1178 }
1180 if (status != 0) {
1181 sfree (writer->statement);
1182 sfree (writer->name);
1183 return status;
1184 }
1186 ++writers_num;
1187 return 0;
1188 } /* c_psql_config_writer */
1190 static int c_psql_config_database (oconfig_item_t *ci)
1191 {
1192 c_psql_database_t *db;
1194 char cb_name[DATA_MAX_NAME_LEN];
1195 user_data_t ud;
1197 static _Bool have_flush = 0;
1199 int i;
1201 if ((1 != ci->values_num)
1202 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1203 log_err ("<Database> expects a single string argument.");
1204 return 1;
1205 }
1207 memset (&ud, 0, sizeof (ud));
1209 db = c_psql_database_new (ci->values[0].value.string);
1210 if (db == NULL)
1211 return -1;
1213 for (i = 0; i < ci->children_num; ++i) {
1214 oconfig_item_t *c = ci->children + i;
1216 if (0 == strcasecmp (c->key, "Host"))
1217 cf_util_get_string (c, &db->host);
1218 else if (0 == strcasecmp (c->key, "Port"))
1219 cf_util_get_service (c, &db->port);
1220 else if (0 == strcasecmp (c->key, "User"))
1221 cf_util_get_string (c, &db->user);
1222 else if (0 == strcasecmp (c->key, "Password"))
1223 cf_util_get_string (c, &db->password);
1224 else if (0 == strcasecmp (c->key, "Instance"))
1225 cf_util_get_string (c, &db->instance);
1226 else if (0 == strcasecmp (c->key, "SSLMode"))
1227 cf_util_get_string (c, &db->sslmode);
1228 else if (0 == strcasecmp (c->key, "KRBSrvName"))
1229 cf_util_get_string (c, &db->krbsrvname);
1230 else if (0 == strcasecmp (c->key, "Service"))
1231 cf_util_get_string (c, &db->service);
1232 else if (0 == strcasecmp (c->key, "Query"))
1233 udb_query_pick_from_list (c, queries, queries_num,
1234 &db->queries, &db->queries_num);
1235 else if (0 == strcasecmp (c->key, "Writer"))
1236 config_add_writer (c, writers, writers_num,
1237 &db->writers, &db->writers_num);
1238 else if (0 == strcasecmp (c->key, "Interval"))
1239 cf_util_get_cdtime (c, &db->interval);
1240 else if (strcasecmp ("CommitInterval", c->key) == 0)
1241 cf_util_get_cdtime (c, &db->commit_interval);
1242 else if (strcasecmp ("ExpireDelay", c->key) == 0)
1243 cf_util_get_cdtime (c, &db->expire_delay);
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 ++db->ref_cnt;
1290 plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
1291 /* interval = */ db->interval, &ud);
1292 }
1293 if (db->writers_num > 0) {
1294 ++db->ref_cnt;
1295 plugin_register_write (cb_name, c_psql_write, &ud);
1297 if (! have_flush) {
1298 /* flush all */
1299 plugin_register_flush ("postgresql",
1300 c_psql_flush, /* user data = */ NULL);
1301 have_flush = 1;
1302 }
1304 /* flush this connection only */
1305 ++db->ref_cnt;
1306 plugin_register_flush (cb_name, c_psql_flush, &ud);
1307 }
1308 else if (db->commit_interval > 0) {
1309 log_warn ("Database '%s': You do not have any writers assigned to "
1310 "this database connection. Setting 'CommitInterval' does "
1311 "not have any effect.", db->database);
1312 }
1313 return 0;
1314 } /* c_psql_config_database */
1316 static int c_psql_config (oconfig_item_t *ci)
1317 {
1318 static int have_def_config = 0;
1320 int i;
1322 if (0 == have_def_config) {
1323 oconfig_item_t *c;
1325 have_def_config = 1;
1327 c = oconfig_parse_file (C_PSQL_DEFAULT_CONF);
1328 if (NULL == c)
1329 log_err ("Failed to read default config ("C_PSQL_DEFAULT_CONF").");
1330 else
1331 c_psql_config (c);
1333 if (NULL == queries)
1334 log_err ("Default config ("C_PSQL_DEFAULT_CONF") did not define "
1335 "any queries - please check your installation.");
1336 }
1338 for (i = 0; i < ci->children_num; ++i) {
1339 oconfig_item_t *c = ci->children + i;
1341 if (0 == strcasecmp (c->key, "Query"))
1342 udb_query_create (&queries, &queries_num, c,
1343 /* callback = */ config_query_callback);
1344 else if (0 == strcasecmp (c->key, "Writer"))
1345 c_psql_config_writer (c);
1346 else if (0 == strcasecmp (c->key, "Database"))
1347 c_psql_config_database (c);
1348 else
1349 log_warn ("Ignoring unknown config key \"%s\".", c->key);
1350 }
1351 return 0;
1352 } /* c_psql_config */
1354 void module_register (void)
1355 {
1356 plugin_register_complex_config ("postgresql", c_psql_config);
1357 plugin_register_shutdown ("postgresql", c_psql_shutdown);
1358 } /* module_register */
1360 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */