if a hostname is not specified, connect over a unix socket instead of
[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, *pgdbsock = 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 (pgdbsock)
199                 free(pgdbsock);
200         if (pgpassword)
201                 free(pgpassword);
202         if (pgdbport)
203                 free(pgdbport);
204         if (table)
205                 free(table);
206         ast_cdr_unregister(name);
207         return 0;
208 }
209
210 static int process_my_load_module(struct ast_config *cfg)
211 {
212         int res;
213         struct ast_variable *var;
214         char *pgerror;
215         char *tmp;
216
217         var = ast_variable_browse(cfg, "global");
218         if (!var) {
219                 /* nothing configured */
220                 return 0;
221         }
222
223         tmp = ast_variable_retrieve(cfg,"global","hostname");
224         if (tmp == NULL) {
225                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
226                 tmp = "";       /* connect via UNIX-socket by default */
227         }
228         pghostname = strdup(tmp);
229         if (pghostname == NULL) {
230                 ast_log(LOG_ERROR,"Out of memory error.\n");
231                 return -1;
232         }
233
234         tmp = ast_variable_retrieve(cfg,"global","dbname");
235         if (tmp == NULL) {
236                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
237                 tmp = "asteriskcdrdb";
238         }
239         pgdbname = strdup(tmp);
240         if (pgdbname == NULL) {
241                 ast_log(LOG_ERROR,"Out of memory error.\n");
242                 return -1;
243         }
244
245         tmp = ast_variable_retrieve(cfg,"global","user");
246         if (tmp == NULL) {
247                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming root\n");
248                 tmp = "root";
249         }
250         pgdbuser = strdup(tmp);
251         if (pgdbuser == NULL) {
252                 ast_log(LOG_ERROR,"Out of memory error.\n");
253                 return -1;
254         }
255
256         tmp = ast_variable_retrieve(cfg,"global","password");
257         if (tmp == NULL) {
258                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
259                 tmp = "";
260         }
261         pgpassword = strdup(tmp);
262         if (pgpassword == NULL) {
263                 ast_log(LOG_ERROR,"Out of memory error.\n");
264                 return -1;
265         }
266
267         tmp = ast_variable_retrieve(cfg,"global","port");
268         if (tmp == NULL) {
269                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
270                 tmp = "5432";
271         }
272         pgdbport = strdup(tmp);
273         if (pgdbport == NULL) {
274                 ast_log(LOG_ERROR,"Out of memory error.\n");
275                 return -1;
276         }
277
278         tmp = ast_variable_retrieve(cfg,"global","table");
279         if (tmp == NULL) {
280                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
281                 tmp = "cdr";
282         }
283         table = strdup(tmp);
284         if (table == NULL) {
285                 ast_log(LOG_ERROR,"Out of memory error.\n");
286                 return -1;
287         }
288
289         if (option_debug) {
290                 if (ast_strlen_zero(pghostname))
291                         ast_log(LOG_DEBUG, "cdr_pgsql: using default unix socket\n");
292                 else
293                         ast_log(LOG_DEBUG, "cdr_pgsql: got hostname of %s\n", pghostname);
294                 ast_log(LOG_DEBUG, "cdr_pgsql: got port of %s\n", pgdbport);
295                 ast_log(LOG_DEBUG, "cdr_pgsql: got user of %s\n", pgdbuser);
296                 ast_log(LOG_DEBUG, "cdr_pgsql: got dbname of %s\n", pgdbname);
297                 ast_log(LOG_DEBUG, "cdr_pgsql: got password of %s\n", pgpassword);
298                 ast_log(LOG_DEBUG, "cdr_pgsql: got sql table name of %s\n", table);
299         }
300         
301         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
302         if (PQstatus(conn) != CONNECTION_BAD) {
303                 if (option_debug)
304                         ast_log(LOG_DEBUG, "Successfully connected to PostgreSQL database.\n");
305                 connected = 1;
306         } else {
307                 pgerror = PQerrorMessage(conn);
308                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
309                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
310                 connected = 0;
311         }
312
313         res = ast_cdr_register(name, desc, pgsql_log);
314         if (res) {
315                 ast_log(LOG_ERROR, "Unable to register PGSQL CDR handling\n");
316         }
317         return res;
318 }
319
320 static int my_load_module(void)
321 {
322         struct ast_config *cfg;
323         int res;
324         cfg = ast_config_load(config);
325         if (!cfg) {
326                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
327                 return 0;
328         }
329         res = process_my_load_module(cfg);
330         ast_config_destroy(cfg);
331         return res;
332 }
333
334 static int load_module(void *mod)
335 {
336         return my_load_module();
337 }
338
339 static int unload_module(void *mod)
340 {
341         return my_unload_module();
342 }
343
344 static int reload(void *mod)
345 {
346         my_unload_module();
347         return my_load_module();
348 }
349
350 static const char *key(void)
351 {
352         return ASTERISK_GPL_KEY;
353 }
354
355 STD_MOD(MOD_0, reload, NULL, NULL);