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