2 * Asterisk -- An open source telephony toolkit.
6 * Steve Murphy - adapted to CEL, from:
7 * Matthew D. Hardeman <mhardemn@papersoft.com>
8 * Adapted from the MySQL CDR logger originally by James Sharp
10 * Modified April, 2007; Dec, 2008
11 * Steve Murphy <murf@digium.com>
13 * Modified September 2003
14 * Matthew D. Hardeman <mhardemn@papersoft.com>
16 * See http://www.asterisk.org for more information about
17 * the Asterisk project. Please do not directly contact
18 * any of the maintainers of this project for assistance;
19 * the project provides a web site, mailing lists and IRC
20 * channels for your use.
22 * This program is free software, distributed under the terms of
23 * the GNU General Public License Version 2. See the LICENSE file
24 * at the top of the source tree.
29 * \brief PostgreSQL CEL logger
31 * \author Steve Murphy <murf@digium.com>
32 * \extref PostgreSQL http://www.postgresql.org/
35 * \arg \ref Config_cel
36 * \extref PostgreSQL http://www.postgresql.org/
37 * \ingroup cel_drivers
41 <depend>pgsql</depend>
46 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50 #include "asterisk/config.h"
51 #include "asterisk/options.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/cel.h"
54 #include "asterisk/module.h"
55 #include "asterisk/logger.h"
58 #define DATE_FORMAT "%Y-%m-%d %T"
60 static char *config = "cel_pgsql.conf";
61 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
62 static int connected = 0;
63 static int maxsize = 512, maxsize2 = 512;
65 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
67 static PGconn *conn = NULL;
68 static PGresult *result = NULL;
69 static struct ast_event_sub *event_sub = NULL;
75 unsigned int notnull:1;
76 unsigned int hasdefault:1;
77 AST_RWLIST_ENTRY(columns) list;
80 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
82 #define LENGTHEN_BUF1(size) \
84 /* Lengthen buffer, if necessary */ \
85 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
86 if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) { \
87 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
90 AST_RWLIST_UNLOCK(&psql_columns); \
96 #define LENGTHEN_BUF2(size) \
98 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) { \
99 if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
100 ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
103 AST_RWLIST_UNLOCK(&psql_columns); \
109 static void pgsql_log(const struct ast_event *event, void *userdata)
114 struct ast_cel_event_record record = {
115 .version = AST_CEL_EVENT_RECORD_VERSION,
118 if (ast_cel_fill_record(event, &record)) {
122 ast_mutex_lock(&pgsql_lock);
124 ast_localtime(&record.event_time, &tm, NULL);
125 ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
127 if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
128 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
129 if (PQstatus(conn) != CONNECTION_BAD) {
132 pgerror = PQerrorMessage(conn);
133 ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s. Calls will not be logged!\n", pghostname);
134 ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
141 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
142 char buf[257], escapebuf[513];
156 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
157 ast_str_set(&sql2, 0, " VALUES (");
159 #define SEP (first ? "" : ",")
161 AST_RWLIST_RDLOCK(&psql_columns);
162 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
163 LENGTHEN_BUF1(strlen(cur->name) + 2);
164 ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
166 if (strcmp(cur->name, "eventtime") == 0) {
167 if (strncmp(cur->type, "int", 3) == 0) {
169 ast_str_append(&sql2, 0, "%s%ld", SEP, record.event_time.tv_sec);
170 } else if (strncmp(cur->type, "float", 5) == 0) {
172 ast_str_append(&sql2, 0, "%s%f",
174 (double) record.event_time.tv_sec +
175 (double) record.event_time.tv_usec / 1000000.0);
177 /* char, hopefully */
179 ast_localtime(&record.event_time, &tm, NULL);
180 ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
181 ast_str_append(&sql2, 0, "%s'%s'", SEP, buf);
183 } else if (strcmp(cur->name, "eventtype") == 0) {
184 if (cur->type[0] == 'i') {
185 /* Get integer, no need to escape anything */
187 ast_str_append(&sql2, 0, "%s%d", SEP, (int) record.event_type);
188 } else if (strncmp(cur->type, "float", 5) == 0) {
190 ast_str_append(&sql2, 0, "%s%f", SEP, (double) record.event_type);
192 /* Char field, probably */
193 LENGTHEN_BUF2(strlen(record.event_name) + 1);
194 ast_str_append(&sql2, 0, "%s'%s'", SEP, record.event_name);
196 } else if (strcmp(cur->name, "amaflags") == 0) {
197 if (strncmp(cur->type, "int", 3) == 0) {
198 /* Integer, no need to escape anything */
200 ast_str_append(&sql2, 0, "%s%d", SEP, record.amaflag);
202 /* Although this is a char field, there are no special characters in the values for these fields */
204 ast_str_append(&sql2, 0, "%s'%d'", SEP, record.amaflag);
207 /* Arbitrary field, could be anything */
208 if (strcmp(cur->name, "userdeftype") == 0) {
209 value = record.user_defined_name;
210 } else if (strcmp(cur->name, "cid_name") == 0) {
211 value = record.caller_id_name;
212 } else if (strcmp(cur->name, "cid_num") == 0) {
213 value = record.caller_id_num;
214 } else if (strcmp(cur->name, "cid_ani") == 0) {
215 value = record.caller_id_ani;
216 } else if (strcmp(cur->name, "cid_rdnis") == 0) {
217 value = record.caller_id_rdnis;
218 } else if (strcmp(cur->name, "cid_dnid") == 0) {
219 value = record.caller_id_dnid;
220 } else if (strcmp(cur->name, "exten") == 0) {
221 value = record.extension;
222 } else if (strcmp(cur->name, "context") == 0) {
223 value = record.context;
224 } else if (strcmp(cur->name, "channame") == 0) {
225 value = record.channel_name;
226 } else if (strcmp(cur->name, "appname") == 0) {
227 value = record.application_name;
228 } else if (strcmp(cur->name, "appdata") == 0) {
229 value = record.application_data;
230 } else if (strcmp(cur->name, "accountcode") == 0) {
231 value = record.account_code;
232 } else if (strcmp(cur->name, "peeraccount") == 0) {
233 value = record.peer_account;
234 } else if (strcmp(cur->name, "uniqueid") == 0) {
235 value = record.unique_id;
236 } else if (strcmp(cur->name, "linkedid") == 0) {
237 value = record.linked_id;
238 } else if (strcmp(cur->name, "userfield") == 0) {
239 value = record.user_field;
240 } else if (strcmp(cur->name, "peer") == 0) {
245 if (strncmp(cur->type, "int", 3) == 0) {
247 if (value && sscanf(value, "%30lld", &whatever) == 1) {
249 ast_str_append(&sql2, 0, "%s%lld", SEP, whatever);
252 ast_str_append(&sql2, 0, "%s0", SEP);
254 } else if (strncmp(cur->type, "float", 5) == 0) {
255 long double whatever;
256 if (value && sscanf(value, "%30Lf", &whatever) == 1) {
258 ast_str_append(&sql2, 0, "%s%30Lf", SEP, whatever);
261 ast_str_append(&sql2, 0, "%s0", SEP);
263 /* XXX Might want to handle dates, times, and other misc fields here XXX */
266 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
270 LENGTHEN_BUF2(strlen(escapebuf) + 3);
271 ast_str_append(&sql2, 0, "%s'%s'", SEP, escapebuf);
276 AST_RWLIST_UNLOCK(&psql_columns);
277 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
278 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
279 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
281 ast_debug(2, "inserting a CEL record.\n");
282 /* Test to be sure we're still connected... */
283 /* If we're connected, and connection is working, good. */
284 /* Otherwise, attempt reconnect. If it fails... sorry... */
285 if (PQstatus(conn) == CONNECTION_OK) {
288 ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
290 if (PQstatus(conn) == CONNECTION_OK) {
291 ast_log(LOG_ERROR, "Connection reestablished.\n");
294 pgerror = PQerrorMessage(conn);
295 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
296 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
300 ast_mutex_unlock(&pgsql_lock);
306 result = PQexec(conn, ast_str_buffer(sql));
307 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
308 pgerror = PQresultErrorMessage(result);
309 ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
310 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
311 ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
313 if (PQstatus(conn) == CONNECTION_OK) {
314 ast_log(LOG_ERROR, "Connection reestablished.\n");
317 result = PQexec(conn, ast_str_buffer(sql));
318 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
319 pgerror = PQresultErrorMessage(result);
320 ast_log(LOG_ERROR, "HARD ERROR! Attempted reconnection failed. DROPPING CALL RECORD!\n");
321 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
324 ast_mutex_unlock(&pgsql_lock);
330 ast_mutex_unlock(&pgsql_lock);
334 static int my_unload_module(void)
336 struct columns *current;
338 event_sub = ast_event_unsubscribe(event_sub);
344 ast_free(pghostname);
353 ast_free(pgpassword);
361 AST_RWLIST_WRLOCK(&psql_columns);
362 while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
365 AST_RWLIST_UNLOCK(&psql_columns);
369 static int unload_module(void)
371 return my_unload_module();
374 static int process_my_load_module(struct ast_config *cfg)
376 struct ast_variable *var;
382 if (!(var = ast_variable_browse(cfg, "global"))) {
383 ast_log(LOG_WARNING,"CEL pgsql config file missing global section.\n");
384 return AST_MODULE_LOAD_DECLINE;
386 if (!(tmp = ast_variable_retrieve(cfg,"global","hostname"))) {
387 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified. Assuming unix socket connection\n");
388 tmp = ""; /* connect via UNIX-socket by default */
391 ast_free(pghostname);
392 if (!(pghostname = ast_strdup(tmp))) {
393 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying host info\n");
394 return AST_MODULE_LOAD_DECLINE;
396 if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
397 ast_log(LOG_WARNING,"PostgreSQL database not specified. Assuming asterisk\n");
398 tmp = "asteriskceldb";
402 if (!(pgdbname = ast_strdup(tmp))) {
403 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying dbname info\n");
404 return AST_MODULE_LOAD_DECLINE;
406 if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
407 ast_log(LOG_WARNING,"PostgreSQL database user not specified. Assuming asterisk\n");
412 if (!(pgdbuser = ast_strdup(tmp))) {
413 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying user info\n");
414 return AST_MODULE_LOAD_DECLINE;
416 if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
417 ast_log(LOG_WARNING, "PostgreSQL database password not specified. Assuming blank\n");
421 ast_free(pgpassword);
422 if (!(pgpassword = ast_strdup(tmp))) {
423 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying password info\n");
424 return AST_MODULE_LOAD_DECLINE;
426 if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
427 ast_log(LOG_WARNING,"PostgreSQL database port not specified. Using default 5432.\n");
432 if (!(pgdbport = ast_strdup(tmp))) {
433 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying port info\n");
434 return AST_MODULE_LOAD_DECLINE;
436 if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
437 ast_log(LOG_WARNING,"CEL table not specified. Assuming cel\n");
442 if (!(table = ast_strdup(tmp))) {
443 return AST_MODULE_LOAD_DECLINE;
446 if (ast_strlen_zero(pghostname)) {
447 ast_debug(3, "cel_pgsql: using default unix socket\n");
449 ast_debug(3, "cel_pgsql: got hostname of %s\n", pghostname);
451 ast_debug(3, "cel_pgsql: got port of %s\n", pgdbport);
452 ast_debug(3, "cel_pgsql: got user of %s\n", pgdbuser);
453 ast_debug(3, "cel_pgsql: got dbname of %s\n", pgdbname);
454 ast_debug(3, "cel_pgsql: got password of %s\n", pgpassword);
455 ast_debug(3, "cel_pgsql: got sql table name of %s\n", table);
458 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
459 if (PQstatus(conn) != CONNECTION_BAD) {
461 char *fname, *ftype, *flen, *fnotnull, *fdef;
465 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
468 /* Remove any schema name from the table */
469 if ((tableptr = strrchr(table, '.'))) {
475 /* Query the columns */
476 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", tableptr);
477 result = PQexec(conn, sqlcmd);
478 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
479 pgerror = PQresultErrorMessage(result);
480 ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
483 return AST_MODULE_LOAD_DECLINE;
486 rows = PQntuples(result);
487 for (i = 0; i < rows; i++) {
488 fname = PQgetvalue(result, i, 0);
489 ftype = PQgetvalue(result, i, 1);
490 flen = PQgetvalue(result, i, 2);
491 fnotnull = PQgetvalue(result, i, 3);
492 fdef = PQgetvalue(result, i, 4);
493 ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
494 cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
496 sscanf(flen, "%30d", &cur->len);
497 cur->name = (char *)cur + sizeof(*cur);
498 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
499 strcpy(cur->name, fname);
500 strcpy(cur->type, ftype);
501 if (*fnotnull == 't') {
506 if (!ast_strlen_zero(fdef)) {
511 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
516 pgerror = PQerrorMessage(conn);
517 ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s. CALLS WILL NOT BE LOGGED!!\n", pghostname);
518 ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
521 return AST_MODULE_LOAD_SUCCESS;
524 static int my_load_module(int reload)
526 struct ast_config *cfg;
528 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
530 if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
531 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CEL's: %s\n", config);
532 return AST_MODULE_LOAD_DECLINE;
533 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
534 return AST_MODULE_LOAD_SUCCESS;
537 res = process_my_load_module(cfg);
538 ast_config_destroy(cfg);
540 event_sub = ast_event_subscribe(AST_EVENT_CEL, pgsql_log, "CEL PGSQL backend", NULL, AST_EVENT_IE_END);
543 ast_log(LOG_WARNING, "Unable to subscribe to CEL events for pgsql\n");
544 return AST_MODULE_LOAD_DECLINE;
547 return AST_MODULE_LOAD_SUCCESS;
550 static int load_module(void)
552 return my_load_module(0);
555 static int reload(void)
558 return my_load_module(1);
561 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CEL Backend",
563 .unload = unload_module,