eea4416a5c952d10c8761946368f6d6abdf3d46c
[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 <time.h>
45
46 #include <libpq-fe.h>
47
48 #include "asterisk/config.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/cdr.h"
51 #include "asterisk/module.h"
52
53 #define DATE_FORMAT "%Y-%m-%d %T"
54
55 static char *name = "pgsql";
56 static char *config = "cdr_pgsql.conf";
57 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
58 static int connected = 0;
59
60 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
61
62 static PGconn   *conn = NULL;
63
64 static int pgsql_log(struct ast_cdr *cdr)
65 {
66         struct ast_tm tm;
67         char sqlcmd[2048] = "", timestr[128];
68         char *pgerror;
69         PGresult *result;
70
71         ast_mutex_lock(&pgsql_lock);
72
73         ast_localtime(&cdr->start, &tm, NULL);
74         ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
75
76         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
77                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
78                 if (PQstatus(conn) != CONNECTION_BAD) {
79                         connected = 1;
80                 } else {
81                         pgerror = PQerrorMessage(conn);
82                         ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
83                         ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
84                         PQfinish(conn);
85                         conn = NULL;
86                 }
87         }
88
89         if (connected) {
90                 char *clid=NULL, *dcontext=NULL, *channel=NULL, *dstchannel=NULL, *lastapp=NULL, *lastdata=NULL;
91                 char *src=NULL, *dst=NULL, *uniqueid=NULL, *userfield=NULL;
92                 int pgerr;
93
94                 /* Maximum space needed would be if all characters needed to be escaped, plus a trailing NULL */
95                 if ((clid = alloca(strlen(cdr->clid) * 2 + 1)) != NULL)
96                         PQescapeStringConn(conn, clid, cdr->clid, strlen(cdr->clid), &pgerr);
97                 if ((dcontext = alloca(strlen(cdr->dcontext) * 2 + 1)) != NULL)
98                         PQescapeStringConn(conn, dcontext, cdr->dcontext, strlen(cdr->dcontext), &pgerr);
99                 if ((channel = alloca(strlen(cdr->channel) * 2 + 1)) != NULL)
100                         PQescapeStringConn(conn, channel, cdr->channel, strlen(cdr->channel), &pgerr);
101                 if ((dstchannel = alloca(strlen(cdr->dstchannel) * 2 + 1)) != NULL)
102                         PQescapeStringConn(conn, dstchannel, cdr->dstchannel, strlen(cdr->dstchannel), &pgerr);
103                 if ((lastapp = alloca(strlen(cdr->lastapp) * 2 + 1)) != NULL)
104                         PQescapeStringConn(conn, lastapp, cdr->lastapp, strlen(cdr->lastapp), &pgerr);
105                 if ((lastdata = alloca(strlen(cdr->lastdata) * 2 + 1)) != NULL)
106                         PQescapeStringConn(conn, lastdata, cdr->lastdata, strlen(cdr->lastdata), &pgerr);
107                 if ((uniqueid = alloca(strlen(cdr->uniqueid) * 2 + 1)) != NULL)
108                         PQescapeStringConn(conn, uniqueid, cdr->uniqueid, strlen(cdr->uniqueid), &pgerr);
109                 if ((userfield = alloca(strlen(cdr->userfield) * 2 + 1)) != NULL)
110                         PQescapeStringConn(conn, userfield, cdr->userfield, strlen(cdr->userfield), &pgerr);
111                 if ((src = alloca(strlen(cdr->src) * 2 + 1)) != NULL)
112                         PQescapeStringConn(conn, src, cdr->src, strlen(cdr->src), &pgerr);
113                 if ((dst = alloca(strlen(cdr->dst) * 2 + 1)) != NULL)
114                         PQescapeStringConn(conn, dst, cdr->dst, strlen(cdr->dst), &pgerr);
115
116                 /* Check for all alloca failures above at once */
117                 if ((!clid) || (!dcontext) || (!channel) || (!dstchannel) || (!lastapp) || (!lastdata) || (!uniqueid) || (!userfield) || (!src) || (!dst)) {
118                         ast_log(LOG_ERROR, "cdr_pgsql:  Out of memory error (insert fails)\n");
119                         ast_mutex_unlock(&pgsql_lock);
120                         return -1;
121                 }
122
123                 ast_debug(2, "cdr_pgsql: inserting a CDR record.\n");
124
125                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s (calldate,clid,src,dst,dcontext,channel,dstchannel,"
126                                  "lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES"
127                                  " ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%ld,%ld,'%s',%ld,'%s','%s','%s')",
128                                  table, timestr, clid, src, dst, dcontext, channel, dstchannel, lastapp, lastdata,
129                                  cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
130                 
131                 ast_debug(3, "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                                 PQfinish(conn);
149                                 conn = NULL;
150                                 connected = 0;
151                                 ast_mutex_unlock(&pgsql_lock);
152                                 return -1;
153                         }
154                 }
155                 result = PQexec(conn, sqlcmd);
156                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
157                         pgerror = PQresultErrorMessage(result);
158                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
159                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
160                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
161                         PQreset(conn);
162                         if (PQstatus(conn) == CONNECTION_OK) {
163                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
164                                 connected = 1;
165                                 PQclear(result);
166                                 result = PQexec(conn, sqlcmd);
167                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
168                                         pgerror = PQresultErrorMessage(result);
169                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
170                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
171                                 }
172                         }
173                         ast_mutex_unlock(&pgsql_lock);
174                         PQclear(result);
175                         return -1;
176                 }
177                 PQclear(result);
178         }
179         ast_mutex_unlock(&pgsql_lock);
180         return 0;
181 }
182
183 static int unload_module(void)
184
185         PQfinish(conn);
186         if (pghostname)
187                 ast_free(pghostname);
188         if (pgdbname)
189                 ast_free(pgdbname);
190         if (pgdbuser)
191                 ast_free(pgdbuser);
192         if (pgpassword)
193                 ast_free(pgpassword);
194         if (pgdbport)
195                 ast_free(pgdbport);
196         if (table)
197                 ast_free(table);
198         ast_cdr_unregister(name);
199         return 0;
200 }
201
202 static int config_module(int reload)
203 {
204         struct ast_variable *var;
205         char *pgerror;
206         const char *tmp;
207         struct ast_config *cfg;
208         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
209
210         if ((cfg = ast_config_load(config, config_flags)) == NULL) {
211                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
212                 return -1;
213         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
214                 return 0;
215
216         if (!(var = ast_variable_browse(cfg, "global"))) {
217                 ast_config_destroy(cfg);
218                 return 0;
219         }
220
221         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
222                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
223                 tmp = "";       /* connect via UNIX-socket by default */
224         }
225
226         if (pghostname)
227                 ast_free(pghostname);
228         if (!(pghostname = ast_strdup(tmp))) {
229                 ast_config_destroy(cfg);
230                 return -1;
231         }
232
233         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
234                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
235                 tmp = "asteriskcdrdb";
236         }
237
238         if (pgdbname)
239                 ast_free(pgdbname);
240         if (!(pgdbname = ast_strdup(tmp))) {
241                 ast_config_destroy(cfg);
242                 return -1;
243         }
244
245         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
246                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
247                 tmp = "asterisk";
248         }
249
250         if (pgdbuser)
251                 ast_free(pgdbuser);
252         if (!(pgdbuser = ast_strdup(tmp))) {
253                 ast_config_destroy(cfg);
254                 return -1;
255         }
256
257         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
258                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
259                 tmp = "";
260         }
261
262         if (pgpassword)
263                 ast_free(pgpassword);
264         if (!(pgpassword = ast_strdup(tmp))) {
265                 ast_config_destroy(cfg);
266                 return -1;
267         }
268
269         if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
270                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
271                 tmp = "5432";
272         }
273
274         if (pgdbport)
275                 ast_free(pgdbport);
276         if (!(pgdbport = ast_strdup(tmp))) {
277                 ast_config_destroy(cfg);
278                 return -1;
279         }
280
281         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
282                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
283                 tmp = "cdr";
284         }
285
286         if (table)
287                 ast_free(table);
288         if (!(table = ast_strdup(tmp))) {
289                 ast_config_destroy(cfg);
290                 return -1;
291         }
292
293         if (option_debug) {
294                 if (ast_strlen_zero(pghostname))
295                         ast_debug(1, "cdr_pgsql: using default unix socket\n");
296                 else
297                         ast_debug(1, "cdr_pgsql: got hostname of %s\n", pghostname);
298                         ast_debug(1, "cdr_pgsql: got port of %s\n", pgdbport);
299                         ast_debug(1, "cdr_pgsql: got user of %s\n", pgdbuser);
300                         ast_debug(1, "cdr_pgsql: got dbname of %s\n", pgdbname);
301                         ast_debug(1, "cdr_pgsql: got password of %s\n", pgpassword);
302                         ast_debug(1, "cdr_pgsql: got sql table name of %s\n", table);
303         }
304         
305         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
306         if (PQstatus(conn) != CONNECTION_BAD) {
307                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
308                 connected = 1;
309         } else {
310                 pgerror = PQerrorMessage(conn);
311                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
312                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
313                 connected = 0;
314         }
315
316         ast_config_destroy(cfg);
317
318         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
319 }
320
321 static int load_module(void)
322 {
323         return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
324 }
325
326 static int reload(void)
327 {
328         return config_module(1);
329 }
330
331 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
332                 .load = load_module,
333                 .unload = unload_module,
334                 .reload = reload,
335                );