2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2003 - 2006
6 * Matthew D. Hardeman <mhardemn@papersoft.com>
7 * Adapted from the MySQL CDR logger originally by James Sharp
9 * Modified September 2003
10 * Matthew D. Hardeman <mhardemn@papersoft.com>
12 * See http://www.asterisk.org for more information about
13 * the Asterisk project. Please do not directly contact
14 * any of the maintainers of this project for assistance;
15 * the project provides a web site, mailing lists and IRC
16 * channels for your use.
18 * This program is free software, distributed under the terms of
19 * the GNU General Public License Version 2. See the LICENSE file
20 * at the top of the source tree.
25 * \brief PostgreSQL CDR logger
27 * \author Matthew D. Hardeman <mhardemn@papersoft.com>
28 * \extref PostgreSQL http://www.postgresql.org/
31 * \arg \ref Config_cdr
32 * \arg http://www.postgresql.org/
33 * \ingroup cdr_drivers
37 <depend>pgsql</depend>
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48 #include "asterisk/config.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/cdr.h"
51 #include "asterisk/module.h"
53 #define DATE_FORMAT "'%Y-%m-%d %T'"
55 static char *name = "pgsql";
56 static char *config = "cdr_pgsql.conf";
57 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
58 static int connected = 0;
59 static int maxsize = 512, maxsize2 = 512;
61 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
63 static PGconn *conn = NULL;
69 unsigned int notnull:1;
70 unsigned int hasdefault:1;
71 AST_RWLIST_ENTRY(columns) list;
74 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
76 #define LENGTHEN_BUF1(size) \
78 /* Lengthen buffer, if necessary */ \
79 if ((newsize = lensql + (size) + 3) > sizesql) { \
80 if ((tmp = ast_realloc(sql, (newsize / 512 + 1) * 512))) { \
82 sizesql = (newsize / 512 + 1) * 512; \
84 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
87 AST_RWLIST_UNLOCK(&psql_columns); \
93 #define LENGTHEN_BUF2(size) \
95 if ((newsize = lensql2 + (size) + 3) > sizesql2) { \
96 if ((tmp = ast_realloc(sql2, (newsize / 512 + 1) * 512))) { \
98 sizesql2 = (newsize / 512 + 1) * 512; \
100 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
103 AST_RWLIST_UNLOCK(&psql_columns); \
109 static int pgsql_log(struct ast_cdr *cdr)
115 ast_mutex_lock(&pgsql_lock);
117 if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
118 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
119 if (PQstatus(conn) != CONNECTION_BAD) {
122 pgerror = PQerrorMessage(conn);
123 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s. Calls will not be logged!\n", pghostname);
124 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
132 int lensql, lensql2, sizesql = maxsize, sizesql2 = maxsize2, newsize;
133 char *sql = ast_calloc(sizeof(char), sizesql), *sql2 = ast_calloc(sizeof(char), sizesql2), *tmp, *value;
134 char buf[257], escapebuf[513];
136 lensql = snprintf(sql, sizesql, "INSERT INTO %s (", table);
137 lensql2 = snprintf(sql2, sizesql2, " VALUES (");
139 AST_RWLIST_RDLOCK(&psql_columns);
140 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
141 /* For fields not set, simply skip them */
142 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
144 if (cur->notnull && !cur->hasdefault) {
145 /* Field is NOT NULL (but no default), must include it anyway */
146 LENGTHEN_BUF1(strlen(cur->name));
147 lensql += snprintf(sql + lensql, sizesql - lensql, "%s,", cur->name);
155 LENGTHEN_BUF1(strlen(cur->name));
156 lensql += snprintf(sql + lensql, sizesql - lensql, "%s,", cur->name);
158 if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
159 if (strncmp(cur->type, "int", 3) == 0) {
161 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%ld", cdr->start.tv_sec);
162 } else if (strncmp(cur->type, "float", 5) == 0) {
164 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
166 /* char, hopefully */
168 ast_localtime(&cdr->start, &tm, NULL);
169 lensql2 += ast_strftime(sql2 + lensql2, sizesql2 - lensql2, DATE_FORMAT, &tm);
171 } else if (strcmp(cur->name, "answer") == 0) {
172 if (strncmp(cur->type, "int", 3) == 0) {
174 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%ld", cdr->answer.tv_sec);
175 } else if (strncmp(cur->type, "float", 5) == 0) {
177 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
179 /* char, hopefully */
181 ast_localtime(&cdr->start, &tm, NULL);
182 lensql2 += ast_strftime(sql2 + lensql2, sizesql2 - lensql2, DATE_FORMAT, &tm);
184 } else if (strcmp(cur->name, "end") == 0) {
185 if (strncmp(cur->type, "int", 3) == 0) {
187 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%ld", cdr->end.tv_sec);
188 } else if (strncmp(cur->type, "float", 5) == 0) {
190 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
192 /* char, hopefully */
194 ast_localtime(&cdr->end, &tm, NULL);
195 lensql2 += ast_strftime(sql2 + lensql2, sizesql2 - lensql2, DATE_FORMAT, &tm);
197 } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
198 if (cur->type[0] == 'i') {
199 /* Get integer, no need to escape anything */
200 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
202 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%s", value);
203 } else if (strncmp(cur->type, "float", 5) == 0) {
204 struct timeval *tv = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
206 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->end.tv_sec - tv->tv_sec + cdr->end.tv_usec / 1000000.0 - tv->tv_usec / 1000000.0);
208 /* Char field, probably */
209 struct timeval *tv = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
211 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "'%f'", (double)cdr->end.tv_sec - tv->tv_sec + cdr->end.tv_usec / 1000000.0 - tv->tv_usec / 1000000.0);
213 } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
214 if (strncmp(cur->type, "int", 3) == 0) {
215 /* Integer, no need to escape anything */
216 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
218 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%s", value);
220 /* Although this is a char field, there are no special characters in the values for these fields */
221 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
223 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "'%s'", value);
226 /* Arbitrary field, could be anything */
227 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
228 if (strncmp(cur->type, "int", 3) == 0) {
230 if (value && sscanf(value, "%lld", &whatever) == 1) {
232 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%lld", whatever);
235 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "0");
237 } else if (strncmp(cur->type, "float", 5) == 0) {
238 long double whatever;
239 if (value && sscanf(value, "%Lf", &whatever) == 1) {
241 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%30Lf", whatever);
244 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "0");
246 /* XXX Might want to handle dates, times, and other misc fields here XXX */
249 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
252 LENGTHEN_BUF2(strlen(escapebuf) + 2);
253 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "'%s'", escapebuf);
257 strcat(sql2 + lensql2, ",");
260 AST_RWLIST_UNLOCK(&psql_columns);
261 LENGTHEN_BUF1(lensql2);
262 sql[lensql - 1] = ')';
263 sql2[lensql2 - 1] = ')';
264 strcat(sql + lensql, sql2);
265 ast_verb(11, "[%s]\n", sql);
267 ast_debug(2, "cdr_pgsql: inserting a CDR record.\n");
269 /* Test to be sure we're still connected... */
270 /* If we're connected, and connection is working, good. */
271 /* Otherwise, attempt reconnect. If it fails... sorry... */
272 if (PQstatus(conn) == CONNECTION_OK) {
275 ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
277 if (PQstatus(conn) == CONNECTION_OK) {
278 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
281 pgerror = PQerrorMessage(conn);
282 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
283 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
287 ast_mutex_unlock(&pgsql_lock);
291 result = PQexec(conn, sql);
292 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
293 pgerror = PQresultErrorMessage(result);
294 ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
295 ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
296 ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
298 if (PQstatus(conn) == CONNECTION_OK) {
299 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
302 result = PQexec(conn, sql);
303 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
304 pgerror = PQresultErrorMessage(result);
305 ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR! Attempted reconnection failed. DROPPING CALL RECORD!\n");
306 ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
309 ast_mutex_unlock(&pgsql_lock);
315 ast_mutex_unlock(&pgsql_lock);
319 static int unload_module(void)
322 ast_cdr_unregister(name);
324 /* Give all threads time to finish */
329 ast_free(pghostname);
335 ast_free(pgpassword);
341 AST_RWLIST_WRLOCK(&psql_columns);
342 while ((cur = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
345 AST_RWLIST_UNLOCK(&psql_columns);
350 static int config_module(int reload)
352 struct ast_variable *var;
357 struct ast_config *cfg;
358 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
360 if ((cfg = ast_config_load(config, config_flags)) == NULL) {
361 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
363 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
366 if (!(var = ast_variable_browse(cfg, "global"))) {
367 ast_config_destroy(cfg);
371 if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
372 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified. Assuming unix socket connection\n");
373 tmp = ""; /* connect via UNIX-socket by default */
377 ast_free(pghostname);
378 if (!(pghostname = ast_strdup(tmp))) {
379 ast_config_destroy(cfg);
383 if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
384 ast_log(LOG_WARNING,"PostgreSQL database not specified. Assuming asterisk\n");
385 tmp = "asteriskcdrdb";
390 if (!(pgdbname = ast_strdup(tmp))) {
391 ast_config_destroy(cfg);
395 if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
396 ast_log(LOG_WARNING,"PostgreSQL database user not specified. Assuming asterisk\n");
402 if (!(pgdbuser = ast_strdup(tmp))) {
403 ast_config_destroy(cfg);
407 if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
408 ast_log(LOG_WARNING,"PostgreSQL database password not specified. Assuming blank\n");
413 ast_free(pgpassword);
414 if (!(pgpassword = ast_strdup(tmp))) {
415 ast_config_destroy(cfg);
419 if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
420 ast_log(LOG_WARNING,"PostgreSQL database port not specified. Using default 5432.\n");
426 if (!(pgdbport = ast_strdup(tmp))) {
427 ast_config_destroy(cfg);
431 if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
432 ast_log(LOG_WARNING,"CDR table not specified. Assuming cdr\n");
438 if (!(table = ast_strdup(tmp))) {
439 ast_config_destroy(cfg);
444 if (ast_strlen_zero(pghostname)) {
445 ast_debug(1, "cdr_pgsql: using default unix socket\n");
447 ast_debug(1, "cdr_pgsql: got hostname of %s\n", pghostname);
449 ast_debug(1, "cdr_pgsql: got port of %s\n", pgdbport);
450 ast_debug(1, "cdr_pgsql: got user of %s\n", pgdbuser);
451 ast_debug(1, "cdr_pgsql: got dbname of %s\n", pgdbname);
452 ast_debug(1, "cdr_pgsql: got password of %s\n", pgpassword);
453 ast_debug(1, "cdr_pgsql: got sql table name of %s\n", table);
456 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
457 if (PQstatus(conn) != CONNECTION_BAD) {
459 char *fname, *ftype, *flen, *fnotnull, *fdef;
461 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
464 /* Query the columns */
465 snprintf(sqlcmd, sizeof(sqlcmd), "select a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc 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", table);
466 result = PQexec(conn, sqlcmd);
467 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
468 pgerror = PQresultErrorMessage(result);
469 ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns: %s\n", pgerror);
472 return AST_MODULE_LOAD_DECLINE;
475 rows = PQntuples(result);
476 for (i = 0; i < rows; i++) {
477 fname = PQgetvalue(result, i, 0);
478 ftype = PQgetvalue(result, i, 1);
479 flen = PQgetvalue(result, i, 2);
480 fnotnull = PQgetvalue(result, i, 3);
481 fdef = PQgetvalue(result, i, 4);
482 ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
483 cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
485 sscanf(flen, "%d", &cur->len);
486 cur->name = (char *)cur + sizeof(*cur);
487 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
488 strcpy(cur->name, fname);
489 strcpy(cur->type, ftype);
490 if (*fnotnull == 't') {
495 if (!ast_strlen_zero(fdef)) {
500 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
505 pgerror = PQerrorMessage(conn);
506 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s. CALLS WILL NOT BE LOGGED!!\n", pghostname);
507 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
511 ast_config_destroy(cfg);
513 return ast_cdr_register(name, ast_module_info->description, pgsql_log);
516 static int load_module(void)
518 return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
521 static int reload(void)
523 return config_module(1);
526 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
528 .unload = unload_module,