2379d772811ac0402c09e870b1aa841f00cc310d
[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  * \extref PostgreSQL http://www.postgresql.org/
29  *
30  * See also
31  * \arg \ref Config_cdr
32  * \arg http://www.postgresql.org/
33  * \ingroup cdr_drivers
34  */
35
36 /*** MODULEINFO
37         <depend>pgsql</depend>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include <sys/types.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 #include <time.h>
50
51 #include <libpq-fe.h>
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 *name = "pgsql";
64 static char *config = "cdr_pgsql.conf";
65 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
66 static int connected = 0;
67
68 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
69
70 static PGconn   *conn = NULL;
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         PGresult *result;
78
79         ast_mutex_lock(&pgsql_lock);
80
81         ast_localtime(&cdr->start.tv_sec, &tm, NULL);
82         strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
83
84         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
85                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
86                 if (PQstatus(conn) != CONNECTION_BAD) {
87                         connected = 1;
88                 } else {
89                         pgerror = PQerrorMessage(conn);
90                         PQfinish(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                 ast_debug(2, "cdr_pgsql: inserting a CDR record.\n");
126
127                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s (calldate,clid,src,dst,dcontext,channel,dstchannel,"
128                                  "lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES"
129                                  " ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%ld,%ld,'%s',%ld,'%s','%s','%s')",
130                                  table,timestr,clid,cdr->src, cdr->dst, dcontext,channel, dstchannel, lastapp, lastdata,
131                                  cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
132                 
133                 ast_debug(3, "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                                 PQfinish(conn);
149                                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
150                                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
151                                 connected = 0;
152                                 ast_mutex_unlock(&pgsql_lock);
153                                 return -1;
154                         }
155                 }
156                 result = PQexec(conn, sqlcmd);
157                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
158                         pgerror = PQresultErrorMessage(result);
159                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
160                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
161                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
162                         PQreset(conn);
163                         if (PQstatus(conn) == CONNECTION_OK) {
164                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
165                                 connected = 1;
166                                 PQclear(result);
167                                 result = PQexec(conn, sqlcmd);
168                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
169                                         pgerror = PQresultErrorMessage(result);
170                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
171                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
172                                 }
173                         }
174                         ast_mutex_unlock(&pgsql_lock);
175                         PQclear(result);
176                         return -1;
177                 }
178                 PQclear(result);
179         }
180         ast_mutex_unlock(&pgsql_lock);
181         return 0;
182 }
183
184 static int my_unload_module(void)
185
186         if (conn)
187                 PQfinish(conn);
188         if (pghostname)
189                 ast_free(pghostname);
190         if (pgdbname)
191                 ast_free(pgdbname);
192         if (pgdbuser)
193                 ast_free(pgdbuser);
194         if (pgpassword)
195                 ast_free(pgpassword);
196         if (pgdbport)
197                 ast_free(pgdbport);
198         if (table)
199                 ast_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         struct ast_variable *var;
207         char *pgerror;
208         const char *tmp;
209
210         if (!(var = ast_variable_browse(cfg, "global")))
211                 return 0;
212
213         if (!(tmp = ast_variable_retrieve(cfg,"global","hostname"))) {
214                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
215                 tmp = "";       /* connect via UNIX-socket by default */
216         }
217         
218         if (!(pghostname = ast_strdup(tmp)))
219                 return -1;
220
221         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
222                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
223                 tmp = "asteriskcdrdb";
224         }
225
226         if (!(pgdbname = ast_strdup(tmp)))
227                 return -1;
228
229         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
230                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
231                 tmp = "asterisk";
232         }
233
234         if (!(pgdbuser = ast_strdup(tmp)))
235                 return -1;
236
237         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
238                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
239                 tmp = "";
240         }
241
242         if (!(pgpassword = ast_strdup(tmp)))
243                 return -1;
244
245         if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
246                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
247                 tmp = "5432";
248         }
249
250         if (!(pgdbport = ast_strdup(tmp)))
251                 return -1;
252
253         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
254                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
255                 tmp = "cdr";
256         }
257
258         if (!(table = ast_strdup(tmp)))
259                 return -1;
260
261         if (option_debug) {
262                 if (ast_strlen_zero(pghostname))
263                         ast_debug(1, "cdr_pgsql: using default unix socket\n");
264                 else
265                         ast_debug(1, "cdr_pgsql: got hostname of %s\n", pghostname);
266                         ast_debug(1, "cdr_pgsql: got port of %s\n", pgdbport);
267                         ast_debug(1, "cdr_pgsql: got user of %s\n", pgdbuser);
268                         ast_debug(1, "cdr_pgsql: got dbname of %s\n", pgdbname);
269                         ast_debug(1, "cdr_pgsql: got password of %s\n", pgpassword);
270                         ast_debug(1, "cdr_pgsql: got sql table name of %s\n", table);
271         }
272         
273         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
274         if (PQstatus(conn) != CONNECTION_BAD) {
275                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
276                 connected = 1;
277         } else {
278                 pgerror = PQerrorMessage(conn);
279                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
280                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
281                 connected = 0;
282         }
283
284         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
285 }
286
287 static int my_load_module(void)
288 {
289         struct ast_config *cfg;
290         int res;
291
292         if (!(cfg = ast_config_load(config))) {
293                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
294                 return AST_MODULE_LOAD_DECLINE;
295         }
296
297         res = process_my_load_module(cfg);
298         ast_config_destroy(cfg);
299
300         return res;
301 }
302
303 static int load_module(void)
304 {
305         return my_load_module();
306 }
307
308 static int unload_module(void)
309 {
310         return my_unload_module();
311 }
312
313 static int reload(void)
314 {
315         int res;
316         ast_mutex_lock(&pgsql_lock);
317         my_unload_module();
318         res = my_load_module();
319         ast_mutex_unlock(&pgsql_lock);
320         return res;
321 }
322
323 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
324                 .load = load_module,
325                 .unload = unload_module,
326                 .reload = reload,
327                );