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