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
33 <depend>unixodbc</depend>
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include "asterisk/file.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/config.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/module.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/res_odbc.h"
49 #include "asterisk/time.h"
50 #include "asterisk/astobj2.h"
54 AST_LIST_ENTRY(odbc_class) list;
61 unsigned int haspool:1; /* Boolean - TDS databases need this */
62 unsigned int limit:10; /* Gives a limit of 1023 maximum */
63 unsigned int count:10; /* Running count of pooled connections */
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 idlecheck; /* Recheck the connection if it is idle for this long */
67 struct ao2_container *obj_container;
70 struct ao2_container *class_container;
72 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
73 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
74 static int odbc_register_class(struct odbc_class *class, int connect);
76 static void odbc_class_destructor(void *data)
78 struct odbc_class *class = data;
79 /* Due to refcounts, we can safely assume that any objects with a reference
80 * to us will prevent our destruction, so we don't need to worry about them.
83 ast_free(class->username);
85 ast_free(class->password);
87 ast_free(class->sanitysql);
88 ao2_ref(class->obj_container, -1);
89 SQLFreeHandle(SQL_HANDLE_ENV, class->env);
92 static int null_hash_fn(const void *obj, const int flags)
97 static void odbc_obj_destructor(void *data)
99 struct odbc_obj *obj = data;
100 odbc_obj_disconnect(obj);
101 ast_mutex_destroy(&obj->lock);
102 ao2_ref(obj->parent, -1);
105 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
110 for (attempt = 0; attempt < 2; attempt++) {
111 stmt = exec_cb(obj, data);
117 ast_log(LOG_WARNING, "SQL Exec Direct failed. Attempting a reconnect...\n");
119 odbc_obj_disconnect(obj);
120 odbc_obj_connect(obj);
127 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
129 int res = 0, i, attempt;
130 SQLINTEGER nativeerror=0, numfields=0;
131 SQLSMALLINT diagbytes=0;
132 unsigned char state[10], diagnostic[256];
135 for (attempt = 0; attempt < 2; attempt++) {
136 /* This prepare callback may do more than just prepare -- it may also
137 * bind parameters, bind results, etc. The real key, here, is that
138 * when we disconnect, all handles become invalid for most databases.
139 * We must therefore redo everything when we establish a new
141 stmt = prepare_cb(obj, data);
144 res = SQLExecute(stmt);
145 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
146 if (res == SQL_ERROR) {
147 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
148 for (i = 0; i < numfields; i++) {
149 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
150 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
152 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
158 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
159 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
164 * While this isn't the best way to try to correct an error, this won't automatically
165 * fail when the statement handle invalidates.
167 ast_odbc_sanity_check(obj);
170 obj->last_used = ast_tvnow();
172 } else if (attempt == 0)
173 ast_odbc_sanity_check(obj);
179 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
182 SQLINTEGER nativeerror=0, numfields=0;
183 SQLSMALLINT diagbytes=0;
184 unsigned char state[10], diagnostic[256];
186 res = SQLExecute(stmt);
187 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
188 if (res == SQL_ERROR) {
189 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
190 for (i = 0; i < numfields; i++) {
191 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
192 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
194 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
200 obj->last_used = ast_tvnow();
206 int ast_odbc_sanity_check(struct odbc_obj *obj)
208 char *test_sql = "select 1";
212 if (!ast_strlen_zero(obj->parent->sanitysql))
213 test_sql = obj->parent->sanitysql;
216 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
217 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
220 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
221 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
224 res = SQLExecute(stmt);
225 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
230 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
233 if (!obj->up) { /* Try to reconnect! */
234 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
235 odbc_obj_disconnect(obj);
236 odbc_obj_connect(obj);
241 static int load_odbc_config(void)
243 static char *cfg = "res_odbc.conf";
244 struct ast_config *config;
245 struct ast_variable *v;
247 const char *dsn, *username, *password, *sanitysql;
248 int enabled, pooling, limit, bse;
249 unsigned int idlecheck;
250 int connect = 0, res = 0;
251 struct ast_flags config_flags = { 0 };
253 struct odbc_class *new;
255 config = ast_config_load(cfg, config_flags);
257 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
260 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
261 if (!strcasecmp(cat, "ENV")) {
262 for (v = ast_variable_browse(config, cat); v; v = v->next) {
263 setenv(v->name, v->value, 1);
264 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
267 /* Reset all to defaults for each class of odbc connections */
268 dsn = username = password = sanitysql = NULL;
270 connect = idlecheck = 0;
274 for (v = ast_variable_browse(config, cat); v; v = v->next) {
275 if (!strcasecmp(v->name, "pooling")) {
276 if (ast_true(v->value))
278 } else if (!strncasecmp(v->name, "share", 5)) {
279 /* "shareconnections" is a little clearer in meaning than "pooling" */
280 if (ast_false(v->value))
282 } else if (!strcasecmp(v->name, "limit")) {
283 sscanf(v->value, "%d", &limit);
284 if (ast_true(v->value) && !limit) {
285 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);
287 } else if (ast_false(v->value)) {
288 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
292 } else if (!strcasecmp(v->name, "idlecheck")) {
293 sscanf(v->value, "%d", &idlecheck);
294 } else if (!strcasecmp(v->name, "enabled")) {
295 enabled = ast_true(v->value);
296 } else if (!strcasecmp(v->name, "pre-connect")) {
297 connect = ast_true(v->value);
298 } else if (!strcasecmp(v->name, "dsn")) {
300 } else if (!strcasecmp(v->name, "username")) {
302 } else if (!strcasecmp(v->name, "password")) {
304 } else if (!strcasecmp(v->name, "sanitysql")) {
305 sanitysql = v->value;
306 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
307 bse = ast_true(v->value);
311 if (enabled && !ast_strlen_zero(dsn)) {
312 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
319 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
320 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
322 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
323 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
328 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
331 new->haspool = pooling;
335 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
340 new->backslash_is_escape = bse ? 1 : 0;
341 new->idlecheck = idlecheck;
344 ast_copy_string(new->name, cat, sizeof(new->name));
346 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
347 if (username && !(new->username = ast_strdup(username))) {
351 if (password && !(new->password = ast_strdup(password))) {
355 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
360 odbc_register_class(new, connect);
361 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
367 ast_config_destroy(config);
371 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
373 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
374 struct odbc_class *class;
375 struct odbc_obj *current;
382 e->command = "odbc show";
384 "Usage: odbc show [class]\n"
385 " List settings of a particular ODBC class or,\n"
386 " if not specified, all classes.\n";
391 length = strlen(a->word);
392 while ((class = ao2_iterator_next(&aoi))) {
393 if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
394 ret = ast_strdup(class->name);
400 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
401 ret = ast_strdup("all");
406 ast_cli(a->fd, "\nODBC DSN Settings\n");
407 ast_cli(a->fd, "-----------------\n\n");
408 aoi = ao2_iterator_init(class_container, 0);
409 while ((class = ao2_iterator_next(&aoi))) {
410 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
412 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
414 if (class->haspool) {
415 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
417 ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
419 while ((current = ao2_iterator_next(&aoi2))) {
420 ast_cli(a->fd, " - Connection %d: %s\n", ++count,
421 current->used ? "in use" :
422 current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
423 ao2_ref(current, -1);
426 /* Should only ever be one of these */
427 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
428 while ((current = ao2_iterator_next(&aoi2))) {
429 ast_cli(a->fd, " Pooled: No\n Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
430 ao2_ref(current, -1);
433 ast_cli(a->fd, "\n");
441 static struct ast_cli_entry cli_odbc[] = {
442 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
445 static int odbc_register_class(struct odbc_class *class, int connect)
447 struct odbc_obj *obj;
449 ao2_link(class_container, class);
450 /* I still have a reference in the caller, so a deref is NOT missing here. */
453 /* Request and release builds a connection */
454 obj = ast_odbc_request_obj(class->name, 0);
456 ast_odbc_release_obj(obj);
461 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
466 void ast_odbc_release_obj(struct odbc_obj *obj)
468 /* For pooled connections, this frees the connection to be
469 * reused. For non-pooled connections, it does nothing. */
474 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
476 return obj->parent->backslash_is_escape;
479 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
481 struct odbc_obj *obj = NULL;
482 struct odbc_class *class;
483 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
485 while ((class = ao2_iterator_next(&aoi))) {
486 if (!strcmp(class->name, name))
494 if (class->haspool) {
495 /* Recycle connections before building another */
496 aoi = ao2_iterator_init(class->obj_container, 0);
497 while ((obj = ao2_iterator_next(&aoi))) {
505 if (!obj && (class->count < class->limit)) {
507 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
512 ast_mutex_init(&obj->lock);
513 /* obj inherits the outstanding reference to class */
515 if (odbc_obj_connect(obj) == ODBC_FAIL) {
516 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
517 ast_mutex_destroy(&obj->lock);
523 ao2_link(class->obj_container, obj);
527 /* Non-pooled connection: multiple modules can use the same connection. */
528 aoi = ao2_iterator_init(class->obj_container, 0);
529 while ((obj = ao2_iterator_next(&aoi))) {
530 /* Non-pooled connection: if there is an entry, return it */
535 /* No entry: build one */
536 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
541 ast_mutex_init(&obj->lock);
542 /* obj inherits the outstanding reference to class */
544 if (odbc_obj_connect(obj) == ODBC_FAIL) {
545 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
546 ast_mutex_destroy(&obj->lock);
550 ao2_link(class->obj_container, obj);
556 ast_odbc_sanity_check(obj);
557 } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
558 odbc_obj_connect(obj);
563 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
566 ast_mutex_lock(&obj->lock);
568 res = SQLDisconnect(obj->con);
570 if (res == ODBC_SUCCESS) {
571 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
573 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
574 obj->parent->name, obj->parent->dsn);
577 ast_mutex_unlock(&obj->lock);
581 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
586 unsigned char msg[200], stat[10];
588 SQLINTEGER enable = 1;
589 char *tracefile = "/tmp/odbc.trace";
591 ast_mutex_lock(&obj->lock);
593 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
595 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
596 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
597 ast_mutex_unlock(&obj->lock);
600 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
601 SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
603 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
604 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
608 odbc_obj_disconnect(obj);
609 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
611 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
614 res = SQLConnect(obj->con,
615 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
616 (SQLCHAR *) obj->parent->username, SQL_NTS,
617 (SQLCHAR *) obj->parent->password, SQL_NTS);
619 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
620 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
621 ast_mutex_unlock(&obj->lock);
622 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
625 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
627 obj->last_used = ast_tvnow();
630 ast_mutex_unlock(&obj->lock);
634 static int reload(void)
636 struct odbc_class *class;
637 struct odbc_obj *current;
638 struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
640 /* First, mark all to be purged */
641 while ((class = ao2_iterator_next(&aoi))) {
648 /* Purge remaining classes */
649 aoi = ao2_iterator_init(class_container, OBJ_UNLINK);
650 while ((class = ao2_iterator_next(&aoi))) {
652 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, OBJ_UNLINK);
653 while ((current = ao2_iterator_next(&aoi2))) {
654 ao2_ref(current, -2);
664 static int unload_module(void)
666 /* Prohibit unloading */
670 static int load_module(void)
672 if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
673 return AST_MODULE_LOAD_DECLINE;
674 if (load_odbc_config() == -1)
675 return AST_MODULE_LOAD_DECLINE;
676 ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
677 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
681 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
683 .unload = unload_module,