Increase limit of unshared connections from 1023 to 4.2 billion.
[asterisk/asterisk.git] / res / res_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * res_odbc.c <ODBC resource manager>
9  * Copyright (C) 2004 - 2005 Anthony Minessale II <anthmct@yahoo.com>
10  *
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.
16  *
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.
20  */
21
22 /*! \file
23  *
24  * \brief ODBC resource manager
25  * 
26  * \author Mark Spencer <markster@digium.com>
27  * \author Anthony Minessale II <anthmct@yahoo.com>
28  *
29  * \arg See also: \ref cdr_odbc
30  */
31
32 /*** MODULEINFO
33         <depend>unixodbc</depend>
34         <depend>ltdl</depend>
35  ***/
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
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"
51
52 struct odbc_class
53 {
54         AST_LIST_ENTRY(odbc_class) list;
55         char name[80];
56         char dsn[80];
57         char *username;
58         char *password;
59         char *sanitysql;
60         SQLHENV env;
61         unsigned int haspool:1;              /* Boolean - TDS databases need this */
62         unsigned int delme:1;                /* Purge the class */
63         unsigned int backslash_is_escape:1;  /* On this database, the backslash is a native escape sequence */
64         unsigned int limit;                  /* 1023 wasn't enough for some people */
65         unsigned int count;                  /* Running count of pooled connections */
66         unsigned int idlecheck;              /* Recheck the connection if it is idle for this long */
67         struct ao2_container *obj_container;
68 };
69
70 struct ao2_container *class_container;
71
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);
75
76 static void odbc_class_destructor(void *data)
77 {
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.
81          */
82         if (class->username)
83                 ast_free(class->username);
84         if (class->password)
85                 ast_free(class->password);
86         if (class->sanitysql)
87                 ast_free(class->sanitysql);
88         ao2_ref(class->obj_container, -1);
89         SQLFreeHandle(SQL_HANDLE_ENV, class->env);
90 }
91
92 static int null_hash_fn(const void *obj, const int flags)
93 {
94         return 0;
95 }
96
97 static void odbc_obj_destructor(void *data)
98 {
99         struct odbc_obj *obj = data;
100         odbc_obj_disconnect(obj);
101         ast_mutex_destroy(&obj->lock);
102         ao2_ref(obj->parent, -1);
103 }
104
105 SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
106 {
107         int attempt;
108         SQLHSTMT stmt;
109
110         for (attempt = 0; attempt < 2; attempt++) {
111                 stmt = exec_cb(obj, data);
112
113                 if (stmt) {
114                         break;
115                 } else {
116                         obj->up = 0;
117                         ast_log(LOG_WARNING, "SQL Exec Direct failed.  Attempting a reconnect...\n");
118
119                         odbc_obj_disconnect(obj);
120                         odbc_obj_connect(obj);
121                 }
122         }
123
124         return stmt;
125 }
126
127 SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
128 {
129         int res = 0, i, attempt;
130         SQLINTEGER nativeerror=0, numfields=0;
131         SQLSMALLINT diagbytes=0;
132         unsigned char state[10], diagnostic[256];
133         SQLHSTMT stmt;
134
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
140                  * connection. */
141                 stmt = prepare_cb(obj, data);
142
143                 if (stmt) {
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);
151                                                 if (i > 10) {
152                                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
153                                                         break;
154                                                 }
155                                         }
156                                 }
157
158                                 ast_log(LOG_WARNING, "SQL Execute error %d! Attempting a reconnect...\n", res);
159                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
160                                 stmt = NULL;
161
162                                 obj->up = 0;
163                                 /*
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.
166                                  */
167                                 ast_odbc_sanity_check(obj);
168                                 continue;
169                         } else
170                                 obj->last_used = ast_tvnow();
171                         break;
172                 } else if (attempt == 0)
173                         ast_odbc_sanity_check(obj);
174         }
175
176         return stmt;
177 }
178
179 int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt) 
180 {
181         int res = 0, i;
182         SQLINTEGER nativeerror=0, numfields=0;
183         SQLSMALLINT diagbytes=0;
184         unsigned char state[10], diagnostic[256];
185
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);
193                                 if (i > 10) {
194                                         ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
195                                         break;
196                                 }
197                         }
198                 }
199         } else
200                 obj->last_used = ast_tvnow();
201         
202         return res;
203 }
204
205
206 int ast_odbc_sanity_check(struct odbc_obj *obj) 
207 {
208         char *test_sql = "select 1";
209         SQLHSTMT stmt;
210         int res = 0;
211
212         if (!ast_strlen_zero(obj->parent->sanitysql))
213                 test_sql = obj->parent->sanitysql;
214
215         if (obj->up) {
216                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
217                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
218                         obj->up = 0;
219                 } else {
220                         res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
221                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
222                                 obj->up = 0;
223                         } else {
224                                 res = SQLExecute(stmt);
225                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
226                                         obj->up = 0;
227                                 }
228                         }
229                 }
230                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
231         }
232
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);
237         }
238         return obj->up;
239 }
240
241 static int load_odbc_config(void)
242 {
243         static char *cfg = "res_odbc.conf";
244         struct ast_config *config;
245         struct ast_variable *v;
246         char *cat;
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 };
252
253         struct odbc_class *new;
254
255         config = ast_config_load(cfg, config_flags);
256         if (!config) {
257                 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
258                 return -1;
259         }
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);
265                         }
266                 } else {
267                         /* Reset all to defaults for each class of odbc connections */
268                         dsn = username = password = sanitysql = NULL;
269                         enabled = 1;
270                         connect = idlecheck = 0;
271                         pooling = 0;
272                         limit = 0;
273                         bse = 1;
274                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
275                                 if (!strcasecmp(v->name, "pooling")) {
276                                         if (ast_true(v->value))
277                                                 pooling = 1;
278                                 } else if (!strncasecmp(v->name, "share", 5)) {
279                                         /* "shareconnections" is a little clearer in meaning than "pooling" */
280                                         if (ast_false(v->value))
281                                                 pooling = 1;
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);
286                                                 limit = 1023;
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);
289                                                 enabled = 0;
290                                                 break;
291                                         }
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")) {
299                                         dsn = v->value;
300                                 } else if (!strcasecmp(v->name, "username")) {
301                                         username = v->value;
302                                 } else if (!strcasecmp(v->name, "password")) {
303                                         password = v->value;
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);
308                                 }
309                         }
310
311                         if (enabled && !ast_strlen_zero(dsn)) {
312                                 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
313
314                                 if (!new) {
315                                         res = -1;
316                                         break;
317                                 }
318
319                                 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
320                                 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
321
322                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
323                                         ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
324                                         ao2_ref(new, -1);
325                                         return res;
326                                 }
327
328                                 new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
329
330                                 if (pooling) {
331                                         new->haspool = pooling;
332                                         if (limit) {
333                                                 new->limit = limit;
334                                         } else {
335                                                 ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
336                                                 new->limit = 5;
337                                         }
338                                 }
339
340                                 new->backslash_is_escape = bse ? 1 : 0;
341                                 new->idlecheck = idlecheck;
342
343                                 if (cat)
344                                         ast_copy_string(new->name, cat, sizeof(new->name));
345                                 if (dsn)
346                                         ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
347                                 if (username && !(new->username = ast_strdup(username))) {
348                                         ao2_ref(new, -1);
349                                         break;
350                                 }
351                                 if (password && !(new->password = ast_strdup(password))) {
352                                         ao2_ref(new, -1);
353                                         break;
354                                 }
355                                 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
356                                         ao2_ref(new, -1);
357                                         break;
358                                 }
359
360                                 odbc_register_class(new, connect);
361                                 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
362                                 ao2_ref(new, -1);
363                                 new = NULL;
364                         }
365                 }
366         }
367         ast_config_destroy(config);
368         return res;
369 }
370
371 static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
372 {
373         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
374         struct odbc_class *class;
375         struct odbc_obj *current;
376         int length = 0;
377         int which = 0;
378         char *ret = NULL;
379
380         switch (cmd) {
381         case CLI_INIT:
382                 e->command = "odbc show";
383                 e->usage =
384                                 "Usage: odbc show [class]\n"
385                                 "       List settings of a particular ODBC class or,\n"
386                                 "       if not specified, all classes.\n";
387                 return NULL;
388         case CLI_GENERATE:
389                 if (a->pos != 2)
390                         return NULL;
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);
395                                 ao2_ref(class, -1);
396                                 break;
397                         }
398                         ao2_ref(class, -1);
399                 }
400                 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
401                         ret = ast_strdup("all");
402                 }
403                 return ret;
404         }
405
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))) {
411                         int count = 0;
412                         ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
413
414                         if (class->haspool) {
415                                 struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
416
417                                 ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
418
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);
424                                 }
425                         } else {
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);
431                                 }
432                         }
433                         ast_cli(a->fd, "\n");
434                 }
435                 ao2_ref(class, -1);
436         }
437
438         return CLI_SUCCESS;
439 }
440
441 static struct ast_cli_entry cli_odbc[] = {
442         AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
443 };
444
445 static int odbc_register_class(struct odbc_class *class, int connect)
446 {
447         struct odbc_obj *obj;
448         if (class) {
449                 ao2_link(class_container, class);
450                 /* I still have a reference in the caller, so a deref is NOT missing here. */
451
452                 if (connect) {
453                         /* Request and release builds a connection */
454                         obj = ast_odbc_request_obj(class->name, 0);
455                         if (obj)
456                                 ast_odbc_release_obj(obj);
457                 }
458
459                 return 0;
460         } else {
461                 ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
462                 return -1;
463         }
464 }
465
466 void ast_odbc_release_obj(struct odbc_obj *obj)
467 {
468         /* For pooled connections, this frees the connection to be
469          * reused.  For non-pooled connections, it does nothing. */
470         obj->used = 0;
471         ao2_ref(obj, -1);
472 }
473
474 int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
475 {
476         return obj->parent->backslash_is_escape;
477 }
478
479 struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
480 {
481         struct odbc_obj *obj = NULL;
482         struct odbc_class *class;
483         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
484
485         while ((class = ao2_iterator_next(&aoi))) {
486                 if (!strcmp(class->name, name) && !class->delme) {
487                         break;
488                 }
489                 ao2_ref(class, -1);
490         }
491
492         if (!class)
493                 return NULL;
494
495         if (class->haspool) {
496                 /* Recycle connections before building another */
497                 aoi = ao2_iterator_init(class->obj_container, 0);
498                 while ((obj = ao2_iterator_next(&aoi))) {
499                         if (! obj->used) {
500                                 obj->used = 1;
501                                 break;
502                         }
503                         ao2_ref(obj, -1);
504                 }
505
506                 if (!obj && (class->count < class->limit)) {
507                         class->count++;
508                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
509                         if (!obj) {
510                                 ao2_ref(class, -1);
511                                 return NULL;
512                         }
513                         ast_mutex_init(&obj->lock);
514                         /* obj inherits the outstanding reference to class */
515                         obj->parent = class;
516                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
517                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
518                                 ao2_ref(obj, -1);
519                                 obj = NULL;
520                                 class->count--;
521                         } else {
522                                 obj->used = 1;
523                                 ao2_link(class->obj_container, obj);
524                         }
525                 }
526         } else {
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 */
531                         break;
532                 }
533
534                 if (!obj) {
535                         /* No entry: build one */
536                         obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
537                         if (!obj) {
538                                 ao2_ref(class, -1);
539                                 return NULL;
540                         }
541                         ast_mutex_init(&obj->lock);
542                         /* obj inherits the outstanding reference to class */
543                         obj->parent = class;
544                         if (odbc_obj_connect(obj) == ODBC_FAIL) {
545                                 ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
546                                 ao2_ref(obj, -1);
547                                 obj = NULL;
548                         } else {
549                                 ao2_link(class->obj_container, obj);
550                         }
551                 }
552         }
553
554         if (obj && check) {
555                 ast_odbc_sanity_check(obj);
556         } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
557                 odbc_obj_connect(obj);
558
559         return obj;
560 }
561
562 static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
563 {
564         int res;
565         ast_mutex_lock(&obj->lock);
566
567         res = SQLDisconnect(obj->con);
568
569         if (res == ODBC_SUCCESS) {
570                 ast_log(LOG_WARNING, "res_odbc: disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
571         } else {
572                 ast_log(LOG_WARNING, "res_odbc: %s [%s] already disconnected\n",
573                 obj->parent->name, obj->parent->dsn);
574         }
575         obj->up = 0;
576         ast_mutex_unlock(&obj->lock);
577         return ODBC_SUCCESS;
578 }
579
580 static odbc_status odbc_obj_connect(struct odbc_obj *obj)
581 {
582         int res;
583         SQLINTEGER err;
584         short int mlen;
585         unsigned char msg[200], stat[10];
586 #ifdef NEEDTRACE
587         SQLINTEGER enable = 1;
588         char *tracefile = "/tmp/odbc.trace";
589 #endif
590         ast_mutex_lock(&obj->lock);
591
592         res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
593
594         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
595                 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
596                 ast_mutex_unlock(&obj->lock);
597                 return ODBC_FAIL;
598         }
599         SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
600         SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
601 #ifdef NEEDTRACE
602         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
603         SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
604 #endif
605
606         if (obj->up) {
607                 odbc_obj_disconnect(obj);
608                 ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
609         } else {
610                 ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
611         }
612
613         res = SQLConnect(obj->con,
614                    (SQLCHAR *) obj->parent->dsn, SQL_NTS,
615                    (SQLCHAR *) obj->parent->username, SQL_NTS,
616                    (SQLCHAR *) obj->parent->password, SQL_NTS);
617
618         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
619                 SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
620                 ast_mutex_unlock(&obj->lock);
621                 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
622                 return ODBC_FAIL;
623         } else {
624                 ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
625                 obj->up = 1;
626                 obj->last_used = ast_tvnow();
627         }
628
629         ast_mutex_unlock(&obj->lock);
630         return ODBC_SUCCESS;
631 }
632
633 static int reload(void)
634 {
635         struct odbc_class *class;
636         struct odbc_obj *current;
637         struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
638
639         /* First, mark all to be purged */
640         while ((class = ao2_iterator_next(&aoi))) {
641                 class->delme = 1;
642                 ao2_ref(class, -1);
643         }
644
645         load_odbc_config();
646
647         /* Purge remaining classes */
648
649         /* Note on how this works; this is a case of circular references, so we
650          * explicitly do NOT want to use a callback here (or we wind up in
651          * recursive hell).
652          *
653          * 1. Iterate through all the classes.  Note that the classes will currently
654          * contain two classes of the same name, one of which is marked delme and
655          * will be purged when all remaining objects of the class are released, and
656          * the other, which was created above when we re-parsed the config file.
657          * 2. On each class, there is a reference held by the master container and
658          * a reference held by each connection object.  There are two cases for
659          * destruction of the class, noted below.  However, in all cases, all O-refs
660          * (references to objects) will first be freed, which will cause the C-refs
661          * (references to classes) to be decremented (but never to 0, because the
662          * class container still has a reference).
663          *    a) If the class has outstanding objects, the C-ref by the class
664          *    container will then be freed, which leaves only C-refs by any
665          *    outstanding objects.  When the final outstanding object is released
666          *    (O-refs held by applications and dialplan functions), it will in turn
667          *    free the final C-ref, causing class destruction.
668          *    b) If the class has no outstanding objects, when the class container
669          *    removes the final C-ref, the class will be destroyed.
670          */
671         aoi = ao2_iterator_init(class_container, 0);
672         while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
673                 if (class->delme) {
674                         struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
675                         while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
676                                 ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
677                                 ao2_ref(current, -1); /* O-ref-- (by iterator) */
678                                 /* At this point, either
679                                  * a) there's an outstanding O-ref, or
680                                  * b) the object has already been destroyed.
681                                  */
682                         }
683                         ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
684                         /* At this point, either
685                          * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
686                          * b) the last remaining C-ref is held by the iterator, which will be
687                          * destroyed in the next step.
688                          */
689                 }
690                 ao2_ref(class, -1); /* C-ref-- (by iterator) */
691         }
692
693         return 0;
694 }
695
696 static int unload_module(void)
697 {
698         /* Prohibit unloading */
699         return -1;
700 }
701
702 static int load_module(void)
703 {
704         if (!(class_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr)))
705                 return AST_MODULE_LOAD_DECLINE;
706         if (load_odbc_config() == -1)
707                 return AST_MODULE_LOAD_DECLINE;
708         ast_cli_register_multiple(cli_odbc, sizeof(cli_odbc) / sizeof(struct ast_cli_entry));
709         ast_log(LOG_NOTICE, "res_odbc loaded.\n");
710         return 0;
711 }
712
713 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "ODBC resource",
714                 .load = load_module,
715                 .unload = unload_module,
716                 .reload = reload,
717                );