more removal of duplicate #include lines
[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
55 #define DATE_FORMAT "%Y-%m-%d %T"
56
57 static char *name = "pgsql";
58 static char *config = "cdr_pgsql.conf";
59 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
60 static int connected = 0;
61
62 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
63
64 static PGconn   *conn = NULL;
65
66 static int pgsql_log(struct ast_cdr *cdr)
67 {
68         struct ast_tm tm;
69         char sqlcmd[2048] = "", timestr[128];
70         char *pgerror;
71         PGresult *result;
72
73         ast_mutex_lock(&pgsql_lock);
74
75         ast_localtime(&cdr->start, &tm, NULL);
76         ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
77
78         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
79                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
80                 if (PQstatus(conn) != CONNECTION_BAD) {
81                         connected = 1;
82                 } else {
83                         pgerror = PQerrorMessage(conn);
84                         ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
85                         ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
86                         PQfinish(conn);
87                         conn = NULL;
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_debug(2, "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',%ld,%ld,'%s',%ld,'%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_debug(3, "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                                 PQfinish(conn);
146                                 conn = NULL;
147                                 connected = 0;
148                                 ast_mutex_unlock(&pgsql_lock);
149                                 return -1;
150                         }
151                 }
152                 result = PQexec(conn, sqlcmd);
153                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
154                         pgerror = PQresultErrorMessage(result);
155                         ast_log(LOG_ERROR,"cdr_pgsql: Failed to insert call detail record into database!\n");
156                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
157                         ast_log(LOG_ERROR,"cdr_pgsql: Connection may have been lost... attempting to reconnect.\n");
158                         PQreset(conn);
159                         if (PQstatus(conn) == CONNECTION_OK) {
160                                 ast_log(LOG_ERROR, "cdr_pgsql: Connection reestablished.\n");
161                                 connected = 1;
162                                 PQclear(result);
163                                 result = PQexec(conn, sqlcmd);
164                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
165                                         pgerror = PQresultErrorMessage(result);
166                                         ast_log(LOG_ERROR,"cdr_pgsql: HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
167                                         ast_log(LOG_ERROR,"cdr_pgsql: Reason: %s\n", pgerror);
168                                 }
169                         }
170                         ast_mutex_unlock(&pgsql_lock);
171                         PQclear(result);
172                         return -1;
173                 }
174                 PQclear(result);
175         }
176         ast_mutex_unlock(&pgsql_lock);
177         return 0;
178 }
179
180 static int unload_module(void)
181
182         PQfinish(conn);
183         if (pghostname)
184                 ast_free(pghostname);
185         if (pgdbname)
186                 ast_free(pgdbname);
187         if (pgdbuser)
188                 ast_free(pgdbuser);
189         if (pgpassword)
190                 ast_free(pgpassword);
191         if (pgdbport)
192                 ast_free(pgdbport);
193         if (table)
194                 ast_free(table);
195         ast_cdr_unregister(name);
196         return 0;
197 }
198
199 static int config_module(int reload)
200 {
201         struct ast_variable *var;
202         char *pgerror;
203         const char *tmp;
204         struct ast_config *cfg;
205         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
206
207         if ((cfg = ast_config_load(config, config_flags)) == NULL) {
208                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
209                 return -1;
210         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
211                 return 0;
212
213         if (!(var = ast_variable_browse(cfg, "global"))) {
214                 ast_config_destroy(cfg);
215                 return 0;
216         }
217
218         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
219                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
220                 tmp = "";       /* connect via UNIX-socket by default */
221         }
222
223         if (pghostname)
224                 ast_free(pghostname);
225         if (!(pghostname = ast_strdup(tmp))) {
226                 ast_config_destroy(cfg);
227                 return -1;
228         }
229
230         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
231                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
232                 tmp = "asteriskcdrdb";
233         }
234
235         if (pgdbname)
236                 ast_free(pgdbname);
237         if (!(pgdbname = ast_strdup(tmp))) {
238                 ast_config_destroy(cfg);
239                 return -1;
240         }
241
242         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
243                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
244                 tmp = "asterisk";
245         }
246
247         if (pgdbuser)
248                 ast_free(pgdbuser);
249         if (!(pgdbuser = ast_strdup(tmp))) {
250                 ast_config_destroy(cfg);
251                 return -1;
252         }
253
254         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
255                 ast_log(LOG_WARNING,"PostgreSQL database password not specified.  Assuming blank\n");
256                 tmp = "";
257         }
258
259         if (pgpassword)
260                 ast_free(pgpassword);
261         if (!(pgpassword = ast_strdup(tmp))) {
262                 ast_config_destroy(cfg);
263                 return -1;
264         }
265
266         if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
267                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
268                 tmp = "5432";
269         }
270
271         if (pgdbport)
272                 ast_free(pgdbport);
273         if (!(pgdbport = ast_strdup(tmp))) {
274                 ast_config_destroy(cfg);
275                 return -1;
276         }
277
278         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
279                 ast_log(LOG_WARNING,"CDR table not specified.  Assuming cdr\n");
280                 tmp = "cdr";
281         }
282
283         if (table)
284                 ast_free(table);
285         if (!(table = ast_strdup(tmp))) {
286                 ast_config_destroy(cfg);
287                 return -1;
288         }
289
290         if (option_debug) {
291                 if (ast_strlen_zero(pghostname))
292                         ast_debug(1, "cdr_pgsql: using default unix socket\n");
293                 else
294                         ast_debug(1, "cdr_pgsql: got hostname of %s\n", pghostname);
295                         ast_debug(1, "cdr_pgsql: got port of %s\n", pgdbport);
296                         ast_debug(1, "cdr_pgsql: got user of %s\n", pgdbuser);
297                         ast_debug(1, "cdr_pgsql: got dbname of %s\n", pgdbname);
298                         ast_debug(1, "cdr_pgsql: got password of %s\n", pgpassword);
299                         ast_debug(1, "cdr_pgsql: got sql table name of %s\n", table);
300         }
301         
302         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
303         if (PQstatus(conn) != CONNECTION_BAD) {
304                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
305                 connected = 1;
306         } else {
307                 pgerror = PQerrorMessage(conn);
308                 ast_log(LOG_ERROR, "cdr_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
309                 ast_log(LOG_ERROR, "cdr_pgsql: Reason: %s\n", pgerror);
310                 connected = 0;
311         }
312
313         ast_config_destroy(cfg);
314
315         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
316 }
317
318 static int load_module(void)
319 {
320         return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
321 }
322
323 static int reload(void)
324 {
325         return config_module(1);
326 }
327
328 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "PostgreSQL CDR Backend",
329                 .load = load_module,
330                 .unload = unload_module,
331                 .reload = reload,
332                );