use a macro instead of an inline function, so that backtraces will report the caller...
[asterisk-bristuff.git] / res / res_config_pgsql.c
blob0439d6bc8f1110c4b718f4f8ac35fddcb736373c
1 /*
2 * Asterisk -- A telephony toolkit for Linux.
4 * Copyright (C) 1999-2005, Digium, Inc.
5 *
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
15 /*! \file
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 * \arg http://www.postgresql.org
25 /*** MODULEINFO
26 <depend>pgsql</depend>
27 ***/
29 #include "asterisk.h"
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <libpq-fe.h> /* PostgreSQL */
38 #include "asterisk/file.h"
39 #include "asterisk/logger.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/config.h"
43 #include "asterisk/module.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/options.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/cli.h"
49 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
51 #define RES_CONFIG_PGSQL_CONF "res_pgsql.conf"
53 PGconn *pgsqlConn = NULL;
55 #define MAX_DB_OPTION_SIZE 64
57 static char dbhost[MAX_DB_OPTION_SIZE] = "";
58 static char dbuser[MAX_DB_OPTION_SIZE] = "";
59 static char dbpass[MAX_DB_OPTION_SIZE] = "";
60 static char dbname[MAX_DB_OPTION_SIZE] = "";
61 static char dbsock[MAX_DB_OPTION_SIZE] = "";
62 static int dbport = 5432;
63 static time_t connect_time = 0;
65 static int parse_config(void);
66 static int pgsql_reconnect(const char *database);
67 static int realtime_pgsql_status(int fd, int argc, char **argv);
69 static char cli_realtime_pgsql_status_usage[] =
70 "Usage: realtime pgsql status\n"
71 " Shows connection information for the Postgresql RealTime driver\n";
73 static struct ast_cli_entry cli_realtime[] = {
74 { { "realtime", "pgsql", "status", NULL },
75 realtime_pgsql_status, "Shows connection information for the Postgresql RealTime driver",
76 cli_realtime_pgsql_status_usage },
79 static struct ast_variable *realtime_pgsql(const char *database, const char *table, va_list ap)
81 PGresult *result = NULL;
82 int num_rows = 0;
83 char sql[256];
84 char *stringp;
85 char *chunk;
86 char *op;
87 const char *newparam, *newval;
88 struct ast_variable *var = NULL, *prev = NULL;
90 if (!table) {
91 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
92 return NULL;
95 /* Get the first parameter and first value in our list of passed paramater/value pairs */
96 newparam = va_arg(ap, const char *);
97 newval = va_arg(ap, const char *);
98 if (!newparam || !newval) {
99 ast_log(LOG_WARNING,
100 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
101 if (pgsqlConn) {
102 PQfinish(pgsqlConn);
103 pgsqlConn = NULL;
105 return NULL;
108 /* Create the first part of the query using the first parameter/value pairs we just extracted
109 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
110 op = strchr(newparam, ' ') ? "" : " =";
112 snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op,
113 newval);
114 while ((newparam = va_arg(ap, const char *))) {
115 newval = va_arg(ap, const char *);
116 if (!strchr(newparam, ' '))
117 op = " =";
118 else
119 op = "";
120 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam,
121 op, newval);
123 va_end(ap);
125 /* We now have our complete statement; Lets connect to the server and execute it. */
126 ast_mutex_lock(&pgsql_lock);
127 if (!pgsql_reconnect(database)) {
128 ast_mutex_unlock(&pgsql_lock);
129 return NULL;
132 if (!(result = PQexec(pgsqlConn, sql))) {
133 ast_log(LOG_WARNING,
134 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
135 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
136 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
137 PQerrorMessage(pgsqlConn));
138 ast_mutex_unlock(&pgsql_lock);
139 return NULL;
140 } else {
141 ExecStatusType result_status = PQresultStatus(result);
142 if (result_status != PGRES_COMMAND_OK
143 && result_status != PGRES_TUPLES_OK
144 && result_status != PGRES_NONFATAL_ERROR) {
145 ast_log(LOG_WARNING,
146 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
147 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
148 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
149 PQresultErrorMessage(result), PQresStatus(result_status));
150 ast_mutex_unlock(&pgsql_lock);
151 return NULL;
155 ast_log(LOG_DEBUG, "1Postgresql RealTime: Result=%p Query: %s\n", result, sql);
157 if ((num_rows = PQntuples(result)) > 0) {
158 int i = 0;
159 int rowIndex = 0;
160 int numFields = PQnfields(result);
161 char **fieldnames = NULL;
163 ast_log(LOG_DEBUG, "Postgresql RealTime: Found %d rows.\n", num_rows);
165 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
166 ast_mutex_unlock(&pgsql_lock);
167 PQclear(result);
168 return NULL;
170 for (i = 0; i < numFields; i++)
171 fieldnames[i] = PQfname(result, i);
172 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
173 for (i = 0; i < numFields; i++) {
174 stringp = PQgetvalue(result, rowIndex, i);
175 while (stringp) {
176 chunk = strsep(&stringp, ";");
177 if (chunk && !ast_strlen_zero(ast_strip(chunk))) {
178 if (prev) {
179 prev->next = ast_variable_new(fieldnames[i], chunk);
180 if (prev->next) {
181 prev = prev->next;
183 } else {
184 prev = var = ast_variable_new(fieldnames[i], chunk);
190 free(fieldnames);
191 } else {
192 ast_log(LOG_WARNING,
193 "Postgresql RealTime: Could not find any rows in table %s.\n", table);
196 ast_mutex_unlock(&pgsql_lock);
197 PQclear(result);
199 return var;
202 static struct ast_config *realtime_multi_pgsql(const char *database, const char *table, va_list ap)
204 PGresult *result = NULL;
205 int num_rows = 0;
206 char sql[256];
207 const char *initfield = NULL;
208 char *stringp;
209 char *chunk;
210 char *op;
211 const char *newparam, *newval;
212 struct ast_realloca ra;
213 struct ast_variable *var = NULL;
214 struct ast_config *cfg = NULL;
215 struct ast_category *cat = NULL;
217 if (!table) {
218 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
219 return NULL;
222 memset(&ra, 0, sizeof(ra));
224 if (!(cfg = ast_config_new()))
225 return NULL;
227 /* Get the first parameter and first value in our list of passed paramater/value pairs */
228 newparam = va_arg(ap, const char *);
229 newval = va_arg(ap, const char *);
230 if (!newparam || !newval) {
231 ast_log(LOG_WARNING,
232 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
233 if (pgsqlConn) {
234 PQfinish(pgsqlConn);
235 pgsqlConn = NULL;
237 return NULL;
240 initfield = ast_strdupa(newparam);
241 if ((op = strchr(initfield, ' '))) {
242 *op = '\0';
245 /* Create the first part of the query using the first parameter/value pairs we just extracted
246 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
248 if (!strchr(newparam, ' '))
249 op = " =";
250 else
251 op = "";
253 snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op,
254 newval);
255 while ((newparam = va_arg(ap, const char *))) {
256 newval = va_arg(ap, const char *);
257 if (!strchr(newparam, ' '))
258 op = " =";
259 else
260 op = "";
261 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam,
262 op, newval);
265 if (initfield) {
266 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " ORDER BY %s", initfield);
269 va_end(ap);
271 /* We now have our complete statement; Lets connect to the server and execute it. */
272 ast_mutex_lock(&pgsql_lock);
273 if (!pgsql_reconnect(database)) {
274 ast_mutex_unlock(&pgsql_lock);
275 return NULL;
278 if (!(result = PQexec(pgsqlConn, sql))) {
279 ast_log(LOG_WARNING,
280 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
281 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
282 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
283 PQerrorMessage(pgsqlConn));
284 ast_mutex_unlock(&pgsql_lock);
285 return NULL;
286 } else {
287 ExecStatusType result_status = PQresultStatus(result);
288 if (result_status != PGRES_COMMAND_OK
289 && result_status != PGRES_TUPLES_OK
290 && result_status != PGRES_NONFATAL_ERROR) {
291 ast_log(LOG_WARNING,
292 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
293 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
294 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
295 PQresultErrorMessage(result), PQresStatus(result_status));
296 ast_mutex_unlock(&pgsql_lock);
297 return NULL;
301 ast_log(LOG_DEBUG, "2Postgresql RealTime: Result=%p Query: %s\n", result, sql);
303 if ((num_rows = PQntuples(result)) > 0) {
304 int numFields = PQnfields(result);
305 int i = 0;
306 int rowIndex = 0;
307 char **fieldnames = NULL;
309 ast_log(LOG_DEBUG, "Postgresql RealTime: Found %d rows.\n", num_rows);
311 if (!(fieldnames = ast_calloc(1, numFields * sizeof(char *)))) {
312 ast_mutex_unlock(&pgsql_lock);
313 PQclear(result);
314 return NULL;
316 for (i = 0; i < numFields; i++)
317 fieldnames[i] = PQfname(result, i);
319 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
320 var = NULL;
321 if (!(cat = ast_category_new("")))
322 continue;
323 for (i = 0; i < numFields; i++) {
324 stringp = PQgetvalue(result, rowIndex, i);
325 while (stringp) {
326 chunk = strsep(&stringp, ";");
327 if (chunk && !ast_strlen_zero(ast_strip(chunk))) {
328 if (initfield && !strcmp(initfield, fieldnames[i])) {
329 ast_category_rename(cat, chunk);
331 var = ast_variable_new(fieldnames[i], chunk);
332 ast_variable_append(cat, var);
336 ast_category_append(cfg, cat);
338 free(fieldnames);
339 } else {
340 ast_log(LOG_WARNING,
341 "Postgresql RealTime: Could not find any rows in table %s.\n", table);
344 ast_mutex_unlock(&pgsql_lock);
345 PQclear(result);
347 return cfg;
350 static int update_pgsql(const char *database, const char *table, const char *keyfield,
351 const char *lookup, va_list ap)
353 PGresult *result = NULL;
354 int numrows = 0;
355 char sql[256];
356 const char *newparam, *newval;
358 if (!table) {
359 ast_log(LOG_WARNING, "Postgresql RealTime: No table specified.\n");
360 return -1;
363 /* Get the first parameter and first value in our list of passed paramater/value pairs */
364 newparam = va_arg(ap, const char *);
365 newval = va_arg(ap, const char *);
366 if (!newparam || !newval) {
367 ast_log(LOG_WARNING,
368 "Postgresql RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
369 if (pgsqlConn) {
370 PQfinish(pgsqlConn);
371 pgsqlConn = NULL;
373 return -1;
376 /* Create the first part of the query using the first parameter/value pairs we just extracted
377 If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
379 snprintf(sql, sizeof(sql), "UPDATE %s SET %s = '%s'", table, newparam, newval);
380 while ((newparam = va_arg(ap, const char *))) {
381 newval = va_arg(ap, const char *);
382 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), ", %s = '%s'", newparam,
383 newval);
385 va_end(ap);
386 snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " WHERE %s = '%s'", keyfield,
387 lookup);
389 ast_log(LOG_DEBUG, "Postgresql RealTime: Update SQL: %s\n", sql);
391 /* We now have our complete statement; Lets connect to the server and execute it. */
392 ast_mutex_lock(&pgsql_lock);
393 if (!pgsql_reconnect(database)) {
394 ast_mutex_unlock(&pgsql_lock);
395 return -1;
398 if (!(result = PQexec(pgsqlConn, sql))) {
399 ast_log(LOG_WARNING,
400 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
401 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
402 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
403 PQerrorMessage(pgsqlConn));
404 ast_mutex_unlock(&pgsql_lock);
405 return -1;
406 } else {
407 ExecStatusType result_status = PQresultStatus(result);
408 if (result_status != PGRES_COMMAND_OK
409 && result_status != PGRES_TUPLES_OK
410 && result_status != PGRES_NONFATAL_ERROR) {
411 ast_log(LOG_WARNING,
412 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
413 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
414 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
415 PQresultErrorMessage(result), PQresStatus(result_status));
416 ast_mutex_unlock(&pgsql_lock);
417 return -1;
421 numrows = atoi(PQcmdTuples(result));
422 ast_mutex_unlock(&pgsql_lock);
424 ast_log(LOG_DEBUG, "Postgresql RealTime: Updated %d rows on table: %s\n", numrows,
425 table);
427 /* From http://dev.pgsql.com/doc/pgsql/en/pgsql-affected-rows.html
428 * An integer greater than zero indicates the number of rows affected
429 * Zero indicates that no records were updated
430 * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
433 if (numrows >= 0)
434 return (int) numrows;
436 return -1;
439 static struct ast_config *config_pgsql(const char *database, const char *table,
440 const char *file, struct ast_config *cfg,
441 int withcomments)
443 PGresult *result = NULL;
444 long num_rows;
445 struct ast_variable *new_v;
446 struct ast_category *cur_cat = NULL;
447 char sqlbuf[1024] = "";
448 char *sql;
449 size_t sqlleft = sizeof(sqlbuf);
450 char last[80] = "";
451 int last_cat_metric = 0;
453 last[0] = '\0';
455 if (!file || !strcmp(file, RES_CONFIG_PGSQL_CONF)) {
456 ast_log(LOG_WARNING, "Postgresql RealTime: Cannot configure myself.\n");
457 return NULL;
460 ast_build_string(&sql, &sqlleft, "SELECT category, var_name, var_val, cat_metric FROM %s ", table);
461 ast_build_string(&sql, &sqlleft, "WHERE filename='%s' and commented=0", file);
462 ast_build_string(&sql, &sqlleft, "ORDER BY cat_metric DESC, var_metric ASC, category, var_name ");
464 ast_log(LOG_DEBUG, "Postgresql RealTime: Static SQL: %s\n", sqlbuf);
466 /* We now have our complete statement; Lets connect to the server and execute it. */
467 ast_mutex_lock(&pgsql_lock);
468 if (!pgsql_reconnect(database)) {
469 ast_mutex_unlock(&pgsql_lock);
470 return NULL;
473 if (!(result = PQexec(pgsqlConn, sqlbuf))) {
474 ast_log(LOG_WARNING,
475 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
476 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
477 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s\n",
478 PQerrorMessage(pgsqlConn));
479 ast_mutex_unlock(&pgsql_lock);
480 return NULL;
481 } else {
482 ExecStatusType result_status = PQresultStatus(result);
483 if (result_status != PGRES_COMMAND_OK
484 && result_status != PGRES_TUPLES_OK
485 && result_status != PGRES_NONFATAL_ERROR) {
486 ast_log(LOG_WARNING,
487 "Postgresql RealTime: Failed to query database. Check debug for more info.\n");
488 ast_log(LOG_DEBUG, "Postgresql RealTime: Query: %s\n", sql);
489 ast_log(LOG_DEBUG, "Postgresql RealTime: Query Failed because: %s (%s)\n",
490 PQresultErrorMessage(result), PQresStatus(result_status));
491 ast_mutex_unlock(&pgsql_lock);
492 return NULL;
496 if ((num_rows = PQntuples(result)) > 0) {
497 int rowIndex = 0;
499 ast_log(LOG_DEBUG, "Postgresql RealTime: Found %ld rows.\n", num_rows);
501 for (rowIndex = 0; rowIndex < num_rows; rowIndex++) {
502 char *field_category = PQgetvalue(result, rowIndex, 0);
503 char *field_var_name = PQgetvalue(result, rowIndex, 1);
504 char *field_var_val = PQgetvalue(result, rowIndex, 2);
505 char *field_cat_metric = PQgetvalue(result, rowIndex, 3);
506 if (!strcmp(field_var_name, "#include")) {
507 if (!ast_config_internal_load(field_var_val, cfg, 0)) {
508 PQclear(result);
509 ast_mutex_unlock(&pgsql_lock);
510 return NULL;
512 continue;
515 if (strcmp(last, field_category) || last_cat_metric != atoi(field_cat_metric)) {
516 cur_cat = ast_category_new(field_category);
517 if (!cur_cat)
518 break;
519 strcpy(last, field_category);
520 last_cat_metric = atoi(field_cat_metric);
521 ast_category_append(cfg, cur_cat);
523 new_v = ast_variable_new(field_var_name, field_var_val);
524 ast_variable_append(cur_cat, new_v);
526 } else {
527 ast_log(LOG_WARNING,
528 "Postgresql RealTime: Could not find config '%s' in database.\n", file);
531 PQclear(result);
532 ast_mutex_unlock(&pgsql_lock);
534 return cfg;
537 static struct ast_config_engine pgsql_engine = {
538 .name = "pgsql",
539 .load_func = config_pgsql,
540 .realtime_func = realtime_pgsql,
541 .realtime_multi_func = realtime_multi_pgsql,
542 .update_func = update_pgsql
545 static int load_module(void)
547 if(!parse_config())
548 return AST_MODULE_LOAD_DECLINE;
550 ast_mutex_lock(&pgsql_lock);
552 if (!pgsql_reconnect(NULL)) {
553 ast_log(LOG_WARNING,
554 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
555 ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
556 PQerrorMessage(pgsqlConn));
559 ast_config_engine_register(&pgsql_engine);
560 if (option_verbose) {
561 ast_verbose("Postgresql RealTime driver loaded.\n");
563 ast_cli_register_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
565 ast_mutex_unlock(&pgsql_lock);
567 return 0;
570 static int unload_module(void)
572 /* Aquire control before doing anything to the module itself. */
573 ast_mutex_lock(&pgsql_lock);
575 if (pgsqlConn) {
576 PQfinish(pgsqlConn);
577 pgsqlConn = NULL;
579 ast_cli_unregister_multiple(cli_realtime, sizeof(cli_realtime) / sizeof(struct ast_cli_entry));
580 ast_config_engine_deregister(&pgsql_engine);
581 if (option_verbose) {
582 ast_verbose("Postgresql RealTime unloaded.\n");
585 ast_module_user_hangup_all();
587 /* Unlock so something else can destroy the lock. */
588 ast_mutex_unlock(&pgsql_lock);
590 return 0;
593 static int reload(void)
595 /* Aquire control before doing anything to the module itself. */
596 ast_mutex_lock(&pgsql_lock);
598 if (pgsqlConn) {
599 PQfinish(pgsqlConn);
600 pgsqlConn = NULL;
602 parse_config();
604 if (!pgsql_reconnect(NULL)) {
605 ast_log(LOG_WARNING,
606 "Postgresql RealTime: Couldn't establish connection. Check debug.\n");
607 ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
608 PQerrorMessage(pgsqlConn));
611 ast_verbose(VERBOSE_PREFIX_2 "Postgresql RealTime reloaded.\n");
613 /* Done reloading. Release lock so others can now use driver. */
614 ast_mutex_unlock(&pgsql_lock);
616 return 0;
619 static int parse_config(void)
621 struct ast_config *config;
622 const char *s;
624 config = ast_config_load(RES_CONFIG_PGSQL_CONF);
626 if (!config) {
627 ast_log(LOG_WARNING, "Unable to load config %s\n",RES_CONFIG_PGSQL_CONF);
628 return 0;
630 if (!(s = ast_variable_retrieve(config, "general", "dbuser"))) {
631 ast_log(LOG_WARNING,
632 "Postgresql RealTime: No database user found, using 'asterisk' as default.\n");
633 strcpy(dbuser, "asterisk");
634 } else {
635 ast_copy_string(dbuser, s, sizeof(dbuser));
638 if (!(s = ast_variable_retrieve(config, "general", "dbpass"))) {
639 ast_log(LOG_WARNING,
640 "Postgresql RealTime: No database password found, using 'asterisk' as default.\n");
641 strcpy(dbpass, "asterisk");
642 } else {
643 ast_copy_string(dbpass, s, sizeof(dbpass));
646 if (!(s = ast_variable_retrieve(config, "general", "dbhost"))) {
647 ast_log(LOG_WARNING,
648 "Postgresql RealTime: No database host found, using localhost via socket.\n");
649 dbhost[0] = '\0';
650 } else {
651 ast_copy_string(dbhost, s, sizeof(dbhost));
654 if (!(s = ast_variable_retrieve(config, "general", "dbname"))) {
655 ast_log(LOG_WARNING,
656 "Postgresql RealTime: No database name found, using 'asterisk' as default.\n");
657 strcpy(dbname, "asterisk");
658 } else {
659 ast_copy_string(dbname, s, sizeof(dbname));
662 if (!(s = ast_variable_retrieve(config, "general", "dbport"))) {
663 ast_log(LOG_WARNING,
664 "Postgresql RealTime: No database port found, using 5432 as default.\n");
665 dbport = 5432;
666 } else {
667 dbport = atoi(s);
670 if (!ast_strlen_zero(dbhost) && !(s = ast_variable_retrieve(config, "general", "dbsock"))) {
671 ast_log(LOG_WARNING,
672 "Postgresql RealTime: No database socket found, using '/tmp/pgsql.sock' as default.\n");
673 strcpy(dbsock, "/tmp/pgsql.sock");
674 } else {
675 ast_copy_string(dbsock, s, sizeof(dbsock));
677 ast_config_destroy(config);
679 if (!ast_strlen_zero(dbhost)) {
680 ast_log(LOG_DEBUG, "Postgresql RealTime Host: %s\n", dbhost);
681 ast_log(LOG_DEBUG, "Postgresql RealTime Port: %i\n", dbport);
682 } else {
683 ast_log(LOG_DEBUG, "Postgresql RealTime Socket: %s\n", dbsock);
685 ast_log(LOG_DEBUG, "Postgresql RealTime User: %s\n", dbuser);
686 ast_log(LOG_DEBUG, "Postgresql RealTime Password: %s\n", dbpass);
687 ast_log(LOG_DEBUG, "Postgresql RealTime DBName: %s\n", dbname);
689 return 1;
692 static int pgsql_reconnect(const char *database)
694 char my_database[50];
696 ast_copy_string(my_database, S_OR(database, dbname), sizeof(my_database));
698 /* mutex lock should have been locked before calling this function. */
700 if (pgsqlConn && PQstatus(pgsqlConn) != CONNECTION_OK) {
701 PQfinish(pgsqlConn);
702 pgsqlConn = NULL;
705 if ((!pgsqlConn) && (!ast_strlen_zero(dbhost) || !ast_strlen_zero(dbsock)) && !ast_strlen_zero(dbuser) && !ast_strlen_zero(dbpass) && !ast_strlen_zero(my_database)) {
706 char *connInfo = NULL;
707 unsigned int size = 100 + strlen(dbhost)
708 + strlen(dbuser)
709 + strlen(dbpass)
710 + strlen(my_database);
712 if (!(connInfo = ast_malloc(size)))
713 return 0;
715 sprintf(connInfo, "host=%s port=%d dbname=%s user=%s password=%s",
716 dbhost, dbport, my_database, dbuser, dbpass);
717 ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
718 pgsqlConn = PQconnectdb(connInfo);
719 ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
720 free(connInfo);
721 connInfo = NULL;
722 ast_log(LOG_DEBUG, "pgsqlConn=%p\n", pgsqlConn);
723 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
724 ast_log(LOG_DEBUG, "Postgresql RealTime: Successfully connected to database.\n");
725 connect_time = time(NULL);
726 return 1;
727 } else {
728 ast_log(LOG_ERROR,
729 "Postgresql RealTime: Failed to connect database server %s on %s. Check debug for more info.\n",
730 dbname, dbhost);
731 ast_log(LOG_DEBUG, "Postgresql RealTime: Cannot Connect: %s\n",
732 PQresultErrorMessage(NULL));
733 return 0;
735 } else {
736 ast_log(LOG_DEBUG, "Postgresql RealTime: Everything is fine.\n");
737 return 1;
741 static int realtime_pgsql_status(int fd, int argc, char **argv)
743 char status[256], status2[100] = "";
744 int ctime = time(NULL) - connect_time;
746 if (pgsqlConn && PQstatus(pgsqlConn) == CONNECTION_OK) {
747 if (!ast_strlen_zero(dbhost)) {
748 snprintf(status, 255, "Connected to %s@%s, port %d", dbname, dbhost, dbport);
749 } else if (!ast_strlen_zero(dbsock)) {
750 snprintf(status, 255, "Connected to %s on socket file %s", dbname, dbsock);
751 } else {
752 snprintf(status, 255, "Connected to %s@%s", dbname, dbhost);
755 if (!ast_strlen_zero(dbuser)) {
756 snprintf(status2, 99, " with username %s", dbuser);
759 if (ctime > 31536000) {
760 ast_cli(fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
761 status, status2, ctime / 31536000, (ctime % 31536000) / 86400,
762 (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
763 } else if (ctime > 86400) {
764 ast_cli(fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status,
765 status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60,
766 ctime % 60);
767 } else if (ctime > 3600) {
768 ast_cli(fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2,
769 ctime / 3600, (ctime % 3600) / 60, ctime % 60);
770 } else if (ctime > 60) {
771 ast_cli(fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60,
772 ctime % 60);
773 } else {
774 ast_cli(fd, "%s%s for %d seconds.\n", status, status2, ctime);
777 return RESULT_SUCCESS;
778 } else {
779 return RESULT_FAILURE;
783 /* needs usecount semantics defined */
784 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "PostgreSQL RealTime Configuration Driver",
785 .load = load_module,
786 .unload = unload_module,
787 .reload = reload