Index: res_config_mysql.c =================================================================== --- res_config_mysql.c (revision 220) +++ res_config_mysql.c (working copy) @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -592,6 +593,9 @@ static int mysql_reconnect(const char *database) { char my_database[50]; +#ifdef MYSQL_OPT_RECONNECT + my_bool trueval = 1; +#endif if(!database || ast_strlen_zero(database)) ast_copy_string(my_database, dbname, sizeof(my_database)); @@ -600,6 +604,7 @@ /* mutex lock should have been locked before calling this function. */ +reconnect_tryagain: if((!connected) && (dbhost || dbsock) && dbuser && dbpass && my_database) { if(!mysql_init(&mysql)) { ast_log(LOG_WARNING, "MySQL RealTime: Insufficient memory to allocate MySQL resource.\n"); @@ -607,29 +612,36 @@ return 0; } if(mysql_real_connect(&mysql, dbhost, dbuser, dbpass, my_database, dbport, dbsock, 0)) { +#ifdef MYSQL_OPT_RECONNECT + /* The default is no longer to automatically reconnect on failure, + * (as of 5.0.3) so we have to set that option here. */ + mysql_options(&mysql, MYSQL_OPT_RECONNECT, &trueval); +#endif ast_log(LOG_DEBUG, "MySQL RealTime: Successfully connected to database.\n"); connected = 1; connect_time = time(NULL); return 1; } else { - ast_log(LOG_ERROR, "MySQL RealTime: Failed to connect database server %s on %s. Check debug for more info.\n", dbname, dbhost); - ast_log(LOG_DEBUG, "MySQL RealTime: Cannot Connect: %s\n", mysql_error(&mysql)); + 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)); + ast_log(LOG_DEBUG, "MySQL RealTime: Cannot Connect (%d): %s\n", mysql_errno(&mysql), mysql_error(&mysql)); connected = 0; return 0; } } else { - if(mysql_ping(&mysql) != 0) { + /* MySQL likes to return an error, even if it reconnects successfully. + * So the postman pings twice. */ + if (mysql_ping(&mysql) != 0 && mysql_ping(&mysql) != 0) { connected = 0; - ast_log(LOG_ERROR, "MySQL RealTime: Failed to reconnect. Check debug for more info.\n"); - ast_log(LOG_DEBUG, "MySQL RealTime: Server Error: %s\n", mysql_error(&mysql)); - return 0; + ast_log(LOG_ERROR, "MySQL RealTime: Ping failed (%d). Trying an explicit reconnect.\n", mysql_errno(&mysql)); + ast_log(LOG_DEBUG, "MySQL RealTime: Server Error (%d): %s\n", mysql_errno(&mysql), mysql_error(&mysql)); + goto reconnect_tryagain; } connected = 1; if(mysql_select_db(&mysql, my_database) != 0) { - ast_log(LOG_WARNING, "MySQL RealTime: Unable to select database: %s. Still Connected.\n", my_database); - ast_log(LOG_DEBUG, "MySQL RealTime: Database Select Failed: %s\n", mysql_error(&mysql)); + ast_log(LOG_WARNING, "MySQL RealTime: Unable to select database: %s. Still Connected (%d).\n", my_database, mysql_errno(&mysql)); + ast_log(LOG_DEBUG, "MySQL RealTime: Database Select Failed (%d): %s\n", mysql_error(&mysql), mysql_errno(&mysql)); return 0; }