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