use auto-build for cdr modules
[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 #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 static PGconn   *conn;
68 static 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                 if (option_debug > 1)
122                         ast_log(LOG_DEBUG, "cdr_pgsql: inserting a CDR record.\n");
123
124                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s (calldate,clid,src,dst,dcontext,channel,dstchannel,"
125                                  "lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES"
126                                  " ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%d,%d,'%s',%d,'%s','%s','%s')",
127                                  table,timestr,clid,cdr->src, cdr->dst, dcontext,channel, dstchannel, lastapp, lastdata,
128                                  cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
129                 
130                 if (option_debug > 2)
131                         ast_log(LOG_DEBUG, "cdr_pgsql: SQL command executed:  %s\n",sqlcmd);
132                 
133                 /* Test to be sure we're still connected... */
134                 /* If we're connected, and connection is working, good. */
135                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
136                 if (PQstatus(conn) == CONNECTION_OK) {
137                         connected = 1;
138                 } else {
139                         ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
140                         PQreset(conn);
141                         if (PQstatus(conn) == CONNECTION_OK) {
142                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
143                                 connected = 1;
144                         } else {
145                                 pgerror = PQerrorMessage(conn);
146                                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
147                                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
148                                 connected = 0;
149                                 ast_mutex_unlock(&pgsql_lock);
150                                 return -1;
151                         }
152                 }
153                 result = PQexec(conn, sqlcmd);
154                 if ( PQresultStatus(result) != PGRES_COMMAND_OK) {
155                         pgerror = PQresultErrorMessage(result);
156                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
157                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
158                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
159                         PQreset(conn);
160                         if (PQstatus(conn) == CONNECTION_OK) {
161                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
162                                 connected = 1;
163                                 result = PQexec(conn, sqlcmd);
164                                 if ( PQresultStatus(result) != PGRES_COMMAND_OK)
165                                 {
166                                         pgerror = PQresultErrorMessage(result);
167                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
168                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
169                                 }
170                         }
171                         ast_mutex_unlock(&pgsql_lock);
172                         return -1;
173                 }
174         }
175         ast_mutex_unlock(&pgsql_lock);
176         return 0;
177 }
178
179 char *description(void)
180 {
181         return desc;
182 }
183
184 static int my_unload_module(void)
185
186         if (conn)
187                 PQfinish(conn);
188         if (pghostname)
189                 free(pghostname);
190         if (pgdbname)
191                 free(pgdbname);
192         if (pgdbuser)
193                 free(pgdbuser);
194         if (pgdbsock)
195                 free(pgdbsock);
196         if (pgpassword)
197                 free(pgpassword);
198         if (pgdbport)
199                 free(pgdbport);
200         if (table)
201                 free(table);
202         ast_cdr_unregister(name);
203         return 0;
204 }
205
206 static int process_my_load_module(struct ast_config *cfg)
207 {
208         int res;
209         struct ast_variable *var;
210         char *pgerror;
211         char *tmp;
212
213         var = ast_variable_browse(cfg, "global");
214         if (!var) {
215                 /* nothing configured */
216                 return 0;
217         }
218
219         tmp = ast_variable_retrieve(cfg,"global","hostname");
220         if (tmp == NULL) {
221                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming localhost\n");
222                 tmp = "localhost";
223         }
224         pghostname = strdup(tmp);
225         if (pghostname == NULL) {
226                 ast_log(LOG_ERROR,"Out of memory error.\n");
227                 return -1;
228         }
229
230         tmp = ast_variable_retrieve(cfg,"global","dbname");
231         if (tmp == NULL) {
232                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
233                 tmp = "asteriskcdrdb";
234         }
235         pgdbname = strdup(tmp);
236         if (pgdbname == NULL) {
237                 ast_log(LOG_ERROR,"Out of memory error.\n");
238                 return -1;
239         }
240
241         tmp = ast_variable_retrieve(cfg,"global","user");
242         if (tmp == NULL) {
243                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming root\n");
244                 tmp = "root";
245         }
246         pgdbuser = strdup(tmp);
247         if (pgdbuser == NULL) {
248                 ast_log(LOG_ERROR,"Out of memory error.\n");
249                 return -1;
250         }
251
252         tmp = ast_variable_retrieve(cfg,"global","password");
253         if (tmp == NULL) {
254                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
255                 tmp = "";
256         }
257         pgpassword = strdup(tmp);
258         if (pgpassword == NULL) {
259                 ast_log(LOG_ERROR,"Out of memory error.\n");
260                 return -1;
261         }
262
263         tmp = ast_variable_retrieve(cfg,"global","port");
264         if (tmp == NULL) {
265                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
266                 tmp = "5432";
267         }
268         pgdbport = strdup(tmp);
269         if (pgdbport == NULL) {
270                 ast_log(LOG_ERROR,"Out of memory error.\n");
271                 return -1;
272         }
273
274         tmp = ast_variable_retrieve(cfg,"global","table");
275         if (tmp == NULL) {
276                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
277                 tmp = "cdr";
278         }
279         table = strdup(tmp);
280         if (table == NULL) {
281                 ast_log(LOG_ERROR,"Out of memory error.\n");
282                 return -1;
283         }
284
285         if (option_debug) {
286                 ast_log(LOG_DEBUG, "cdr_pgsql: got hostname of %s\n", pghostname);
287                 ast_log(LOG_DEBUG, "cdr_pgsql: got port of %s\n", pgdbport);
288                 if (pgdbsock)
289                         ast_log(LOG_DEBUG, "cdr_pgsql: got sock file of %s\n", pgdbsock);
290                 ast_log(LOG_DEBUG, "cdr_pgsql: got user of %s\n", pgdbuser);
291                 ast_log(LOG_DEBUG, "cdr_pgsql: got dbname of %s\n", pgdbname);
292                 ast_log(LOG_DEBUG, "cdr_pgsql: got password of %s\n", pgpassword);
293                 ast_log(LOG_DEBUG, "cdr_pgsql: got sql table name of %s\n", table);
294         }
295         
296         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
297         if (PQstatus(conn) != CONNECTION_BAD) {
298                 if (option_debug)
299                         ast_log(LOG_DEBUG, "Successfully connected to PostgreSQL database.\n");
300                 connected = 1;
301         } else {
302                 pgerror = PQerrorMessage(conn);
303                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
304                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
305                 connected = 0;
306         }
307
308         res = ast_cdr_register(name, desc, pgsql_log);
309         if (res) {
310                 ast_log(LOG_ERROR, "Unable to register PGSQL CDR handling\n");
311         }
312         return res;
313 }
314
315 static int my_load_module(void)
316 {
317         struct ast_config *cfg;
318         int res;
319         cfg = ast_config_load(config);
320         if (!cfg) {
321                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
322                 return 0;
323         }
324         res = process_my_load_module(cfg);
325         ast_config_destroy(cfg);
326         return res;
327 }
328
329 int load_module(void)
330 {
331         return my_load_module();
332 }
333
334 int unload_module(void)
335 {
336         return my_unload_module();
337 }
338
339 int reload(void)
340 {
341         my_unload_module();
342         return my_load_module();
343 }
344
345 int usecount(void)
346 {
347         /* To be able to unload the module */
348         if ( ast_mutex_trylock(&pgsql_lock) ) {
349                 return 1;
350         } else {
351                 ast_mutex_unlock(&pgsql_lock);
352                 return 0;
353         }
354 }
355
356 char *key()
357 {
358         return ASTERISK_GPL_KEY;
359 }