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$")
46 #include "asterisk/file.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/config.h"
50 #include "asterisk/options.h"
51 #include "asterisk/pbx.h"
52 #include "asterisk/module.h"
53 #include "asterisk/cli.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/res_odbc.h"
59 AST_LIST_ENTRY(odbc_class) list;
66 unsigned int haspool:1; /* Boolean - TDS databases need this */
67 unsigned int limit:10; /* Gives a limit of 1023 maximum */
68 unsigned int count:10; /* Running count of pooled connections */
69 unsigned int delme:1; /* Purge the class */
70 AST_LIST_HEAD(, odbc_obj) odbc_obj;
73 AST_LIST_HEAD_STATIC(odbc_list, odbc_class);
75 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
76 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
77 static int odbc_register_class(struct odbc_class *class, int connect);
80 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
85 for (attempt = 0; attempt < 2; attempt++) {
86 stmt = exec_cb(obj, data);
92 ast_log(LOG_WARNING, "SQL Exec Direct failed. Attempting a reconnect...\n");
94 odbc_obj_disconnect(obj);
95 odbc_obj_connect(obj);
102 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
104 int res = 0, i, attempt;
105 SQLINTEGER nativeerror=0, numfields=0;
106 SQLSMALLINT diagbytes=0;
107 unsigned char state[10], diagnostic[256];
110 for (attempt = 0; attempt < 2; attempt++) {
111 /* This prepare callback may do more than just prepare -- it may also
112 * bind parameters, bind results, etc. The real key, here, is that
113 * when we disconnect, all handles become invalid for most databases.
114 * We must therefore redo everything when we establish a new
116 stmt = prepare_cb(obj, data);
119 res = SQLExecute(stmt);
120 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
121 if (res == SQL_ERROR) {
122 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
123 for (i = 0; i < numfields; i++) {
124 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
125 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
127 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
133 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
134 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
139 * While this isn't the best way to try to correct an error, this won't automatically
140 * fail when the statement handle invalidates.
142 ast_odbc_sanity_check(obj);
146 } else if (attempt == 0)
147 ast_odbc_sanity_check(obj);
153 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
156 SQLINTEGER nativeerror=0, numfields=0;
157 SQLSMALLINT diagbytes=0;
158 unsigned char state[10], diagnostic[256];
160 res = SQLExecute(stmt);
161 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
162 if (res == SQL_ERROR) {
163 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
164 for (i = 0; i < numfields; i++) {
165 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
166 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
168 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
174 /* This is a really bad method of trying to correct a dead connection. It
175 * only ever really worked with MySQL. It will not work with any other
176 * database, since most databases prepare their statements on the server,
177 * and if you disconnect, you invalidate the statement handle. Hence, if
178 * you disconnect, you're going to fail anyway, whether you try to execute
179 * a second time or not.
181 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
182 ast_mutex_lock(&obj->lock);
184 ast_mutex_unlock(&obj->lock);
185 odbc_obj_disconnect(obj);
186 odbc_obj_connect(obj);
187 res = SQLExecute(stmt);
195 int ast_odbc_sanity_check(struct odbc_obj *obj)
197 char *test_sql = "select 1";
201 if (!ast_strlen_zero(obj->parent->sanitysql))
202 test_sql = obj->parent->sanitysql;
205 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
206 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
209 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
210 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
213 res = SQLExecute(stmt);
214 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
219 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
222 if (!obj->up) { /* Try to reconnect! */
223 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
224 odbc_obj_disconnect(obj);
225 odbc_obj_connect(obj);
230 static int load_odbc_config(void)
232 static char *cfg = "res_odbc.conf";
233 struct ast_config *config;
234 struct ast_variable *v;
235 char *cat, *dsn, *username, *password, *sanitysql;
236 int enabled, pooling, limit;
237 int connect = 0, res = 0;
238 struct ast_flags config_flags = { 0 };
240 struct odbc_class *new;
242 config = ast_config_load(cfg, config_flags);
244 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
247 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
248 if (!strcasecmp(cat, "ENV")) {
249 for (v = ast_variable_browse(config, cat); v; v = v->next) {
250 setenv(v->name, v->value, 1);
251 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
254 /* Reset all to defaults for each class of odbc connections */
255 dsn = username = password = sanitysql = NULL;
260 for (v = ast_variable_browse(config, cat); v; v = v->next) {
261 if (!strcasecmp(v->name, "pooling")) {
262 if (ast_true(v->value))
264 } else if (!strcasecmp(v->name, "limit")) {
265 sscanf(v->value, "%d", &limit);
266 if (ast_true(v->value) && !limit) {
267 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);
269 } else if (ast_false(v->value)) {
270 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
274 } else if (!strcasecmp(v->name, "enabled")) {
275 enabled = ast_true(v->value);
276 } else if (!strcasecmp(v->name, "pre-connect")) {
277 connect = ast_true(v->value);
278 } else if (!strcasecmp(v->name, "dsn")) {
280 } else if (!strcasecmp(v->name, "username")) {
282 } else if (!strcasecmp(v->name, "password")) {
284 } else if (!strcasecmp(v->name, "sanitysql")) {
285 sanitysql = v->value;
289 if (enabled && !ast_strlen_zero(dsn)) {
290 new = ast_calloc(1, sizeof(*new));
298 ast_copy_string(new->name, cat, sizeof(new->name));
300 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
302 ast_copy_string(new->username, username, sizeof(new->username));
304 ast_copy_string(new->password, password, sizeof(new->password));
306 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
308 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
309 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
311 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
312 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
313 SQLFreeHandle(SQL_HANDLE_ENV, new->env);
318 new->haspool = pooling;
322 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
327 odbc_register_class(new, connect);
328 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
332 ast_config_destroy(config);
336 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
338 struct odbc_class *class;
339 struct odbc_obj *current;
346 e->command = "odbc show";
348 "Usage: odbc show [class]\n"
349 " List settings of a particular ODBC class or,\n"
350 " if not specified, all classes.\n";
355 length = strlen(a->word);
356 AST_LIST_LOCK(&odbc_list);
357 AST_LIST_TRAVERSE(&odbc_list, class, list) {
358 if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
359 ret = ast_strdup(class->name);
363 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
364 ret = ast_strdup("all");
366 AST_LIST_UNLOCK(&odbc_list);
370 ast_cli(a->fd, "\nODBC DSN Settings\n");
371 ast_cli(a->fd, "-----------------\n\n");
372 AST_LIST_LOCK(&odbc_list);
373 AST_LIST_TRAVERSE(&odbc_list, class, list) {
374 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
376 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
378 if (class->haspool) {
379 ast_cli(a->fd, " Pooled: Yes\n Limit: %d\n Connections in use: %d\n", class->limit, class->count);
381 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
382 ast_cli(a->fd, " - Connection %d: %s\n", ++count, current->used ? "in use" : current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
385 /* Should only ever be one of these */
386 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
387 ast_cli(a->fd, " Pooled: No\n Connected: %s\n", current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
390 ast_cli(a->fd, "\n");
393 AST_LIST_UNLOCK(&odbc_list);
398 static struct ast_cli_entry cli_odbc[] = {
399 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
402 static int odbc_register_class(struct odbc_class *class, int connect)
404 struct odbc_obj *obj;
406 AST_LIST_LOCK(&odbc_list);
407 AST_LIST_INSERT_HEAD(&odbc_list, class, list);
408 AST_LIST_UNLOCK(&odbc_list);
411 /* Request and release builds a connection */
412 obj = ast_odbc_request_obj(class->name, 0);
414 ast_odbc_release_obj(obj);
419 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
424 void ast_odbc_release_obj(struct odbc_obj *obj)
426 /* For pooled connections, this frees the connection to be
427 * reused. For non-pooled connections, it does nothing. */
431 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
433 struct odbc_obj *obj = NULL;
434 struct odbc_class *class;
436 AST_LIST_LOCK(&odbc_list);
437 AST_LIST_TRAVERSE(&odbc_list, class, list) {
438 if (!strcmp(class->name, name))
441 AST_LIST_UNLOCK(&odbc_list);
446 AST_LIST_LOCK(&class->odbc_obj);
447 if (class->haspool) {
448 /* Recycle connections before building another */
449 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
456 if (!obj && (class->count < class->limit)) {
458 obj = ast_calloc(1, sizeof(*obj));
460 AST_LIST_UNLOCK(&class->odbc_obj);
463 ast_mutex_init(&obj->lock);
465 if (odbc_obj_connect(obj) == ODBC_FAIL) {
466 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
467 ast_mutex_destroy(&obj->lock);
473 AST_LIST_INSERT_TAIL(&class->odbc_obj, obj, list);
477 /* Non-pooled connection: multiple modules can use the same connection. */
478 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
479 /* Non-pooled connection: if there is an entry, return it */
484 /* No entry: build one */
485 obj = ast_calloc(1, sizeof(*obj));
487 AST_LIST_UNLOCK(&class->odbc_obj);
490 ast_mutex_init(&obj->lock);
492 if (odbc_obj_connect(obj) == ODBC_FAIL) {
493 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
494 ast_mutex_destroy(&obj->lock);
498 AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
502 AST_LIST_UNLOCK(&class->odbc_obj);
505 ast_odbc_sanity_check(obj);
510 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
513 ast_mutex_lock(&obj->lock);
515 res = SQLDisconnect(obj->con);
517 if (res == ODBC_SUCCESS) {
518 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
520 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
521 obj->parent->name, obj->parent->dsn);
524 ast_mutex_unlock(&obj->lock);
528 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
533 unsigned char msg[200], stat[10];
535 SQLINTEGER enable = 1;
536 char *tracefile = "/tmp/odbc.trace";
538 ast_mutex_lock(&obj->lock);
540 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
542 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
543 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
544 ast_mutex_unlock(&obj->lock);
547 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
549 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
550 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
554 odbc_obj_disconnect(obj);
555 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
557 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
560 res = SQLConnect(obj->con,
561 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
562 (SQLCHAR *) obj->parent->username, SQL_NTS,
563 (SQLCHAR *) obj->parent->password, SQL_NTS);
565 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
566 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
567 ast_mutex_unlock(&obj->lock);
568 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
571 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
575 ast_mutex_unlock(&obj->lock);
579 static int reload(void)
581 static char *cfg = "res_odbc.conf";
582 struct ast_config *config;
583 struct ast_variable *v;
584 char *cat, *dsn, *username, *password, *sanitysql;
585 int enabled, pooling, limit;
586 int connect = 0, res = 0;
587 struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
589 struct odbc_class *new, *class;
590 struct odbc_obj *current;
592 /* First, mark all to be purged */
593 AST_LIST_LOCK(&odbc_list);
594 AST_LIST_TRAVERSE(&odbc_list, class, list) {
598 config = ast_config_load(cfg, config_flags);
599 if (config != NULL && config != CONFIG_STATUS_FILEUNCHANGED) {
600 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
601 if (!strcasecmp(cat, "ENV")) {
602 for (v = ast_variable_browse(config, cat); v; v = v->next) {
603 setenv(v->name, v->value, 1);
604 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
607 /* Reset all to defaults for each class of odbc connections */
608 dsn = username = password = sanitysql = NULL;
613 for (v = ast_variable_browse(config, cat); v; v = v->next) {
614 if (!strcasecmp(v->name, "pooling")) {
616 } else if (!strcasecmp(v->name, "limit")) {
617 sscanf(v->value, "%d", &limit);
618 if (ast_true(v->value) && !limit) {
619 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);
621 } else if (ast_false(v->value)) {
622 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
626 } else if (!strcasecmp(v->name, "enabled")) {
627 enabled = ast_true(v->value);
628 } else if (!strcasecmp(v->name, "pre-connect")) {
629 connect = ast_true(v->value);
630 } else if (!strcasecmp(v->name, "dsn")) {
632 } else if (!strcasecmp(v->name, "username")) {
634 } else if (!strcasecmp(v->name, "password")) {
636 } else if (!strcasecmp(v->name, "sanitysql")) {
637 sanitysql = v->value;
641 if (enabled && !ast_strlen_zero(dsn)) {
642 /* First, check the list to see if it already exists */
643 AST_LIST_TRAVERSE(&odbc_list, class, list) {
644 if (!strcmp(class->name, cat)) {
653 new = ast_calloc(1, sizeof(*new));
662 ast_copy_string(new->name, cat, sizeof(new->name));
664 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
666 ast_copy_string(new->username, username, sizeof(new->username));
668 ast_copy_string(new->password, password, sizeof(new->password));
670 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
673 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
674 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
676 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
677 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
678 SQLFreeHandle(SQL_HANDLE_ENV, new->env);
679 AST_LIST_UNLOCK(&odbc_list);
685 new->haspool = pooling;
689 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
695 ast_log(LOG_NOTICE, "Refreshing ODBC class '%s' dsn->[%s]\n", cat, dsn);
697 odbc_register_class(new, connect);
698 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
703 ast_config_destroy(config);
706 /* Purge classes that we know can go away (pooled with 0, only) */
707 AST_LIST_TRAVERSE_SAFE_BEGIN(&odbc_list, class, list) {
708 if (class->delme && class->haspool && class->count == 0) {
709 while ((current = AST_LIST_REMOVE_HEAD(&class->odbc_obj, list))) {
710 odbc_obj_disconnect(current);
711 ast_mutex_destroy(¤t->lock);
715 AST_LIST_REMOVE_CURRENT(list);
719 AST_LIST_TRAVERSE_SAFE_END;
720 AST_LIST_UNLOCK(&odbc_list);
725 static int unload_module(void)
727 /* Prohibit unloading */
731 static int load_module(void)
733 if(load_odbc_config() == -1)
734 return AST_MODULE_LOAD_DECLINE;
735 ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
736 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
740 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
742 .unload = unload_module,