cdr_pgsql.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2003 - 2012
  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. * \brief PostgreSQL CDR logger
  25. *
  26. * \author Matthew D. Hardeman <mhardemn@papersoft.com>
  27. * PostgreSQL http://www.postgresql.org/
  28. *
  29. * See also
  30. * \arg \ref Config_cdr
  31. * PostgreSQL http://www.postgresql.org/
  32. * \ingroup cdr_drivers
  33. */
  34. /*! \li \ref cdr_pgsql.c uses the configuration file \ref cdr_pgsql.conf
  35. * \addtogroup configuration_file Configuration Files
  36. */
  37. /*!
  38. * \page cdr_pgsql.conf cdr_pgsql.conf
  39. * \verbinclude cdr_pgsql.conf.sample
  40. */
  41. /*** MODULEINFO
  42. <depend>pgsql</depend>
  43. <support_level>extended</support_level>
  44. ***/
  45. #include "asterisk.h"
  46. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  47. #include <libpq-fe.h>
  48. #include "asterisk/config.h"
  49. #include "asterisk/channel.h"
  50. #include "asterisk/cdr.h"
  51. #include "asterisk/cli.h"
  52. #include "asterisk/module.h"
  53. #define DATE_FORMAT "'%Y-%m-%d %T'"
  54. static const char name[] = "pgsql";
  55. static const char config[] = "cdr_pgsql.conf";
  56. static char *pghostname;
  57. static char *pgdbname;
  58. static char *pgdbuser;
  59. static char *pgpassword;
  60. static char *pgappname;
  61. static char *pgdbport;
  62. static char *table;
  63. static char *encoding;
  64. static char *tz;
  65. static int connected = 0;
  66. static int maxsize = 512, maxsize2 = 512;
  67. static time_t connect_time = 0;
  68. static int totalrecords = 0;
  69. static int records;
  70. static char *handle_cdr_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  71. static struct ast_cli_entry cdr_pgsql_status_cli[] = {
  72. AST_CLI_DEFINE(handle_cdr_pgsql_status, "Show connection status of the PostgreSQL CDR driver (cdr_pgsql)"),
  73. };
  74. AST_MUTEX_DEFINE_STATIC(pgsql_lock);
  75. static PGconn *conn = NULL;
  76. struct columns {
  77. char *name;
  78. char *type;
  79. int len;
  80. unsigned int notnull:1;
  81. unsigned int hasdefault:1;
  82. AST_RWLIST_ENTRY(columns) list;
  83. };
  84. static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
  85. #define LENGTHEN_BUF1(size) \
  86. do { \
  87. /* Lengthen buffer, if necessary */ \
  88. if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
  89. if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) { \
  90. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
  91. ast_free(sql); \
  92. ast_free(sql2); \
  93. AST_RWLIST_UNLOCK(&psql_columns); \
  94. ast_mutex_unlock(&pgsql_lock); \
  95. return -1; \
  96. } \
  97. } \
  98. } while (0)
  99. #define LENGTHEN_BUF2(size) \
  100. do { \
  101. if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) { \
  102. if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
  103. ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CDR failed.\n"); \
  104. ast_free(sql); \
  105. ast_free(sql2); \
  106. AST_RWLIST_UNLOCK(&psql_columns); \
  107. ast_mutex_unlock(&pgsql_lock); \
  108. return -1; \
  109. } \
  110. } \
  111. } while (0)
  112. /*! \brief Handle the CLI command cdr show pgsql status */
  113. static char *handle_cdr_pgsql_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  114. {
  115. switch (cmd) {
  116. case CLI_INIT:
  117. e->command = "cdr show pgsql status";
  118. e->usage =
  119. "Usage: cdr show pgsql status\n"
  120. " Shows current connection status for cdr_pgsql\n";
  121. return NULL;
  122. case CLI_GENERATE:
  123. return NULL;
  124. }
  125. if (a->argc != e->args)
  126. return CLI_SHOWUSAGE;
  127. if (connected) {
  128. char status[256], status2[100] = "";
  129. int ctime = time(NULL) - connect_time;
  130. if (pgdbport) {
  131. snprintf(status, 255, "Connected to %s@%s, port %s", pgdbname, pghostname, pgdbport);
  132. } else {
  133. snprintf(status, 255, "Connected to %s@%s", pgdbname, pghostname);
  134. }
  135. if (pgdbuser && *pgdbuser) {
  136. snprintf(status2, 99, " with username %s", pgdbuser);
  137. }
  138. if (table && *table) {
  139. snprintf(status2, 99, " using table %s", table);
  140. }
  141. if (ctime > 31536000) {
  142. ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 31536000, (ctime % 31536000) / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
  143. } else if (ctime > 86400) {
  144. ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
  145. } else if (ctime > 3600) {
  146. ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 3600, (ctime % 3600) / 60, ctime % 60);
  147. } else if (ctime > 60) {
  148. ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60, ctime % 60);
  149. } else {
  150. ast_cli(a->fd, "%s%s for %d seconds.\n", status, status2, ctime);
  151. }
  152. if (records == totalrecords) {
  153. ast_cli(a->fd, " Wrote %d records since last restart.\n", totalrecords);
  154. } else {
  155. ast_cli(a->fd, " Wrote %d records since last restart and %d records since last reconnect.\n", totalrecords, records);
  156. }
  157. } else {
  158. ast_cli(a->fd, "Not currently connected to a PgSQL server.\n");
  159. }
  160. return CLI_SUCCESS;
  161. }
  162. static void pgsql_reconnect(void)
  163. {
  164. struct ast_str *conn_info = ast_str_create(128);
  165. if (!conn_info) {
  166. ast_log(LOG_ERROR, "Failed to allocate memory for connection string.\n");
  167. return;
  168. }
  169. if (conn) {
  170. PQfinish(conn);
  171. conn = NULL;
  172. }
  173. ast_str_set(&conn_info, 0, "host=%s port=%s dbname=%s user=%s",
  174. pghostname, pgdbport, pgdbname, pgdbuser);
  175. if (!ast_strlen_zero(pgappname)) {
  176. ast_str_append(&conn_info, 0, " application_name=%s", pgappname);
  177. }
  178. if (!ast_strlen_zero(pgpassword)) {
  179. ast_str_append(&conn_info, 0, " password=%s", pgpassword);
  180. }
  181. conn = PQconnectdb(ast_str_buffer(conn_info));
  182. ast_free(conn_info);
  183. }
  184. static int pgsql_log(struct ast_cdr *cdr)
  185. {
  186. struct ast_tm tm;
  187. char *pgerror;
  188. PGresult *result;
  189. int res = -1;
  190. ast_mutex_lock(&pgsql_lock);
  191. if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
  192. pgsql_reconnect();
  193. if (PQstatus(conn) != CONNECTION_BAD) {
  194. connected = 1;
  195. connect_time = time(NULL);
  196. records = 0;
  197. if (PQsetClientEncoding(conn, encoding)) {
  198. #ifdef HAVE_PGSQL_pg_encoding_to_char
  199. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
  200. #else
  201. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
  202. #endif
  203. }
  204. } else {
  205. pgerror = PQerrorMessage(conn);
  206. ast_log(LOG_ERROR, "Unable to connect to database server %s. Calls will not be logged!\n", pghostname);
  207. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  208. PQfinish(conn);
  209. conn = NULL;
  210. }
  211. }
  212. if (connected) {
  213. struct columns *cur;
  214. struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
  215. char buf[257];
  216. char *escapebuf = NULL, *value;
  217. int first = 1;
  218. size_t bufsize = 513;
  219. escapebuf = ast_malloc(bufsize);
  220. if (!escapebuf || !sql || !sql2) {
  221. goto ast_log_cleanup;
  222. }
  223. ast_str_set(&sql, 0, "INSERT INTO %s (", table);
  224. ast_str_set(&sql2, 0, " VALUES (");
  225. AST_RWLIST_RDLOCK(&psql_columns);
  226. AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
  227. /* For fields not set, simply skip them */
  228. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  229. if (strcmp(cur->name, "calldate") == 0 && !value) {
  230. ast_cdr_format_var(cdr, "start", &value, buf, sizeof(buf), 0);
  231. }
  232. if (!value) {
  233. if (cur->notnull && !cur->hasdefault) {
  234. /* Field is NOT NULL (but no default), must include it anyway */
  235. LENGTHEN_BUF1(strlen(cur->name) + 2);
  236. ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
  237. LENGTHEN_BUF2(3);
  238. ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
  239. first = 0;
  240. }
  241. continue;
  242. }
  243. LENGTHEN_BUF1(strlen(cur->name) + 2);
  244. ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
  245. if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
  246. if (strncmp(cur->type, "int", 3) == 0) {
  247. LENGTHEN_BUF2(13);
  248. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->start.tv_sec);
  249. } else if (strncmp(cur->type, "float", 5) == 0) {
  250. LENGTHEN_BUF2(31);
  251. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
  252. } else {
  253. /* char, hopefully */
  254. LENGTHEN_BUF2(31);
  255. ast_localtime(&cdr->start, &tm, tz);
  256. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  257. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  258. }
  259. } else if (strcmp(cur->name, "answer") == 0) {
  260. if (strncmp(cur->type, "int", 3) == 0) {
  261. LENGTHEN_BUF2(13);
  262. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->answer.tv_sec);
  263. } else if (strncmp(cur->type, "float", 5) == 0) {
  264. LENGTHEN_BUF2(31);
  265. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
  266. } else {
  267. /* char, hopefully */
  268. LENGTHEN_BUF2(31);
  269. ast_localtime(&cdr->answer, &tm, tz);
  270. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  271. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  272. }
  273. } else if (strcmp(cur->name, "end") == 0) {
  274. if (strncmp(cur->type, "int", 3) == 0) {
  275. LENGTHEN_BUF2(13);
  276. ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->end.tv_sec);
  277. } else if (strncmp(cur->type, "float", 5) == 0) {
  278. LENGTHEN_BUF2(31);
  279. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
  280. } else {
  281. /* char, hopefully */
  282. LENGTHEN_BUF2(31);
  283. ast_localtime(&cdr->end, &tm, tz);
  284. ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
  285. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
  286. }
  287. } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
  288. if (cur->type[0] == 'i') {
  289. /* Get integer, no need to escape anything */
  290. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  291. LENGTHEN_BUF2(13);
  292. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
  293. } else if (strncmp(cur->type, "float", 5) == 0) {
  294. struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
  295. LENGTHEN_BUF2(31);
  296. ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
  297. } else {
  298. /* Char field, probably */
  299. struct timeval *when = cur->name[0] == 'd' ? &cdr->start : ast_tvzero(cdr->answer) ? &cdr->end : &cdr->answer;
  300. LENGTHEN_BUF2(31);
  301. ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
  302. }
  303. } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
  304. if (strncmp(cur->type, "int", 3) == 0) {
  305. /* Integer, no need to escape anything */
  306. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 1);
  307. LENGTHEN_BUF2(13);
  308. ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
  309. } else {
  310. /* Although this is a char field, there are no special characters in the values for these fields */
  311. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  312. LENGTHEN_BUF2(31);
  313. ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
  314. }
  315. } else {
  316. /* Arbitrary field, could be anything */
  317. ast_cdr_format_var(cdr, cur->name, &value, buf, sizeof(buf), 0);
  318. if (strncmp(cur->type, "int", 3) == 0) {
  319. long long whatever;
  320. if (value && sscanf(value, "%30lld", &whatever) == 1) {
  321. LENGTHEN_BUF2(26);
  322. ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
  323. } else {
  324. LENGTHEN_BUF2(2);
  325. ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
  326. }
  327. } else if (strncmp(cur->type, "float", 5) == 0) {
  328. long double whatever;
  329. if (value && sscanf(value, "%30Lf", &whatever) == 1) {
  330. LENGTHEN_BUF2(51);
  331. ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
  332. } else {
  333. LENGTHEN_BUF2(2);
  334. ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
  335. }
  336. /* XXX Might want to handle dates, times, and other misc fields here XXX */
  337. } else {
  338. if (value) {
  339. size_t required_size = strlen(value) * 2 + 1;
  340. /* If our argument size exceeds our buffer, grow it,
  341. * as PQescapeStringConn() expects the buffer to be
  342. * adequitely sized and does *NOT* do size checking.
  343. */
  344. if (required_size > bufsize) {
  345. char *tmpbuf = ast_realloc(escapebuf, required_size);
  346. if (!tmpbuf) {
  347. AST_RWLIST_UNLOCK(&psql_columns);
  348. goto ast_log_cleanup;
  349. }
  350. escapebuf = tmpbuf;
  351. bufsize = required_size;
  352. }
  353. PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
  354. } else {
  355. escapebuf[0] = '\0';
  356. }
  357. LENGTHEN_BUF2(strlen(escapebuf) + 3);
  358. ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
  359. }
  360. }
  361. first = 0;
  362. }
  363. LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
  364. AST_RWLIST_UNLOCK(&psql_columns);
  365. ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
  366. ast_debug(3, "Inserting a CDR record: [%s]\n", ast_str_buffer(sql));
  367. /* Test to be sure we're still connected... */
  368. /* If we're connected, and connection is working, good. */
  369. /* Otherwise, attempt reconnect. If it fails... sorry... */
  370. if (PQstatus(conn) == CONNECTION_OK) {
  371. connected = 1;
  372. } else {
  373. ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
  374. PQreset(conn);
  375. if (PQstatus(conn) == CONNECTION_OK) {
  376. ast_log(LOG_ERROR, "Connection reestablished.\n");
  377. connected = 1;
  378. connect_time = time(NULL);
  379. records = 0;
  380. } else {
  381. pgerror = PQerrorMessage(conn);
  382. ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
  383. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  384. PQfinish(conn);
  385. conn = NULL;
  386. connected = 0;
  387. goto ast_log_cleanup;
  388. }
  389. }
  390. result = PQexec(conn, ast_str_buffer(sql));
  391. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  392. pgerror = PQresultErrorMessage(result);
  393. ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
  394. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  395. ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
  396. PQreset(conn);
  397. if (PQstatus(conn) == CONNECTION_OK) {
  398. ast_log(LOG_ERROR, "Connection reestablished.\n");
  399. connected = 1;
  400. connect_time = time(NULL);
  401. records = 0;
  402. PQclear(result);
  403. result = PQexec(conn, ast_str_buffer(sql));
  404. if (PQresultStatus(result) != PGRES_COMMAND_OK) {
  405. pgerror = PQresultErrorMessage(result);
  406. ast_log(LOG_ERROR, "HARD ERROR! Attempted reconnection failed. DROPPING CALL RECORD!\n");
  407. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  408. } else {
  409. /* Second try worked out ok */
  410. totalrecords++;
  411. records++;
  412. res = 0;
  413. }
  414. }
  415. } else {
  416. totalrecords++;
  417. records++;
  418. res = 0;
  419. }
  420. PQclear(result);
  421. ast_log_cleanup:
  422. ast_free(escapebuf);
  423. ast_free(sql);
  424. ast_free(sql2);
  425. }
  426. ast_mutex_unlock(&pgsql_lock);
  427. return res;
  428. }
  429. /* This function should be called without holding the pgsql_columns lock */
  430. static void empty_columns(void)
  431. {
  432. struct columns *current;
  433. AST_RWLIST_WRLOCK(&psql_columns);
  434. while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
  435. ast_free(current);
  436. }
  437. AST_RWLIST_UNLOCK(&psql_columns);
  438. }
  439. static int unload_module(void)
  440. {
  441. if (ast_cdr_unregister(name)) {
  442. return -1;
  443. }
  444. ast_cli_unregister_multiple(cdr_pgsql_status_cli, ARRAY_LEN(cdr_pgsql_status_cli));
  445. if (conn) {
  446. PQfinish(conn);
  447. conn = NULL;
  448. }
  449. ast_free(pghostname);
  450. ast_free(pgdbname);
  451. ast_free(pgdbuser);
  452. ast_free(pgpassword);
  453. ast_free(pgappname);
  454. ast_free(pgdbport);
  455. ast_free(table);
  456. ast_free(encoding);
  457. ast_free(tz);
  458. empty_columns();
  459. return 0;
  460. }
  461. static int config_module(int reload)
  462. {
  463. char *pgerror;
  464. struct columns *cur;
  465. PGresult *result;
  466. const char *tmp;
  467. struct ast_config *cfg;
  468. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  469. if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
  470. ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
  471. return -1;
  472. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  473. return 0;
  474. }
  475. ast_mutex_lock(&pgsql_lock);
  476. if (!ast_variable_browse(cfg, "global")) {
  477. ast_config_destroy(cfg);
  478. ast_mutex_unlock(&pgsql_lock);
  479. ast_log(LOG_NOTICE, "cdr_pgsql configuration contains no global section, skipping module %s.\n",
  480. reload ? "reload" : "load");
  481. return -1;
  482. }
  483. if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
  484. ast_log(LOG_WARNING, "PostgreSQL server hostname not specified. Assuming unix socket connection\n");
  485. tmp = ""; /* connect via UNIX-socket by default */
  486. }
  487. ast_free(pghostname);
  488. if (!(pghostname = ast_strdup(tmp))) {
  489. ast_config_destroy(cfg);
  490. ast_mutex_unlock(&pgsql_lock);
  491. return -1;
  492. }
  493. if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
  494. ast_log(LOG_WARNING, "PostgreSQL database not specified. Assuming asterisk\n");
  495. tmp = "asteriskcdrdb";
  496. }
  497. ast_free(pgdbname);
  498. if (!(pgdbname = ast_strdup(tmp))) {
  499. ast_config_destroy(cfg);
  500. ast_mutex_unlock(&pgsql_lock);
  501. return -1;
  502. }
  503. if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
  504. ast_log(LOG_WARNING, "PostgreSQL database user not specified. Assuming asterisk\n");
  505. tmp = "asterisk";
  506. }
  507. ast_free(pgdbuser);
  508. if (!(pgdbuser = ast_strdup(tmp))) {
  509. ast_config_destroy(cfg);
  510. ast_mutex_unlock(&pgsql_lock);
  511. return -1;
  512. }
  513. if (!(tmp = ast_variable_retrieve(cfg, "global", "appname"))) {
  514. tmp = "";
  515. }
  516. ast_free(pgappname);
  517. if (!(pgappname = ast_strdup(tmp))) {
  518. ast_config_destroy(cfg);
  519. ast_mutex_unlock(&pgsql_lock);
  520. return -1;
  521. }
  522. if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
  523. ast_log(LOG_WARNING, "PostgreSQL database password not specified. Assuming blank\n");
  524. tmp = "";
  525. }
  526. ast_free(pgpassword);
  527. if (!(pgpassword = ast_strdup(tmp))) {
  528. ast_config_destroy(cfg);
  529. ast_mutex_unlock(&pgsql_lock);
  530. return -1;
  531. }
  532. if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
  533. ast_log(LOG_WARNING, "PostgreSQL database port not specified. Using default 5432.\n");
  534. tmp = "5432";
  535. }
  536. ast_free(pgdbport);
  537. if (!(pgdbport = ast_strdup(tmp))) {
  538. ast_config_destroy(cfg);
  539. ast_mutex_unlock(&pgsql_lock);
  540. return -1;
  541. }
  542. if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
  543. ast_log(LOG_WARNING, "CDR table not specified. Assuming cdr\n");
  544. tmp = "cdr";
  545. }
  546. ast_free(table);
  547. if (!(table = ast_strdup(tmp))) {
  548. ast_config_destroy(cfg);
  549. ast_mutex_unlock(&pgsql_lock);
  550. return -1;
  551. }
  552. if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
  553. ast_log(LOG_WARNING, "Encoding not specified. Assuming LATIN9\n");
  554. tmp = "LATIN9";
  555. }
  556. ast_free(encoding);
  557. if (!(encoding = ast_strdup(tmp))) {
  558. ast_config_destroy(cfg);
  559. ast_mutex_unlock(&pgsql_lock);
  560. return -1;
  561. }
  562. if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
  563. tmp = "";
  564. }
  565. ast_free(tz);
  566. tz = NULL;
  567. if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
  568. ast_config_destroy(cfg);
  569. ast_mutex_unlock(&pgsql_lock);
  570. return -1;
  571. }
  572. if (DEBUG_ATLEAST(1)) {
  573. if (ast_strlen_zero(pghostname)) {
  574. ast_log(LOG_DEBUG, "using default unix socket\n");
  575. } else {
  576. ast_log(LOG_DEBUG, "got hostname of %s\n", pghostname);
  577. }
  578. ast_log(LOG_DEBUG, "got port of %s\n", pgdbport);
  579. ast_log(LOG_DEBUG, "got user of %s\n", pgdbuser);
  580. ast_log(LOG_DEBUG, "got dbname of %s\n", pgdbname);
  581. ast_log(LOG_DEBUG, "got password of %s\n", pgpassword);
  582. ast_log(LOG_DEBUG, "got application name of %s\n", pgappname);
  583. ast_log(LOG_DEBUG, "got sql table name of %s\n", table);
  584. ast_log(LOG_DEBUG, "got encoding of %s\n", encoding);
  585. ast_log(LOG_DEBUG, "got timezone of %s\n", tz);
  586. }
  587. pgsql_reconnect();
  588. if (PQstatus(conn) != CONNECTION_BAD) {
  589. char sqlcmd[768];
  590. char *fname, *ftype, *flen, *fnotnull, *fdef;
  591. int i, rows, version;
  592. ast_debug(1, "Successfully connected to PostgreSQL database.\n");
  593. connected = 1;
  594. connect_time = time(NULL);
  595. records = 0;
  596. if (PQsetClientEncoding(conn, encoding)) {
  597. #ifdef HAVE_PGSQL_pg_encoding_to_char
  598. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
  599. #else
  600. ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
  601. #endif
  602. }
  603. version = PQserverVersion(conn);
  604. if (version >= 70300) {
  605. char *schemaname, *tablename, *tmp_schemaname, *tmp_tablename;
  606. if (strchr(table, '.')) {
  607. tmp_schemaname = ast_strdupa(table);
  608. tmp_tablename = strchr(tmp_schemaname, '.');
  609. *tmp_tablename++ = '\0';
  610. } else {
  611. tmp_schemaname = "";
  612. tmp_tablename = table;
  613. }
  614. tablename = ast_alloca(strlen(tmp_tablename) * 2 + 1);
  615. PQescapeStringConn(conn, tablename, tmp_tablename, strlen(tmp_tablename), NULL);
  616. schemaname = ast_alloca(strlen(tmp_schemaname) * 2 + 1);
  617. PQescapeStringConn(conn, schemaname, tmp_schemaname, strlen(tmp_schemaname), NULL);
  618. snprintf(sqlcmd, sizeof(sqlcmd), "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND c.relname = '%s' AND n.nspname = %s%s%s) INNER JOIN pg_catalog.pg_attribute a ON (NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum ORDER BY n.nspname, c.relname, attnum",
  619. tablename,
  620. ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
  621. } else {
  622. snprintf(sqlcmd, sizeof(sqlcmd), "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM pg_class c, pg_type t, pg_attribute a LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", table);
  623. }
  624. /* Query the columns */
  625. result = PQexec(conn, sqlcmd);
  626. if (PQresultStatus(result) != PGRES_TUPLES_OK) {
  627. pgerror = PQresultErrorMessage(result);
  628. ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
  629. PQclear(result);
  630. unload_module();
  631. ast_mutex_unlock(&pgsql_lock);
  632. return AST_MODULE_LOAD_DECLINE;
  633. }
  634. rows = PQntuples(result);
  635. if (rows == 0) {
  636. ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
  637. PQclear(result);
  638. unload_module();
  639. ast_mutex_unlock(&pgsql_lock);
  640. return AST_MODULE_LOAD_DECLINE;
  641. }
  642. /* Clear out the columns list. */
  643. empty_columns();
  644. for (i = 0; i < rows; i++) {
  645. fname = PQgetvalue(result, i, 0);
  646. ftype = PQgetvalue(result, i, 1);
  647. flen = PQgetvalue(result, i, 2);
  648. fnotnull = PQgetvalue(result, i, 3);
  649. fdef = PQgetvalue(result, i, 4);
  650. if (atoi(flen) == -1) {
  651. /* For varchar columns, the maximum length is encoded in a different field */
  652. flen = PQgetvalue(result, i, 5);
  653. }
  654. cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
  655. if (cur) {
  656. sscanf(flen, "%30d", &cur->len);
  657. cur->name = (char *)cur + sizeof(*cur);
  658. cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
  659. strcpy(cur->name, fname);
  660. strcpy(cur->type, ftype);
  661. if (*fnotnull == 't') {
  662. cur->notnull = 1;
  663. } else {
  664. cur->notnull = 0;
  665. }
  666. if (!ast_strlen_zero(fdef)) {
  667. cur->hasdefault = 1;
  668. } else {
  669. cur->hasdefault = 0;
  670. }
  671. AST_RWLIST_WRLOCK(&psql_columns);
  672. AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
  673. AST_RWLIST_UNLOCK(&psql_columns);
  674. }
  675. }
  676. PQclear(result);
  677. } else {
  678. pgerror = PQerrorMessage(conn);
  679. ast_log(LOG_ERROR, "Unable to connect to database server %s. CALLS WILL NOT BE LOGGED!!\n", pghostname);
  680. ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
  681. connected = 0;
  682. PQfinish(conn);
  683. conn = NULL;
  684. }
  685. ast_config_destroy(cfg);
  686. ast_mutex_unlock(&pgsql_lock);
  687. return 0;
  688. }
  689. static int load_module(void)
  690. {
  691. ast_cli_register_multiple(cdr_pgsql_status_cli, sizeof(cdr_pgsql_status_cli) / sizeof(struct ast_cli_entry));
  692. if (config_module(0)) {
  693. return AST_MODULE_LOAD_DECLINE;
  694. }
  695. return ast_cdr_register(name, ast_module_info->description, pgsql_log)
  696. ? AST_MODULE_LOAD_DECLINE : 0;
  697. }
  698. static int reload(void)
  699. {
  700. return config_module(1);
  701. }
  702. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
  703. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  704. .load = load_module,
  705. .unload = unload_module,
  706. .reload = reload,
  707. .load_pri = AST_MODPRI_CDR_DRIVER,
  708. );