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