2 * Asterisk -- A telephony toolkit for Linux.
4 * Copyright (C) 1999-2010, Digium, Inc.
6 * Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
7 * Mark Spencer <markster@digium.com> - Asterisk Author
8 * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
10 * res_config_pgsql.c <PostgreSQL plugin for RealTime configuration engine>
12 * v1.0 - (07-11-05) - Initial version based on res_config_mysql v2.0
17 * \brief PostgreSQL plugin for Asterisk RealTime Architecture
19 * \author Mark Spencer <markster@digium.com>
20 * \author Manuel Guesdon <mguesdon@oxymium.net> - PostgreSQL RealTime Driver Author/Adaptor
22 * \extref PostgreSQL http://www.postgresql.org
26 <depend>pgsql</depend>
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33 #include <libpq-fe.h> /* PostgreSQL */
35 #include "asterisk/file.h"
36 #include "asterisk/channel.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/config.h"
39 #include "asterisk/module.h"
40 #include "asterisk/lock.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/cli.h"
44 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
45 AST_THREADSTORAGE(sql_buf);
46 AST_THREADSTORAGE(findtable_buf);
47 AST_THREADSTORAGE(where_buf);
48 AST_THREADSTORAGE(escapebuf_buf);
49 AST_THREADSTORAGE(semibuf_buf);
51 #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
53 static PGconn *pgsqlConn = NULL;
55 #define has_schema_support (version > 70300 ? 1 : 0)
57 #define MAX_DB_OPTION_SIZE 64
63 unsigned int notnull:1;
64 unsigned int hasdefault:1;
65 AST_LIST_ENTRY(columns) list;
70 AST_LIST_HEAD_NOLOCK(psql_columns, columns) columns;
71 AST_LIST_ENTRY(tables) list;
75 static AST_LIST_HEAD_STATIC(psql_tables, tables);
77 static char dbhost[MAX_DB_OPTION_SIZE] = "";
78 static char dbuser[MAX_DB_OPTION_SIZE] = "";
79 static char dbpass[MAX_DB_OPTION_SIZE] = "";
80 static char dbname[MAX_DB_OPTION_SIZE] = "";
81 static char dbsock[MAX_DB_OPTION_SIZE] = "";
82 static int dbport = 5432;
83 static time_t connect_time = 0;
85 static int parse_config(int reload);
86 static int pgsql_reconnect(const char *database);
87 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
88 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
90 static enum { RQ_WARN, RQ_CREATECLOSE, RQ_CREATECHAR } requirements;
92 static struct ast_cli_entry cli_realtime[] = {
93 AST_CLI_DEFINE(handle_cli_realtime_pgsql_status, "Shows connection information for the PostgreSQL RealTime driver"),
94 AST_CLI_DEFINE(handle_cli_realtime_pgsql_cache, "Shows cached tables within the PostgreSQL realtime driver"),
97 #define ESCAPE_STRING(buffer, stringname) \
99 int len = strlen(stringname); \
100 struct ast_str *semi = ast_str_thread_get(&semibuf_buf, len * 3 + 1); \
101 const char *chunk = stringname; \
102 ast_str_reset(semi); \
103 for (; *chunk; chunk++) { \
104 if (strchr(";^", *chunk)) { \
105 ast_str_append(&semi, 0, "^%02hhX", *chunk); \
107 ast_str_append(&semi, 0, "%c", *chunk); \
110 if (ast_str_strlen(semi) > (ast_str_size(buffer) - 1) / 2) { \
111 ast_str_make_space(&buffer, ast_str_strlen(semi) * 2 + 1); \
113 PQescapeStringConn(pgsqlConn, ast_str_buffer(buffer), ast_str_buffer(semi), ast_str_size(buffer), &pgresult); \
116 static void destroy_table(struct tables *table)
118 struct columns *column;
119 ast_rwlock_wrlock(&table->lock);
120 while ((column = AST_LIST_REMOVE_HEAD(&table->columns, list))) {
123 ast_rwlock_unlock(&table->lock);
124 ast_rwlock_destroy(&table->lock);
128 static struct tables *find_table(const char *orig_tablename)
130 struct columns *column;
131 struct tables *table;
132 struct ast_str *sql = ast_str_thread_get(&findtable_buf, 330);
135 char *fname, *ftype, *flen, *fnotnull, *fdef;
138 AST_LIST_LOCK(&psql_tables);
139 AST_LIST_TRAVERSE(&psql_tables, table, list) {
140 if (!strcasecmp(table->name, orig_tablename)) {
141 ast_debug(1, "Found table in cache; now locking\n");
142 ast_rwlock_rdlock(&table->lock);
143 ast_debug(1, "Lock cached table; now returning\n");
144 AST_LIST_UNLOCK(&psql_tables);
149 ast_debug(1, "Table '%s' not found in cache, querying now\n", orig_tablename);
151 /* Not found, scan the table */
152 if (has_schema_support) {
153 char *schemaname, *tablename;
154 if (strchr(orig_tablename, '.')) {
155 schemaname = ast_strdupa(orig_tablename);
156 tablename = strchr(schemaname, '.');
160 tablename = ast_strdupa(orig_tablename);
163 /* Escape special characters in schemaname */
164 if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
165 char *tmp = schemaname, *ptr;
167 ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
168 for (; *tmp; tmp++) {
169 if (strchr("\\'", *tmp)) {
176 /* Escape special characters in tablename */
177 if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
178 char *tmp = tablename, *ptr;
180 ptr = tablename = alloca(strlen(tmp) * 2 + 1);
181 for (; *tmp; tmp++) {
182 if (strchr("\\'", *tmp)) {
190 ast_str_set(&sql, 0, "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND c.relname = '%s' AND n.nspname = %s%s%s) INNER JOIN pg_catalog.pg_attribute a ON (NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum ORDER BY n.nspname, c.relname, attnum",
192 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
194 /* Escape special characters in tablename */
195 if (strchr(orig_tablename, '\\') || strchr(orig_tablename, '\'')) {
196 const char *tmp = orig_tablename;
199 orig_tablename = ptr = alloca(strlen(tmp) * 2 + 1);
200 for (; *tmp; tmp++) {
201 if (strchr("\\'", *tmp)) {
209 ast_str_set(&sql, 0, "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM pg_class c, pg_type t, pg_attribute a LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", orig_tablename);
212 result = PQexec(pgsqlConn, ast_str_buffer(sql));
213 ast_debug(1, "Query of table structure complete. Now retrieving results.\n");
214 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
215 pgerror = PQresultErrorMessage(result);
216 ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
218 AST_LIST_UNLOCK(&psql_tables);
222 if (!(table = ast_calloc(1, sizeof(*table) + strlen(orig_tablename) + 1))) {
223 ast_log(LOG_ERROR, "Unable to allocate memory for new table structure\n");
224 AST_LIST_UNLOCK(&psql_tables);
227 strcpy(table->name, orig_tablename); /* SAFE */
228 ast_rwlock_init(&table->lock);
229 AST_LIST_HEAD_INIT_NOLOCK(&table->columns);
231 rows = PQntuples(result);
232 for (i = 0; i < rows; i++) {
233 fname = PQgetvalue(result, i, 0);
234 ftype = PQgetvalue(result, i, 1);
235 flen = PQgetvalue(result, i, 2);
236 fnotnull = PQgetvalue(result, i, 3);
237 fdef = PQgetvalue(result, i, 4);
238 ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
240 if (!(column = ast_calloc(1, sizeof(*column) + strlen(fname) + strlen(ftype) + 2))) {
241 ast_log(LOG_ERROR, "Unable to allocate column element for %s, %s\n", orig_tablename, fname);
242 destroy_table(table);
243 AST_LIST_UNLOCK(&psql_tables);
247 if (strcmp(flen, "-1") == 0) {
248 /* Some types, like chars, have the length stored in a different field */
249 flen = PQgetvalue(result, i, 5);
250 sscanf(flen, "%30d", &column->len);
253 sscanf(flen, "%30d", &column->len);
255 column->name = (char *)column + sizeof(*column);
256 column->type = (char *)column + sizeof(*column) + strlen(fname) + 1;
257 strcpy(column->name, fname);
258 strcpy(column->type, ftype);
259 if (*fnotnull == 't') {
264 if (!ast_strlen_zero(fdef)) {
265 column->hasdefault = 1;
267 column->hasdefault = 0;
269 AST_LIST_INSERT_TAIL(&table->columns, column, list);
273 AST_LIST_INSERT_TAIL(&psql_tables, table, list);
274 ast_rwlock_rdlock(&table->lock);
275 AST_LIST_UNLOCK(&psql_tables);
279 #define release_table(table) ast_rwlock_unlock(&(table)->lock);
281 static struct columns *find_column(struct tables *t, const char *colname)
283 struct columns *column;
285 /* Check that the column exists in the table */
286 AST_LIST_TRAVERSE(&t->columns, column, list) {
287 if (strcmp(column->name, colname) == 0) {
294 static struct ast_variable *realtime_pgsql(const char *database, const char *tablename, va_list ap)
296 PGresult *result = NULL;
297 int num_rows = 0, pgresult;
298 struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
299 struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
303 const char *newparam, *newval;
304 struct ast_variable *var = NULL, *prev = NULL;
307 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
311 /* Get the first parameter and first value in our list of passed paramater/value pairs */
312 newparam = va_arg(ap, const char *);
313 newval = va_arg(ap, const char *);
314 if (!newparam || !newval) {
316 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
324 /* Create the first part of the query using the first parameter/value pairs we just extracted
325 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
326 op = strchr(newparam, ' ') ? "" : " =";
328 ESCAPE_STRING(escapebuf, newval);
330 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
335 ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", tablename, newparam, op, ast_str_buffer(escapebuf));
336 while ((newparam = va_arg(ap, const char *))) {
337 newval = va_arg(ap, const char *);
338 if (!strchr(newparam, ' '))
343 ESCAPE_STRING(escapebuf, newval);
345 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
350 ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(escapebuf));
354 /* We now have our complete statement; Lets connect to the server and execute it. */
355 ast_mutex_lock(&pgsql_lock);
356 if (!pgsql_reconnect(database)) {
357 ast_mutex_unlock(&pgsql_lock);
361 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
363 "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", tablename, database);
364 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
365 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
366 ast_mutex_unlock(&pgsql_lock);
369 ExecStatusType result_status = PQresultStatus(result);
370 if (result_status != PGRES_COMMAND_OK
371 && result_status != PGRES_TUPLES_OK
372 && result_status != PGRES_NONFATAL_ERROR) {
374 "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", tablename, database);
375 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
376 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
377 PQresultErrorMessage(result), PQresStatus(result_status));
378 ast_mutex_unlock(&pgsql_lock);
383 ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
385 if ((num_rows = PQntuples(result)) > 0) {
388 int numFields = PQnfields(result);
389 char **fieldnames = NULL;
391 ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
393 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
394 ast_mutex_unlock(&pgsql_lock);
398 for (i = 0; i < numFields; i++)
399 fieldnames[i] = PQfname(result, i);
400 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
401 for (i = 0; i < numFields; i++) {
402 stringp = PQgetvalue(result, rowIndex, i);
404 chunk = strsep(&stringp, ";");
405 if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
407 prev->next = ast_variable_new(fieldnames[i], chunk, "");
412 prev = var = ast_variable_new(fieldnames[i], chunk, "");
418 ast_free(fieldnames);
420 ast_debug(1, "Postgresql RealTime: Could not find any rows in table %s@%s.\n", tablename, database);
423 ast_mutex_unlock(&pgsql_lock);
429 static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, va_list ap)
431 PGresult *result = NULL;
432 int num_rows = 0, pgresult;
433 struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
434 struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
435 const char *initfield = NULL;
439 const char *newparam, *newval;
440 struct ast_variable *var = NULL;
441 struct ast_config *cfg = NULL;
442 struct ast_category *cat = NULL;
445 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
449 if (!(cfg = ast_config_new()))
452 /* Get the first parameter and first value in our list of passed paramater/value pairs */
453 newparam = va_arg(ap, const char *);
454 newval = va_arg(ap, const char *);
455 if (!newparam || !newval) {
457 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
465 initfield = ast_strdupa(newparam);
466 if ((op = strchr(initfield, ' '))) {
470 /* Create the first part of the query using the first parameter/value pairs we just extracted
471 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
473 if (!strchr(newparam, ' '))
478 ESCAPE_STRING(escapebuf, newval);
480 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
485 ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, ast_str_buffer(escapebuf));
486 while ((newparam = va_arg(ap, const char *))) {
487 newval = va_arg(ap, const char *);
488 if (!strchr(newparam, ' '))
493 ESCAPE_STRING(escapebuf, newval);
495 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
500 ast_str_append(&sql, 0, " AND %s%s '%s'", newparam, op, ast_str_buffer(escapebuf));
504 ast_str_append(&sql, 0, " ORDER BY %s", initfield);
509 /* We now have our complete statement; Lets connect to the server and execute it. */
510 ast_mutex_lock(&pgsql_lock);
511 if (!pgsql_reconnect(database)) {
512 ast_mutex_unlock(&pgsql_lock);
516 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
518 "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
519 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
520 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
521 ast_mutex_unlock(&pgsql_lock);
524 ExecStatusType result_status = PQresultStatus(result);
525 if (result_status != PGRES_COMMAND_OK
526 && result_status != PGRES_TUPLES_OK
527 && result_status != PGRES_NONFATAL_ERROR) {
529 "PostgreSQL RealTime: Failed to query %s@%s. Check debug for more info.\n", table, database);
530 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
531 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
532 PQresultErrorMessage(result), PQresStatus(result_status));
533 ast_mutex_unlock(&pgsql_lock);
538 ast_debug(1, "PostgreSQL RealTime: Result=%p Query: %s\n", result, ast_str_buffer(sql));
540 if ((num_rows = PQntuples(result)) > 0) {
541 int numFields = PQnfields(result);
544 char **fieldnames = NULL;
546 ast_debug(1, "PostgreSQL RealTime: Found %d rows.\n", num_rows);
548 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
549 ast_mutex_unlock(&pgsql_lock);
553 for (i = 0; i < numFields; i++)
554 fieldnames[i] = PQfname(result, i);
556 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
558 if (!(cat = ast_category_new("","",99999)))
560 for (i = 0; i < numFields; i++) {
561 stringp = PQgetvalue(result, rowIndex, i);
563 chunk = strsep(&stringp, ";");
564 if (chunk && !ast_strlen_zero(ast_realtime_decode_chunk(ast_strip(chunk)))) {
565 if (initfield && !strcmp(initfield, fieldnames[i])) {
566 ast_category_rename(cat, chunk);
568 var = ast_variable_new(fieldnames[i], chunk, "");
569 ast_variable_append(cat, var);
573 ast_category_append(cfg, cat);
575 ast_free(fieldnames);
577 ast_debug(1, "PostgreSQL RealTime: Could not find any rows in table %s.\n", table);
580 ast_mutex_unlock(&pgsql_lock);
586 static int update_pgsql(const char *database, const char *tablename, const char *keyfield,
587 const char *lookup, va_list ap)
589 PGresult *result = NULL;
590 int numrows = 0, pgresult;
591 const char *newparam, *newval;
592 struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
593 struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 100);
594 struct tables *table;
595 struct columns *column = NULL;
598 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
602 if (!(table = find_table(tablename))) {
603 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
607 /* Get the first parameter and first value in our list of passed paramater/value pairs */
608 newparam = va_arg(ap, const char *);
609 newval = va_arg(ap, const char *);
610 if (!newparam || !newval) {
612 "PostgreSQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
617 release_table(table);
621 /* Check that the column exists in the table */
622 AST_LIST_TRAVERSE(&table->columns, column, list) {
623 if (strcmp(column->name, newparam) == 0) {
629 ast_log(LOG_ERROR, "PostgreSQL RealTime: Updating on column '%s', but that column does not exist within the table '%s'!\n", newparam, tablename);
630 release_table(table);
634 /* Create the first part of the query using the first parameter/value pairs we just extracted
635 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
637 ESCAPE_STRING(escapebuf, newval);
639 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
641 release_table(table);
644 ast_str_set(&sql, 0, "UPDATE %s SET %s = '%s'", tablename, newparam, ast_str_buffer(escapebuf));
646 while ((newparam = va_arg(ap, const char *))) {
647 newval = va_arg(ap, const char *);
649 if (!find_column(table, newparam)) {
650 ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s', but column does not exist!\n", newparam, tablename);
654 ESCAPE_STRING(escapebuf, newval);
656 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
658 release_table(table);
662 ast_str_append(&sql, 0, ", %s = '%s'", newparam, ast_str_buffer(escapebuf));
665 release_table(table);
667 ESCAPE_STRING(escapebuf, lookup);
669 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", lookup);
674 ast_str_append(&sql, 0, " WHERE %s = '%s'", keyfield, ast_str_buffer(escapebuf));
676 ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
678 /* We now have our complete statement; Lets connect to the server and execute it. */
679 ast_mutex_lock(&pgsql_lock);
680 if (!pgsql_reconnect(database)) {
681 ast_mutex_unlock(&pgsql_lock);
685 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
687 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
688 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
689 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
690 ast_mutex_unlock(&pgsql_lock);
693 ExecStatusType result_status = PQresultStatus(result);
694 if (result_status != PGRES_COMMAND_OK
695 && result_status != PGRES_TUPLES_OK
696 && result_status != PGRES_NONFATAL_ERROR) {
698 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
699 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
700 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
701 PQresultErrorMessage(result), PQresStatus(result_status));
702 ast_mutex_unlock(&pgsql_lock);
707 numrows = atoi(PQcmdTuples(result));
708 ast_mutex_unlock(&pgsql_lock);
710 ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
712 /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
713 * An integer greater than zero indicates the number of rows affected
714 * Zero indicates that no records were updated
715 * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
719 return (int) numrows;
724 static int update2_pgsql(const char *database, const char *tablename, va_list ap)
726 PGresult *result = NULL;
727 int numrows = 0, pgresult, first = 1;
728 struct ast_str *escapebuf = ast_str_thread_get(&escapebuf_buf, 16);
729 const char *newparam, *newval;
730 struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
731 struct ast_str *where = ast_str_thread_get(&where_buf, 100);
732 struct tables *table;
735 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
739 if (!escapebuf || !sql || !where) {
740 /* Memory error, already handled */
744 if (!(table = find_table(tablename))) {
745 ast_log(LOG_ERROR, "Table '%s' does not exist!!\n", tablename);
749 ast_str_set(&sql, 0, "UPDATE %s SET ", tablename);
750 ast_str_set(&where, 0, "WHERE");
752 while ((newparam = va_arg(ap, const char *))) {
753 if (!find_column(table, newparam)) {
754 ast_log(LOG_ERROR, "Attempted to update based on criteria column '%s' (%s@%s), but that column does not exist!\n", newparam, tablename, database);
755 release_table(table);
759 newval = va_arg(ap, const char *);
760 ESCAPE_STRING(escapebuf, newval);
762 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
763 release_table(table);
767 ast_str_append(&where, 0, "%s %s='%s'", first ? "" : " AND", newparam, ast_str_buffer(escapebuf));
773 "PostgreSQL RealTime: Realtime update requires at least 1 parameter and 1 value to search on.\n");
778 release_table(table);
782 /* Now retrieve the columns to update */
784 while ((newparam = va_arg(ap, const char *))) {
785 newval = va_arg(ap, const char *);
787 /* If the column is not within the table, then skip it */
788 if (!find_column(table, newparam)) {
789 ast_log(LOG_NOTICE, "Attempted to update column '%s' in table '%s@%s', but column does not exist!\n", newparam, tablename, database);
793 ESCAPE_STRING(escapebuf, newval);
795 ast_log(LOG_ERROR, "Postgres detected invalid input: '%s'\n", newval);
796 release_table(table);
801 ast_str_append(&sql, 0, "%s %s='%s'", first ? "" : ",", newparam, ast_str_buffer(escapebuf));
803 release_table(table);
805 ast_str_append(&sql, 0, " %s", ast_str_buffer(where));
807 ast_debug(1, "PostgreSQL RealTime: Update SQL: %s\n", ast_str_buffer(sql));
809 /* We now have our complete statement; connect to the server and execute it. */
810 ast_mutex_lock(&pgsql_lock);
811 if (!pgsql_reconnect(database)) {
812 ast_mutex_unlock(&pgsql_lock);
816 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
818 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
819 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
820 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
821 ast_mutex_unlock(&pgsql_lock);
824 ExecStatusType result_status = PQresultStatus(result);
825 if (result_status != PGRES_COMMAND_OK
826 && result_status != PGRES_TUPLES_OK
827 && result_status != PGRES_NONFATAL_ERROR) {
829 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
830 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
831 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
832 PQresultErrorMessage(result), PQresStatus(result_status));
833 ast_mutex_unlock(&pgsql_lock);
838 numrows = atoi(PQcmdTuples(result));
839 ast_mutex_unlock(&pgsql_lock);
841 ast_debug(1, "PostgreSQL RealTime: Updated %d rows on table: %s\n", numrows, tablename);
843 /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
844 * An integer greater than zero indicates the number of rows affected
845 * Zero indicates that no records were updated
846 * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
850 return (int) numrows;
856 static int store_pgsql(const char *database, const char *table, va_list ap)
858 PGresult *result = NULL;
860 struct ast_str *buf = ast_str_thread_get(&escapebuf_buf, 256);
861 struct ast_str *sql1 = ast_str_thread_get(&sql_buf, 256);
862 struct ast_str *sql2 = ast_str_thread_get(&where_buf, 256);
864 const char *newparam, *newval;
867 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
871 /* Get the first parameter and first value in our list of passed paramater/value pairs */
872 newparam = va_arg(ap, const char *);
873 newval = va_arg(ap, const char *);
874 if (!newparam || !newval) {
876 "PostgreSQL RealTime: Realtime storage requires at least 1 parameter and 1 value to store.\n");
884 /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
885 ast_mutex_lock(&pgsql_lock);
886 if (!pgsql_reconnect(database)) {
887 ast_mutex_unlock(&pgsql_lock);
891 /* Create the first part of the query using the first parameter/value pairs we just extracted
892 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
893 ESCAPE_STRING(buf, newparam);
894 ast_str_set(&sql1, 0, "INSERT INTO %s (%s", table, ast_str_buffer(buf));
895 ESCAPE_STRING(buf, newval);
896 ast_str_set(&sql2, 0, ") VALUES ('%s'", ast_str_buffer(buf));
897 while ((newparam = va_arg(ap, const char *))) {
898 newval = va_arg(ap, const char *);
899 ESCAPE_STRING(buf, newparam);
900 ast_str_append(&sql1, 0, ", %s", ast_str_buffer(buf));
901 ESCAPE_STRING(buf, newval);
902 ast_str_append(&sql2, 0, ", '%s'", ast_str_buffer(buf));
905 ast_str_append(&sql1, 0, "%s)", ast_str_buffer(sql2));
907 ast_debug(1, "PostgreSQL RealTime: Insert SQL: %s\n", ast_str_buffer(sql1));
909 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql1)))) {
911 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
912 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql1));
913 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
914 ast_mutex_unlock(&pgsql_lock);
917 ExecStatusType result_status = PQresultStatus(result);
918 if (result_status != PGRES_COMMAND_OK
919 && result_status != PGRES_TUPLES_OK
920 && result_status != PGRES_NONFATAL_ERROR) {
922 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
923 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql1));
924 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
925 PQresultErrorMessage(result), PQresStatus(result_status));
926 ast_mutex_unlock(&pgsql_lock);
931 insertid = PQoidValue(result);
932 ast_mutex_unlock(&pgsql_lock);
934 ast_debug(1, "PostgreSQL RealTime: row inserted on table: %s, id: %u\n", table, insertid);
936 /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
937 * An integer greater than zero indicates the number of rows affected
938 * Zero indicates that no records were updated
939 * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
943 return (int) insertid;
948 static int destroy_pgsql(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
950 PGresult *result = NULL;
953 struct ast_str *sql = ast_str_thread_get(&sql_buf, 256);
954 struct ast_str *buf1 = ast_str_thread_get(&where_buf, 60), *buf2 = ast_str_thread_get(&escapebuf_buf, 60);
955 const char *newparam, *newval;
958 ast_log(LOG_WARNING, "PostgreSQL RealTime: No table specified.\n");
962 /* Get the first parameter and first value in our list of passed paramater/value pairs */
963 /*newparam = va_arg(ap, const char *);
964 newval = va_arg(ap, const char *);
965 if (!newparam || !newval) {*/
966 if (ast_strlen_zero(keyfield) || ast_strlen_zero(lookup)) {
968 "PostgreSQL RealTime: Realtime destroy requires at least 1 parameter and 1 value to search on.\n");
976 /* Must connect to the server before anything else, as the escape function requires the connection handle.. */
977 ast_mutex_lock(&pgsql_lock);
978 if (!pgsql_reconnect(database)) {
979 ast_mutex_unlock(&pgsql_lock);
984 /* Create the first part of the query using the first parameter/value pairs we just extracted
985 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
987 ESCAPE_STRING(buf1, keyfield);
988 ESCAPE_STRING(buf2, lookup);
989 ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s = '%s'", table, ast_str_buffer(buf1), ast_str_buffer(buf2));
990 while ((newparam = va_arg(ap, const char *))) {
991 newval = va_arg(ap, const char *);
992 ESCAPE_STRING(buf1, newparam);
993 ESCAPE_STRING(buf2, newval);
994 ast_str_append(&sql, 0, " AND %s = '%s'", ast_str_buffer(buf1), ast_str_buffer(buf2));
998 ast_debug(1, "PostgreSQL RealTime: Delete SQL: %s\n", ast_str_buffer(sql));
1000 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
1001 ast_log(LOG_WARNING,
1002 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
1003 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1004 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
1005 ast_mutex_unlock(&pgsql_lock);
1008 ExecStatusType result_status = PQresultStatus(result);
1009 if (result_status != PGRES_COMMAND_OK
1010 && result_status != PGRES_TUPLES_OK
1011 && result_status != PGRES_NONFATAL_ERROR) {
1012 ast_log(LOG_WARNING,
1013 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
1014 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1015 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
1016 PQresultErrorMessage(result), PQresStatus(result_status));
1017 ast_mutex_unlock(&pgsql_lock);
1022 numrows = atoi(PQcmdTuples(result));
1023 ast_mutex_unlock(&pgsql_lock);
1025 ast_debug(1, "PostgreSQL RealTime: Deleted %d rows on table: %s\n", numrows, table);
1027 /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
1028 * An integer greater than zero indicates the number of rows affected
1029 * Zero indicates that no records were updated
1030 * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
1034 return (int) numrows;
1040 static struct ast_config *config_pgsql(const char *database, const char *table,
1041 const char *file, struct ast_config *cfg,
1042 struct ast_flags flags, const char *suggested_incl, const char *who_asked)
1044 PGresult *result = NULL;
1046 struct ast_variable *new_v;
1047 struct ast_category *cur_cat = NULL;
1048 struct ast_str *sql = ast_str_thread_get(&sql_buf, 100);
1050 int last_cat_metric = 0;
1054 if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
1055 ast_log(LOG_WARNING, "PostgreSQL RealTime: Cannot configure myself.\n");
1059 ast_str_set(&sql, 0, "SELECT category, var_name, var_val, cat_metric FROM %s "
1060 "WHERE filename='%s' and commented=0"
1061 "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ", table, file);
1063 ast_debug(1, "PostgreSQL RealTime: Static SQL: %s\n", ast_str_buffer(sql));
1065 /* We now have our complete statement; Lets connect to the server and execute it. */
1066 ast_mutex_lock(&pgsql_lock);
1067 if (!pgsql_reconnect(database)) {
1068 ast_mutex_unlock(&pgsql_lock);
1072 if (!(result = PQexec(pgsqlConn, ast_str_buffer(sql)))) {
1073 ast_log(LOG_WARNING,
1074 "PostgreSQL RealTime: Failed to query '%s@%s'. Check debug for more info.\n", table, database);
1075 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1076 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s\n", PQerrorMessage(pgsqlConn));
1077 ast_mutex_unlock(&pgsql_lock);
1080 ExecStatusType result_status = PQresultStatus(result);
1081 if (result_status != PGRES_COMMAND_OK
1082 && result_status != PGRES_TUPLES_OK
1083 && result_status != PGRES_NONFATAL_ERROR) {
1084 ast_log(LOG_WARNING,
1085 "PostgreSQL RealTime: Failed to query database. Check debug for more info.\n");
1086 ast_debug(1, "PostgreSQL RealTime: Query: %s\n", ast_str_buffer(sql));
1087 ast_debug(1, "PostgreSQL RealTime: Query Failed because: %s (%s)\n",
1088 PQresultErrorMessage(result), PQresStatus(result_status));
1089 ast_mutex_unlock(&pgsql_lock);
1094 if ((num_rows = PQntuples(result)) > 0) {
1097 ast_debug(1, "PostgreSQL RealTime: Found %ld rows.\n", num_rows);
1099 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
1100 char *field_category = PQgetvalue(result, rowIndex, 0);
1101 char *field_var_name = PQgetvalue(result, rowIndex, 1);
1102 char *field_var_val = PQgetvalue(result, rowIndex, 2);
1103 char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
1104 if (!strcmp(field_var_name, "#include")) {
1105 if (!ast_config_internal_load(field_var_val, cfg, flags, "", who_asked)) {
1107 ast_mutex_unlock(&pgsql_lock);
1113 if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
1114 cur_cat = ast_category_new(field_category, "", 99999);
1117 strcpy(last, field_category);
1118 last_cat_metric = atoi(field_cat_metric);
1119 ast_category_append(cfg, cur_cat);
1121 new_v = ast_variable_new(field_var_name, field_var_val, "");
1122 ast_variable_append(cur_cat, new_v);
1125 ast_log(LOG_WARNING,
1126 "PostgreSQL RealTime: Could not find config '%s' in database.\n", file);
1130 ast_mutex_unlock(&pgsql_lock);
1135 static int require_pgsql(const char *database, const char *tablename, va_list ap)
1137 struct columns *column;
1138 struct tables *table = find_table(tablename);
1140 int type, size, res = 0;
1143 ast_log(LOG_WARNING, "Table %s not found in database. This table should exist if you're using realtime.\n", tablename);
1147 while ((elm = va_arg(ap, char *))) {
1148 type = va_arg(ap, require_type);
1149 size = va_arg(ap, int);
1150 AST_LIST_TRAVERSE(&table->columns, column, list) {
1151 if (strcmp(column->name, elm) == 0) {
1152 /* Char can hold anything, as long as it is large enough */
1153 if ((strncmp(column->type, "char", 4) == 0 || strncmp(column->type, "varchar", 7) == 0 || strcmp(column->type, "bpchar") == 0)) {
1154 if ((size > column->len) && column->len != -1) {
1155 ast_log(LOG_WARNING, "Column '%s' should be at least %d long, but is only %d long.\n", column->name, size, column->len);
1158 } else if (strncmp(column->type, "int", 3) == 0) {
1159 int typesize = atoi(column->type + 3);
1160 /* Integers can hold only other integers */
1161 if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1162 type == RQ_INTEGER4 || type == RQ_UINTEGER4 ||
1163 type == RQ_INTEGER3 || type == RQ_UINTEGER3 ||
1164 type == RQ_UINTEGER2) && typesize == 2) {
1165 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1167 } else if ((type == RQ_INTEGER8 || type == RQ_UINTEGER8 ||
1168 type == RQ_UINTEGER4) && typesize == 4) {
1169 ast_log(LOG_WARNING, "Column '%s' may not be large enough for the required data length: %d\n", column->name, size);
1171 } else if (type == RQ_CHAR || type == RQ_DATETIME || type == RQ_FLOAT || type == RQ_DATE) {
1172 ast_log(LOG_WARNING, "Column '%s' is of the incorrect type: (need %s(%d) but saw %s)\n",
1174 type == RQ_CHAR ? "char" :
1175 type == RQ_DATETIME ? "datetime" :
1176 type == RQ_DATE ? "date" :
1177 type == RQ_FLOAT ? "float" :
1178 "a rather stiff drink ",
1179 size, column->type);
1182 } else if (strncmp(column->type, "float", 5) == 0 && !ast_rq_is_int(type) && type != RQ_FLOAT) {
1183 ast_log(LOG_WARNING, "Column %s cannot be a %s\n", column->name, column->type);
1185 } else { /* There are other types that no module implements yet */
1186 ast_log(LOG_WARNING, "Possibly unsupported column type '%s' on column '%s'\n", column->type, column->name);
1194 if (requirements == RQ_WARN) {
1195 ast_log(LOG_WARNING, "Table %s requires a column '%s' of size '%d', but no such column exists.\n", tablename, elm, size);
1197 struct ast_str *sql = ast_str_create(100);
1201 if (requirements == RQ_CREATECHAR || type == RQ_CHAR) {
1202 /* Size is minimum length; make it at least 50% greater,
1203 * just to be sure, because PostgreSQL doesn't support
1204 * resizing columns. */
1205 snprintf(fieldtype, sizeof(fieldtype), "CHAR(%d)",
1206 size < 15 ? size * 2 :
1207 (size * 3 / 2 > 255) ? 255 : size * 3 / 2);
1208 } else if (type == RQ_INTEGER1 || type == RQ_UINTEGER1 || type == RQ_INTEGER2) {
1209 snprintf(fieldtype, sizeof(fieldtype), "INT2");
1210 } else if (type == RQ_UINTEGER2 || type == RQ_INTEGER3 || type == RQ_UINTEGER3 || type == RQ_INTEGER4) {
1211 snprintf(fieldtype, sizeof(fieldtype), "INT4");
1212 } else if (type == RQ_UINTEGER4 || type == RQ_INTEGER8) {
1213 snprintf(fieldtype, sizeof(fieldtype), "INT8");
1214 } else if (type == RQ_UINTEGER8) {
1215 /* No such type on PostgreSQL */
1216 snprintf(fieldtype, sizeof(fieldtype), "CHAR(20)");
1217 } else if (type == RQ_FLOAT) {
1218 snprintf(fieldtype, sizeof(fieldtype), "FLOAT8");
1219 } else if (type == RQ_DATE) {
1220 snprintf(fieldtype, sizeof(fieldtype), "DATE");
1221 } else if (type == RQ_DATETIME) {
1222 snprintf(fieldtype, sizeof(fieldtype), "TIMESTAMP");
1224 ast_log(LOG_ERROR, "Unrecognized request type %d\n", type);
1228 ast_str_set(&sql, 0, "ALTER TABLE %s ADD COLUMN %s %s", tablename, elm, fieldtype);
1229 ast_debug(1, "About to lock pgsql_lock (running alter on table '%s' to add column '%s')\n", tablename, elm);
1231 ast_mutex_lock(&pgsql_lock);
1232 if (!pgsql_reconnect(database)) {
1233 ast_mutex_unlock(&pgsql_lock);
1234 ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
1239 ast_debug(1, "About to run ALTER query on table '%s' to add column '%s'\n", tablename, elm);
1240 result = PQexec(pgsqlConn, ast_str_buffer(sql));
1241 ast_debug(1, "Finished running ALTER query on table '%s'\n", tablename);
1242 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
1243 ast_log(LOG_ERROR, "Unable to add column: %s\n", ast_str_buffer(sql));
1246 ast_mutex_unlock(&pgsql_lock);
1252 release_table(table);
1256 static int unload_pgsql(const char *database, const char *tablename)
1259 ast_debug(2, "About to lock table cache list\n");
1260 AST_LIST_LOCK(&psql_tables);
1261 ast_debug(2, "About to traverse table cache list\n");
1262 AST_LIST_TRAVERSE_SAFE_BEGIN(&psql_tables, cur, list) {
1263 if (strcmp(cur->name, tablename) == 0) {
1264 ast_debug(2, "About to remove matching cache entry\n");
1265 AST_LIST_REMOVE_CURRENT(list);
1266 ast_debug(2, "About to destroy matching cache entry\n");
1268 ast_debug(1, "Cache entry '%s@%s' destroyed\n", tablename, database);
1272 AST_LIST_TRAVERSE_SAFE_END
1273 AST_LIST_UNLOCK(&psql_tables);
1274 ast_debug(2, "About to return\n");
1275 return cur ? 0 : -1;
1278 static struct ast_config_engine pgsql_engine = {
1280 .load_func = config_pgsql,
1281 .realtime_func = realtime_pgsql,
1282 .realtime_multi_func = realtime_multi_pgsql,
1283 .store_func = store_pgsql,
1284 .destroy_func = destroy_pgsql,
1285 .update_func = update_pgsql,
1286 .update2_func = update2_pgsql,
1287 .require_func = require_pgsql,
1288 .unload_func = unload_pgsql,
1291 static int load_module(void)
1293 if(!parse_config(0))
1294 return AST_MODULE_LOAD_DECLINE;
1296 ast_config_engine_register(&pgsql_engine);
1297 ast_verb(1, "PostgreSQL RealTime driver loaded.\n");
1298 ast_cli_register_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1303 static int unload_module(void)
1305 struct tables *table;
1306 /* Acquire control before doing anything to the module itself. */
1307 ast_mutex_lock(&pgsql_lock);
1310 PQfinish(pgsqlConn);
1313 ast_cli_unregister_multiple(cli_realtime, ARRAY_LEN(cli_realtime));
1314 ast_config_engine_deregister(&pgsql_engine);
1315 ast_verb(1, "PostgreSQL RealTime unloaded.\n");
1317 /* Destroy cached table info */
1318 AST_LIST_LOCK(&psql_tables);
1319 while ((table = AST_LIST_REMOVE_HEAD(&psql_tables, list))) {
1320 destroy_table(table);
1322 AST_LIST_UNLOCK(&psql_tables);
1324 /* Unlock so something else can destroy the lock. */
1325 ast_mutex_unlock(&pgsql_lock);
1330 static int reload(void)
1337 static int parse_config(int is_reload)
1339 struct ast_config *config;
1341 struct ast_flags config_flags = { is_reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1343 config = ast_config_load(RES_CONFIG_PGSQL_CONF, config_flags);
1344 if (config == CONFIG_STATUS_FILEUNCHANGED) {
1348 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1349 ast_log(LOG_WARNING, "Unable to load config %s\n", RES_CONFIG_PGSQL_CONF);
1353 ast_mutex_lock(&pgsql_lock);
1356 PQfinish(pgsqlConn);
1360 if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
1361 ast_log(LOG_WARNING,
1362 "PostgreSQL RealTime: No database user found, using 'asterisk' as default.\n");
1363 strcpy(dbuser, "asterisk");
1365 ast_copy_string(dbuser, s, sizeof(dbuser));
1368 if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
1369 ast_log(LOG_WARNING,
1370 "PostgreSQL RealTime: No database password found, using 'asterisk' as default.\n");
1371 strcpy(dbpass, "asterisk");
1373 ast_copy_string(dbpass, s, sizeof(dbpass));
1376 if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
1377 ast_log(LOG_WARNING,
1378 "PostgreSQL RealTime: No database host found, using localhost via socket.\n");
1381 ast_copy_string(dbhost, s, sizeof(dbhost));
1384 if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
1385 ast_log(LOG_WARNING,
1386 "PostgreSQL RealTime: No database name found, using 'asterisk' as default.\n");
1387 strcpy(dbname, "asterisk");
1389 ast_copy_string(dbname, s, sizeof(dbname));
1392 if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
1393 ast_log(LOG_WARNING,
1394 "PostgreSQL RealTime: No database port found, using 5432 as default.\n");
1400 if (!ast_strlen_zero(dbhost)) {
1401 /* No socket needed */
1402 } else if (!(s = ast_variable_retrieve(config, "general", "dbsock"))) {
1403 ast_log(LOG_WARNING,
1404 "PostgreSQL RealTime: No database socket found, using '/tmp/.s.PGSQL.%d' as default.\n", dbport);
1405 strcpy(dbsock, "/tmp");
1407 ast_copy_string(dbsock, s, sizeof(dbsock));
1410 if (!(s = ast_variable_retrieve(config, "general", "requirements"))) {
1411 ast_log(LOG_WARNING,
1412 "PostgreSQL RealTime: no requirements setting found, using 'warn' as default.\n");
1413 requirements = RQ_WARN;
1414 } else if (!strcasecmp(s, "createclose")) {
1415 requirements = RQ_CREATECLOSE;
1416 } else if (!strcasecmp(s, "createchar")) {
1417 requirements = RQ_CREATECHAR;
1420 ast_config_destroy(config);
1423 if (!ast_strlen_zero(dbhost)) {
1424 ast_debug(1, "PostgreSQL RealTime Host: %s\n", dbhost);
1425 ast_debug(1, "PostgreSQL RealTime Port: %i\n", dbport);
1427 ast_debug(1, "PostgreSQL RealTime Socket: %s\n", dbsock);
1429 ast_debug(1, "PostgreSQL RealTime User: %s\n", dbuser);
1430 ast_debug(1, "PostgreSQL RealTime Password: %s\n", dbpass);
1431 ast_debug(1, "PostgreSQL RealTime DBName: %s\n", dbname);
1434 if (!pgsql_reconnect(NULL)) {
1435 ast_log(LOG_WARNING,
1436 "PostgreSQL RealTime: Couldn't establish connection. Check debug.\n");
1437 ast_debug(1, "PostgreSQL RealTime: Cannot Connect: %s\n", PQerrorMessage(pgsqlConn));
1440 ast_verb(2, "PostgreSQL RealTime reloaded.\n");
1442 /* Done reloading. Release lock so others can now use driver. */
1443 ast_mutex_unlock(&pgsql_lock);
1448 static int pgsql_reconnect(const char *database)
1450 char my_database[50];
1452 ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
1454 /* mutex lock should have been locked before calling this function. */
1456 if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
1457 PQfinish(pgsqlConn);
1461 /* DB password can legitimately be 0-length */
1462 if ((!pgsqlConn) && (!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(my_database)) {
1463 struct ast_str *connInfo = ast_str_create(32);
1465 ast_str_set(&connInfo, 0, "host=%s port=%d dbname=%s user=%s",
1466 S_OR(dbhost, dbsock), dbport, my_database, dbuser);
1467 if (!ast_strlen_zero(dbpass))
1468 ast_str_append(&connInfo, 0, " password=%s", dbpass);
1470 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1471 pgsqlConn = PQconnectdb(ast_str_buffer(connInfo));
1472 ast_debug(1, "%u connInfo=%s\n", (unsigned int)ast_str_size(connInfo), ast_str_buffer(connInfo));
1476 ast_debug(1, "pgsqlConn=%p\n", pgsqlConn);
1477 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1478 ast_debug(1, "PostgreSQL RealTime: Successfully connected to database.\n");
1479 connect_time = time(NULL);
1480 version = PQserverVersion(pgsqlConn);
1484 "PostgreSQL RealTime: Failed to connect database %s on %s: %s\n",
1485 dbname, dbhost, PQresultErrorMessage(NULL));
1489 ast_debug(1, "PostgreSQL RealTime: One or more of the parameters in the config does not pass our validity checks.\n");
1494 static char *handle_cli_realtime_pgsql_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1502 e->command = "realtime show pgsql cache";
1504 "Usage: realtime show pgsql cache [<table>]\n"
1505 " Shows table cache for the PostgreSQL RealTime driver\n";
1511 l = strlen(a->word);
1513 AST_LIST_LOCK(&psql_tables);
1514 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1515 if (!strncasecmp(a->word, cur->name, l) && ++which > a->n) {
1516 ret = ast_strdup(cur->name);
1520 AST_LIST_UNLOCK(&psql_tables);
1525 /* List of tables */
1526 AST_LIST_LOCK(&psql_tables);
1527 AST_LIST_TRAVERSE(&psql_tables, cur, list) {
1528 ast_cli(a->fd, "%s\n", cur->name);
1530 AST_LIST_UNLOCK(&psql_tables);
1531 } else if (a->argc == 5) {
1532 /* List of columns */
1533 if ((cur = find_table(a->argv[4]))) {
1534 struct columns *col;
1535 ast_cli(a->fd, "Columns for Table Cache '%s':\n", a->argv[4]);
1536 ast_cli(a->fd, "%-20.20s %-20.20s %-3.3s %-8.8s\n", "Name", "Type", "Len", "Nullable");
1537 AST_LIST_TRAVERSE(&cur->columns, col, list) {
1538 ast_cli(a->fd, "%-20.20s %-20.20s %3d %-8.8s\n", col->name, col->type, col->len, col->notnull ? "NOT NULL" : "");
1542 ast_cli(a->fd, "No such table '%s'\n", a->argv[4]);
1548 static char *handle_cli_realtime_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1550 char status[256], credentials[100] = "";
1551 int ctimesec = time(NULL) - connect_time;
1555 e->command = "realtime show pgsql status";
1557 "Usage: realtime show pgsql status\n"
1558 " Shows connection information for the PostgreSQL RealTime driver\n";
1565 return CLI_SHOWUSAGE;
1567 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
1568 if (!ast_strlen_zero(dbhost))
1569 snprintf(status, sizeof(status), "Connected to %s@%s, port %d", dbname, dbhost, dbport);
1570 else if (!ast_strlen_zero(dbsock))
1571 snprintf(status, sizeof(status), "Connected to %s on socket file %s", dbname, dbsock);
1573 snprintf(status, sizeof(status), "Connected to %s@%s", dbname, dbhost);
1575 if (!ast_strlen_zero(dbuser))
1576 snprintf(credentials, sizeof(credentials), " with username %s", dbuser);
1578 if (ctimesec > 31536000)
1579 ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
1580 status, credentials, ctimesec / 31536000, (ctimesec % 31536000) / 86400,
1581 (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1582 else if (ctimesec > 86400)
1583 ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
1584 credentials, ctimesec / 86400, (ctimesec % 86400) / 3600, (ctimesec % 3600) / 60,
1586 else if (ctimesec > 3600)
1587 ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, credentials,
1588 ctimesec / 3600, (ctimesec % 3600) / 60, ctimesec % 60);
1589 else if (ctimesec > 60)
1590 ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials, ctimesec / 60,
1593 ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
1601 /* needs usecount semantics defined */
1602 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL RealTime Configuration Driver",
1603 .load = load_module,
1604 .unload = unload_module,