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 AST_RWLIST_ENTRY(columns) list;
72 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
74 #define LENGTHEN_BUF1(size) \
76 /* Lengthen buffer, if necessary */ \
77 if ((newsize = lensql + (size) + 3) > sizesql) { \
78 if ((tmp = ast_realloc(sql, (newsize / 512 + 1) * 512))) { \
80 sizesql = (newsize / 512 + 1) * 512; \
82 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
85 AST_RWLIST_UNLOCK(&psql_columns); \
91 #define LENGTHEN_BUF2(size) \
93 if ((newsize = lensql2 + (size) + 3) > sizesql2) { \
94 if ((tmp = ast_realloc(sql2, (newsize / 512 + 1) * 512))) { \
96 sizesql2 = (newsize / 512 + 1) * 512; \
98 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
101 AST_RWLIST_UNLOCK(&psql_columns); \
107 static int pgsql_log(struct ast_cdr *cdr)
113 ast_mutex_lock(&pgsql_lock);
115 if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
116 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
117 if (PQstatus(conn) != CONNECTION_BAD) {
120 pgerror = PQerrorMessage(conn);
121 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s. Calls will not be logged!\n", pghostname);
122 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
130 int lensql, lensql2, sizesql = maxsize, sizesql2 = maxsize2, newsize;
131 char *sql = ast_calloc(sizeof(char), sizesql), *sql2 = ast_calloc(sizeof(char), sizesql2), *tmp, *value;
132 char buf[257], escapebuf[513];
134 lensql = snprintf(sql, sizesql, "INSERT INTO %s (", table);
135 lensql2 = snprintf(sql2, sizesql2, " VALUES (");
137 AST_RWLIST_RDLOCK(&psql_columns);
138 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
139 /* For fields not set, simply skip them */
140 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
144 LENGTHEN_BUF1(strlen(cur->name));
145 lensql += snprintf(sql + lensql, sizesql - lensql, "%s,", cur->name);
147 if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
148 if (strncmp(cur->type, "int", 3) == 0) {
150 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%ld", cdr->start.tv_sec);
151 } else if (strncmp(cur->type, "float", 5) == 0) {
153 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
155 /* char, hopefully */
157 ast_localtime(&cdr->start, &tm, NULL);
158 lensql2 += ast_strftime(sql2 + lensql2, sizesql2 - lensql2, DATE_FORMAT, &tm);
160 } else if (strcmp(cur->name, "answer") == 0) {
161 if (strncmp(cur->type, "int", 3) == 0) {
163 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%ld", cdr->answer.tv_sec);
164 } else if (strncmp(cur->type, "float", 5) == 0) {
166 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
168 /* char, hopefully */
170 ast_localtime(&cdr->start, &tm, NULL);
171 lensql2 += ast_strftime(sql2 + lensql2, sizesql2 - lensql2, DATE_FORMAT, &tm);
173 } else if (strcmp(cur->name, "end") == 0) {
174 if (strncmp(cur->type, "int", 3) == 0) {
176 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%ld", cdr->end.tv_sec);
177 } else if (strncmp(cur->type, "float", 5) == 0) {
179 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%f", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
181 /* char, hopefully */
183 ast_localtime(&cdr->end, &tm, NULL);
184 lensql2 += ast_strftime(sql2 + lensql2, sizesql2 - lensql2, DATE_FORMAT, &tm);
186 } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
187 if (cur->type[0] == 'i') {
188 /* Get integer, no need to escape anything */
189 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
191 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%s", value);
192 } else if (strncmp(cur->type, "float", 5) == 0) {
193 struct timeval *tv = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
195 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);
197 /* Char field, probably */
198 struct timeval *tv = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
200 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);
202 } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
203 if (strncmp(cur->type, "int", 3) == 0) {
204 /* Integer, no need to escape anything */
205 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
207 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%s", value);
209 /* Although this is a char field, there are no special characters in the values for these fields */
210 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
212 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "'%s'", value);
215 /* Arbitrary field, could be anything */
216 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
217 if (strncmp(cur->type, "int", 3) == 0) {
219 if (value && sscanf(value, "%lld", &whatever) == 1) {
221 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%lld", whatever);
224 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "0");
226 } else if (strncmp(cur->type, "float", 5) == 0) {
227 long double whatever;
228 if (value && sscanf(value, "%Lf", &whatever) == 1) {
230 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "%30Lf", whatever);
233 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "0");
235 /* XXX Might want to handle dates, times, and other misc fields here XXX */
238 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
241 LENGTHEN_BUF2(strlen(escapebuf) + 2);
242 lensql2 += snprintf(sql2 + lensql2, sizesql2 - lensql2, "'%s'", escapebuf);
246 strcat(sql2 + lensql2, ",");
249 AST_RWLIST_UNLOCK(&psql_columns);
250 LENGTHEN_BUF1(lensql2);
251 sql[lensql - 1] = ')';
252 sql2[lensql2 - 1] = ')';
253 strcat(sql + lensql, sql2);
254 ast_verb(11, "[%s]\n", sql);
256 ast_debug(2, "cdr_pgsql: inserting a CDR record.\n");
258 /* Test to be sure we're still connected... */
259 /* If we're connected, and connection is working, good. */
260 /* Otherwise, attempt reconnect. If it fails... sorry... */
261 if (PQstatus(conn) == CONNECTION_OK) {
264 ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
266 if (PQstatus(conn) == CONNECTION_OK) {
267 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
270 pgerror = PQerrorMessage(conn);
271 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
272 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
276 ast_mutex_unlock(&pgsql_lock);
280 result = PQexec(conn, sql);
281 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
282 pgerror = PQresultErrorMessage(result);
283 ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
284 ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
285 ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
287 if (PQstatus(conn) == CONNECTION_OK) {
288 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
291 result = PQexec(conn, sql);
292 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
293 pgerror = PQresultErrorMessage(result);
294 ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR! Attempted reconnection failed. DROPPING CALL RECORD!\n");
295 ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
298 ast_mutex_unlock(&pgsql_lock);
304 ast_mutex_unlock(&pgsql_lock);
308 static int unload_module(void)
311 ast_cdr_unregister(name);
313 /* Give all threads time to finish */
318 ast_free(pghostname);
324 ast_free(pgpassword);
330 AST_RWLIST_WRLOCK(&psql_columns);
331 while ((cur = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
334 AST_RWLIST_UNLOCK(&psql_columns);
339 static int config_module(int reload)
341 struct ast_variable *var;
346 struct ast_config *cfg;
347 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
349 if ((cfg = ast_config_load(config, config_flags)) == NULL) {
350 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
352 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
355 if (!(var = ast_variable_browse(cfg, "global"))) {
356 ast_config_destroy(cfg);
360 if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
361 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified. Assuming unix socket connection\n");
362 tmp = ""; /* connect via UNIX-socket by default */
366 ast_free(pghostname);
367 if (!(pghostname = ast_strdup(tmp))) {
368 ast_config_destroy(cfg);
372 if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
373 ast_log(LOG_WARNING,"PostgreSQL database not specified. Assuming asterisk\n");
374 tmp = "asteriskcdrdb";
379 if (!(pgdbname = ast_strdup(tmp))) {
380 ast_config_destroy(cfg);
384 if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
385 ast_log(LOG_WARNING,"PostgreSQL database user not specified. Assuming asterisk\n");
391 if (!(pgdbuser = ast_strdup(tmp))) {
392 ast_config_destroy(cfg);
396 if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
397 ast_log(LOG_WARNING,"PostgreSQL database password not specified. Assuming blank\n");
402 ast_free(pgpassword);
403 if (!(pgpassword = ast_strdup(tmp))) {
404 ast_config_destroy(cfg);
408 if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
409 ast_log(LOG_WARNING,"PostgreSQL database port not specified. Using default 5432.\n");
415 if (!(pgdbport = ast_strdup(tmp))) {
416 ast_config_destroy(cfg);
420 if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
421 ast_log(LOG_WARNING,"CDR table not specified. Assuming cdr\n");
427 if (!(table = ast_strdup(tmp))) {
428 ast_config_destroy(cfg);
433 if (ast_strlen_zero(pghostname))
434 ast_debug(1, "cdr_pgsql: using default unix socket\n");
436 ast_debug(1, "cdr_pgsql: got hostname of %s\n", pghostname);
437 ast_debug(1, "cdr_pgsql: got port of %s\n", pgdbport);
438 ast_debug(1, "cdr_pgsql: got user of %s\n", pgdbuser);
439 ast_debug(1, "cdr_pgsql: got dbname of %s\n", pgdbname);
440 ast_debug(1, "cdr_pgsql: got password of %s\n", pgpassword);
441 ast_debug(1, "cdr_pgsql: got sql table name of %s\n", table);
444 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
445 if (PQstatus(conn) != CONNECTION_BAD) {
447 char *fname, *ftype, *flen;
449 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
452 /* Query the columns */
453 snprintf(sqlcmd, sizeof(sqlcmd), "select a.attname, t.typname, a.attlen from pg_class c, pg_attribute a, pg_type t where c.oid = a.attrelid and a.atttypid = t.oid and (a.attnum > 0) and c.relname = '%s' order by c.relname, attnum", table);
454 result = PQexec(conn, sqlcmd);
455 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
456 pgerror = PQresultErrorMessage(result);
457 ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns: %s\n", pgerror);
460 return AST_MODULE_LOAD_DECLINE;
463 rows = PQntuples(result);
464 for (i = 0; i < rows; i++) {
465 fname = PQgetvalue(result, i, 0);
466 ftype = PQgetvalue(result, i, 1);
467 flen = PQgetvalue(result, i, 2);
468 ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
469 cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
471 sscanf(flen, "%d", &cur->len);
472 cur->name = (char *)cur + sizeof(*cur);
473 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
474 strcpy(cur->name, fname);
475 strcpy(cur->type, ftype);
476 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
481 pgerror = PQerrorMessage(conn);
482 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s. CALLS WILL NOT BE LOGGED!!\n", pghostname);
483 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
487 ast_config_destroy(cfg);
489 return ast_cdr_register(name, ast_module_info->description, pgsql_log);
492 static int load_module(void)
494 return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
497 static int reload(void)
499 return config_module(1);
502 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
504 .unload = unload_module,