Asterisk - The Open Source Telephony Project GIT-master-5963e62
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
res_odbc.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2012, 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 * \author Tilghman Lesher <tilghman@digium.com>
29 *
30 * \arg See also: \ref cdr_odbc.c
31 */
32
33/*! \li \ref res_odbc.c uses the configuration file \ref res_odbc.conf
34 * \addtogroup configuration_file Configuration Files
35 */
36
37/*!
38 * \page res_odbc.conf res_odbc.conf
39 * \verbinclude res_odbc.conf.sample
40 */
41
42/*** MODULEINFO
43 <depend>generic_odbc</depend>
44 <depend>res_odbc_transaction</depend>
45 <support_level>core</support_level>
46 ***/
47
48#include "asterisk.h"
49
50#include "asterisk/file.h"
51#include "asterisk/channel.h"
52#include "asterisk/config.h"
53#include "asterisk/pbx.h"
54#include "asterisk/module.h"
55#include "asterisk/cli.h"
56#include "asterisk/lock.h"
57#include "asterisk/res_odbc.h"
58#include "asterisk/time.h"
59#include "asterisk/astobj2.h"
60#include "asterisk/app.h"
61#include "asterisk/strings.h"
63
65{
67 char name[80];
68 char dsn[80];
69 char *username;
70 char *password;
71 char *sanitysql;
72 SQLHENV env;
73 unsigned int delme:1; /*!< Purge the class */
74 unsigned int backslash_is_escape:1; /*!< On this database, the backslash is a native escape sequence */
75 unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
76 unsigned int cache_is_queue:1; /*!< Connection cache should be a queue (round-robin use) rather than a stack (last release, first re-use) */
77 unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
78 unsigned int conntimeout; /*!< Maximum time the connection process should take */
79 unsigned int maxconnections; /*!< Maximum number of allowed connections */
80 /*! When a connection fails, cache that failure for how long? */
82 /*! When a connection fails, when did that last occur? */
83 struct timeval last_negative_connect;
84 /*! A pool of available connections */
86 /*! Lock to protect the connections */
88 /*! Condition to notify any pending connection requesters */
90 /*! The total number of current connections */
92 /*! Whether logging is enabled on this class or not */
93 unsigned int logging;
94 /*! The number of prepares executed on this class (total from all connections */
96 /*! The number of queries executed on this class (total from all connections) */
98 /*! The longest execution time for a query executed on this class */
100 /*! The SQL query that took the longest to execute */
101 char *sql_text;
102 /*! Slow query limit (in milliseconds) */
103 unsigned int slowquerylimit;
104 /*! Maximum number of cached connections, default is maxconnections */
105 unsigned int max_cache_size;
106 /*! Current cached connection count, when cache_size will exceed max_cache_size, longest-idle connection will be dropped from the cache */
107 unsigned int cur_cache;
108};
109
111
113
114static odbc_status odbc_obj_connect(struct odbc_obj *obj);
115static odbc_status odbc_obj_disconnect(struct odbc_obj *obj);
116static void odbc_register_class(struct odbc_class *class, int connect);
117
119
123 struct odbc_obj *obj; /*!< Database handle within which transacted statements are run */
124 /*!\brief Is this record the current active transaction within the channel?
125 * Note that the active flag is really only necessary for statements which
126 * are triggered from the dialplan, as there isn't a direct correlation
127 * between multiple statements. Applications wishing to use transactions
128 * may simply perform each statement on the same odbc_obj, which keeps the
129 * transaction persistent.
130 */
131 unsigned int active:1;
132 unsigned int forcecommit:1; /*!< Should uncommitted transactions be auto-committed on handle release? */
133 unsigned int isolation; /*!< Flags for how the DB should deal with data in other, uncommitted transactions */
134 char name[0]; /*!< Name of this transaction ID */
135};
136
137const char *ast_odbc_isolation2text(int iso)
138{
139 if (iso == SQL_TXN_READ_COMMITTED) {
140 return "read_committed";
141 } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
142 return "read_uncommitted";
143 } else if (iso == SQL_TXN_SERIALIZABLE) {
144 return "serializable";
145 } else if (iso == SQL_TXN_REPEATABLE_READ) {
146 return "repeatable_read";
147 } else {
148 return "unknown";
149 }
150}
151
152int ast_odbc_text2isolation(const char *txt)
153{
154 if (strncasecmp(txt, "read_", 5) == 0) {
155 if (strncasecmp(txt + 5, "c", 1) == 0) {
156 return SQL_TXN_READ_COMMITTED;
157 } else if (strncasecmp(txt + 5, "u", 1) == 0) {
158 return SQL_TXN_READ_UNCOMMITTED;
159 } else {
160 return 0;
161 }
162 } else if (strncasecmp(txt, "ser", 3) == 0) {
163 return SQL_TXN_SERIALIZABLE;
164 } else if (strncasecmp(txt, "rep", 3) == 0) {
165 return SQL_TXN_REPEATABLE_READ;
166 } else {
167 return 0;
168 }
169}
170
171static void odbc_class_destructor(void *data)
172{
173 struct odbc_class *class = data;
174 struct odbc_obj *obj;
175
176 /* Due to refcounts, we can safely assume that any objects with a reference
177 * to us will prevent our destruction, so we don't need to worry about them.
178 */
179 if (class->username) {
180 ast_free(class->username);
181 }
182 if (class->password) {
183 ast_free(class->password);
184 }
185 if (class->sanitysql) {
186 ast_free(class->sanitysql);
187 }
188
189 while ((obj = AST_LIST_REMOVE_HEAD(&class->connections, list))) {
190 ao2_ref(obj, -1);
191 }
192
193 SQLFreeHandle(SQL_HANDLE_ENV, class->env);
194 ast_mutex_destroy(&class->lock);
195 ast_cond_destroy(&class->cond);
196 ast_free(class->sql_text);
197}
198
199static void odbc_obj_destructor(void *data)
200{
201 struct odbc_obj *obj = data;
202
204}
205
207{
208 struct odbc_cache_columns *col;
209
210 ast_debug(1, "Destroying table cache for %s\n", table->table);
211
212 AST_RWLIST_WRLOCK(&table->columns);
213 while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
214 ast_free(col);
215 }
216 AST_RWLIST_UNLOCK(&table->columns);
218
220}
221
222/*!
223 * XXX This creates a connection and disconnects it. In some situations, the caller of
224 * this function has its own connection and could donate it to this function instead of
225 * needing to create another one.
226 *
227 * XXX The automatic readlock of the columns is awkward. It's done because it's possible for
228 * multiple threads to have references to the table, and the table is not refcounted. Possible
229 * changes here would be
230 * * Eliminate the table cache entirely. The use of ast_odbc_find_table() is generally
231 * questionable. The only real good use right now is from ast_realtime_require_field() in
232 * order to make sure the DB has the expected columns in it. Since that is only used sparingly,
233 * the need to cache tables is questionable. Instead, the table structure can be fetched from
234 * the DB directly each time, resulting in a single owner of the data.
235 * * Make odbc_cache_tables a refcounted object.
236 */
237struct odbc_cache_tables *ast_odbc_find_table(const char *database, const char *tablename)
238{
239 struct odbc_cache_tables *tableptr;
240 struct odbc_cache_columns *entry;
241 char columnname[80];
242 SQLLEN sqlptr;
243 SQLHSTMT stmt = NULL;
244 int res = 0, error = 0;
245 struct odbc_obj *obj;
246
249 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
250 break;
251 }
252 }
253 if (tableptr) {
254 AST_RWLIST_RDLOCK(&tableptr->columns);
256 return tableptr;
257 }
258
259 if (!(obj = ast_odbc_request_obj(database, 0))) {
260 ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
262 return NULL;
263 }
264
265 /* Table structure not already cached; build it now. */
266 do {
267 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
268 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
269 ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
270 break;
271 }
272
273 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
274 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
275 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
276 ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
277 break;
278 }
279
280 if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
281 ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
282 break;
283 }
284
285 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
286 tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
287 strcpy(tableptr->connection, database); /* SAFE */
288 strcpy(tableptr->table, tablename); /* SAFE */
289 AST_RWLIST_HEAD_INIT(&(tableptr->columns));
290
291 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
292 SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
293
294 if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
295 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
296 error = 1;
297 break;
298 }
299 entry->name = (char *)entry + sizeof(*entry);
300 strcpy(entry->name, columnname);
301
302 SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
303 SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
304 SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
305 SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
306 SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
307 SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
308
309 /* Specification states that the octenlen should be the maximum number of bytes
310 * returned in a char or binary column, but it seems that some drivers just set
311 * it to NULL. (Bad Postgres! No biscuit!) */
312 if (entry->octetlen == 0) {
313 entry->octetlen = entry->size;
314 }
315
316 ast_debug(3, "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);
317 /* Insert column info into column list */
318 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
319 }
320 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
321
323 AST_RWLIST_RDLOCK(&(tableptr->columns));
324 break;
325 } while (1);
326
328
329 if (error) {
330 destroy_table_cache(tableptr);
331 tableptr = NULL;
332 }
334 return tableptr;
335}
336
338{
339 struct odbc_cache_columns *col;
340 AST_RWLIST_TRAVERSE(&table->columns, col, list) {
341 if (strcasecmp(col->name, colname) == 0) {
342 return col;
343 }
344 }
345 return NULL;
346}
347
348int ast_odbc_clear_cache(const char *database, const char *tablename)
349{
350 struct odbc_cache_tables *tableptr;
351
354 if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
356 destroy_table_cache(tableptr);
357 break;
358 }
359 }
362 return tableptr ? 0 : -1;
363}
364
365SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT (*exec_cb)(struct odbc_obj *obj, void *data), void *data)
366{
367 struct timeval start;
368 SQLHSTMT stmt;
369
370 if (obj->parent->logging) {
371 start = ast_tvnow();
372 }
373
374 stmt = exec_cb(obj, data);
375
376 if (obj->parent->logging) {
377 long execution_time = ast_tvdiff_ms(ast_tvnow(), start);
378
379 if (obj->parent->slowquerylimit && execution_time > obj->parent->slowquerylimit) {
380 ast_log(LOG_WARNING, "SQL query '%s' took %ld milliseconds to execute on class '%s', this may indicate a database problem\n",
381 obj->sql_text, execution_time, obj->parent->name);
382 }
383
384 ast_mutex_lock(&obj->parent->lock);
385 if (execution_time > obj->parent->longest_query_execution_time || !obj->parent->sql_text) {
386 obj->parent->longest_query_execution_time = execution_time;
387 /* Due to the callback nature of the res_odbc API it's not possible to ensure that
388 * the SQL text is removed from the connection in all cases, so only if it becomes the
389 * new longest executing query do we steal the SQL text. In other cases what will happen
390 * is that the SQL text will be freed if the connection is released back to the class or
391 * if a new query is done on the connection.
392 */
393 ast_free(obj->parent->sql_text);
394 obj->parent->sql_text = obj->sql_text;
395 obj->sql_text = NULL;
396 }
398 }
399
400 return stmt;
401}
402
403SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT (*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
404{
405 struct timeval start;
406 int res = 0;
407 SQLHSTMT stmt;
408
409 if (obj->parent->logging) {
410 start = ast_tvnow();
411 }
412
413 /* This prepare callback may do more than just prepare -- it may also
414 * bind parameters, bind results, etc. The real key, here, is that
415 * when we disconnect, all handles become invalid for most databases.
416 * We must therefore redo everything when we establish a new
417 * connection. */
418 stmt = prepare_cb(obj, data);
419 if (!stmt) {
420 return NULL;
421 }
422
423 res = SQLExecute(stmt);
424 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
425 if (res == SQL_ERROR) {
426 ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
427 }
428
429 ast_log(LOG_WARNING, "SQL Execute error %d!\n", res);
430 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
431 stmt = NULL;
432 } else if (obj->parent->logging) {
433 long execution_time = ast_tvdiff_ms(ast_tvnow(), start);
434
435 if (obj->parent->slowquerylimit && execution_time > obj->parent->slowquerylimit) {
436 ast_log(LOG_WARNING, "SQL query '%s' took %ld milliseconds to execute on class '%s', this may indicate a database problem\n",
437 obj->sql_text, execution_time, obj->parent->name);
438 }
439
440 ast_mutex_lock(&obj->parent->lock);
441
442 /* If this takes the record on longest query execution time, update the parent class
443 * with the information.
444 */
445 if (execution_time > obj->parent->longest_query_execution_time || !obj->parent->sql_text) {
446 obj->parent->longest_query_execution_time = execution_time;
447 ast_free(obj->parent->sql_text);
448 obj->parent->sql_text = obj->sql_text;
449 obj->sql_text = NULL;
450 }
452
454 }
455
456 return stmt;
457}
458
459int ast_odbc_prepare(struct odbc_obj *obj, SQLHSTMT *stmt, const char *sql)
460{
461 if (obj->parent->logging) {
462 /* It is possible for this connection to be reused without being
463 * released back to the class, so we free what may already exist
464 * and place the new SQL in.
465 */
466 ast_free(obj->sql_text);
467 obj->sql_text = ast_strdup(sql);
469 }
470
471 return SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
472}
473
474SQLRETURN ast_odbc_execute_sql(struct odbc_obj *obj, SQLHSTMT *stmt, const char *sql)
475{
476 if (obj->parent->logging) {
477 ast_free(obj->sql_text);
478 obj->sql_text = ast_strdup(sql);
480 }
481
482 return SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
483}
484
485int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
486{
487 int res = 0;
488
489 res = SQLExecute(stmt);
490 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
491 if (res == SQL_ERROR) {
492 ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
493 }
494 }
495
496 if (obj->parent->logging) {
498 }
499
500 return res;
501}
502
503SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
504{
505 SQLRETURN res;
506
507 if (pmaxlen == 0) {
508 if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
509 ast_str_make_space(buf, *StrLen_or_Ind + 1);
510 }
511 } else if (pmaxlen > 0) {
512 ast_str_make_space(buf, pmaxlen);
513 }
514 res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
516
517 return res;
518}
519
520struct ast_str *ast_odbc_print_errors(SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
521{
522 struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
523 SQLINTEGER nativeerror = 0;
524 SQLSMALLINT diagbytes = 0;
525 SQLSMALLINT i;
526 unsigned char state[10];
527 unsigned char diagnostic[256];
528
529 ast_str_reset(errors);
530 i = 0;
531 while (SQLGetDiagRec(handle_type, handle, ++i, state, &nativeerror,
532 diagnostic, sizeof(diagnostic), &diagbytes) == SQL_SUCCESS) {
533 ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
534 ast_log(LOG_WARNING, "%s returned an error: %s: %s\n", operation, state, diagnostic);
535 /* XXX Why is this here? */
536 if (i > 10) {
537 ast_log(LOG_WARNING, "There are more than 10 diagnostic records! Ignore the rest.\n");
538 break;
539 }
540 }
541
542 return errors;
543}
544
545unsigned int ast_odbc_class_get_isolation(struct odbc_class *class)
546{
547 return class->isolation;
548}
549
551{
552 return class->forcecommit;
553}
554
555const char *ast_odbc_class_get_name(struct odbc_class *class)
556{
557 return class->name;
558}
559
560static int load_odbc_config(void)
561{
562 static char *cfg = "res_odbc.conf";
563 struct ast_config *config;
564 struct ast_variable *v;
565 char *cat;
566 const char *dsn, *username, *password, *sanitysql;
567 int enabled, bse, conntimeout, forcecommit, isolation, maxconnections, logging, slowquerylimit;
568 struct timeval ncache = { 0, 0 };
569 int preconnect = 0, res = 0, cache_is_queue = 0;
570 struct ast_flags config_flags = { 0 };
571 unsigned int max_cache_size;
572
573 struct odbc_class *new;
574
575 config = ast_config_load(cfg, config_flags);
577 ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
578 return -1;
579 }
580 for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
581 if (!strcasecmp(cat, "ENV")) {
582 for (v = ast_variable_browse(config, cat); v; v = v->next) {
583 setenv(v->name, v->value, 1);
584 ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
585 }
586 } else {
587 /* Reset all to defaults for each class of odbc connections */
589 enabled = 1;
590 preconnect = 0;
591 bse = 1;
592 conntimeout = 10;
593 forcecommit = 0;
594 isolation = SQL_TXN_READ_COMMITTED;
595 maxconnections = 1;
596 logging = 0;
597 slowquerylimit = 5000;
598 cache_is_queue = 0;
599 max_cache_size = UINT_MAX;
600 for (v = ast_variable_browse(config, cat); v; v = v->next) {
601 if (!strcasecmp(v->name, "pooling") ||
602 !strncasecmp(v->name, "share", 5) ||
603 !strcasecmp(v->name, "limit") ||
604 !strcasecmp(v->name, "idlecheck")) {
605 ast_log(LOG_WARNING, "The 'pooling', 'shared_connections', 'limit', and 'idlecheck' options were replaced by 'max_connections'. See res_odbc.conf.sample.\n");
606 } else if (!strcasecmp(v->name, "enabled")) {
607 enabled = ast_true(v->value);
608 } else if (!strcasecmp(v->name, "pre-connect")) {
609 preconnect = ast_true(v->value);
610 } else if (!strcasecmp(v->name, "dsn")) {
611 dsn = v->value;
612 } else if (!strcasecmp(v->name, "username")) {
613 username = v->value;
614 } else if (!strcasecmp(v->name, "password")) {
615 password = v->value;
616 } else if (!strcasecmp(v->name, "sanitysql")) {
617 sanitysql = v->value;
618 } else if (!strcasecmp(v->name, "backslash_is_escape")) {
619 bse = ast_true(v->value);
620 } else if (!strcasecmp(v->name, "connect_timeout")) {
621 if (sscanf(v->value, "%d", &conntimeout) != 1 || conntimeout < 1) {
622 ast_log(LOG_WARNING, "connect_timeout must be a positive integer\n");
623 conntimeout = 10;
624 }
625 } else if (!strcasecmp(v->name, "negative_connection_cache")) {
626 double dncache;
627 if (sscanf(v->value, "%lf", &dncache) != 1 || dncache < 0) {
628 ast_log(LOG_WARNING, "negative_connection_cache must be a non-negative integer\n");
629 /* 5 minutes sounds like a reasonable default */
630 ncache.tv_sec = 300;
631 ncache.tv_usec = 0;
632 } else {
633 ncache.tv_sec = (int)dncache;
634 ncache.tv_usec = (dncache - ncache.tv_sec) * 1000000;
635 }
636 } else if (!strcasecmp(v->name, "forcecommit")) {
638 } else if (!strcasecmp(v->name, "isolation")) {
639 if ((isolation = ast_odbc_text2isolation(v->value)) == 0) {
640 ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
641 isolation = SQL_TXN_READ_COMMITTED;
642 }
643 } else if (!strcasecmp(v->name, "max_connections")) {
644 if (sscanf(v->value, "%30d", &maxconnections) != 1 || maxconnections < 1) {
645 ast_log(LOG_WARNING, "max_connections must be a positive integer\n");
646 maxconnections = 1;
647 }
648 } else if (!strcasecmp(v->name, "logging")) {
649 logging = ast_true(v->value);
650 } else if (!strcasecmp(v->name, "slow_query_limit")) {
651 if (sscanf(v->value, "%30d", &slowquerylimit) != 1) {
652 ast_log(LOG_WARNING, "slow_query_limit must be a positive integer\n");
653 slowquerylimit = 5000;
654 }
655 } else if (!strcasecmp(v->name, "cache_type")) {
656 cache_is_queue = !strcasecmp(v->value, "rr") ||
657 !strcasecmp(v->value, "roundrobin") ||
658 !strcasecmp(v->value, "queue");
659 } else if (!strcasecmp(v->name, "cache_size")) {
660 if (!strcasecmp(v->value, "-1")) {
661 max_cache_size = UINT_MAX;
662 } else if (sscanf(v->value, "%u", &max_cache_size) != 1) {
663 ast_log(LOG_WARNING, "cache_size must be a non-negative integer or -1 (infinite)\n");
664 }
665 }
666 }
667
668 if (enabled && !ast_strlen_zero(dsn)) {
669 new = ao2_alloc(sizeof(*new), odbc_class_destructor);
670
671 if (!new) {
672 res = -1;
673 break;
674 }
675
676 SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
677 res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
678
679 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
680 ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
681 ao2_ref(new, -1);
682 return res;
683 }
684
685 new->backslash_is_escape = bse ? 1 : 0;
686 new->forcecommit = forcecommit ? 1 : 0;
687 new->isolation = isolation;
688 new->conntimeout = conntimeout;
689 new->negative_connection_cache = ncache;
690 new->maxconnections = maxconnections;
691 new->logging = logging;
692 new->slowquerylimit = slowquerylimit;
693 new->cache_is_queue = cache_is_queue;
694 new->max_cache_size = max_cache_size;
695 new->cur_cache = 0;
696
697 if (cat)
698 ast_copy_string(new->name, cat, sizeof(new->name));
699 if (dsn)
700 ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
701 if (username && !(new->username = ast_strdup(username))) {
702 ao2_ref(new, -1);
703 break;
704 }
705 if (password && !(new->password = ast_strdup(password))) {
706 ao2_ref(new, -1);
707 break;
708 }
709 if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
710 ao2_ref(new, -1);
711 break;
712 }
713
714 ast_mutex_init(&new->lock);
715 ast_cond_init(&new->cond, NULL);
716
717 odbc_register_class(new, preconnect);
718 ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
719 ao2_ref(new, -1);
720 new = NULL;
721 }
722 }
723 }
725 return res;
726}
727
728static char *handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
729{
730 struct ao2_iterator aoi;
731 struct odbc_class *class;
732 int length = 0;
733 int which = 0;
734 char *ret = NULL;
735
736 switch (cmd) {
737 case CLI_INIT:
738 e->command = "odbc show";
739 e->usage =
740 "Usage: odbc show [class]\n"
741 " List settings of a particular ODBC class or,\n"
742 " if not specified, all classes.\n";
743 return NULL;
744 case CLI_GENERATE:
745 if (a->pos != 2)
746 return NULL;
747 length = strlen(a->word);
749 while ((class = ao2_iterator_next(&aoi))) {
750 if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
751 ret = ast_strdup(class->name);
752 }
753 ao2_ref(class, -1);
754 if (ret) {
755 break;
756 }
757 }
759 if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
760 ret = ast_strdup("all");
761 }
762 return ret;
763 }
764
765 ast_cli(a->fd, "\nODBC DSN Settings\n");
766 ast_cli(a->fd, "-----------------\n\n");
768 while ((class = ao2_iterator_next(&aoi))) {
769 if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
770 char timestr[80];
771 struct ast_tm tm;
772
773 ast_cli(a->fd, " Name: %s\n DSN: %s\n", class->name, class->dsn);
774
775 if (class->last_negative_connect.tv_sec > 0) {
776 ast_localtime(&class->last_negative_connect, &tm, NULL);
777 ast_strftime(timestr, sizeof(timestr), "%Y-%m-%d %T", &tm);
778 ast_cli(a->fd, " Last fail connection attempt: %s\n", timestr);
779 }
780
781 ast_cli(a->fd, " Number of active connections: %zd (out of %d)\n", class->connection_cnt, class->maxconnections);
782 ast_cli(a->fd, " Cache Type: %s\n", class->cache_is_queue ? "round-robin queue" : "stack (last release, first re-use)");
783 ast_cli(a->fd, " Cache Usage: %u cached out of %u\n", class->cur_cache,
784 class->max_cache_size < class->maxconnections ? class->max_cache_size : class->maxconnections);
785 ast_cli(a->fd, " Logging: %s\n", class->logging ? "Enabled" : "Disabled");
786 if (class->logging) {
787 ast_cli(a->fd, " Number of prepares executed: %d\n", class->prepares_executed);
788 ast_cli(a->fd, " Number of queries executed: %d\n", class->queries_executed);
789 ast_mutex_lock(&class->lock);
790 if (class->sql_text) {
791 ast_cli(a->fd, " Longest running SQL query: %s (%ld milliseconds)\n", class->sql_text, class->longest_query_execution_time);
792 }
793 ast_mutex_unlock(&class->lock);
794 }
795 ast_cli(a->fd, "\n");
796 }
797 ao2_ref(class, -1);
798 }
800
801 return CLI_SUCCESS;
802}
803
804static struct ast_cli_entry cli_odbc[] = {
805 AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
806};
807
808static void odbc_register_class(struct odbc_class *class, int preconnect)
809{
810 struct odbc_obj *obj;
811
813 /* I still have a reference in the caller, so a deref is NOT missing here. */
814
815 if (!preconnect) {
816 return;
817 }
818
819 /* Request and release builds a connection */
820 obj = ast_odbc_request_obj(class->name, 0);
821 if (obj) {
823 }
824
825 return;
826}
827
829{
830 struct odbc_class *class = obj->parent;
831
832 ast_debug(2, "Releasing ODBC handle %p into pool\n", obj);
833
834 /* The odbc_obj only holds a reference to the class when it is
835 * actively being used. This guarantees no circular reference
836 * between odbc_class and odbc_obj. Since it is being released
837 * we also release our class reference. If a reload occurred before
838 * the class will go away automatically once all odbc_obj are
839 * released back.
840 */
841 obj->parent = NULL;
842
843 /* Free the SQL text so that the next user of this connection has
844 * a fresh start.
845 */
846 ast_free(obj->sql_text);
847 obj->sql_text = NULL;
848
849 ast_mutex_lock(&class->lock);
850 if (class->cache_is_queue) {
851 AST_LIST_INSERT_TAIL(&class->connections, obj, list);
852 } else {
853 AST_LIST_INSERT_HEAD(&class->connections, obj, list);
854 }
855
856 if (class->cur_cache >= class->max_cache_size) {
857 /* cache is full */
858 if (class->cache_is_queue) {
859 /* HEAD will be oldest */
860 obj = AST_LIST_REMOVE_HEAD(&class->connections, list);
861 } else {
862 /* TAIL will be oldest */
863 obj = AST_LIST_LAST(&class->connections);
864 AST_LIST_REMOVE(&class->connections, obj, list);
865 }
866 --class->connection_cnt;
867 ast_mutex_unlock(&class->lock);
868
869 ast_debug(2, "ODBC Pool '%s' exceeded cache size, dropping '%p', connection count is %zd (%u cached)\n",
870 class->name, obj, class->connection_cnt, class->cur_cache);
871
872 ao2_ref(obj, -1);
873
874 ast_mutex_lock(&class->lock);
875 } else {
876 ++class->cur_cache;
877 }
878 ast_cond_signal(&class->cond);
879 ast_mutex_unlock(&class->lock);
880
881 ao2_ref(class, -1);
882}
883
885{
886 return obj->parent->backslash_is_escape;
887}
888
889static int aoro2_class_cb(void *obj, void *arg, int flags)
890{
891 struct odbc_class *class = obj;
892 char *name = arg;
893 if (!strcmp(class->name, name) && !class->delme) {
894 return CMP_MATCH | CMP_STOP;
895 }
896 return 0;
897}
898
899unsigned int ast_odbc_get_max_connections(const char *name)
900{
901 struct odbc_class *class;
902 unsigned int max_connections;
903
904 class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name);
905 if (!class) {
906 return 0;
907 }
908
909 max_connections = class->maxconnections;
910 ao2_ref(class, -1);
911
912 return max_connections;
913}
914
915/*!
916 * \brief Determine if the connection has died.
917 *
918 * \param connection The connection to check
919 * \param class The ODBC class
920 * \retval 1 Yep, it's dead
921 * \retval 0 It's alive and well
922 */
923static int connection_dead(struct odbc_obj *connection, struct odbc_class *class)
924{
925 char *test_sql = "select 1";
926 SQLINTEGER dead;
927 SQLRETURN res;
928 SQLHSTMT stmt;
929
930 res = SQLGetConnectAttr(connection->con, SQL_ATTR_CONNECTION_DEAD, &dead, 0, 0);
931 if (SQL_SUCCEEDED(res)) {
932 return dead == SQL_CD_TRUE ? 1 : 0;
933 }
934
935 /* If the Driver doesn't support SQL_ATTR_CONNECTION_DEAD do a
936 * probing query instead
937 */
938 res = SQLAllocHandle(SQL_HANDLE_STMT, connection->con, &stmt);
939 if (!SQL_SUCCEEDED(res)) {
940 return 1;
941 }
942
943 if (!ast_strlen_zero(class->sanitysql)) {
944 test_sql = class->sanitysql;
945 }
946
947 res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
948 if (!SQL_SUCCEEDED(res)) {
949 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
950 return 1;
951 }
952
953 res = SQLExecute(stmt);
954 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
955
956 return SQL_SUCCEEDED(res) ? 0 : 1;
957}
958
959struct odbc_obj *_ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
960{
961 struct odbc_obj *obj = NULL;
962 struct odbc_class *class;
963
964 if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
965 ast_debug(1, "Class '%s' not found!\n", name);
966 return NULL;
967 }
968
969 while (!obj) {
970 ast_mutex_lock(&class->lock);
971
972 obj = AST_LIST_REMOVE_HEAD(&class->connections, list);
973 if (obj) {
974 --class->cur_cache;
975 }
976
977 ast_mutex_unlock(&class->lock);
978
979 if (!obj) {
980 ast_mutex_lock(&class->lock);
981
982 if (class->connection_cnt < class->maxconnections) {
983 /* If no connection is immediately available establish a new
984 * one if allowed. If we try and fail we give up completely as
985 * we could go into an infinite loop otherwise.
986 */
987 obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
988 if (!obj) {
989 ast_mutex_unlock(&class->lock);
990 break;
991 }
992
993 obj->parent = ao2_bump(class);
994
995 class->connection_cnt++;
996
997 ast_mutex_unlock(&class->lock);
998
999 if (odbc_obj_connect(obj) == ODBC_FAIL) {
1000 ast_mutex_lock(&class->lock);
1001 class->connection_cnt--;
1002 ast_cond_signal(&class->cond);
1003 ast_mutex_unlock(&class->lock);
1004 ao2_ref(obj->parent, -1);
1005 ao2_ref(obj, -1);
1006 obj = NULL;
1007 break;
1008 }
1009
1010 ast_mutex_lock(&class->lock);
1011
1012 ast_debug(2, "Created ODBC handle %p on class '%s', new count is %zd\n", obj,
1013 name, class->connection_cnt);
1014
1015 } else {
1016 /* Otherwise if we're not allowed to create a new one we
1017 * wait for another thread to give up the connection they
1018 * own.
1019 */
1020 ast_cond_wait(&class->cond, &class->lock);
1021 }
1022
1023 ast_mutex_unlock(&class->lock);
1024
1025 } else if (connection_dead(obj, class)) {
1026 /* If the connection is dead try to grab another functional one from the
1027 * pool instead of trying to resurrect this one.
1028 */
1029 ast_mutex_lock(&class->lock);
1030
1031 class->connection_cnt--;
1032 /* this thread will re-acquire, and if that fails will signal,
1033 * thus no need to signal class->cond here */
1034 ast_debug(2, "ODBC handle %p dead - removing from class '%s', new count is %zd\n",
1035 obj, name, class->connection_cnt);
1036
1037 ast_mutex_unlock(&class->lock);
1038
1039 ao2_ref(obj, -1);
1040 obj = NULL;
1041 } else {
1042 /* We successfully grabbed a connection from the pool and all is well!
1043 */
1044 obj->parent = ao2_bump(class);
1045 ast_debug(2, "Reusing ODBC handle %p from class '%s'\n", obj, name);
1046 }
1047 }
1048
1049 ao2_ref(class, -1);
1050
1051 return obj;
1052}
1053
1054struct odbc_obj *_ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
1055{
1056 struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
1057 /* XXX New flow means that the "check" parameter doesn't do anything. We're requesting
1058 * a connection from ODBC. We'll either get a new one, which obviously is already connected, or
1059 * we'll get one from the ODBC connection pool. In that case, it will ensure to only give us a
1060 * live connection
1061 */
1062 return _ast_odbc_request_obj2(name, flags, file, function, lineno);
1063}
1064
1066{
1067 int res;
1068 SQLINTEGER err;
1069 short int mlen;
1070 unsigned char msg[200], state[10];
1071 SQLHDBC con;
1072
1073 /* Nothing to disconnect */
1074 if (!obj->con) {
1075 return ODBC_SUCCESS;
1076 }
1077
1078 con = obj->con;
1079 obj->con = NULL;
1080 res = SQLDisconnect(con);
1081
1082 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) == SQL_SUCCESS) {
1083 ast_debug(3, "Database handle %p (connection %p) deallocated\n", obj, con);
1084 } else {
1085 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
1086 ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
1087 }
1088
1089 return ODBC_SUCCESS;
1090}
1091
1093{
1094 int res;
1095 SQLINTEGER err;
1096 short int mlen;
1097 unsigned char msg[200], state[10];
1098#ifdef NEEDTRACE
1099 SQLINTEGER enable = 1;
1100 char *tracefile = "/tmp/odbc.trace";
1101#endif
1102 SQLHDBC con;
1103 long int negative_cache_expiration;
1104
1105 ast_assert(obj->con == NULL);
1106 ast_debug(3, "Connecting %s(%p)\n", obj->parent->name, obj);
1107
1108 /* Dont connect while server is marked as unreachable via negative_connection_cache */
1109 negative_cache_expiration = obj->parent->last_negative_connect.tv_sec + obj->parent->negative_connection_cache.tv_sec;
1110 if (time(NULL) < negative_cache_expiration) {
1111 char secs[AST_TIME_T_LEN];
1112 ast_time_t_to_string(negative_cache_expiration - time(NULL), secs, sizeof(secs));
1113 ast_log(LOG_WARNING, "Not connecting to %s. Negative connection cache for %s seconds\n", obj->parent->name, secs);
1114 return ODBC_FAIL;
1115 }
1116
1117 res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &con);
1118
1119 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1120 ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
1122 return ODBC_FAIL;
1123 }
1124 SQLSetConnectAttr(con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1125 SQLSetConnectAttr(con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *)(long) obj->parent->conntimeout, 0);
1126#ifdef NEEDTRACE
1127 SQLSetConnectAttr(con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
1128 SQLSetConnectAttr(con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
1129#endif
1130
1131 res = SQLConnect(con,
1132 (SQLCHAR *) obj->parent->dsn, SQL_NTS,
1133 (SQLCHAR *) obj->parent->username, SQL_NTS,
1134 (SQLCHAR *) obj->parent->password, SQL_NTS);
1135
1136 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1137 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
1139 ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
1140 if ((res = SQLFreeHandle(SQL_HANDLE_DBC, con)) != SQL_SUCCESS) {
1141 SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &err, msg, 100, &mlen);
1142 ast_log(LOG_WARNING, "Unable to deallocate database handle %p? %d errno=%d %s\n", con, res, (int)err, msg);
1143 }
1144 return ODBC_FAIL;
1145 } else {
1146 ast_debug(3, "res_odbc: Connected to %s [%s (%p)]\n", obj->parent->name, obj->parent->dsn, obj);
1147 }
1148
1149 obj->con = con;
1150 return ODBC_SUCCESS;
1151}
1152
1153static int reload(void)
1154{
1155 struct odbc_cache_tables *table;
1156 struct odbc_class *class;
1158
1159 /* First, mark all to be purged */
1160 while ((class = ao2_iterator_next(&aoi))) {
1161 class->delme = 1;
1162 ao2_ref(class, -1);
1163 }
1165
1167
1169 while ((class = ao2_iterator_next(&aoi))) {
1170 if (class->delme) {
1172 }
1173 ao2_ref(class, -1);
1174 }
1176
1177 /* Empty the cache; it will get rebuilt the next time the tables are needed. */
1179 while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
1181 }
1183
1184 return 0;
1185}
1186
1187static int unload_module(void)
1188{
1191
1192 return 0;
1193}
1194
1195static int load_module(void)
1196{
1198 if (!class_container) {
1200 }
1201
1202 if (load_odbc_config() == -1) {
1204 }
1205
1208
1210}
1211
1213 .support_level = AST_MODULE_SUPPORT_CORE,
1214 .load = load_module,
1215 .unload = unload_module,
1216 .reload = reload,
1217 .load_pri = AST_MODPRI_REALTIME_DEPEND,
1218 .requires = "res_odbc_transaction",
int setenv(const char *name, const char *value, int overwrite)
Asterisk main include file. File version handling, generic pbx functions.
#define ast_free(a)
Definition: astmm.h:180
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:241
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:202
#define ast_log
Definition: astobj2.c:42
#define ao2_iterator_next(iter)
Definition: astobj2.h:1911
#define ao2_link(container, obj)
Add an object to a container.
Definition: astobj2.h:1532
@ CMP_MATCH
Definition: astobj2.h:1027
@ CMP_STOP
Definition: astobj2.h:1028
@ AO2_ALLOC_OPT_LOCK_MUTEX
Definition: astobj2.h:363
int ao2_match_by_addr(void *obj, void *arg, int flags)
A common ao2_callback is one that matches by address.
#define ao2_callback(c, flags, cb_fn, arg)
ao2_callback() is a generic function that applies cb_fn() to all objects in a container,...
Definition: astobj2.h:1693
#define ao2_cleanup(obj)
Definition: astobj2.h:1934
#define ao2_unlink(container, obj)
Remove an object from a container.
Definition: astobj2.h:1578
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result
Create an iterator for a container.
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition: astobj2.h:459
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
Definition: astobj2.h:480
void ao2_iterator_destroy(struct ao2_iterator *iter)
Destroy a container iterator.
#define ao2_container_alloc_list(ao2_options, container_options, sort_fn, cmp_fn)
Allocate and initialize a list container.
Definition: astobj2.h:1327
#define ao2_alloc(data_size, destructor_fn)
Definition: astobj2.h:409
static char * dsn
Definition: cdr_odbc.c:55
static char * table
Definition: cdr_odbc.c:55
static const char config[]
Definition: chan_ooh323.c:111
General Asterisk PBX channel definitions.
Standard Command Line Interface.
#define CLI_SUCCESS
Definition: cli.h:44
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
Definition: clicompat.c:30
#define AST_CLI_DEFINE(fn, txt,...)
Definition: cli.h:197
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
@ CLI_INIT
Definition: cli.h:152
@ CLI_GENERATE
Definition: cli.h:153
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition: cli.h:265
static int enabled
Definition: dnsmgr.c:91
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
Generic File Format Support. Should be included by clients of the file handling routines....
static const char name[]
Definition: format_mp3.c:68
Application convenience functions, designed to give consistent look and feel to Asterisk apps.
Configuration File Parser.
#define ast_config_load(filename, flags)
Load a config file.
char * ast_category_browse(struct ast_config *config, const char *prev_name)
Browse categories.
Definition: extconf.c:3326
#define CONFIG_STATUS_FILEMISSING
#define CONFIG_STATUS_FILEINVALID
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
Definition: extconf.c:1289
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition: extconf.c:1215
#define ast_debug(level,...)
Log a DEBUG message.
#define LOG_ERROR
#define LOG_NOTICE
#define LOG_WARNING
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
Definition: linkedlists.h:78
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
Definition: linkedlists.h:225
#define AST_LIST_LAST(head)
Returns the last entry contained in a list.
Definition: linkedlists.h:429
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:545
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:52
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:151
#define AST_RWLIST_HEAD_INIT(head)
Initializes an rwlist head structure.
Definition: linkedlists.h:639
#define AST_RWLIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a read/write list of specified type, statically initialized.
Definition: linkedlists.h:333
#define AST_RWLIST_REMOVE_HEAD
Definition: linkedlists.h:844
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:731
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:410
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:617
#define AST_RWLIST_TRAVERSE
Definition: linkedlists.h:494
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
Definition: linkedlists.h:711
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
Definition: linkedlists.h:856
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:557
#define AST_RWLIST_INSERT_TAIL
Definition: linkedlists.h:741
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:833
#define AST_RWLIST_HEAD_DESTROY(head)
Destroys an rwlist head structure.
Definition: linkedlists.h:667
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition: localtime.c:1739
int ast_strftime(char *buf, size_t len, const char *format, const struct ast_tm *tm)
Special version of strftime(3) that handles fractions of a second. Takes the same arguments as strfti...
Definition: localtime.c:2524
Asterisk locking-related definitions:
#define ast_cond_destroy(cond)
Definition: lock.h:209
#define ast_cond_wait(cond, mutex)
Definition: lock.h:212
#define ast_cond_init(cond, attr)
Definition: lock.h:208
#define ast_mutex_init(pmutex)
Definition: lock.h:193
#define ast_mutex_unlock(a)
Definition: lock.h:197
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition: lock.h:764
pthread_cond_t ast_cond_t
Definition: lock.h:185
#define ast_mutex_destroy(a)
Definition: lock.h:195
#define ast_mutex_lock(a)
Definition: lock.h:196
#define ast_cond_signal(cond)
Definition: lock.h:210
Asterisk module definitions.
@ AST_MODFLAG_LOAD_ORDER
Definition: module.h:331
@ AST_MODFLAG_GLOBAL_SYMBOLS
Definition: module.h:330
#define ast_module_shutdown_ref(mod)
Prevent unload of the module before shutdown.
Definition: module.h:478
#define AST_MODULE_INFO(keystr, flags_to_set, desc, fields...)
Definition: module.h:557
@ AST_MODPRI_REALTIME_DEPEND
Definition: module.h:335
@ AST_MODULE_SUPPORT_CORE
Definition: module.h:121
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
@ AST_MODULE_LOAD_SUCCESS
Definition: module.h:70
@ AST_MODULE_LOAD_DECLINE
Module has failed to load, may be in an inconsistent state.
Definition: module.h:78
Core PBX routines and definitions.
static char * handle_cli_odbc_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: res_odbc.c:728
static struct ast_threadstorage errors_buf
Definition: res_odbc.c:118
static struct ast_cli_entry cli_odbc[]
Definition: res_odbc.c:804
static void odbc_register_class(struct odbc_class *class, int connect)
Definition: res_odbc.c:808
static int load_odbc_config(void)
Definition: res_odbc.c:560
static int aoro2_class_cb(void *obj, void *arg, int flags)
Definition: res_odbc.c:889
static void odbc_obj_destructor(void *data)
Definition: res_odbc.c:199
static odbc_status odbc_obj_connect(struct odbc_obj *obj)
Definition: res_odbc.c:1092
int ast_odbc_prepare(struct odbc_obj *obj, SQLHSTMT *stmt, const char *sql)
Prepares a SQL query on a statement.
Definition: res_odbc.c:459
unsigned int ast_odbc_class_get_isolation(struct odbc_class *class)
Get the transaction isolation setting for an ODBC class.
Definition: res_odbc.c:545
void ast_odbc_release_obj(struct odbc_obj *obj)
Releases an ODBC object previously allocated by ast_odbc_request_obj()
Definition: res_odbc.c:828
struct odbc_cache_tables * ast_odbc_find_table(const char *database, const char *tablename)
Find or create an entry describing the table specified.
Definition: res_odbc.c:237
unsigned int ast_odbc_get_max_connections(const char *name)
Return the current configured maximum number of connections for a class.
Definition: res_odbc.c:899
int ast_odbc_clear_cache(const char *database, const char *tablename)
Remove a cache entry from memory This function may be called to clear entries created and cached by t...
Definition: res_odbc.c:348
struct odbc_cache_columns * ast_odbc_find_column(struct odbc_cache_tables *table, const char *colname)
Find a column entry within a cached table structure.
Definition: res_odbc.c:337
static void odbc_class_destructor(void *data)
Definition: res_odbc.c:171
struct odbc_obj * _ast_odbc_request_obj(const char *name, int check, const char *file, const char *function, int lineno)
Definition: res_odbc.c:1054
static struct ao2_container * class_container
Definition: res_odbc.c:110
struct ast_str * ast_odbc_print_errors(SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
Shortcut for printing errors to logs after a failed SQL operation.
Definition: res_odbc.c:520
static void destroy_table_cache(struct odbc_cache_tables *table)
Definition: res_odbc.c:206
int ast_odbc_backslash_is_escape(struct odbc_obj *obj)
Checks if the database natively supports backslash as an escape character.
Definition: res_odbc.c:884
const char * ast_odbc_isolation2text(int iso)
Convert from numeric transaction isolation values to their textual counterparts.
Definition: res_odbc.c:137
const char * ast_odbc_class_get_name(struct odbc_class *class)
Get the name of an ODBC class.
Definition: res_odbc.c:555
SQLRETURN ast_odbc_ast_str_SQLGetData(struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
Wrapper for SQLGetData to use with dynamic strings.
Definition: res_odbc.c:503
SQLHSTMT ast_odbc_direct_execute(struct odbc_obj *obj, SQLHSTMT(*exec_cb)(struct odbc_obj *obj, void *data), void *data)
Executes an non prepared statement and returns the resulting statement handle.
Definition: res_odbc.c:365
unsigned int ast_odbc_class_get_forcecommit(struct odbc_class *class)
Get the transaction forcecommit setting for an ODBC class.
Definition: res_odbc.c:550
static int load_module(void)
Definition: res_odbc.c:1195
SQLRETURN ast_odbc_execute_sql(struct odbc_obj *obj, SQLHSTMT *stmt, const char *sql)
Execute a unprepared SQL query.
Definition: res_odbc.c:474
static odbc_status odbc_obj_disconnect(struct odbc_obj *obj)
Definition: res_odbc.c:1065
static int unload_module(void)
Definition: res_odbc.c:1187
static int reload(void)
Definition: res_odbc.c:1153
SQLHSTMT ast_odbc_prepare_and_execute(struct odbc_obj *obj, SQLHSTMT(*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
Prepares, executes, and returns the resulting statement handle.
Definition: res_odbc.c:403
int ast_odbc_text2isolation(const char *txt)
Convert from textual transaction isolation values to their numeric constants.
Definition: res_odbc.c:152
static int connection_dead(struct odbc_obj *connection, struct odbc_class *class)
Determine if the connection has died.
Definition: res_odbc.c:923
struct odbc_obj * _ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
Definition: res_odbc.c:959
int ast_odbc_smart_execute(struct odbc_obj *obj, SQLHSTMT stmt)
Executes a prepared statement handle.
Definition: res_odbc.c:485
ODBC resource manager.
odbc_status
Definition: res_odbc.h:36
@ ODBC_FAIL
Definition: res_odbc.h:36
@ ODBC_SUCCESS
Definition: res_odbc.h:36
@ RES_ODBC_SANITY_CHECK
Definition: res_odbc.h:40
#define ast_odbc_request_obj(name, check)
Get a ODBC connection object.
Definition: res_odbc.h:120
#define NULL
Definition: resample.c:96
String manipulation functions.
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:1139
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:761
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true"....
Definition: utils.c:2199
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:65
void ast_str_reset(struct ast_str *buf)
Reset the content of a dynamic string. Useful before a series of ast_str_append.
Definition: strings.h:693
#define ast_str_make_space(buf, new_len)
Definition: strings.h:828
void ast_str_update(struct ast_str *buf)
Update the length of the buffer, after using ast_str merely as a buffer.
Definition: strings.h:703
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:730
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
size_t ast_str_size(const struct ast_str *buf)
Returns the current maximum length (without reallocation) of the current buffer.
Definition: strings.h:742
struct ast_str * ast_str_thread_get(struct ast_threadstorage *ts, size_t init_len)
Retrieve a thread locally stored dynamic string.
Definition: strings.h:909
Generic container type.
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
Definition: astobj2.h:1821
Main Channel structure associated with a channel.
descriptor for a cli entry.
Definition: cli.h:171
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
Structure used to handle boolean flags.
Definition: utils.h:199
unsigned int flags
Definition: utils.h:200
struct ast_module * self
Definition: module.h:356
Structure for mutex and tracking information.
Definition: lock.h:142
Support for dynamic strings.
Definition: strings.h:623
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
Data source name.
Definition: func_odbc.c:181
These structures are used for adaptive capabilities.
Definition: res_odbc.h:59
SQLSMALLINT decimals
Definition: res_odbc.h:63
SQLSMALLINT radix
Definition: res_odbc.h:64
SQLSMALLINT type
Definition: res_odbc.h:61
SQLINTEGER octetlen
Definition: res_odbc.h:66
SQLINTEGER size
Definition: res_odbc.h:62
SQLSMALLINT nullable
Definition: res_odbc.h:65
char * connection
Definition: res_odbc.h:71
struct odbc_cache_tables::_columns columns
unsigned int slowquerylimit
Definition: res_odbc.c:103
unsigned int max_cache_size
Definition: res_odbc.c:105
char dsn[80]
Definition: res_odbc.c:68
ast_cond_t cond
Definition: res_odbc.c:89
char * sql_text
Definition: res_odbc.c:101
unsigned int delme
Definition: res_odbc.c:73
int queries_executed
Definition: res_odbc.c:97
char name[80]
Definition: res_odbc.c:67
size_t connection_cnt
Definition: res_odbc.c:91
unsigned int logging
Definition: res_odbc.c:93
char * password
Definition: res_odbc.c:70
unsigned int maxconnections
Definition: res_odbc.c:79
unsigned int cur_cache
Definition: res_odbc.c:107
int prepares_executed
Definition: res_odbc.c:95
struct timeval negative_connection_cache
Definition: res_odbc.c:81
unsigned int isolation
Definition: res_odbc.c:77
unsigned int backslash_is_escape
Definition: res_odbc.c:74
unsigned int cache_is_queue
Definition: res_odbc.c:76
char * username
Definition: res_odbc.c:69
SQLHENV env
Definition: res_odbc.c:72
long longest_query_execution_time
Definition: res_odbc.c:99
struct odbc_class::@447 list
struct odbc_class::@448 connections
unsigned int conntimeout
Definition: res_odbc.c:78
struct timeval last_negative_connect
Definition: res_odbc.c:83
unsigned int forcecommit
Definition: res_odbc.c:75
ast_mutex_t lock
Definition: res_odbc.c:87
char * sanitysql
Definition: res_odbc.c:71
ODBC container.
Definition: res_odbc.h:46
struct odbc_obj::@260 list
char * sql_text
Definition: res_odbc.h:54
struct odbc_class * parent
Definition: res_odbc.h:48
SQLHDBC con
Definition: res_odbc.h:47
struct odbc_txn_frame::@449 list
char name[0]
Definition: res_odbc.c:134
unsigned int isolation
Definition: res_odbc.c:133
struct ast_channel * owner
Definition: res_odbc.c:122
unsigned int active
Is this record the current active transaction within the channel? Note that the active flag is really...
Definition: res_odbc.c:131
unsigned int forcecommit
Definition: res_odbc.c:132
struct odbc_obj * obj
Definition: res_odbc.c:123
const char * name
static struct test_val a
Definitions to aid in the use of thread local storage.
#define AST_THREADSTORAGE(name)
Define a thread storage variable.
Definition: threadstorage.h:86
Time-related functions and macros.
int ast_time_t_to_string(time_t time, char *buf, size_t length)
Converts to a string representation of a time_t as decimal seconds since the epoch....
Definition: time.c:152
#define AST_TIME_T_LEN
Definition: time.h:45
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:107
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159
int error(const char *format,...)
Definition: utils/frame.c:999
#define ast_assert(a)
Definition: utils.h:745
#define ARRAY_LEN(a)
Definition: utils.h:672