2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, 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>
28 * \author Tilghman Lesher <tilghman@digium.com>
30 * \arg See also: \ref cdr_odbc
34 <depend>generic_odbc</depend>
36 <support_level>core</support_level>
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"
53 #include "asterisk/app.h"
54 #include "asterisk/strings.h"
55 #include "asterisk/threadstorage.h"
56 #include "asterisk/data.h"
59 <function name="ODBC" language="en_US">
61 Controls ODBC transaction properties.
64 <parameter name="property" required="true">
66 <enum name="transaction">
67 <para>Gets or sets the active transaction ID. If set, and the transaction ID does not
68 exist and a <replaceable>database name</replaceable> is specified as an argument, it will be created.</para>
70 <enum name="forcecommit">
71 <para>Controls whether a transaction will be automatically committed when the channel
72 hangs up. Defaults to false. If a <replaceable>transaction ID</replaceable> is specified in the optional argument,
73 the property will be applied to that ID, otherwise to the current active ID.</para>
75 <enum name="isolation">
76 <para>Controls the data isolation on uncommitted transactions. May be one of the
77 following: <literal>read_committed</literal>, <literal>read_uncommitted</literal>,
78 <literal>repeatable_read</literal>, or <literal>serializable</literal>. Defaults to the
79 database setting in <filename>res_odbc.conf</filename> or <literal>read_committed</literal>
80 if not specified. If a <replaceable>transaction ID</replaceable> is specified as an optional argument, it will be
81 applied to that ID, otherwise the current active ID.</para>
85 <parameter name="argument" required="false" />
88 <para>The ODBC() function allows setting several properties to influence how a connected
89 database processes transactions.</para>
92 <application name="ODBC_Commit" language="en_US">
94 Commits a currently open database transaction.
97 <parameter name="transaction ID" required="no" />
100 <para>Commits the database transaction specified by <replaceable>transaction ID</replaceable>
101 or the current active transaction, if not specified.</para>
104 <application name="ODBC_Rollback" language="en_US">
106 Rollback a currently open database transaction.
109 <parameter name="transaction ID" required="no" />
112 <para>Rolls back the database transaction specified by <replaceable>transaction ID</replaceable>
113 or the current active transaction, if not specified.</para>
120 AST_LIST_ENTRY(odbc_class) list;
127 unsigned int haspool:1; /*!< Boolean - TDS databases need this */
128 unsigned int delme:1; /*!< Purge the class */
129 unsigned int backslash_is_escape:1; /*!< On this database, the backslash is a native escape sequence */
130 unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
131 unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
132 unsigned int limit; /*!< Maximum number of database handles we will allow */
133 int count; /*!< Running count of pooled connections */
134 unsigned int idlecheck; /*!< Recheck the connection if it is idle for this long (in seconds) */
135 unsigned int conntimeout; /*!< Maximum time the connection process should take */
136 /*! When a connection fails, cache that failure for how long? */
137 struct timeval negative_connection_cache;
138 /*! When a connection fails, when did that last occur? */
139 struct timeval last_negative_connect;
140 /*! List of handles associated with this class */
141 struct ao2_container *obj_container;
144 static struct ao2_container *class_container;
146 static AST_RWLIST_HEAD_STATIC(odbc_tables, odbc_cache_tables);
148 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
149 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
150 static int odbc_register_class(struct odbc_class *class, int connect);
151 static void odbc_txn_free(void *data);
152 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx);
154 AST_THREADSTORAGE(errors_buf);
156 static struct ast_datastore_info txn_info = {
157 .type = "ODBC_Transaction",
158 .destroy = odbc_txn_free,
161 struct odbc_txn_frame {
162 AST_LIST_ENTRY(odbc_txn_frame) list;
163 struct ast_channel *owner;
164 struct odbc_obj *obj; /*!< Database handle within which transacted statements are run */
165 /*!\brief Is this record the current active transaction within the channel?
166 * Note that the active flag is really only necessary for statements which
167 * are triggered from the dialplan, as there isn't a direct correlation
168 * between multiple statements. Applications wishing to use transactions
169 * may simply perform each statement on the same odbc_obj, which keeps the
170 * transaction persistent.
172 unsigned int active:1;
173 unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
174 unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
175 char name[0]; /*!< Name of this transaction ID */
178 #define DATA_EXPORT_ODBC_CLASS(MEMBER) \
179 MEMBER(odbc_class, name, AST_DATA_STRING) \
180 MEMBER(odbc_class, dsn, AST_DATA_STRING) \
181 MEMBER(odbc_class, username, AST_DATA_STRING) \
182 MEMBER(odbc_class, password, AST_DATA_PASSWORD) \
183 MEMBER(odbc_class, limit, AST_DATA_INTEGER) \
184 MEMBER(odbc_class, count, AST_DATA_INTEGER) \
185 MEMBER(odbc_class, forcecommit, AST_DATA_BOOLEAN)
187 AST_DATA_STRUCTURE(odbc_class, DATA_EXPORT_ODBC_CLASS);
189 static const char *isolation2text(int iso)
191 if (iso == SQL_TXN_READ_COMMITTED) {
192 return "read_committed";
193 } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
194 return "read_uncommitted";
195 } else if (iso == SQL_TXN_SERIALIZABLE) {
196 return "serializable";
197 } else if (iso == SQL_TXN_REPEATABLE_READ) {
198 return "repeatable_read";
204 static int text2isolation(const char *txt)
206 if (strncasecmp(txt, "read_", 5) == 0) {
207 if (strncasecmp(txt + 5, "c", 1) == 0) {
208 return SQL_TXN_READ_COMMITTED;
209 } else if (strncasecmp(txt + 5, "u", 1) == 0) {
210 return SQL_TXN_READ_UNCOMMITTED;
214 } else if (strncasecmp(txt, "ser", 3) == 0) {
215 return SQL_TXN_SERIALIZABLE;
216 } else if (strncasecmp(txt, "rep", 3) == 0) {
217 return SQL_TXN_REPEATABLE_READ;
223 static struct odbc_txn_frame *find_transaction(struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
225 struct ast_datastore *txn_store;
226 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
227 struct odbc_txn_frame *txn = NULL;
229 if (!chan && obj && obj->txf && obj->txf->owner) {
230 chan = obj->txf->owner;
232 /* No channel == no transaction */
236 ast_channel_lock(chan);
237 if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
238 oldlist = txn_store->data;
240 /* Need to create a new datastore */
241 if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
242 ast_log(LOG_ERROR, "Unable to allocate a new datastore. Cannot create a new transaction.\n");
243 ast_channel_unlock(chan);
247 if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
248 ast_log(LOG_ERROR, "Unable to allocate datastore list head. Cannot create a new transaction.\n");
249 ast_datastore_free(txn_store);
250 ast_channel_unlock(chan);
254 txn_store->data = oldlist;
255 AST_LIST_HEAD_INIT(oldlist);
256 ast_channel_datastore_add(chan, txn_store);
259 AST_LIST_LOCK(oldlist);
260 ast_channel_unlock(chan);
262 /* Scanning for an object is *fast*. Scanning for a name is much slower. */
263 if (obj != NULL || active == 1) {
264 AST_LIST_TRAVERSE(oldlist, txn, list) {
265 if (txn->obj == obj || txn->active) {
266 AST_LIST_UNLOCK(oldlist);
273 AST_LIST_TRAVERSE(oldlist, txn, list) {
274 if (!strcasecmp(txn->name, name)) {
275 AST_LIST_UNLOCK(oldlist);
281 /* Nothing found, create one */
282 if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
283 struct odbc_txn_frame *otxn;
285 strcpy(txn->name, name); /* SAFE */
287 txn->isolation = obj->parent->isolation;
288 txn->forcecommit = obj->parent->forcecommit;
292 /* On creation, the txn becomes active, and all others inactive */
293 AST_LIST_TRAVERSE(oldlist, otxn, list) {
296 AST_LIST_INSERT_TAIL(oldlist, txn, list);
301 AST_LIST_UNLOCK(oldlist);
306 static struct odbc_txn_frame *release_transaction(struct odbc_txn_frame *tx)
312 ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
314 /* If we have an owner, disassociate */
316 struct ast_datastore *txn_store;
317 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
319 ast_channel_lock(tx->owner);
320 if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
321 oldlist = txn_store->data;
322 AST_LIST_LOCK(oldlist);
323 AST_LIST_REMOVE(oldlist, tx, list);
324 AST_LIST_UNLOCK(oldlist);
326 ast_channel_unlock(tx->owner);
331 /* If we have any uncommitted transactions, they are handled when we release the object */
332 struct odbc_obj *obj = tx->obj;
333 /* Prevent recursion during destruction */
336 odbc_release_obj2(obj, tx);
342 static void odbc_txn_free(void *vdata)
344 struct odbc_txn_frame *tx;
345 AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
347 ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
349 AST_LIST_LOCK(oldlist);
350 while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
351 release_transaction(tx);
353 AST_LIST_UNLOCK(oldlist);
354 AST_LIST_HEAD_DESTROY(oldlist);
358 static int mark_transaction_active(struct ast_channel *chan, struct odbc_txn_frame *tx)
360 struct ast_datastore *txn_store;
361 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
362 struct odbc_txn_frame *active = NULL, *txn;
364 if (!chan && tx && tx->owner) {
368 ast_channel_lock(chan);
369 if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
370 ast_channel_unlock(chan);
374 oldlist = txn_store->data;
375 AST_LIST_LOCK(oldlist);
376 AST_LIST_TRAVERSE(oldlist, txn, list) {
384 AST_LIST_UNLOCK(oldlist);
385 ast_channel_unlock(chan);
386 return active ? 0 : -1;
389 static void odbc_class_destructor(void *data)
391 struct odbc_class *class = data;
392 /* Due to refcounts, we can safely assume that any objects with a reference
393 * to us will prevent our destruction, so we don't need to worry about them.
395 if (class->username) {
396 ast_free(class->username);
398 if (class->password) {
399 ast_free(class->password);
401 if (class->sanitysql) {
402 ast_free(class->sanitysql);
404 ao2_ref(class->obj_container, -1);
405 SQLFreeHandle(SQL_HANDLE_ENV, class->env);
408 static int null_hash_fn(const void *obj, const int flags)
413 static void odbc_obj_destructor(void *data)
415 struct odbc_obj *obj = data;
416 struct odbc_class *class = obj->parent;
418 odbc_obj_disconnect(obj);
419 ast_mutex_destroy(&obj->lock);
423 static void destroy_table_cache(struct odbc_cache_tables *table) {
424 struct odbc_cache_columns *col;
425 ast_debug(1, "Destroying table cache for %s\n", table->table);
426 AST_RWLIST_WRLOCK(&table->columns);
427 while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
430 AST_RWLIST_UNLOCK(&table->columns);
431 AST_RWLIST_HEAD_DESTROY(&table->columns);
436 * \brief Find or create an entry describing the table specified.
437 * \param database Name of an ODBC class on which to query the table
438 * \param tablename Tablename to describe
439 * \retval A structure describing the table layout, or NULL, if the table is not found or another error occurs.
440 * When a structure is returned, the contained columns list will be
441 * rdlock'ed, to ensure that it will be retained in memory.
444 struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
446 struct odbc_cache_tables *tableptr;
447 struct odbc_cache_columns *entry;
450 SQLHSTMT stmt = NULL;
451 int res = 0, error = 0, try = 0;
452 struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
454 AST_RWLIST_RDLOCK(&odbc_tables);
455 AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
456 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
461 AST_RWLIST_RDLOCK(&tableptr->columns);
462 AST_RWLIST_UNLOCK(&odbc_tables);
464 ast_odbc_release_obj(obj);
470 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
471 AST_RWLIST_UNLOCK(&odbc_tables);
475 /* Table structure not already cached; build it now. */
477 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
478 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
481 ast_odbc_sanity_check(obj);
484 ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
488 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
489 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
492 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
493 ast_odbc_sanity_check(obj);
496 ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
500 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
501 ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
505 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
506 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
507 strcpy(tableptr->connection, database); /* SAFE */
508 strcpy(tableptr->table, tablename); /* SAFE */
509 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
511 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
512 SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
514 if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
515 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
519 entry->name = (char *)entry + sizeof(*entry);
520 strcpy(entry->name, columnname);
522 SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
523 SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
524 SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
525 SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
526 SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
527 SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
529 /* Specification states that the octenlen should be the maximum number of bytes
530 * returned in a char or binary column, but it seems that some drivers just set
531 * it to NULL. (Bad Postgres! No biscuit!) */
532 if (entry->octetlen == 0) {
533 entry->octetlen = entry->size;
536 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);
537 /* Insert column info into column list */
538 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
540 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
542 AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
543 AST_RWLIST_RDLOCK(&(tableptr->columns));
547 AST_RWLIST_UNLOCK(&odbc_tables);
550 destroy_table_cache(tableptr);
554 ast_odbc_release_obj(obj);
559 struct odbc_cache_columns *ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
561 struct odbc_cache_columns *col;
562 AST_RWLIST_TRAVERSE(&table->columns, col, list) {
563 if (strcasecmp(col->name, colname) == 0) {
570 int ast_odbc_clear_cache(const char *database, const char *tablename)
572 struct odbc_cache_tables *tableptr;
574 AST_RWLIST_WRLOCK(&odbc_tables);
575 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
576 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
577 AST_LIST_REMOVE_CURRENT(list);
578 destroy_table_cache(tableptr);
582 AST_RWLIST_TRAVERSE_SAFE_END
583 AST_RWLIST_UNLOCK(&odbc_tables);
584 return tableptr ? 0 : -1;
587 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
592 for (attempt = 0; attempt < 2; attempt++) {
593 stmt = exec_cb(obj, data);
597 } else if (obj->tx) {
598 ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
600 } else if (attempt == 0) {
601 ast_log(LOG_WARNING, "SQL Execute error! Verifying connection to %s [%s]...\n", obj->parent->name, obj->parent->dsn);
603 if (!ast_odbc_sanity_check(obj)) {
611 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
613 int res = 0, i, attempt;
614 SQLINTEGER nativeerror=0, numfields=0;
615 SQLSMALLINT diagbytes=0;
616 unsigned char state[10], diagnostic[256];
619 for (attempt = 0; attempt < 2; attempt++) {
620 /* This prepare callback may do more than just prepare -- it may also
621 * bind parameters, bind results, etc. The real key, here, is that
622 * when we disconnect, all handles become invalid for most databases.
623 * We must therefore redo everything when we establish a new
625 stmt = prepare_cb(obj, data);
628 res = SQLExecute(stmt);
629 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
630 if (res == SQL_ERROR) {
631 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
632 for (i = 0; i < numfields; i++) {
633 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
634 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
636 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
643 ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
646 ast_log(LOG_WARNING, "SQL Execute error %d! Verifying connection to %s [%s]...\n", res, obj->parent->name, obj->parent->dsn);
647 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
652 * While this isn't the best way to try to correct an error, this won't automatically
653 * fail when the statement handle invalidates.
655 if (!ast_odbc_sanity_check(obj)) {
661 obj->last_used = ast_tvnow();
664 } else if (attempt == 0) {
665 ast_odbc_sanity_check(obj);
672 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
675 SQLINTEGER nativeerror=0, numfields=0;
676 SQLSMALLINT diagbytes=0;
677 unsigned char state[10], diagnostic[256];
679 res = SQLExecute(stmt);
680 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
681 if (res == SQL_ERROR) {
682 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
683 for (i = 0; i < numfields; i++) {
684 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
685 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
687 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
693 obj->last_used = ast_tvnow();
699 SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
704 if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
705 ast_str_make_space(buf, *StrLen_or_Ind + 1);
707 } else if (pmaxlen > 0) {
708 ast_str_make_space(buf, pmaxlen);
710 res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
711 ast_str_update(*buf);
716 int ast_odbc_sanity_check(struct odbc_obj *obj)
718 char *test_sql = "select 1";
722 if (!ast_strlen_zero(obj->parent->sanitysql))
723 test_sql = obj->parent->sanitysql;
726 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
727 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
730 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
731 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
734 res = SQLExecute(stmt);
735 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
740 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
743 if (!obj->up && !obj->tx) { /* Try to reconnect! */
744 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
745 odbc_obj_disconnect(obj);
746 odbc_obj_connect(obj);
751 static int load_odbc_config(void)
753 static char *cfg = "res_odbc.conf";
754 struct ast_config *config;
755 struct ast_variable *v;
757 const char *dsn, *username, *password, *sanitysql;
758 int enabled, pooling, limit, bse, conntimeout, forcecommit, isolation;
759 struct timeval ncache = { 0, 0 };
760 unsigned int idlecheck;
761 int preconnect = 0, res = 0;
762 struct ast_flags config_flags = { 0 };
764 struct odbc_class *new;
766 config = ast_config_load(cfg, config_flags);
767 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
768 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
771 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
772 if (!strcasecmp(cat, "ENV")) {
773 for (v = ast_variable_browse(config, cat); v; v = v->next) {
774 setenv(v->name, v->value, 1);
775 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
778 /* Reset all to defaults for each class of odbc connections */
779 dsn = username = password = sanitysql = NULL;
781 preconnect = idlecheck = 0;
787 isolation = SQL_TXN_READ_COMMITTED;
788 for (v = ast_variable_browse(config, cat); v; v = v->next) {
789 if (!strcasecmp(v->name, "pooling")) {
790 if (ast_true(v->value))
792 } else if (!strncasecmp(v->name, "share", 5)) {
793 /* "shareconnections" is a little clearer in meaning than "pooling" */
794 if (ast_false(v->value))
796 } else if (!strcasecmp(v->name, "limit")) {
797 sscanf(v->value, "%30d", &limit);
798 if (ast_true(v->value) && !limit) {
799 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);
801 } else if (ast_false(v->value)) {
802 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
806 } else if (!strcasecmp(v->name, "idlecheck")) {
807 sscanf(v->value, "%30u", &idlecheck);
808 } else if (!strcasecmp(v->name, "enabled")) {
809 enabled = ast_true(v->value);
810 } else if (!strcasecmp(v->name, "pre-connect")) {
811 preconnect = ast_true(v->value);
812 } else if (!strcasecmp(v->name, "dsn")) {
814 } else if (!strcasecmp(v->name, "username")) {
816 } else if (!strcasecmp(v->name, "password")) {
818 } else if (!strcasecmp(v->name, "sanitysql")) {
819 sanitysql = v->value;
820 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
821 bse = ast_true(v->value);
822 } else if (!strcasecmp(v->name, "connect_timeout")) {
823 if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
824 ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
827 } else if (!strcasecmp(v->name, "negative_connection_cache")) {
829 if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
830 ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
831 /* 5 minutes sounds like a reasonable default */
835 ncache.tv_sec = (int)dncache;
836 ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
838 } else if (!strcasecmp(v->name, "forcecommit")) {
839 forcecommit = ast_true(v->value);
840 } else if (!strcasecmp(v->name, "isolation")) {
841 if ((isolation = text2isolation(v->value)) == 0) {
842 ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
843 isolation = SQL_TXN_READ_COMMITTED;
848 if (enabled && !ast_strlen_zero(dsn)) {
849 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
856 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
857 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
859 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
860 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
865 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
868 new->haspool = pooling;
872 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
877 new->backslash_is_escape = bse ? 1 : 0;
878 new->forcecommit = forcecommit ? 1 : 0;
879 new->isolation = isolation;
880 new->idlecheck = idlecheck;
881 new->conntimeout = conntimeout;
882 new->negative_connection_cache = ncache;
885 ast_copy_string(new->name, cat, sizeof(new->name));
887 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
888 if (username && !(new->username = ast_strdup(username))) {
892 if (password && !(new->password = ast_strdup(password))) {
896 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
901 odbc_register_class(new, preconnect);
902 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
908 ast_config_destroy(config);
912 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
914 struct ao2_iterator aoi;
915 struct odbc_class *class;
916 struct odbc_obj *current;
923 e->command = "odbc show";
925 "Usage: odbc show [class]\n"
926 " List settings of a particular ODBC class or,\n"
927 " if not specified, all classes.\n";
932 length = strlen(a->word);
933 aoi = ao2_iterator_init(class_container, 0);
934 while ((class = ao2_iterator_next(&aoi))) {
935 if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
936 ret = ast_strdup(class->name);
943 ao2_iterator_destroy(&aoi);
944 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
945 ret = ast_strdup("all");
950 ast_cli(a->fd, "\nODBC DSN Settings\n");
951 ast_cli(a->fd, "-----------------\n\n");
952 aoi = ao2_iterator_init(class_container, 0);
953 while ((class = ao2_iterator_next(&aoi))) {
954 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
959 ast_localtime(&class->last_negative_connect, &tm, NULL);
960 ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
961 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
962 ast_cli(a->fd, " Last connection attempt: %s\n", timestr);
964 if (class->haspool) {
965 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
967 ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
969 while ((current = ao2_iterator_next(&aoi2))) {
970 ast_mutex_lock(¤t->lock);
972 ast_cli(a->fd, " - Connection %d: %s (%s:%d %s)\n", ++count,
973 current->used ? "in use" :
974 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
975 current->file, current->lineno, current->function);
977 ast_cli(a->fd, " - Connection %d: %s\n", ++count,
978 current->used ? "in use" :
979 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
981 ast_mutex_unlock(¤t->lock);
982 ao2_ref(current, -1);
984 ao2_iterator_destroy(&aoi2);
986 /* Should only ever be one of these (unless there are transactions) */
987 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
988 while ((current = ao2_iterator_next(&aoi2))) {
989 ast_cli(a->fd, " Pooled: No\n Connected: %s\n", current->used ? "In use" :
990 current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
991 ao2_ref(current, -1);
993 ao2_iterator_destroy(&aoi2);
995 ast_cli(a->fd, "\n");
999 ao2_iterator_destroy(&aoi);
1004 static struct ast_cli_entry cli_odbc[] = {
1005 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
1008 static int odbc_register_class(struct odbc_class *class, int preconnect)
1010 struct odbc_obj *obj;
1012 ao2_link(class_container, class);
1013 /* I still have a reference in the caller, so a deref is NOT missing here. */
1016 /* Request and release builds a connection */
1017 obj = ast_odbc_request_obj(class->name, 0);
1019 ast_odbc_release_obj(obj);
1025 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
1030 static void odbc_release_obj2(struct odbc_obj *obj, struct odbc_txn_frame *tx)
1032 SQLINTEGER nativeerror=0, numfields=0;
1033 SQLSMALLINT diagbytes=0, i;
1034 unsigned char state[10], diagnostic[256];
1036 ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
1038 ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
1039 if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
1040 /* Handle possible transaction commit failure */
1041 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1042 for (i = 0; i < numfields; i++) {
1043 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1044 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1045 if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
1046 /* These codes mean that a commit failed and a transaction
1047 * is still active. We must rollback, or things will get
1048 * very, very weird for anybody using the handle next. */
1049 SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
1052 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1058 /* Transaction is done, reset autocommit */
1059 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1060 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1061 for (i = 0; i < numfields; i++) {
1062 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1063 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1065 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1072 #ifdef DEBUG_THREADS
1073 obj->file[0] = '\0';
1074 obj->function[0] = '\0';
1078 /* For pooled connections, this frees the connection to be
1079 * reused. For non-pooled connections, it does nothing. */
1082 /* Prevent recursion -- transaction is already closed out. */
1083 obj->txf->obj = NULL;
1084 obj->txf = release_transaction(obj->txf);
1089 void ast_odbc_release_obj(struct odbc_obj *obj)
1091 struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
1092 odbc_release_obj2(obj, tx);
1095 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
1097 return obj->parent->backslash_is_escape;
1100 static int commit_exec(struct ast_channel *chan, const char *data)
1102 struct odbc_txn_frame *tx;
1103 SQLINTEGER nativeerror=0, numfields=0;
1104 SQLSMALLINT diagbytes=0, i;
1105 unsigned char state[10], diagnostic[256];
1107 if (ast_strlen_zero(data)) {
1108 tx = find_transaction(chan, NULL, NULL, 1);
1110 tx = find_transaction(chan, NULL, data, 0);
1113 pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
1116 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
1117 struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1118 ast_str_reset(errors);
1120 /* Handle possible transaction commit failure */
1121 SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1122 for (i = 0; i < numfields; i++) {
1123 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1124 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1125 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1127 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1131 pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
1137 static int rollback_exec(struct ast_channel *chan, const char *data)
1139 struct odbc_txn_frame *tx;
1140 SQLINTEGER nativeerror=0, numfields=0;
1141 SQLSMALLINT diagbytes=0, i;
1142 unsigned char state[10], diagnostic[256];
1144 if (ast_strlen_zero(data)) {
1145 tx = find_transaction(chan, NULL, NULL, 1);
1147 tx = find_transaction(chan, NULL, data, 0);
1150 pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
1153 if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
1154 struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
1155 ast_str_reset(errors);
1157 /* Handle possible transaction commit failure */
1158 SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1159 for (i = 0; i < numfields; i++) {
1160 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1161 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
1162 ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
1164 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1168 pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
1174 static int aoro2_class_cb(void *obj, void *arg, int flags)
1176 struct odbc_class *class = obj;
1178 if (!strcmp(class->name, name) && !class->delme) {
1179 return CMP_MATCH | CMP_STOP;
1184 #define USE_TX (void *)(long)1
1185 #define NO_TX (void *)(long)2
1186 #define EOR_TX (void *)(long)3
1188 static int aoro2_obj_cb(void *vobj, void *arg, int flags)
1190 struct odbc_obj *obj = vobj;
1191 ast_mutex_lock(&obj->lock);
1192 if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
1194 ast_mutex_unlock(&obj->lock);
1195 return CMP_MATCH | CMP_STOP;
1197 ast_mutex_unlock(&obj->lock);
1201 struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
1203 struct odbc_obj *obj = NULL;
1204 struct odbc_class *class;
1205 SQLINTEGER nativeerror=0, numfields=0;
1206 SQLSMALLINT diagbytes=0, i;
1207 unsigned char state[10], diagnostic[256];
1209 if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
1210 ast_debug(1, "Class '%s' not found!\n", name);
1214 ast_assert(ao2_ref(class, 0) > 1);
1216 if (class->haspool) {
1217 /* Recycle connections before building another */
1218 obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
1221 ast_assert(ao2_ref(obj, 0) > 1);
1223 if (!obj && (ast_atomic_fetchadd_int(&class->count, +1) < class->limit) &&
1224 (time(NULL) > class->last_negative_connect.tv_sec + class->negative_connection_cache.tv_sec)) {
1225 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1229 ast_debug(3, "Unable to allocate object\n");
1230 ast_atomic_fetchadd_int(&class->count, -1);
1233 ast_assert(ao2_ref(obj, 0) == 1);
1234 ast_mutex_init(&obj->lock);
1235 /* obj inherits the outstanding reference to class */
1236 obj->parent = class;
1238 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1239 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1240 ast_assert(ao2_ref(obj->parent, 0) > 0);
1241 /* Because it was never within the container, we have to manually decrement the count here */
1242 ast_atomic_fetchadd_int(&obj->parent->count, -1);
1247 ao2_link(obj->parent->obj_container, obj);
1250 /* If construction fails due to the limit (or negative timecache), reverse our increment. */
1252 ast_atomic_fetchadd_int(&class->count, -1);
1254 /* Object is not constructed, so delete outstanding reference to class. */
1259 if (obj && ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1260 /* Ensure this connection has autocommit turned off. */
1261 if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1262 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1263 for (i = 0; i < numfields; i++) {
1264 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1265 ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1267 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1273 } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
1274 /* Non-pooled connections -- but must use a separate connection handle */
1275 if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
1276 ast_debug(1, "Object not found\n");
1277 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
1280 ast_debug(3, "Unable to allocate object\n");
1283 ast_mutex_init(&obj->lock);
1284 /* obj inherits the outstanding reference to class */
1285 obj->parent = class;
1287 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1288 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1293 ao2_link(obj->parent->obj_container, obj);
1294 ast_atomic_fetchadd_int(&obj->parent->count, +1);
1298 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
1299 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1300 for (i = 0; i < numfields; i++) {
1301 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1302 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1304 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1310 /* Non-pooled connection: multiple modules can use the same connection. */
1311 if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, NO_TX))) {
1312 /* Object is not constructed, so delete outstanding reference to class. */
1313 ast_assert(ao2_ref(class, 0) > 1);
1317 /* No entry: build one */
1318 if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
1319 ast_assert(ao2_ref(class, 0) > 1);
1321 ast_debug(3, "Unable to allocate object\n");
1324 ast_mutex_init(&obj->lock);
1325 /* obj inherits the outstanding reference to class */
1326 obj->parent = class;
1328 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1329 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
1333 ao2_link(obj->parent->obj_container, obj);
1334 ast_assert(ao2_ref(obj, 0) > 1);
1338 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
1339 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1340 for (i = 0; i < numfields; i++) {
1341 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1342 ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
1344 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1351 /* Set the isolation property */
1352 if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
1353 SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1354 for (i = 0; i < numfields; i++) {
1355 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1356 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1358 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1364 if (obj && ast_test_flag(&flags, RES_ODBC_CONNECTED) && !obj->up) {
1365 /* Check if this connection qualifies for reconnection, with negative connection cache time */
1366 if (time(NULL) > obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec) {
1367 odbc_obj_connect(obj);
1369 } else if (obj && ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
1370 ast_odbc_sanity_check(obj);
1371 } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck) {
1372 odbc_obj_connect(obj);
1375 #ifdef DEBUG_THREADS
1377 ast_copy_string(obj->file, file, sizeof(obj->file));
1378 ast_copy_string(obj->function, function, sizeof(obj->function));
1379 obj->lineno = lineno;
1382 ast_assert(class == NULL);
1385 ast_assert(ao2_ref(obj, 0) > 1);
1390 struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
1392 struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
1393 return _ast_odbc_request_obj2(name, flags, file, function, lineno);
1396 struct odbc_obj *ast_odbc_retrieve_transaction_obj(struct ast_channel *chan, const char *objname)
1398 struct ast_datastore *txn_store;
1399 AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
1400 struct odbc_txn_frame *txn = NULL;
1403 /* No channel == no transaction */
1407 ast_channel_lock(chan);
1408 if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
1409 oldlist = txn_store->data;
1411 ast_channel_unlock(chan);
1415 AST_LIST_LOCK(oldlist);
1416 ast_channel_unlock(chan);
1418 AST_LIST_TRAVERSE(oldlist, txn, list) {
1419 if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
1420 AST_LIST_UNLOCK(oldlist);
1424 AST_LIST_UNLOCK(oldlist);
1428 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
1433 unsigned char msg[200], state[10];
1435 /* Nothing to disconnect */
1437 return ODBC_SUCCESS;
1440 ast_mutex_lock(&obj->lock);
1442 res = SQLDisconnect(obj->con);
1445 if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
1446 ast_debug(1, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
1448 ast_debug(1, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
1452 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
1454 ast_debug(1, "Database handle deallocated\n");
1456 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1457 ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
1461 ast_mutex_unlock(&obj->lock);
1462 return ODBC_SUCCESS;
1465 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
1470 unsigned char msg[200], state[10];
1472 SQLINTEGER enable = 1;
1473 char *tracefile = "/tmp/odbc.trace";
1475 ast_mutex_lock(&obj->lock);
1478 odbc_obj_disconnect(obj);
1479 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
1481 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
1484 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
1486 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1487 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
1488 obj->parent->last_negative_connect = ast_tvnow();
1489 ast_mutex_unlock(&obj->lock);
1492 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1493 SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1495 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
1496 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
1499 res = SQLConnect(obj->con,
1500 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
1501 (SQLCHAR *) obj->parent->username, SQL_NTS,
1502 (SQLCHAR *) obj->parent->password, SQL_NTS);
1504 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1505 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
1506 obj->parent->last_negative_connect = ast_tvnow();
1507 ast_mutex_unlock(&obj->lock);
1508 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
1511 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
1513 obj->last_used = ast_tvnow();
1516 ast_mutex_unlock(&obj->lock);
1517 return ODBC_SUCCESS;
1520 static int acf_transaction_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
1522 AST_DECLARE_APP_ARGS(args,
1523 AST_APP_ARG(property);
1526 struct odbc_txn_frame *tx;
1528 AST_STANDARD_APP_ARGS(args, data);
1529 if (strcasecmp(args.property, "transaction") == 0) {
1530 if ((tx = find_transaction(chan, NULL, NULL, 1))) {
1531 ast_copy_string(buf, tx->name, len);
1534 } else if (strcasecmp(args.property, "isolation") == 0) {
1535 if (!ast_strlen_zero(args.opt)) {
1536 tx = find_transaction(chan, NULL, args.opt, 0);
1538 tx = find_transaction(chan, NULL, NULL, 1);
1541 ast_copy_string(buf, isolation2text(tx->isolation), len);
1544 } else if (strcasecmp(args.property, "forcecommit") == 0) {
1545 if (!ast_strlen_zero(args.opt)) {
1546 tx = find_transaction(chan, NULL, args.opt, 0);
1548 tx = find_transaction(chan, NULL, NULL, 1);
1551 ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
1558 static int acf_transaction_write(struct ast_channel *chan, const char *cmd, char *s, const char *value)
1560 AST_DECLARE_APP_ARGS(args,
1561 AST_APP_ARG(property);
1564 struct odbc_txn_frame *tx;
1565 SQLINTEGER nativeerror=0, numfields=0;
1566 SQLSMALLINT diagbytes=0, i;
1567 unsigned char state[10], diagnostic[256];
1569 AST_STANDARD_APP_ARGS(args, s);
1570 if (strcasecmp(args.property, "transaction") == 0) {
1571 /* Set active transaction */
1572 struct odbc_obj *obj;
1573 if ((tx = find_transaction(chan, NULL, value, 0))) {
1574 mark_transaction_active(chan, tx);
1576 /* No such transaction, create one */
1577 struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
1578 if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
1579 ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
1580 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
1583 if (!(tx = find_transaction(chan, obj, value, 0))) {
1584 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1589 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1591 } else if (strcasecmp(args.property, "forcecommit") == 0) {
1592 /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
1593 if (ast_strlen_zero(args.opt)) {
1594 tx = find_transaction(chan, NULL, NULL, 1);
1596 tx = find_transaction(chan, NULL, args.opt, 0);
1599 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1602 if (ast_true(value)) {
1603 tx->forcecommit = 1;
1604 } else if (ast_false(value)) {
1605 tx->forcecommit = 0;
1607 ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
1608 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1612 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1614 } else if (strcasecmp(args.property, "isolation") == 0) {
1615 /* How do uncommitted transactions affect reads? */
1616 int isolation = text2isolation(value);
1617 if (ast_strlen_zero(args.opt)) {
1618 tx = find_transaction(chan, NULL, NULL, 1);
1620 tx = find_transaction(chan, NULL, args.opt, 0);
1623 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
1626 if (isolation == 0) {
1627 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
1628 ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
1629 } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
1630 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
1631 SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
1632 for (i = 0; i < numfields; i++) {
1633 SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
1634 ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
1636 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
1641 pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
1642 tx->isolation = isolation;
1646 ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
1651 static struct ast_custom_function odbc_function = {
1653 .read = acf_transaction_read,
1654 .write = acf_transaction_write,
1657 static const char * const app_commit = "ODBC_Commit";
1658 static const char * const app_rollback = "ODBC_Rollback";
1662 * \brief Implements the channels provider.
1664 static int data_odbc_provider_handler(const struct ast_data_search *search,
1665 struct ast_data *root)
1667 struct ao2_iterator aoi, aoi2;
1668 struct odbc_class *class;
1669 struct odbc_obj *current;
1670 struct ast_data *data_odbc_class, *data_odbc_connections, *data_odbc_connection;
1671 struct ast_data *enum_node;
1674 aoi = ao2_iterator_init(class_container, 0);
1675 while ((class = ao2_iterator_next(&aoi))) {
1676 data_odbc_class = ast_data_add_node(root, "class");
1677 if (!data_odbc_class) {
1682 ast_data_add_structure(odbc_class, data_odbc_class, class);
1684 if (!ao2_container_count(class->obj_container)) {
1689 data_odbc_connections = ast_data_add_node(data_odbc_class, "connections");
1690 if (!data_odbc_connections) {
1695 ast_data_add_bool(data_odbc_class, "shared", !class->haspool);
1697 enum_node = ast_data_add_node(data_odbc_class, "isolation");
1702 ast_data_add_int(enum_node, "value", class->isolation);
1703 ast_data_add_str(enum_node, "text", isolation2text(class->isolation));
1706 aoi2 = ao2_iterator_init(class->obj_container, 0);
1707 while ((current = ao2_iterator_next(&aoi2))) {
1708 data_odbc_connection = ast_data_add_node(data_odbc_connections, "connection");
1709 if (!data_odbc_connection) {
1710 ao2_ref(current, -1);
1714 ast_mutex_lock(¤t->lock);
1715 ast_data_add_str(data_odbc_connection, "status", current->used ? "in use" :
1716 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
1717 ast_data_add_bool(data_odbc_connection, "transactional", current->tx);
1718 ast_mutex_unlock(¤t->lock);
1720 if (class->haspool) {
1721 ast_data_add_int(data_odbc_connection, "number", ++count);
1724 ao2_ref(current, -1);
1726 ao2_iterator_destroy(&aoi2);
1729 if (!ast_data_search_match(search, data_odbc_class)) {
1730 ast_data_remove_node(root, data_odbc_class);
1733 ao2_iterator_destroy(&aoi);
1739 * \brief /asterisk/res/odbc/listprovider.
1741 static const struct ast_data_handler odbc_provider = {
1742 .version = AST_DATA_HANDLER_VERSION,
1743 .get = data_odbc_provider_handler
1746 static const struct ast_data_entry odbc_providers[] = {
1747 AST_DATA_ENTRY("/asterisk/res/odbc", &odbc_provider),
1750 static int reload(void)
1752 struct odbc_cache_tables *table;
1753 struct odbc_class *class;
1754 struct odbc_obj *current;
1755 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
1757 /* First, mark all to be purged */
1758 while ((class = ao2_iterator_next(&aoi))) {
1762 ao2_iterator_destroy(&aoi);
1766 /* Purge remaining classes */
1768 /* Note on how this works; this is a case of circular references, so we
1769 * explicitly do NOT want to use a callback here (or we wind up in
1772 * 1. Iterate through all the classes. Note that the classes will currently
1773 * contain two classes of the same name, one of which is marked delme and
1774 * will be purged when all remaining objects of the class are released, and
1775 * the other, which was created above when we re-parsed the config file.
1776 * 2. On each class, there is a reference held by the master container and
1777 * a reference held by each connection object. There are two cases for
1778 * destruction of the class, noted below. However, in all cases, all O-refs
1779 * (references to objects) will first be freed, which will cause the C-refs
1780 * (references to classes) to be decremented (but never to 0, because the
1781 * class container still has a reference).
1782 * a) If the class has outstanding objects, the C-ref by the class
1783 * container will then be freed, which leaves only C-refs by any
1784 * outstanding objects. When the final outstanding object is released
1785 * (O-refs held by applications and dialplan functions), it will in turn
1786 * free the final C-ref, causing class destruction.
1787 * b) If the class has no outstanding objects, when the class container
1788 * removes the final C-ref, the class will be destroyed.
1790 aoi = ao2_iterator_init(class_container, 0);
1791 while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
1793 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
1794 while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
1795 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
1796 ao2_ref(current, -1); /* O-ref-- (by iterator) */
1797 /* At this point, either
1798 * a) there's an outstanding O-ref, or
1799 * b) the object has already been destroyed.
1802 ao2_iterator_destroy(&aoi2);
1803 ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
1804 /* At this point, either
1805 * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
1806 * b) the last remaining C-ref is held by the iterator, which will be
1807 * destroyed in the next step.
1810 ao2_ref(class, -1); /* C-ref-- (by iterator) */
1812 ao2_iterator_destroy(&aoi);
1814 /* Empty the cache; it will get rebuilt the next time the tables are needed. */
1815 AST_RWLIST_WRLOCK(&odbc_tables);
1816 while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
1817 destroy_table_cache(table);
1819 AST_RWLIST_UNLOCK(&odbc_tables);
1824 static int unload_module(void)
1826 /* Prohibit unloading */
1830 static int load_module(void)
1832 if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
1833 return AST_MODULE_LOAD_DECLINE;
1834 if (load_odbc_config() == -1)
1835 return AST_MODULE_LOAD_DECLINE;
1836 ast_cli_register_multiple(cli_odbc, ARRAY_LEN(cli_odbc));
1837 ast_data_register_multiple(odbc_providers, ARRAY_LEN(odbc_providers));
1838 ast_register_application_xml(app_commit, commit_exec);
1839 ast_register_application_xml(app_rollback, rollback_exec);
1840 ast_custom_function_register(&odbc_function);
1841 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
1845 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "ODBC resource",
1846 .load = load_module,
1847 .unload = unload_module,
1849 .load_pri = AST_MODPRI_REALTIME_DEPEND,