From b3a4885d6459bb7aee1d51b6ab30566308a9135c Mon Sep 17 00:00:00 2001 From: Lucien Sadi Date: Sun, 28 May 2017 21:24:41 -0700 Subject: [PATCH] Added MySQL DB cleanup on shutdown. Also added a potential error-recovery handler for error 2006 (DB has gone away). --- src/comm.cpp | 3 +++ src/db.cpp | 6 ++++++ src/newdb.cpp | 30 +++++++++++++++++++++++++++--- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/comm.cpp b/src/comm.cpp index 2283510dc..5a49f7eee 100644 --- a/src/comm.cpp +++ b/src/comm.cpp @@ -123,6 +123,7 @@ char *colorize(struct descriptor_data *d, char *str); /* extern fcnts */ extern void DBInit(); +extern void DBFinalize(); void boot_world(void); void zone_update(void); void spec_update(void); @@ -359,6 +360,8 @@ void init_game(int port) close(mother_desc); + DBFinalize(); + if (circle_reboot) { log("Rebooting."); exit(52); /* what's so great about HHGTTG, anyhow? */ diff --git a/src/db.cpp b/src/db.cpp index db81c1c3a..b1c28f77c 100644 --- a/src/db.cpp +++ b/src/db.cpp @@ -384,6 +384,12 @@ void DBInit() log("Boot db -- DONE."); } +/* A simple method to clean up after our DB. */ +void DBFinalize() { + if (mysql) + mysql_close(mysql); +} + /* reset the time in the game from file weekday is lost on reboot.... implement something different if this is mission diff --git a/src/newdb.cpp b/src/newdb.cpp index 677488066..61e8c52ff 100644 --- a/src/newdb.cpp +++ b/src/newdb.cpp @@ -55,11 +55,35 @@ int mysql_wrapper(MYSQL *mysql, char *query) #endif int result = mysql_query(mysql, query); - - if (mysql_errno(mysql)) { + int errnum = mysql_errno(mysql); + + if (errnum) { sprintf(buf, "MYSQLERROR: %s", mysql_error(mysql)); log(buf); - // log(query); + sprintf(buf, "Offending query: %s", query); + log(buf); + + // Recovery procedures for certain errors. + switch (errnum) { + case 2006: + // 'MySQL server has gone away.' + log("The MySQL server connection appears to have dropped. Attempting to establish a new one."); + mysql_close(mysql); + mysql = mysql_init(NULL); + if (!mysql_real_connect(mysql, mysql_host, mysql_user, mysql_password, mysql_db, 0, NULL, 0)) { + sprintf(buf, "FATAL ERROR: %s\r\n", mysql_error(mysql)); + log(buf); + log("Suggestion: Make sure your DB is running and that you've specified your connection info in src/mysql_config.cpp.\r\n"); + + // High chance this won't succeed-- the calling function will likely attempt to read + // the results of the query, but the query had no results and will refuse a read. + // This is crash-inducing behavior 99% of the time. + shutdown(); + } + break; + default: + break; + } } return result; }