Fri Jul 3 20:35:39 2009

Asterisk developer's documentation


res_config_mysql.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Copyright (C) 1999-2005, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>  - Asterisk Author
00007  * Matthew Boehm <mboehm@cytelcom.com> - MySQL RealTime Driver Author
00008  *
00009  * res_config_mysql.c <mysql plugin for RealTime configuration engine>
00010  *
00011  * v2.0   - (10-07-05) - mutex_lock fixes (bug #4973, comment #0034602)
00012  *
00013  * v1.9   - (08-19-05) - Added support to correctly honor the family database specified
00014  *                       in extconfig.conf (bug #4973)
00015  *
00016  * v1.8   - (04-21-05) - Modified return values of update_mysql to better indicate
00017  *                       what really happened.
00018  *
00019  * v1.7   - (01-28-05) - Fixed non-initialization of ast_category struct
00020  *                       in realtime_multi_mysql function which caused segfault. 
00021  *
00022  * v1.6   - (00-00-00) - Skipped to bring comments into sync with version number in CVS.
00023  *
00024  * v1.5.1 - (01-26-05) - Added better(?) locking stuff
00025  *
00026  * v1.5   - (01-26-05) - Brought up to date with new config.h changes (bug #3406)
00027  *                     - Added in extra locking provided by georg (bug #3248)
00028  *
00029  * v1.4   - (12-02-04) - Added realtime_multi_mysql function
00030  *                        This function will return an ast_config with categories,
00031  *                        unlike standard realtime_mysql which only returns
00032  *                        a linked list of ast_variables
00033  *
00034  * v1.3   - (12-01-04) - Added support other operators
00035  *                       Ex: =, !=, LIKE, NOT LIKE, RLIKE, etc...
00036  *
00037  * v1.2   - (11-DD-04) - Added reload. Updated load and unload.
00038  *                       Code beautification (doc/CODING-GUIDELINES)
00039  */
00040 /*** MODULEINFO
00041    <depend>mysqlclient</depend>
00042  ***/
00043 
00044 /*** MODULEINFO
00045    <depend>mysqlclient</depend>
00046  ***/
00047 
00048 #include <asterisk.h>
00049 
00050 #include <asterisk/channel.h>
00051 #include <asterisk/logger.h>
00052 #include <asterisk/config.h>
00053 #include <asterisk/module.h>
00054 #include <asterisk/lock.h>
00055 #include <asterisk/options.h>
00056 #include <asterisk/cli.h>
00057 #include <asterisk/utils.h>
00058 #include <stdlib.h>
00059 #include <stdio.h>
00060 #include <string.h>
00061 #include <stdio.h>
00062 #include <mysql/mysql.h>
00063 #include <mysql/mysql_version.h>
00064 #include <mysql/errmsg.h>
00065 
00066 AST_MUTEX_DEFINE_STATIC(mysql_lock);
00067 #define RES_CONFIG_MYSQL_CONF "res_mysql.conf"
00068 MYSQL         mysql;
00069 static char   dbhost[50];
00070 static char   dbuser[50];
00071 static char   dbpass[50];
00072 static char   dbname[50];
00073 static char   dbsock[50];
00074 static int    dbport;
00075 static int    connected;
00076 static time_t connect_time;
00077 
00078 static int parse_config(void);
00079 static int mysql_reconnect(const char *database);
00080 static int realtime_mysql_status(int fd, int argc, char **argv);
00081 
00082 static char cli_realtime_mysql_status_usage[] =
00083 "Usage: realtime mysql status\n"
00084 "       Shows connection information for the MySQL RealTime driver\n";
00085 
00086 static struct ast_cli_entry cli_realtime_mysql_status = {
00087         { "realtime", "mysql", "status", NULL }, realtime_mysql_status,
00088         "Shows connection information for the MySQL RealTime driver", cli_realtime_mysql_status_usage, NULL };
00089 
00090 static struct ast_variable *realtime_mysql(const char *database, const char *table, va_list ap)
00091 {
00092    MYSQL_RES *result;
00093    MYSQL_ROW row;
00094    MYSQL_FIELD *fields;
00095    int numFields, i, valsz;
00096    char sql[512];
00097    char buf[511]; /* Keep this size uneven as it is 2n+1. */
00098    char *stringp;
00099    char *chunk;
00100    char *op;
00101    const char *newparam, *newval;
00102    struct ast_variable *var=NULL, *prev=NULL;
00103 
00104    if(!table) {
00105       ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
00106       return NULL;
00107    }
00108 
00109    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00110    newparam = va_arg(ap, const char *);
00111    newval = va_arg(ap, const char *);
00112    if(!newparam || !newval)  {
00113       ast_log(LOG_WARNING, "MySQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00114       return NULL;
00115    }
00116 
00117    /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
00118    ast_mutex_lock(&mysql_lock);
00119    if (!mysql_reconnect(database)) {
00120       ast_mutex_unlock(&mysql_lock);
00121       return NULL;
00122    }
00123 
00124    /* Create the first part of the query using the first parameter/value pairs we just extracted
00125       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00126 
00127    if(!strchr(newparam, ' ')) op = " ="; else op = "";
00128 
00129    if ((valsz = strlen (newval)) * 2 + 1 > sizeof(buf))
00130       valsz = (sizeof(buf) - 1) / 2;
00131    mysql_real_escape_string(&mysql, buf, newval, valsz);
00132    snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, buf);
00133    while((newparam = va_arg(ap, const char *))) {
00134       newval = va_arg(ap, const char *);
00135       if(!strchr(newparam, ' ')) op = " ="; else op = "";
00136       if ((valsz = strlen (newval)) * 2 + 1 > sizeof(buf))
00137          valsz = (sizeof(buf) - 1) / 2;
00138       mysql_real_escape_string(&mysql, buf, newval, valsz);
00139       snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam, op, buf);
00140    }
00141    va_end(ap);
00142 
00143    ast_log(LOG_DEBUG, "MySQL RealTime: Retrieve SQL: %s\n", sql);
00144 
00145    /* Execution. */
00146    if(mysql_real_query(&mysql, sql, strlen(sql))) {
00147       ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database. Check debug for more info.\n");
00148       ast_log(LOG_DEBUG, "MySQL RealTime: Query: %s\n", sql);
00149       ast_log(LOG_DEBUG, "MySQL RealTime: Query Failed because: %s\n", mysql_error(&mysql));
00150       ast_mutex_unlock(&mysql_lock);
00151       return NULL;
00152    }
00153 
00154    if((result = mysql_store_result(&mysql))) {
00155       numFields = mysql_num_fields(result);
00156       fields = mysql_fetch_fields(result);
00157 
00158       while((row = mysql_fetch_row(result))) {
00159          for(i = 0; i < numFields; i++) {
00160             stringp = row[i];
00161             while(stringp) {
00162                chunk = strsep(&stringp, ";");
00163                if(chunk && !ast_strlen_zero(ast_strip(chunk))) {
00164                   if(prev) {
00165                      prev->next = ast_variable_new(fields[i].name, chunk);
00166                      if (prev->next) {
00167                         prev = prev->next;
00168                      }
00169                   } else {
00170                      prev = var = ast_variable_new(fields[i].name, chunk);
00171                   }
00172                }
00173             }
00174          }
00175       }
00176    } else {                                
00177       ast_log(LOG_WARNING, "MySQL RealTime: Could not find any rows in table %s.\n", table);
00178    }
00179 
00180    ast_mutex_unlock(&mysql_lock);
00181    mysql_free_result(result);
00182 
00183    return var;
00184 }
00185 
00186 static struct ast_config *realtime_multi_mysql(const char *database, const char *table, va_list ap)
00187 {
00188    MYSQL_RES *result;
00189    MYSQL_ROW row;
00190    MYSQL_FIELD *fields;
00191    int numFields, i, valsz;
00192    char sql[512];
00193    char buf[511]; /* Keep this size uneven as it is 2n+1. */
00194    const char *initfield = NULL;
00195    char *stringp;
00196    char *chunk;
00197    char *op;
00198    const char *newparam, *newval;
00199    struct ast_realloca ra;
00200    struct ast_variable *var=NULL;
00201    struct ast_config *cfg = NULL;
00202    struct ast_category *cat = NULL;
00203 
00204    if(!table) {
00205       ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
00206       return NULL;
00207    }
00208    
00209    memset(&ra, 0, sizeof(ra));
00210 
00211    cfg = ast_config_new();
00212    if (!cfg) {
00213       /* If I can't alloc memory at this point, why bother doing anything else? */
00214       ast_log(LOG_WARNING, "Out of memory!\n");
00215       return NULL;
00216    }
00217 
00218    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00219    newparam = va_arg(ap, const char *);
00220    newval = va_arg(ap, const char *);
00221    if(!newparam || !newval)  {
00222       ast_log(LOG_WARNING, "MySQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00223       ast_config_destroy(cfg);
00224       return NULL;
00225    }
00226 
00227    initfield = ast_strdupa(newparam);
00228    if(initfield && (op = strchr(initfield, ' '))) {
00229       *op = '\0';
00230    }
00231 
00232    /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
00233    ast_mutex_lock(&mysql_lock);
00234    if (!mysql_reconnect(database)) {
00235       ast_mutex_unlock(&mysql_lock);
00236       return NULL;
00237    }
00238 
00239    /* Create the first part of the query using the first parameter/value pairs we just extracted
00240       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00241 
00242    if(!strchr(newparam, ' ')) op = " ="; else op = "";
00243 
00244    if ((valsz = strlen (newval)) * 2 + 1 > sizeof(buf))
00245       valsz = (sizeof(buf) - 1) / 2;
00246    mysql_real_escape_string(&mysql, buf, newval, valsz);
00247    snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE %s%s '%s'", table, newparam, op, buf);
00248    while((newparam = va_arg(ap, const char *))) {
00249       newval = va_arg(ap, const char *);
00250       if(!strchr(newparam, ' ')) op = " ="; else op = "";
00251       if ((valsz = strlen (newval)) * 2 + 1 > sizeof(buf))
00252          valsz = (sizeof(buf) - 1) / 2;
00253       mysql_real_escape_string(&mysql, buf, newval, valsz);
00254       snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " AND %s%s '%s'", newparam, op, buf);
00255    }
00256 
00257    if(initfield) {
00258       snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " ORDER BY %s", initfield);
00259    }
00260 
00261    va_end(ap);
00262 
00263    ast_log(LOG_DEBUG, "MySQL RealTime: Retrieve SQL: %s\n", sql);
00264 
00265    /* Execution. */
00266    if(mysql_real_query(&mysql, sql, strlen(sql))) {
00267       ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database. Check debug for more info.\n");
00268       ast_log(LOG_DEBUG, "MySQL RealTime: Query: %s\n", sql);
00269       ast_log(LOG_DEBUG, "MySQL RealTime: Query Failed because: %s\n", mysql_error(&mysql));
00270       ast_mutex_unlock(&mysql_lock);
00271       ast_config_destroy(cfg);
00272       return NULL;
00273    }
00274 
00275    if((result = mysql_store_result(&mysql))) {
00276       numFields = mysql_num_fields(result);
00277       fields = mysql_fetch_fields(result);
00278 
00279       while((row = mysql_fetch_row(result))) {
00280          var = NULL;
00281          cat = ast_category_new("");
00282          if(!cat) {
00283             ast_log(LOG_WARNING, "Out of memory!\n");
00284             continue;
00285          }
00286          for(i = 0; i < numFields; i++) {
00287             stringp = row[i];
00288             while(stringp) {
00289                chunk = strsep(&stringp, ";");
00290                if(chunk && !ast_strlen_zero(ast_strip(chunk))) {
00291                   if(initfield && !strcmp(initfield, fields[i].name)) {
00292                      ast_category_rename(cat, chunk);
00293                   }
00294                   var = ast_variable_new(fields[i].name, chunk);
00295                   ast_variable_append(cat, var);
00296                }
00297             }
00298          }
00299          ast_category_append(cfg, cat);
00300       }
00301    } else {
00302       ast_log(LOG_WARNING, "MySQL RealTime: Could not find any rows in table %s.\n", table);
00303    }
00304 
00305    ast_mutex_unlock(&mysql_lock);
00306    mysql_free_result(result);
00307 
00308    return cfg;
00309 }
00310 
00311 static int update_mysql(const char *database, const char *table, const char *keyfield, const char *lookup, va_list ap)
00312 {
00313    my_ulonglong numrows;
00314    char sql[512];
00315    char buf[511]; /* Keep this size uneven as it is 2n+1. */
00316    int valsz;
00317    const char *newparam, *newval;
00318 
00319    if(!table) {
00320       ast_log(LOG_WARNING, "MySQL RealTime: No table specified.\n");
00321                return -1;
00322    }
00323 
00324    /* Get the first parameter and first value in our list of passed paramater/value pairs */
00325    newparam = va_arg(ap, const char *);
00326    newval = va_arg(ap, const char *);
00327    if(!newparam || !newval)  {
00328       ast_log(LOG_WARNING, "MySQL RealTime: Realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00329                return -1;
00330    }
00331 
00332    /* Must connect to the server before anything else, as the escape function requires the mysql handle. */
00333    ast_mutex_lock(&mysql_lock);
00334    if (!mysql_reconnect(database)) {
00335       ast_mutex_unlock(&mysql_lock);
00336       return -1;
00337    }
00338 
00339    /* Create the first part of the query using the first parameter/value pairs we just extracted
00340       If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00341 
00342    if ((valsz = strlen (newval)) * 1 + 1 > sizeof(buf))
00343       valsz = (sizeof(buf) - 1) / 2;
00344    mysql_real_escape_string(&mysql, buf, newval, valsz);
00345    snprintf(sql, sizeof(sql), "UPDATE %s SET %s = '%s'", table, newparam, buf);
00346    while((newparam = va_arg(ap, const char *))) {
00347       newval = va_arg(ap, const char *);
00348       if ((valsz = strlen (newval)) * 2 + 1 > sizeof(buf))
00349          valsz = (sizeof(buf) - 1) / 2;
00350       mysql_real_escape_string(&mysql, buf, newval, valsz);
00351       snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), ", %s = '%s'", newparam, buf);
00352    }
00353    va_end(ap);
00354    if ((valsz = strlen (lookup)) * 1 + 1 > sizeof(buf))
00355       valsz = (sizeof(buf) - 1) / 2;
00356    mysql_real_escape_string(&mysql, buf, lookup, valsz);
00357    snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), " WHERE %s = '%s'", keyfield, buf);
00358 
00359    ast_log(LOG_DEBUG,"MySQL RealTime: Update SQL: %s\n", sql);
00360 
00361    /* Execution. */
00362    if(mysql_real_query(&mysql, sql, strlen(sql))) {
00363       ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database. Check debug for more info.\n");
00364       ast_log(LOG_DEBUG, "MySQL RealTime: Query: %s\n", sql);
00365       ast_log(LOG_DEBUG, "MySQL RealTime: Query Failed because: %s\n", mysql_error(&mysql));
00366       ast_mutex_unlock(&mysql_lock);
00367       return -1;
00368    }
00369 
00370    numrows = mysql_affected_rows(&mysql);
00371    ast_mutex_unlock(&mysql_lock);
00372 
00373    ast_log(LOG_DEBUG,"MySQL RealTime: Updated %llu rows on table: %s\n", numrows, table);
00374 
00375    /* From http://dev.mysql.com/doc/mysql/en/mysql-affected-rows.html
00376     * An integer greater than zero indicates the number of rows affected
00377     * Zero indicates that no records were updated
00378     * -1 indicates that the query returned an error (although, if the query failed, it should have been caught above.)
00379    */
00380 
00381    if(numrows >= 0)
00382       return (int)numrows;
00383 
00384    return -1;
00385 }
00386 
00387 static struct ast_config *config_mysql(const char *database, const char *table, const char *file, struct ast_config *cfg, int withcomments)
00388 {
00389    MYSQL_RES *result;
00390    MYSQL_ROW row;
00391    my_ulonglong num_rows;
00392    struct ast_variable *new_v;
00393    struct ast_category *cur_cat;
00394    char sql[250] = "";
00395    char last[80] = "";
00396    int last_cat_metric = 0;
00397 
00398    last[0] = '\0';
00399 
00400    if(!file || !strcmp(file, RES_CONFIG_MYSQL_CONF)) {
00401       ast_log(LOG_WARNING, "MySQL RealTime: Cannot configure myself.\n");
00402       return NULL;
00403    }
00404 
00405    snprintf(sql, sizeof(sql), "SELECT category, var_name, var_val, cat_metric FROM %s WHERE filename='%s' and commented=0 ORDER BY filename, cat_metric desc, var_metric asc, category, var_name, var_val, id", table, file);
00406 
00407    ast_log(LOG_DEBUG, "MySQL RealTime: Static SQL: %s\n", sql);
00408 
00409    /* We now have our complete statement; Lets connect to the server and execute it. */
00410    ast_mutex_lock(&mysql_lock);
00411    if(!mysql_reconnect(database)) {
00412       ast_mutex_unlock(&mysql_lock);
00413       return NULL;
00414    }
00415 
00416    if(mysql_real_query(&mysql, sql, strlen(sql))) {
00417       ast_log(LOG_WARNING, "MySQL RealTime: Failed to query database. Check debug for more info.\n");
00418       ast_log(LOG_DEBUG, "MySQL RealTime: Query: %s\n", sql);
00419       ast_log(LOG_DEBUG, "MySQL RealTime: Query Failed because: %s\n", mysql_error(&mysql));
00420       ast_mutex_unlock(&mysql_lock);
00421       return NULL;
00422    }
00423 
00424    if((result = mysql_store_result(&mysql))) {
00425       num_rows = mysql_num_rows(result);
00426       ast_log(LOG_DEBUG, "MySQL RealTime: Found %llu rows.\n", num_rows);
00427 
00428       /* There might exist a better way to access the column names other than counting,
00429                    but I believe that would require another loop that we don't need. */
00430 
00431       while((row = mysql_fetch_row(result))) {
00432          if(!strcmp(row[1], "#include")) {
00433             if (!ast_config_internal_load(row[2], cfg, 0)) {
00434                mysql_free_result(result);
00435                ast_mutex_unlock(&mysql_lock);
00436                return NULL;
00437             }
00438             continue;
00439          }
00440 
00441          if(strcmp(last, row[0]) || last_cat_metric != atoi(row[3])) {
00442             cur_cat = ast_category_new(row[0]);
00443             if (!cur_cat) {
00444                ast_log(LOG_WARNING, "Out of memory!\n");
00445                break;
00446             }
00447             strcpy(last, row[0]);
00448             last_cat_metric = atoi(row[3]);
00449             ast_category_append(cfg, cur_cat);
00450          }
00451          new_v = ast_variable_new(row[1], row[2]);
00452          ast_variable_append(cur_cat, new_v);
00453       }
00454    } else {
00455       ast_log(LOG_WARNING, "MySQL RealTime: Could not find config '%s' in database.\n", file);
00456    }
00457 
00458    mysql_free_result(result);
00459    ast_mutex_unlock(&mysql_lock);
00460 
00461    return cfg;
00462 }
00463 
00464 static struct ast_config_engine mysql_engine = {
00465    .name = "mysql",
00466    .load_func = config_mysql,
00467    .realtime_func = realtime_mysql,
00468    .realtime_multi_func = realtime_multi_mysql,
00469    .update_func = update_mysql
00470 };
00471 
00472 static int load_module(void)
00473 {
00474    parse_config();
00475 
00476    ast_mutex_lock(&mysql_lock);
00477 
00478    if(!mysql_reconnect(NULL)) {
00479       ast_log(LOG_WARNING, "MySQL RealTime: Couldn't establish connection. Check debug.\n");
00480       ast_log(LOG_DEBUG, "MySQL RealTime: Cannot Connect: %s\n", mysql_error(&mysql));
00481    }
00482 
00483    ast_config_engine_register(&mysql_engine);
00484    if(option_verbose) {
00485       ast_verbose("MySQL RealTime driver loaded.\n");
00486    }
00487    ast_cli_register(&cli_realtime_mysql_status);
00488 
00489    ast_mutex_unlock(&mysql_lock);
00490 
00491    return 0;
00492 }
00493 
00494 static int unload_module(void)
00495 {
00496    /* Aquire control before doing anything to the module itself. */
00497    ast_mutex_lock(&mysql_lock);
00498 
00499    mysql_close(&mysql);
00500    ast_cli_unregister(&cli_realtime_mysql_status);
00501    ast_config_engine_deregister(&mysql_engine);
00502    if(option_verbose) {
00503       ast_verbose("MySQL RealTime unloaded.\n");
00504    }
00505 
00506    ast_module_user_hangup_all();
00507 
00508    /* Unlock so something else can destroy the lock. */
00509    ast_mutex_unlock(&mysql_lock);
00510 
00511    return 0;
00512 }
00513 
00514 static int reload(void)
00515 {
00516    /* Aquire control before doing anything to the module itself. */
00517    ast_mutex_lock(&mysql_lock);
00518 
00519    mysql_close(&mysql);
00520    connected = 0;
00521    parse_config();
00522 
00523    if(!mysql_reconnect(NULL)) {
00524       ast_log(LOG_WARNING, "MySQL RealTime: Couldn't establish connection. Check debug.\n");
00525       ast_log(LOG_DEBUG, "MySQL RealTime: Cannot Connect: %s\n", mysql_error(&mysql));
00526    }
00527 
00528    ast_verbose(VERBOSE_PREFIX_2 "MySQL RealTime reloaded.\n");
00529 
00530    /* Done reloading. Release lock so others can now use driver. */
00531    ast_mutex_unlock(&mysql_lock);
00532 
00533    return 0;
00534 }
00535 
00536 static int parse_config (void)
00537 {
00538    struct ast_config *config;
00539    const char *s;
00540 
00541    config = ast_config_load(RES_CONFIG_MYSQL_CONF);
00542 
00543    if(config) {
00544       if(!(s=ast_variable_retrieve(config, "general", "dbuser"))) {
00545          ast_log(LOG_WARNING, "MySQL RealTime: No database user found, using 'asterisk' as default.\n");
00546          strncpy(dbuser, "asterisk", sizeof(dbuser) - 1);
00547       } else {
00548          strncpy(dbuser, s, sizeof(dbuser) - 1);
00549       }
00550 
00551       if(!(s=ast_variable_retrieve(config, "general", "dbpass"))) {
00552                         ast_log(LOG_WARNING, "MySQL RealTime: No database password found, using 'asterisk' as default.\n");
00553                         strncpy(dbpass, "asterisk", sizeof(dbpass) - 1);
00554                 } else {
00555                         strncpy(dbpass, s, sizeof(dbpass) - 1);
00556                 }
00557 
00558       if(!(s=ast_variable_retrieve(config, "general", "dbhost"))) {
00559                         ast_log(LOG_WARNING, "MySQL RealTime: No database host found, using localhost via socket.\n");
00560          dbhost[0] = '\0';
00561                 } else {
00562                         strncpy(dbhost, s, sizeof(dbhost) - 1);
00563                 }
00564 
00565       if(!(s=ast_variable_retrieve(config, "general", "dbname"))) {
00566                         ast_log(LOG_WARNING, "MySQL RealTime: No database name found, using 'asterisk' as default.\n");
00567          strncpy(dbname, "asterisk", sizeof(dbname) - 1);
00568                 } else {
00569                         strncpy(dbname, s, sizeof(dbname) - 1);
00570                 }
00571 
00572       if(!(s=ast_variable_retrieve(config, "general", "dbport"))) {
00573                         ast_log(LOG_WARNING, "MySQL RealTime: No database port found, using 3306 as default.\n");
00574          dbport = 3306;
00575                 } else {
00576          dbport = atoi(s);
00577                 }
00578 
00579       if(dbhost && !(s=ast_variable_retrieve(config, "general", "dbsock"))) {
00580                         ast_log(LOG_WARNING, "MySQL RealTime: No database socket found, using '/tmp/mysql.sock' as default.\n");
00581                         strncpy(dbsock, "/tmp/mysql.sock", sizeof(dbsock) - 1);
00582                 } else {
00583                         strncpy(dbsock, s, sizeof(dbsock) - 1);
00584                 }
00585    }
00586    ast_config_destroy(config);
00587 
00588    if(dbhost) {
00589       ast_log(LOG_DEBUG, "MySQL RealTime Host: %s\n", dbhost);
00590       ast_log(LOG_DEBUG, "MySQL RealTime Port: %i\n", dbport);
00591    } else {
00592       ast_log(LOG_DEBUG, "MySQL RealTime Socket: %s\n", dbsock);
00593    }
00594    ast_log(LOG_DEBUG, "MySQL RealTime User: %s\n", dbuser);
00595    ast_log(LOG_DEBUG, "MySQL RealTime Password: %s\n", dbpass);
00596 
00597    return 1;
00598 }
00599 
00600 static int mysql_reconnect(const char *database)
00601 {
00602    char my_database[50];
00603 #ifdef MYSQL_OPT_RECONNECT
00604    my_bool trueval = 1;
00605 #endif
00606 
00607    if(!database || ast_strlen_zero(database))
00608       ast_copy_string(my_database, dbname, sizeof(my_database));
00609    else
00610       ast_copy_string(my_database, database, sizeof(my_database));
00611 
00612    /* mutex lock should have been locked before calling this function. */
00613 
00614 reconnect_tryagain:
00615    if((!connected) && (dbhost || dbsock) && dbuser && dbpass && my_database) {
00616       if(!mysql_init(&mysql)) {
00617          ast_log(LOG_WARNING, "MySQL RealTime: Insufficient memory to allocate MySQL resource.\n");
00618          connected = 0;
00619          return 0;
00620       }
00621       if(mysql_real_connect(&mysql, dbhost, dbuser, dbpass, my_database, dbport, dbsock, 0)) {
00622 #ifdef MYSQL_OPT_RECONNECT
00623          /* The default is no longer to automatically reconnect on failure,
00624           * (as of 5.0.3) so we have to set that option here. */
00625          mysql_options(&mysql, MYSQL_OPT_RECONNECT, &trueval);
00626 #endif
00627          ast_log(LOG_DEBUG, "MySQL RealTime: Successfully connected to database.\n");
00628          connected = 1;
00629          connect_time = time(NULL);
00630          return 1;
00631       } else {
00632          ast_log(LOG_ERROR, "MySQL RealTime: Failed to connect database server %s on %s (err %d). Check debug for more info.\n", dbname, dbhost, mysql_errno(&mysql));
00633          ast_log(LOG_DEBUG, "MySQL RealTime: Cannot Connect (%d): %s\n", mysql_errno(&mysql), mysql_error(&mysql));
00634          connected = 0;
00635          return 0;
00636       }
00637    } else {
00638       /* MySQL likes to return an error, even if it reconnects successfully.
00639        * So the postman pings twice. */
00640       if (mysql_ping(&mysql) != 0 && mysql_ping(&mysql) != 0) {
00641          connected = 0;
00642          ast_log(LOG_ERROR, "MySQL RealTime: Ping failed (%d).  Trying an explicit reconnect.\n", mysql_errno(&mysql));
00643          ast_log(LOG_DEBUG, "MySQL RealTime: Server Error (%d): %s\n", mysql_errno(&mysql), mysql_error(&mysql));
00644          goto reconnect_tryagain;
00645       }
00646 
00647       connected = 1;
00648       connect_time = time(NULL);
00649 
00650       if(mysql_select_db(&mysql, my_database) != 0) {
00651          ast_log(LOG_WARNING, "MySQL RealTime: Unable to select database: %s. Still Connected (%u).\n", my_database, mysql_errno(&mysql));
00652          ast_log(LOG_DEBUG, "MySQL RealTime: Database Select Failed (%u): %s\n", mysql_errno(&mysql), mysql_error(&mysql));
00653          return 0;
00654       }
00655 
00656       ast_log(LOG_DEBUG, "MySQL RealTime: Everything is fine.\n");
00657       return 1;
00658    }
00659 }
00660 
00661 static int realtime_mysql_status(int fd, int argc, char **argv)
00662 {
00663    char status[256], status2[100] = "";
00664    int ctime = time(NULL) - connect_time;
00665 
00666    if(mysql_reconnect(NULL)) {
00667       if(dbhost) {
00668          snprintf(status, 255, "Connected to %s@%s, port %d", dbname, dbhost, dbport);
00669       } else if(dbsock) {
00670          snprintf(status, 255, "Connected to %s on socket file %s", dbname, dbsock);
00671       } else {
00672          snprintf(status, 255, "Connected to %s@%s", dbname, dbhost);
00673       }
00674 
00675       if(dbuser && *dbuser) {
00676          snprintf(status2, 99, " with username %s", dbuser);
00677       }
00678 
00679       if (ctime > 31536000) {
00680          ast_cli(fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 31536000, (ctime % 31536000) / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
00681       } else if (ctime > 86400) {
00682          ast_cli(fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 86400, (ctime % 86400) / 3600, (ctime % 3600) / 60, ctime % 60);
00683       } else if (ctime > 3600) {
00684          ast_cli(fd, "%s%s for %d hours, %d minutes, %d seconds.\n", status, status2, ctime / 3600, (ctime % 3600) / 60, ctime % 60);
00685       } else if (ctime > 60) {
00686          ast_cli(fd, "%s%s for %d minutes, %d seconds.\n", status, status2, ctime / 60, ctime % 60);
00687       } else {
00688          ast_cli(fd, "%s%s for %d seconds.\n", status, status2, ctime);
00689       }
00690 
00691       return RESULT_SUCCESS;
00692    } else {
00693       return RESULT_FAILURE;
00694    }
00695 }
00696 
00697 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "MySQL RealTime Configuration Driver");

Generated on Fri Jul 3 20:35:39 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9