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