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