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