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