2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * res_odbc.c <ODBC resource manager>
9 * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
11 * See http://www.asterisk.org for more information about
12 * the Asterisk project. Please do not directly contact
13 * any of the maintainers of this project for assistance;
14 * the project provides a web site, mailing lists and IRC
15 * channels for your use.
17 * This program is free software, distributed under the terms of
18 * the GNU General Public License Version 2. See the LICENSE file
19 * at the top of the source tree.
24 * \brief ODBC resource manager
26 * \author Mark Spencer <markster@digium.com>
27 * \author Anthony Minessale II <anthmct@yahoo.com>
29 * \arg See also: \ref cdr_odbc
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include "asterisk/file.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/config.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/lock.h"
50 #include "asterisk/res_odbc.h"
51 #include "asterisk/time.h"
52 #include "asterisk/astobj2.h"
56 AST_LIST_ENTRY(odbc_class) list;
63 unsigned int haspool:1; /* Boolean - TDS databases need this */
64 unsigned int delme:1; /* Purge the class */
65 unsigned int backslash_is_escape:1; /* On this database, the backslash is a native escape sequence */
66 unsigned int limit; /* 1023 wasn't enough for some people */
67 unsigned int count; /* Running count of pooled connections */
68 unsigned int idlecheck; /* Recheck the connection if it is idle for this long */
69 struct ao2_container *obj_container;
72 struct ao2_container *class_container;
74 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
76 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
77 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
78 static int odbc_register_class(struct odbc_class *class, int connect);
80 static void odbc_class_destructor(void *data)
82 struct odbc_class *class = data;
83 /* Due to refcounts, we can safely assume that any objects with a reference
84 * to us will prevent our destruction, so we don't need to worry about them.
87 ast_free(class->username);
89 ast_free(class->password);
91 ast_free(class->sanitysql);
92 ao2_ref(class->obj_container, -1);
93 SQLFreeHandle(SQL_HANDLE_ENV, class->env);
96 static int null_hash_fn(const void *obj, const int flags)
101 static void odbc_obj_destructor(void *data)
103 struct odbc_obj *obj = data;
104 odbc_obj_disconnect(obj);
105 ast_mutex_destroy(&obj->lock);
106 ao2_ref(obj->parent, -1);
109 static void destroy_table_cache(struct odbc_cache_tables *table) {
110 struct odbc_cache_columns *col;
111 ast_debug(1, "Destroying table cache for %s\n", table->table);
112 AST_RWLIST_WRLOCK(&table->columns);
113 while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
116 AST_RWLIST_UNLOCK(&table->columns);
117 AST_RWLIST_HEAD_DESTROY(&table->columns);
122 * \brief Find or create an entry describing the table specified.
123 * \param obj An active ODBC handle on which to query the table
124 * \param table Tablename to describe
125 * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
126 * When a structure is returned, the contained columns list will be
127 * rdlock'ed, to ensure that it will be retained in memory.
129 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
131 struct odbc_cache_tables *tableptr;
132 struct odbc_cache_columns *entry;
135 SQLHSTMT stmt = NULL;
136 int res = 0, error = 0, try = 0;
137 struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
139 AST_RWLIST_RDLOCK(&odbc_tables);
140 AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
141 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
146 AST_RWLIST_RDLOCK(&tableptr->columns);
147 AST_RWLIST_UNLOCK(&odbc_tables);
149 ast_odbc_release_obj(obj);
155 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
159 /* Table structure not already cached; build it now. */
162 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
163 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
166 ast_odbc_sanity_check(obj);
169 ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
173 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
174 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
177 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
178 ast_odbc_sanity_check(obj);
181 ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
185 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
186 ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
190 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
191 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
192 strcpy(tableptr->connection, database); /* SAFE */
193 strcpy(tableptr->table, tablename); /* SAFE */
194 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
196 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
197 SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
199 if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
200 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
204 entry->name = (char *)entry + sizeof(*entry);
205 strcpy(entry->name, columnname);
207 SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
208 SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
209 SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
210 SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
211 SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
212 SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
214 /* Specification states that the octenlen should be the maximum number of bytes
215 * returned in a char or binary column, but it seems that some drivers just set
216 * it to NULL. (Bad Postgres! No biscuit!) */
217 if (entry->octetlen == 0) {
218 entry->octetlen = entry->size;
221 ast_verb(10, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
222 /* Insert column info into column list */
223 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
225 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
227 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
228 AST_RWLIST_RDLOCK(&(tableptr->columns));
231 AST_RWLIST_UNLOCK(&odbc_tables);
234 destroy_table_cache(tableptr);
238 ast_odbc_release_obj(obj);
243 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
245 struct odbc_cache_columns *col;
246 AST_RWLIST_TRAVERSE(&table->columns, col, list) {
247 if (strcasecmp(col->name, colname) == 0) {
254 int ast_odbc_clear_cache(const char *database, const char *tablename)
256 struct odbc_cache_tables *tableptr;
258 AST_RWLIST_WRLOCK(&odbc_tables);
259 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
260 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
261 AST_LIST_REMOVE_CURRENT(list);
262 destroy_table_cache(tableptr);
266 AST_RWLIST_TRAVERSE_SAFE_END
267 AST_RWLIST_UNLOCK(&odbc_tables);
268 return tableptr ? 0 : -1;
271 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
276 for (attempt = 0; attempt < 2; attempt++) {
277 stmt = exec_cb(obj, data);
283 ast_log(LOG_WARNING, "SQL Exec Direct failed. Attempting a reconnect...\n");
285 odbc_obj_disconnect(obj);
286 odbc_obj_connect(obj);
293 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
295 int res = 0, i, attempt;
296 SQLINTEGER nativeerror=0, numfields=0;
297 SQLSMALLINT diagbytes=0;
298 unsigned char state[10], diagnostic[256];
301 for (attempt = 0; attempt < 2; attempt++) {
302 /* This prepare callback may do more than just prepare -- it may also
303 * bind parameters, bind results, etc. The real key, here, is that
304 * when we disconnect, all handles become invalid for most databases.
305 * We must therefore redo everything when we establish a new
307 stmt = prepare_cb(obj, data);
310 res = SQLExecute(stmt);
311 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
312 if (res == SQL_ERROR) {
313 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
314 for (i = 0; i < numfields; i++) {
315 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
316 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
318 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
324 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
325 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
330 * While this isn't the best way to try to correct an error, this won't automatically
331 * fail when the statement handle invalidates.
333 ast_odbc_sanity_check(obj);
336 obj->last_used = ast_tvnow();
338 } else if (attempt == 0)
339 ast_odbc_sanity_check(obj);
345 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
348 SQLINTEGER nativeerror=0, numfields=0;
349 SQLSMALLINT diagbytes=0;
350 unsigned char state[10], diagnostic[256];
352 res = SQLExecute(stmt);
353 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
354 if (res == SQL_ERROR) {
355 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
356 for (i = 0; i < numfields; i++) {
357 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
358 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
360 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
366 obj->last_used = ast_tvnow();
372 int ast_odbc_sanity_check(struct odbc_obj *obj)
374 char *test_sql = "select 1";
378 if (!ast_strlen_zero(obj->parent->sanitysql))
379 test_sql = obj->parent->sanitysql;
382 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
383 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
386 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
387 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
390 res = SQLExecute(stmt);
391 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
396 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
399 if (!obj->up) { /* Try to reconnect! */
400 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
401 odbc_obj_disconnect(obj);
402 odbc_obj_connect(obj);
407 static int load_odbc_config(void)
409 static char *cfg = "res_odbc.conf";
410 struct ast_config *config;
411 struct ast_variable *v;
413 const char *dsn, *username, *password, *sanitysql;
414 int enabled, pooling, limit, bse;
415 unsigned int idlecheck;
416 int preconnect = 0, res = 0;
417 struct ast_flags config_flags = { 0 };
419 struct odbc_class *new;
421 config = ast_config_load(cfg, config_flags);
422 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
423 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
426 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
427 if (!strcasecmp(cat, "ENV")) {
428 for (v = ast_variable_browse(config, cat); v; v = v->next) {
429 setenv(v->name, v->value, 1);
430 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
433 /* Reset all to defaults for each class of odbc connections */
434 dsn = username = password = sanitysql = NULL;
436 preconnect = idlecheck = 0;
440 for (v = ast_variable_browse(config, cat); v; v = v->next) {
441 if (!strcasecmp(v->name, "pooling")) {
442 if (ast_true(v->value))
444 } else if (!strncasecmp(v->name, "share", 5)) {
445 /* "shareconnections" is a little clearer in meaning than "pooling" */
446 if (ast_false(v->value))
448 } else if (!strcasecmp(v->name, "limit")) {
449 sscanf(v->value, "%d", &limit);
450 if (ast_true(v->value) && !limit) {
451 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Setting limit to 1023 for ODBC class '%s'.\n", v->value, cat);
453 } else if (ast_false(v->value)) {
454 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
458 } else if (!strcasecmp(v->name, "idlecheck")) {
459 sscanf(v->value, "%d", &idlecheck);
460 } else if (!strcasecmp(v->name, "enabled")) {
461 enabled = ast_true(v->value);
462 } else if (!strcasecmp(v->name, "pre-connect")) {
463 preconnect = ast_true(v->value);
464 } else if (!strcasecmp(v->name, "dsn")) {
466 } else if (!strcasecmp(v->name, "username")) {
468 } else if (!strcasecmp(v->name, "password")) {
470 } else if (!strcasecmp(v->name, "sanitysql")) {
471 sanitysql = v->value;
472 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
473 bse = ast_true(v->value);
477 if (enabled && !ast_strlen_zero(dsn)) {
478 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
485 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
486 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
488 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
489 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
494 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
497 new->haspool = pooling;
501 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
506 new->backslash_is_escape = bse ? 1 : 0;
507 new->idlecheck = idlecheck;
510 ast_copy_string(new->name, cat, sizeof(new->name));
512 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
513 if (username && !(new->username = ast_strdup(username))) {
517 if (password && !(new->password = ast_strdup(password))) {
521 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
526 odbc_register_class(new, preconnect);
527 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
533 ast_config_destroy(config);
537 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
539 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
540 struct odbc_class *class;
541 struct odbc_obj *current;
548 e->command = "odbc show";
550 "Usage: odbc show [class]\n"
551 " List settings of a particular ODBC class or,\n"
552 " if not specified, all classes.\n";
557 length = strlen(a->word);
558 while ((class = ao2_iterator_next(&aoi))) {
559 if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
560 ret = ast_strdup(class->name);
566 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
567 ret = ast_strdup("all");
572 ast_cli(a->fd, "\nODBC DSN Settings\n");
573 ast_cli(a->fd, "-----------------\n\n");
574 aoi = ao2_iterator_init(class_container, 0);
575 while ((class = ao2_iterator_next(&aoi))) {
576 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
578 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
580 if (class->haspool) {
581 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
583 ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
585 while ((current = ao2_iterator_next(&aoi2))) {
586 ast_mutex_lock(¤t->lock);
588 ast_cli(a->fd, " - Connection %d: %s (%s:%d %s)\n", ++count,
589 current->used ? "in use" :
590 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
591 current->file, current->lineno, current->function);
593 ast_cli(a->fd, " - Connection %d: %s\n", ++count,
594 current->used ? "in use" :
595 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
597 ast_mutex_unlock(¤t->lock);
598 ao2_ref(current, -1);
601 /* Should only ever be one of these */
602 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
603 while ((current = ao2_iterator_next(&aoi2))) {
604 ast_cli(a->fd, " Pooled: No\n Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
605 ao2_ref(current, -1);
608 ast_cli(a->fd, "\n");
616 static struct ast_cli_entry cli_odbc[] = {
617 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
620 static int odbc_register_class(struct odbc_class *class, int preconnect)
622 struct odbc_obj *obj;
624 ao2_link(class_container, class);
625 /* I still have a reference in the caller, so a deref is NOT missing here. */
628 /* Request and release builds a connection */
629 obj = ast_odbc_request_obj(class->name, 0);
631 ast_odbc_release_obj(obj);
636 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
641 void ast_odbc_release_obj(struct odbc_obj *obj)
643 /* For pooled connections, this frees the connection to be
644 * reused. For non-pooled connections, it does nothing. */
648 obj->function[0] = '\0';
654 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
656 return obj->parent->backslash_is_escape;
660 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
662 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
665 struct odbc_obj *obj = NULL;
666 struct odbc_class *class;
667 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
669 while ((class = ao2_iterator_next(&aoi))) {
670 if (!strcmp(class->name, name) && !class->delme) {
679 if (class->haspool) {
680 /* Recycle connections before building another */
681 aoi = ao2_iterator_init(class->obj_container, 0);
682 while ((obj = ao2_iterator_next(&aoi))) {
684 ast_mutex_lock(&obj->lock);
686 ast_mutex_unlock(&obj->lock);
692 if (!obj && (class->count < class->limit)) {
694 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
699 ast_mutex_init(&obj->lock);
700 /* obj inherits the outstanding reference to class */
702 if (odbc_obj_connect(obj) == ODBC_FAIL) {
703 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
709 ao2_link(class->obj_container, obj);
713 /* Non-pooled connection: multiple modules can use the same connection. */
714 aoi = ao2_iterator_init(class->obj_container, 0);
715 while ((obj = ao2_iterator_next(&aoi))) {
716 /* Non-pooled connection: if there is an entry, return it */
721 /* No entry: build one */
722 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
727 ast_mutex_init(&obj->lock);
728 /* obj inherits the outstanding reference to class */
730 if (odbc_obj_connect(obj) == ODBC_FAIL) {
731 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
735 ao2_link(class->obj_container, obj);
741 ast_odbc_sanity_check(obj);
742 } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
743 odbc_obj_connect(obj);
747 ast_copy_string(obj->file, file, sizeof(obj->file));
748 ast_copy_string(obj->function, function, sizeof(obj->function));
749 obj->lineno = lineno;
756 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
761 unsigned char msg[200], state[10];
763 /* Nothing to disconnect */
768 ast_mutex_lock(&obj->lock);
770 res = SQLDisconnect(obj->con);
772 if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
773 ast_log(LOG_DEBUG, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
775 ast_log(LOG_DEBUG, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
778 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
780 ast_log(LOG_DEBUG, "Database handle deallocated\n");
782 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
783 ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
787 ast_mutex_unlock(&obj->lock);
791 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
796 unsigned char msg[200], state[10];
798 SQLINTEGER enable = 1;
799 char *tracefile = "/tmp/odbc.trace";
801 ast_mutex_lock(&obj->lock);
804 odbc_obj_disconnect(obj);
805 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
807 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
810 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
812 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
813 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
814 ast_mutex_unlock(&obj->lock);
817 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
818 SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
820 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
821 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
824 res = SQLConnect(obj->con,
825 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
826 (SQLCHAR *) obj->parent->username, SQL_NTS,
827 (SQLCHAR *) obj->parent->password, SQL_NTS);
829 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
830 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
831 ast_mutex_unlock(&obj->lock);
832 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
835 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
837 obj->last_used = ast_tvnow();
840 ast_mutex_unlock(&obj->lock);
844 static int reload(void)
846 struct odbc_cache_tables *table;
847 struct odbc_class *class;
848 struct odbc_obj *current;
849 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
851 /* First, mark all to be purged */
852 while ((class = ao2_iterator_next(&aoi))) {
859 /* Purge remaining classes */
861 /* Note on how this works; this is a case of circular references, so we
862 * explicitly do NOT want to use a callback here (or we wind up in
865 * 1. Iterate through all the classes. Note that the classes will currently
866 * contain two classes of the same name, one of which is marked delme and
867 * will be purged when all remaining objects of the class are released, and
868 * the other, which was created above when we re-parsed the config file.
869 * 2. On each class, there is a reference held by the master container and
870 * a reference held by each connection object. There are two cases for
871 * destruction of the class, noted below. However, in all cases, all O-refs
872 * (references to objects) will first be freed, which will cause the C-refs
873 * (references to classes) to be decremented (but never to 0, because the
874 * class container still has a reference).
875 * a) If the class has outstanding objects, the C-ref by the class
876 * container will then be freed, which leaves only C-refs by any
877 * outstanding objects. When the final outstanding object is released
878 * (O-refs held by applications and dialplan functions), it will in turn
879 * free the final C-ref, causing class destruction.
880 * b) If the class has no outstanding objects, when the class container
881 * removes the final C-ref, the class will be destroyed.
883 aoi = ao2_iterator_init(class_container, 0);
884 while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
886 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
887 while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
888 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
889 ao2_ref(current, -1); /* O-ref-- (by iterator) */
890 /* At this point, either
891 * a) there's an outstanding O-ref, or
892 * b) the object has already been destroyed.
895 ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
896 /* At this point, either
897 * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
898 * b) the last remaining C-ref is held by the iterator, which will be
899 * destroyed in the next step.
902 ao2_ref(class, -1); /* C-ref-- (by iterator) */
905 /* Empty the cache; it will get rebuilt the next time the tables are needed. */
906 AST_RWLIST_WRLOCK(&odbc_tables);
907 while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
908 destroy_table_cache(table);
910 AST_RWLIST_UNLOCK(&odbc_tables);
915 static int unload_module(void)
917 /* Prohibit unloading */
921 static int load_module(void)
923 if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
924 return AST_MODULE_LOAD_DECLINE;
925 if (load_odbc_config() == -1)
926 return AST_MODULE_LOAD_DECLINE;
927 ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
928 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
932 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
934 .unload = unload_module,