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>
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45 #include "asterisk/file.h"
46 #include "asterisk/logger.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/config.h"
49 #include "asterisk/options.h"
50 #include "asterisk/pbx.h"
51 #include "asterisk/module.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/lock.h"
54 #include "asterisk/res_odbc.h"
58 AST_LIST_ENTRY(odbc_class) list;
65 unsigned int haspool:1; /* Boolean - TDS databases need this */
66 unsigned int limit:10; /* Gives a limit of 1023 maximum */
67 unsigned int count:10; /* Running count of pooled connections */
68 unsigned int delme:1; /* Purge the class */
69 AST_LIST_HEAD(, odbc_obj) odbc_obj;
72 AST_LIST_HEAD_STATIC(odbc_list, odbc_class);
74 static odbc_status odbc_obj_connect(struct odbc_obj *obj);
75 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
76 static int odbc_register_class(struct odbc_class *class, int connect);
79 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
81 int res = 0, i, attempt;
82 SQLINTEGER nativeerror=0, numfields=0;
83 SQLSMALLINT diagbytes=0;
84 unsigned char state[10], diagnostic[256];
87 for (attempt = 0; attempt < 2; attempt++) {
88 /* This prepare callback may do more than just prepare -- it may also
89 * bind parameters, bind results, etc. The real key, here, is that
90 * when we disconnect, all handles become invalid for most databases.
91 * We must therefore redo everything when we establish a new
93 stmt = prepare_cb(obj, data);
96 res = SQLExecute(stmt);
97 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
98 if (res == SQL_ERROR) {
99 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
100 for (i=0; i< numfields + 1; i++) {
101 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
102 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
104 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
110 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
111 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
116 * While this isn't the best way to try to correct an error, this won't automatically
117 * fail when the statement handle invalidates.
119 ast_odbc_sanity_check(obj);
123 } else if (attempt == 0)
124 ast_odbc_sanity_check(obj);
130 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
133 SQLINTEGER nativeerror=0, numfields=0;
134 SQLSMALLINT diagbytes=0;
135 unsigned char state[10], diagnostic[256];
137 res = SQLExecute(stmt);
138 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
139 if (res == SQL_ERROR) {
140 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
141 for (i=0; i< numfields + 1; i++) {
142 SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
143 ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
145 ast_log(LOG_WARNING, "Oh, that was good. There are really %d diagnostics?\n", (int)numfields);
151 /* This is a really bad method of trying to correct a dead connection. It
152 * only ever really worked with MySQL. It will not work with any other
153 * database, since most databases prepare their statements on the server,
154 * and if you disconnect, you invalidate the statement handle. Hence, if
155 * you disconnect, you're going to fail anyway, whether you try to execute
156 * a second time or not.
158 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
159 ast_mutex_lock(&obj->lock);
161 ast_mutex_unlock(&obj->lock);
162 odbc_obj_disconnect(obj);
163 odbc_obj_connect(obj);
164 res = SQLExecute(stmt);
172 int ast_odbc_sanity_check(struct odbc_obj *obj)
174 char *test_sql = "select 1";
178 if (obj->parent->sanitysql)
179 test_sql = obj->parent->sanitysql;
182 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
183 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
186 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
187 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
190 res = SQLExecute(stmt);
191 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
196 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
199 if (!obj->up) { /* Try to reconnect! */
200 ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
201 odbc_obj_disconnect(obj);
202 odbc_obj_connect(obj);
207 static int load_odbc_config(void)
209 static char *cfg = "res_odbc.conf";
210 struct ast_config *config;
211 struct ast_variable *v;
212 char *cat, *dsn, *username, *password, *sanitysql;
213 int enabled, pooling, limit;
214 int connect = 0, res = 0;
216 struct odbc_class *new;
218 config = ast_config_load(cfg);
220 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
223 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
224 if (!strcasecmp(cat, "ENV")) {
225 for (v = ast_variable_browse(config, cat); v; v = v->next) {
226 setenv(v->name, v->value, 1);
227 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
230 /* Reset all to defaults for each class of odbc connections */
231 dsn = username = password = sanitysql = NULL;
236 for (v = ast_variable_browse(config, cat); v; v = v->next) {
237 if (!strcasecmp(v->name, "pooling")) {
238 if (ast_true(v->value))
240 } else if (!strcasecmp(v->name, "limit")) {
241 sscanf(v->value, "%d", &limit);
242 if (ast_true(v->value) && !limit) {
243 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);
245 } else if (ast_false(v->value)) {
246 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
250 } else if (!strcasecmp(v->name, "enabled")) {
251 enabled = ast_true(v->value);
252 } else if (!strcasecmp(v->name, "pre-connect")) {
253 connect = ast_true(v->value);
254 } else if (!strcasecmp(v->name, "dsn")) {
256 } else if (!strcasecmp(v->name, "username")) {
258 } else if (!strcasecmp(v->name, "password")) {
260 } else if (!strcasecmp(v->name, "sanitysql")) {
261 sanitysql = v->value;
265 if (enabled && !ast_strlen_zero(dsn)) {
266 new = ast_calloc(1, sizeof(*new));
274 ast_copy_string(new->name, cat, sizeof(new->name));
276 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
278 ast_copy_string(new->username, username, sizeof(new->username));
280 ast_copy_string(new->password, password, sizeof(new->password));
282 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
284 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
285 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
287 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
288 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
289 SQLFreeHandle(SQL_HANDLE_ENV, new->env);
294 new->haspool = pooling;
298 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
303 odbc_register_class(new, connect);
304 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
308 ast_config_destroy(config);
312 static int odbc_show_command(int fd, int argc, char **argv)
314 struct odbc_class *class;
315 struct odbc_obj *current;
317 AST_LIST_LOCK(&odbc_list);
318 AST_LIST_TRAVERSE(&odbc_list, class, list) {
319 if ((argc == 2) || (argc == 3 && !strcmp(argv[2], "all")) || (!strcmp(argv[2], class->name))) {
321 ast_cli(fd, "Name: %s\nDSN: %s\n", class->name, class->dsn);
323 if (class->haspool) {
324 ast_cli(fd, "Pooled: yes\nLimit: %d\nConnections in use: %d\n", class->limit, class->count);
326 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
327 ast_cli(fd, " Connection %d: %s", ++count, current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
330 /* Should only ever be one of these */
331 AST_LIST_TRAVERSE(&(class->odbc_obj), current, list) {
332 ast_cli(fd, "Pooled: no\nConnected: %s\n", current->up && ast_odbc_sanity_check(current) ? "yes" : "no");
339 AST_LIST_UNLOCK(&odbc_list);
344 static const char show_usage[] =
345 "Usage: odbc show [<class>]\n"
346 " List settings of a particular ODBC class.\n"
347 " or, if not specified, all classes.\n";
349 static struct ast_cli_entry cli_odbc[] = {
350 { { "odbc", "show", NULL },
351 odbc_show_command, "List ODBC DSN(s)",
355 static int odbc_register_class(struct odbc_class *class, int connect)
357 struct odbc_obj *obj;
359 AST_LIST_LOCK(&odbc_list);
360 AST_LIST_INSERT_HEAD(&odbc_list, class, list);
361 AST_LIST_UNLOCK(&odbc_list);
364 /* Request and release builds a connection */
365 obj = ast_odbc_request_obj(class->name, 0);
366 ast_odbc_release_obj(obj);
371 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
376 void ast_odbc_release_obj(struct odbc_obj *obj)
378 /* For pooled connections, this frees the connection to be
379 * reused. For non-pooled connections, it does nothing. */
383 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
385 struct odbc_obj *obj = NULL;
386 struct odbc_class *class;
388 AST_LIST_LOCK(&odbc_list);
389 AST_LIST_TRAVERSE(&odbc_list, class, list) {
390 if (!strcmp(class->name, name))
393 AST_LIST_UNLOCK(&odbc_list);
398 AST_LIST_LOCK(&class->odbc_obj);
399 if (class->haspool) {
400 /* Recycle connections before building another */
401 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
408 if (!obj && (class->count < class->limit)) {
410 obj = ast_calloc(1, sizeof(*obj));
412 AST_LIST_UNLOCK(&class->odbc_obj);
415 ast_mutex_init(&obj->lock);
417 odbc_obj_connect(obj);
418 AST_LIST_INSERT_TAIL(&class->odbc_obj, obj, list);
421 /* Non-pooled connection: multiple modules can use the same connection. */
422 AST_LIST_TRAVERSE(&class->odbc_obj, obj, list) {
423 /* Non-pooled connection: if there is an entry, return it */
428 /* No entry: build one */
429 obj = ast_calloc(1, sizeof(*obj));
431 AST_LIST_UNLOCK(&class->odbc_obj);
434 ast_mutex_init(&obj->lock);
436 if (odbc_obj_connect(obj) == ODBC_FAIL) {
437 ast_log(LOG_WARNING, "Failed to connect\n");
438 ast_mutex_destroy(&obj->lock);
441 AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
445 AST_LIST_UNLOCK(&class->odbc_obj);
448 ast_odbc_sanity_check(obj);
453 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
456 ast_mutex_lock(&obj->lock);
458 res = SQLDisconnect(obj->con);
460 if (res == ODBC_SUCCESS) {
461 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
463 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
464 obj->parent->name, obj->parent->dsn);
467 ast_mutex_unlock(&obj->lock);
471 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
476 unsigned char msg[200], stat[10];
478 SQLINTEGER enable = 1;
479 char *tracefile = "/tmp/odbc.trace";
481 ast_mutex_lock(&obj->lock);
483 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
485 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
487 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
488 SQLFreeHandle(SQL_HANDLE_ENV, obj->parent->env);
490 ast_mutex_unlock(&obj->lock);
493 SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
495 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
496 SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
500 odbc_obj_disconnect(obj);
501 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
503 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
506 res = SQLConnect(obj->con,
507 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
508 (SQLCHAR *) obj->parent->username, SQL_NTS,
509 (SQLCHAR *) obj->parent->password, SQL_NTS);
511 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
512 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
513 ast_mutex_unlock(&obj->lock);
514 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
517 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
521 ast_mutex_unlock(&obj->lock);
525 static int reload(void)
527 static char *cfg = "res_odbc.conf";
528 struct ast_config *config;
529 struct ast_variable *v;
530 char *cat, *dsn, *username, *password, *sanitysql;
531 int enabled, pooling, limit;
532 int connect = 0, res = 0;
534 struct odbc_class *new, *class;
535 struct odbc_obj *current;
537 /* First, mark all to be purged */
538 AST_LIST_LOCK(&odbc_list);
539 AST_LIST_TRAVERSE(&odbc_list, class, list) {
543 config = ast_config_load(cfg);
545 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
546 if (!strcasecmp(cat, "ENV")) {
547 for (v = ast_variable_browse(config, cat); v; v = v->next) {
548 setenv(v->name, v->value, 1);
549 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
552 /* Reset all to defaults for each class of odbc connections */
553 dsn = username = password = sanitysql = NULL;
558 for (v = ast_variable_browse(config, cat); v; v = v->next) {
559 if (!strcasecmp(v->name, "pooling")) {
561 } else if (!strcasecmp(v->name, "limit")) {
562 sscanf(v->value, "%d", &limit);
563 if (ast_true(v->value) && !limit) {
564 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);
566 } else if (ast_false(v->value)) {
567 ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'. Disabling ODBC class '%s'.\n", v->value, cat);
571 } else if (!strcasecmp(v->name, "enabled")) {
572 enabled = ast_true(v->value);
573 } else if (!strcasecmp(v->name, "pre-connect")) {
574 connect = ast_true(v->value);
575 } else if (!strcasecmp(v->name, "dsn")) {
577 } else if (!strcasecmp(v->name, "username")) {
579 } else if (!strcasecmp(v->name, "password")) {
581 } else if (!strcasecmp(v->name, "sanitysql")) {
582 sanitysql = v->value;
586 if (enabled && !ast_strlen_zero(dsn)) {
587 /* First, check the list to see if it already exists */
588 AST_LIST_TRAVERSE(&odbc_list, class, list) {
589 if (!strcmp(class->name, cat)) {
598 new = ast_calloc(1, sizeof(*new));
607 ast_copy_string(new->name, cat, sizeof(new->name));
609 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
611 ast_copy_string(new->username, username, sizeof(new->username));
613 ast_copy_string(new->password, password, sizeof(new->password));
615 ast_copy_string(new->sanitysql, sanitysql, sizeof(new->sanitysql));
618 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
619 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
621 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
622 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
623 SQLFreeHandle(SQL_HANDLE_ENV, new->env);
624 AST_LIST_UNLOCK(&odbc_list);
630 new->haspool = pooling;
634 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless. Changing limit from 0 to 5.\n");
640 ast_log(LOG_NOTICE, "Refreshing ODBC class '%s' dsn->[%s]\n", cat, dsn);
642 odbc_register_class(new, connect);
643 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
648 ast_config_destroy(config);
651 /* Purge classes that we know can go away (pooled with 0, only) */
652 AST_LIST_TRAVERSE_SAFE_BEGIN(&odbc_list, class, list) {
653 if (class->delme && class->haspool && class->count == 0) {
654 AST_LIST_TRAVERSE_SAFE_BEGIN(&(class->odbc_obj), current, list) {
655 AST_LIST_REMOVE_CURRENT(&(class->odbc_obj), list);
656 odbc_obj_disconnect(current);
657 ast_mutex_destroy(¤t->lock);
660 AST_LIST_TRAVERSE_SAFE_END;
662 AST_LIST_REMOVE_CURRENT(&odbc_list, list);
666 AST_LIST_TRAVERSE_SAFE_END;
667 AST_LIST_UNLOCK(&odbc_list);
672 static int unload_module(void)
674 /* Prohibit unloading */
678 static int load_module(void)
680 if(load_odbc_config() == -1)
681 return AST_MODULE_LOAD_DECLINE;
682 ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
683 ast_log(LOG_NOTICE, "res_odbc loaded.\n");
687 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC Resource",
689 .unload = unload_module,