Merged revisions 80360 via svnmerge from
[asterisk/asterisk.git] / cdr / cdr_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003 - 2006
5  *
6  * Matthew D. Hardeman <mhardemn@papersoft.com> 
7  * Adapted from the MySQL CDR logger originally by James Sharp 
8  *
9  * Modified September 2003
10  * Matthew D. Hardeman <mhardemn@papersoft.com>
11  *
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.
17  *
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.
21  */
22
23 /*! \file
24  *
25  * \brief PostgreSQL CDR logger 
26  * 
27  * \author Matthew D. Hardeman <mhardemn@papersoft.com> 
28  * \extref PostgreSQL http://www.postgresql.org/
29  *
30  * See also
31  * \arg \ref Config_cdr
32  * \arg http://www.postgresql.org/
33  * \ingroup cdr_drivers
34  */
35
36 /*** MODULEINFO
37         <depend>pgsql</depend>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include <sys/types.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 #include <time.h>
50
51 #include <libpq-fe.h>
52
53 #include "asterisk/config.h"
54 #include "asterisk/options.h"
55 #include "asterisk/channel.h"
56 #include "asterisk/cdr.h"
57 #include "asterisk/module.h"
58 #include "asterisk/logger.h"
59 #include "asterisk.h"
60
61 #define DATE_FORMAT "%Y-%m-%d %T"
62
63 static char *name = "pgsql";
64 static char *config = "cdr_pgsql.conf";
65 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
66 static int connected = 0;
67
68 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
69
70 static PGconn   *conn = NULL;
71
72 static int pgsql_log(struct ast_cdr *cdr)
73 {
74         struct ast_tm tm;
75         char sqlcmd[2048] = "", timestr[128];
76         char *pgerror;
77         PGresult *result;
78
79         ast_mutex_lock(&pgsql_lock);
80
81         ast_localtime(&cdr->start, &tm, NULL);
82         ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
83
84         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
85                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
86                 if (PQstatus(conn) != CONNECTION_BAD) {
87                         connected = 1;
88                 } else {
89                         pgerror = PQerrorMessage(conn);
90                         ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
91                         ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
92                         PQfinish(conn);
93                         conn = NULL;
94                 }
95         }
96
97         if (connected) {
98                 char *clid=NULL, *dcontext=NULL, *channel=NULL, *dstchannel=NULL, *lastapp=NULL, *lastdata=NULL;
99                 char *uniqueid=NULL, *userfield=NULL;
100
101                 /* Maximum space needed would be if all characters needed to be escaped, plus a trailing NULL */
102                 if ((clid = alloca(strlen(cdr->clid) * 2 + 1)) != NULL)
103                         PQescapeString(clid, cdr->clid, strlen(cdr->clid));
104                 if ((dcontext = alloca(strlen(cdr->dcontext) * 2 + 1)) != NULL)
105                         PQescapeString(dcontext, cdr->dcontext, strlen(cdr->dcontext));
106                 if ((channel = alloca(strlen(cdr->channel) * 2 + 1)) != NULL)
107                         PQescapeString(channel, cdr->channel, strlen(cdr->channel));
108                 if ((dstchannel = alloca(strlen(cdr->dstchannel) * 2 + 1)) != NULL)
109                         PQescapeString(dstchannel, cdr->dstchannel, strlen(cdr->dstchannel));
110                 if ((lastapp = alloca(strlen(cdr->lastapp) * 2 + 1)) != NULL)
111                         PQescapeString(lastapp, cdr->lastapp, strlen(cdr->lastapp));
112                 if ((lastdata = alloca(strlen(cdr->lastdata) * 2 + 1)) != NULL)
113                         PQescapeString(lastdata, cdr->lastdata, strlen(cdr->lastdata));
114                 if ((uniqueid = alloca(strlen(cdr->uniqueid) * 2 + 1)) != NULL)
115                         PQescapeString(uniqueid, cdr->uniqueid, strlen(cdr->uniqueid));
116                 if ((userfield = alloca(strlen(cdr->userfield) * 2 + 1)) != NULL)
117                         PQescapeString(userfield, cdr->userfield, strlen(cdr->userfield));
118
119                 /* Check for all alloca failures above at once */
120                 if ((!clid) || (!dcontext) || (!channel) || (!dstchannel) || (!lastapp) || (!lastdata) || (!uniqueid) || (!userfield)) {
121                         ast_log(LOG_ERROR, "cdr_pgsql:  Out of memory error (insert fails)\n");
122                         ast_mutex_unlock(&pgsql_lock);
123                         return -1;
124                 }
125
126                 ast_debug(2, "cdr_pgsql: inserting a CDR record.\n");
127
128                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s (calldate,clid,src,dst,dcontext,channel,dstchannel,"
129                                  "lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES"
130                                  " ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%ld,%ld,'%s',%ld,'%s','%s','%s')",
131                                  table,timestr,clid,cdr->src, cdr->dst, dcontext,channel, dstchannel, lastapp, lastdata,
132                                  cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
133                 
134                 ast_debug(3, "cdr_pgsql: SQL command executed:  %s\n",sqlcmd);
135                 
136                 /* Test to be sure we're still connected... */
137                 /* If we're connected, and connection is working, good. */
138                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
139                 if (PQstatus(conn) == CONNECTION_OK) {
140                         connected = 1;
141                 } else {
142                         ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
143                         PQreset(conn);
144                         if (PQstatus(conn) == CONNECTION_OK) {
145                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
146                                 connected = 1;
147                         } else {
148                                 pgerror = PQerrorMessage(conn);
149                                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
150                                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
151                                 PQfinish(conn);
152                                 conn = NULL;
153                                 connected = 0;
154                                 ast_mutex_unlock(&pgsql_lock);
155                                 return -1;
156                         }
157                 }
158                 result = PQexec(conn, sqlcmd);
159                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
160                         pgerror = PQresultErrorMessage(result);
161                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
162                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
163                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
164                         PQreset(conn);
165                         if (PQstatus(conn) == CONNECTION_OK) {
166                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
167                                 connected = 1;
168                                 PQclear(result);
169                                 result = PQexec(conn, sqlcmd);
170                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
171                                         pgerror = PQresultErrorMessage(result);
172                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
173                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
174                                 }
175                         }
176                         ast_mutex_unlock(&pgsql_lock);
177                         PQclear(result);
178                         return -1;
179                 }
180                 PQclear(result);
181         }
182         ast_mutex_unlock(&pgsql_lock);
183         return 0;
184 }
185
186 static int unload_module(void)
187
188         PQfinish(conn);
189         if (pghostname)
190                 ast_free(pghostname);
191         if (pgdbname)
192                 ast_free(pgdbname);
193         if (pgdbuser)
194                 ast_free(pgdbuser);
195         if (pgpassword)
196                 ast_free(pgpassword);
197         if (pgdbport)
198                 ast_free(pgdbport);
199         if (table)
200                 ast_free(table);
201         ast_cdr_unregister(name);
202         return 0;
203 }
204
205 static int config_module(int reload)
206 {
207         struct ast_variable *var;
208         char *pgerror;
209         const char *tmp;
210         struct ast_config *cfg;
211         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
212
213         if ((cfg = ast_config_load(config, config_flags)) == NULL) {
214                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
215                 return -1;
216         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
217                 return 0;
218
219         if (!(var = ast_variable_browse(cfg, "global")))
220                 return 0;
221
222         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
223                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
224                 tmp = "";       /* connect via UNIX-socket by default */
225         }
226
227         if (pghostname)
228                 ast_free(pghostname);
229         if (!(pghostname = ast_strdup(tmp)))
230                 return -1;
231
232         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
233                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
234                 tmp = "asteriskcdrdb";
235         }
236
237         if (pgdbname)
238                 ast_free(pgdbname);
239         if (!(pgdbname = ast_strdup(tmp)))
240                 return -1;
241
242         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
243                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
244                 tmp = "asterisk";
245         }
246
247         if (pgdbuser)
248                 ast_free(pgdbuser);
249         if (!(pgdbuser = ast_strdup(tmp)))
250                 return -1;
251
252         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
253                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
254                 tmp = "";
255         }
256
257         if (pgpassword)
258                 ast_free(pgpassword);
259         if (!(pgpassword = ast_strdup(tmp)))
260                 return -1;
261
262         if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
263                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
264                 tmp = "5432";
265         }
266
267         if (pgdbport)
268                 ast_free(pgdbport);
269         if (!(pgdbport = ast_strdup(tmp)))
270                 return -1;
271
272         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
273                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
274                 tmp = "cdr";
275         }
276
277         if (table)
278                 ast_free(table);
279         if (!(table = ast_strdup(tmp)))
280                 return -1;
281
282         if (option_debug) {
283                 if (ast_strlen_zero(pghostname))
284                         ast_debug(1, "cdr_pgsql: using default unix socket\n");
285                 else
286                         ast_debug(1, "cdr_pgsql: got hostname of %s\n", pghostname);
287                         ast_debug(1, "cdr_pgsql: got port of %s\n", pgdbport);
288                         ast_debug(1, "cdr_pgsql: got user of %s\n", pgdbuser);
289                         ast_debug(1, "cdr_pgsql: got dbname of %s\n", pgdbname);
290                         ast_debug(1, "cdr_pgsql: got password of %s\n", pgpassword);
291                         ast_debug(1, "cdr_pgsql: got sql table name of %s\n", table);
292         }
293         
294         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
295         if (PQstatus(conn) != CONNECTION_BAD) {
296                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
297                 connected = 1;
298         } else {
299                 pgerror = PQerrorMessage(conn);
300                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
301                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
302                 connected = 0;
303         }
304
305         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
306 }
307
308 static int load_module(void)
309 {
310         return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
311 }
312
313 static int reload(void)
314 {
315         return config_module(1);
316 }
317
318 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
319                 .load = load_module,
320                 .unload = unload_module,
321                 .reload = reload,
322                );