more license/copyright header updates (thanks Ian!)
[asterisk/asterisk.git] / cdr / cdr_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003 - 2005
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 /*
24  *
25  * PostgreSQL CDR logger 
26  *
27  */
28
29 #include <sys/types.h>
30 #include <stdio.h>
31 #include <string.h>
32
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <time.h>
36
37 #include <libpq-fe.h>
38
39 #include "asterisk.h"
40
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include "asterisk/config.h"
44 #include "asterisk/options.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/cdr.h"
47 #include "asterisk/module.h"
48 #include "asterisk/logger.h"
49 #include "asterisk.h"
50
51 #define DATE_FORMAT "%Y-%m-%d %T"
52
53 static char *desc = "PostgreSQL CDR Backend";
54 static char *name = "pgsql";
55 static char *config = "cdr_pgsql.conf";
56 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbsock = NULL, *pgdbport = NULL, *table = NULL;
57 static int connected = 0;
58
59 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
60
61 PGconn          *conn;
62 PGresult        *result;
63
64 static int pgsql_log(struct ast_cdr *cdr)
65 {
66         struct tm tm;
67         char sqlcmd[2048] = "", timestr[128];
68         char *pgerror;
69
70         ast_mutex_lock(&pgsql_lock);
71
72         localtime_r(&cdr->start.tv_sec,&tm);
73         strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
74
75         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
76                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
77                 if (PQstatus(conn) != CONNECTION_BAD) {
78                         connected = 1;
79                 } else {
80                         pgerror = PQerrorMessage(conn);
81                         ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
82                         ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
83                 }
84         }
85
86         if (connected) {
87                 char *clid=NULL, *dcontext=NULL, *channel=NULL, *dstchannel=NULL, *lastapp=NULL, *lastdata=NULL;
88                 char *uniqueid=NULL, *userfield=NULL;
89
90                 /* Maximum space needed would be if all characters needed to be escaped, plus a trailing NULL */
91                 if ((clid = alloca(strlen(cdr->clid) * 2 + 1)) != NULL)
92                         PQescapeString(clid, cdr->clid, strlen(cdr->clid));
93                 if ((dcontext = alloca(strlen(cdr->dcontext) * 2 + 1)) != NULL)
94                         PQescapeString(dcontext, cdr->dcontext, strlen(cdr->dcontext));
95                 if ((channel = alloca(strlen(cdr->channel) * 2 + 1)) != NULL)
96                         PQescapeString(channel, cdr->channel, strlen(cdr->channel));
97                 if ((dstchannel = alloca(strlen(cdr->dstchannel) * 2 + 1)) != NULL)
98                         PQescapeString(dstchannel, cdr->dstchannel, strlen(cdr->dstchannel));
99                 if ((lastapp = alloca(strlen(cdr->lastapp) * 2 + 1)) != NULL)
100                         PQescapeString(lastapp, cdr->lastapp, strlen(cdr->lastapp));
101                 if ((lastdata = alloca(strlen(cdr->lastdata) * 2 + 1)) != NULL)
102                         PQescapeString(lastdata, cdr->lastdata, strlen(cdr->lastdata));
103                 if ((uniqueid = alloca(strlen(cdr->uniqueid) * 2 + 1)) != NULL)
104                         PQescapeString(uniqueid, cdr->uniqueid, strlen(cdr->uniqueid));
105                 if ((userfield = alloca(strlen(cdr->userfield) * 2 + 1)) != NULL)
106                         PQescapeString(userfield, cdr->userfield, strlen(cdr->userfield));
107
108                 /* Check for all alloca failures above at once */
109                 if ((!clid) || (!dcontext) || (!channel) || (!dstchannel) || (!lastapp) || (!lastdata) || (!uniqueid) || (!userfield)) {
110                         ast_log(LOG_ERROR, "cdr_pgsql:  Out of memory error (insert fails)\n");
111                         ast_mutex_unlock(&pgsql_lock);
112                         return -1;
113                 }
114
115                 ast_log(LOG_DEBUG,"cdr_pgsql: inserting a CDR record.\n");
116
117                 snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s (calldate,clid,src,dst,dcontext,channel,dstchannel,"
118                                  "lastapp,lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) VALUES"
119                                  " ('%s','%s','%s','%s','%s', '%s','%s','%s','%s',%d,%d,'%s',%d,'%s','%s','%s')",
120                                  table,timestr,clid,cdr->src, cdr->dst, dcontext,channel, dstchannel, lastapp, lastdata,
121                                  cdr->duration,cdr->billsec,ast_cdr_disp2str(cdr->disposition),cdr->amaflags, cdr->accountcode, uniqueid, userfield);
122                 
123                 ast_log(LOG_DEBUG,"cdr_pgsql: SQL command executed:  %s\n",sqlcmd);
124                 
125                 /* Test to be sure we're still connected... */
126                 /* If we're connected, and connection is working, good. */
127                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
128                 if (PQstatus(conn) == CONNECTION_OK) {
129                         connected = 1;
130                 } else {
131                         ast_log(LOG_ERROR, "cdr_pgsql: Connection was lost... attempting to reconnect.\n");
132                         PQreset(conn);
133                         if (PQstatus(conn) == CONNECTION_OK) {
134                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
135                                 connected = 1;
136                         } else {
137                                 pgerror = PQerrorMessage(conn);
138                                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
139                                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
140                                 connected = 0;
141                                 ast_mutex_unlock(&pgsql_lock);
142                                 return -1;
143                         }
144                 }
145                 result = PQexec(conn, sqlcmd);
146                 if ( PQresultStatus(result) != PGRES_COMMAND_OK) {
147                         pgerror = PQresultErrorMessage(result);
148                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
149                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
150                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
151                         PQreset(conn);
152                         if (PQstatus(conn) == CONNECTION_OK) {
153                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
154                                 connected = 1;
155                                 result = PQexec(conn, sqlcmd);
156                                 if ( PQresultStatus(result) != PGRES_COMMAND_OK)
157                                 {
158                                         pgerror = PQresultErrorMessage(result);
159                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
160                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
161                                 }
162                         }
163                         ast_mutex_unlock(&pgsql_lock);
164                         return -1;
165                 }
166         }
167         ast_mutex_unlock(&pgsql_lock);
168         return 0;
169 }
170
171 char *description(void)
172 {
173         return desc;
174 }
175
176 static int my_unload_module(void)
177
178         if (conn)
179                 PQfinish(conn);
180         if (pghostname)
181                 free(pghostname);
182         if (pgdbname)
183                 free(pgdbname);
184         if (pgdbuser)
185                 free(pgdbuser);
186         if (pgdbsock)
187                 free(pgdbsock);
188         if (pgpassword)
189                 free(pgpassword);
190         if (pgdbport)
191                 free(pgdbport);
192         if (table)
193                 free(table);
194         ast_cdr_unregister(name);
195         return 0;
196 }
197
198 static int process_my_load_module(struct ast_config *cfg)
199 {
200         int res;
201         struct ast_variable *var;
202         char *pgerror;
203         char *tmp;
204
205         var = ast_variable_browse(cfg, "global");
206         if (!var) {
207                 /* nothing configured */
208                 return 0;
209         }
210
211         tmp = ast_variable_retrieve(cfg,"global","hostname");
212         if (tmp == NULL) {
213                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming localhost\n");
214                 tmp = "localhost";
215         }
216         pghostname = strdup(tmp);
217         if (pghostname == NULL) {
218                 ast_log(LOG_ERROR,"Out of memory error.\n");
219                 return -1;
220         }
221
222         tmp = ast_variable_retrieve(cfg,"global","dbname");
223         if (tmp == NULL) {
224                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
225                 tmp = "asteriskcdrdb";
226         }
227         pgdbname = strdup(tmp);
228         if (pgdbname == NULL) {
229                 ast_log(LOG_ERROR,"Out of memory error.\n");
230                 return -1;
231         }
232
233         tmp = ast_variable_retrieve(cfg,"global","user");
234         if (tmp == NULL) {
235                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming root\n");
236                 tmp = "root";
237         }
238         pgdbuser = strdup(tmp);
239         if (pgdbuser == NULL) {
240                 ast_log(LOG_ERROR,"Out of memory error.\n");
241                 return -1;
242         }
243
244         tmp = ast_variable_retrieve(cfg,"global","password");
245         if (tmp == NULL) {
246                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
247                 tmp = "";
248         }
249         pgpassword = strdup(tmp);
250         if (pgpassword == NULL) {
251                 ast_log(LOG_ERROR,"Out of memory error.\n");
252                 return -1;
253         }
254
255         tmp = ast_variable_retrieve(cfg,"global","port");
256         if (tmp == NULL) {
257                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
258                 tmp = "5432";
259         }
260         pgdbport = strdup(tmp);
261         if (pgdbport == NULL) {
262                 ast_log(LOG_ERROR,"Out of memory error.\n");
263                 return -1;
264         }
265
266         tmp = ast_variable_retrieve(cfg,"global","table");
267         if (tmp == NULL) {
268                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
269                 tmp = "cdr";
270         }
271         table = strdup(tmp);
272         if (table == NULL) {
273                 ast_log(LOG_ERROR,"Out of memory error.\n");
274                 return -1;
275         }
276
277         ast_log(LOG_DEBUG,"cdr_pgsql: got hostname of %s\n",pghostname);
278         ast_log(LOG_DEBUG,"cdr_pgsql: got port of %s\n",pgdbport);
279         if (pgdbsock)
280                 ast_log(LOG_DEBUG,"cdr_pgsql: got sock file of %s\n",pgdbsock);
281         ast_log(LOG_DEBUG,"cdr_pgsql: got user of %s\n",pgdbuser);
282         ast_log(LOG_DEBUG,"cdr_pgsql: got dbname of %s\n",pgdbname);
283         ast_log(LOG_DEBUG,"cdr_pgsql: got password of %s\n",pgpassword);
284         ast_log(LOG_DEBUG,"cdr_pgsql: got sql table name of %s\n",table);
285         
286         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
287         if (PQstatus(conn) != CONNECTION_BAD) {
288                 ast_log(LOG_DEBUG,"Successfully connected to PostgreSQL database.\n");
289                 connected = 1;
290         } else {
291                 pgerror = PQerrorMessage(conn);
292                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
293                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
294                 connected = 0;
295         }
296
297         res = ast_cdr_register(name, desc, pgsql_log);
298         if (res) {
299                 ast_log(LOG_ERROR, "Unable to register PGSQL CDR handling\n");
300         }
301         return res;
302 }
303
304 static int my_load_module(void)
305 {
306         struct ast_config *cfg;
307         int res;
308         cfg = ast_config_load(config);
309         if (!cfg) {
310                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
311                 return 0;
312         }
313         res = process_my_load_module(cfg);
314         ast_config_destroy(cfg);
315         return res;
316 }
317
318 int load_module(void)
319 {
320         return my_load_module();
321 }
322
323 int unload_module(void)
324 {
325         return my_unload_module();
326 }
327
328 int reload(void)
329 {
330         my_unload_module();
331         return my_load_module();
332 }
333
334 int usecount(void)
335 {
336         /* To be able to unload the module */
337         if ( ast_mutex_trylock(&pgsql_lock) ) {
338                 return 1;
339         } else {
340                 ast_mutex_unlock(&pgsql_lock);
341                 return 0;
342         }
343 }
344
345 char *key()
346 {
347         return ASTERISK_GPL_KEY;
348 }