Files
TCPlayerbotCore/src/server/database/Database/DatabaseWorkerPool.h
T

553 lines
21 KiB
C++
Raw Normal View History

2010-10-07 15:54:07 +02:00
/*
2016-01-01 00:34:25 +01:00
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
2010-10-07 15:54:07 +02:00
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
2010-08-18 02:25:52 +02:00
*/
#ifndef _DATABASEWORKERPOOL_H
#define _DATABASEWORKERPOOL_H
2010-09-03 00:04:14 +02:00
#include "Common.h"
2010-08-18 19:48:51 +02:00
#include "Callback.h"
2010-08-18 02:25:52 +02:00
#include "MySQLConnection.h"
2010-09-03 00:04:14 +02:00
#include "Transaction.h"
2010-09-02 17:47:50 +02:00
#include "DatabaseWorker.h"
2010-09-03 00:08:20 +02:00
#include "PreparedStatement.h"
#include "Log.h"
2010-09-11 21:10:54 +02:00
#include "QueryResult.h"
#include "QueryHolder.h"
#include "AdhocStatement.h"
#include "StringFormat.h"
2010-08-18 02:25:52 +02:00
2015-02-04 19:44:34 +00:00
#include <mysqld_error.h>
#include <memory>
#include <array>
2015-02-04 19:44:34 +00:00
#define MIN_MYSQL_SERVER_VERSION 50100u
#define MIN_MYSQL_CLIENT_VERSION 50100u
2010-09-25 01:05:24 +02:00
class PingOperation : public SQLOperation
{
//! Operation for idle delaythreads
2014-08-09 20:17:40 +01:00
bool Execute() override
2010-09-25 01:05:24 +02:00
{
m_conn->Ping();
return true;
2010-09-25 01:05:24 +02:00
}
};
2010-09-02 17:47:50 +02:00
template <class T>
2010-08-18 02:25:52 +02:00
class DatabaseWorkerPool
{
private:
enum InternalIndex
{
IDX_ASYNC,
IDX_SYNCH,
IDX_SIZE
};
2010-08-18 02:25:52 +02:00
public:
/* Activity state */
2015-03-21 21:07:20 +01:00
DatabaseWorkerPool() : _queue(new ProducerConsumerQueue<SQLOperation*>()),
_async_threads(0), _synch_threads(0)
2010-09-02 17:47:50 +02:00
{
WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe.");
WPFatal(mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION, "TrinityCore does not support MySQL versions below 5.1");
WPFatal(mysql_get_client_version() == MYSQL_VERSION_ID, "Used MySQL library version (%s) does not match the version used to compile TrinityCore (%s).",
mysql_get_client_info(), MYSQL_SERVER_VERSION);
2010-09-02 17:47:50 +02:00
}
~DatabaseWorkerPool()
{
_queue->Cancel();
}
void SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads)
{
_connectionInfo = Trinity::make_unique<MySQLConnectionInfo>(infoString);
_async_threads = asyncThreads;
_synch_threads = synchThreads;
2010-09-02 17:47:50 +02:00
}
uint32 Open()
2010-09-02 17:47:50 +02:00
{
WPFatal(_connectionInfo.get(), "Connection info was not set!");
TC_LOG_INFO("sql.driver", "Opening DatabasePool '%s'. Asynchronous connections: %u, synchronous connections: %u.",
GetDatabaseName(), _async_threads, _synch_threads);
2010-09-03 10:52:32 +02:00
uint32 error = OpenConnections(IDX_ASYNC, _async_threads);
2010-09-02 17:47:50 +02:00
if (error)
return error;
error = OpenConnections(IDX_SYNCH, _synch_threads);
2010-12-04 21:50:36 +01:00
if (!error)
{
TC_LOG_INFO("sql.driver", "DatabasePool '%s' opened successfully. %u total connections running.",
GetDatabaseName(), (_connections[IDX_SYNCH].size() + _connections[IDX_ASYNC].size()));
}
return error;
2010-09-02 17:47:50 +02:00
}
void Close()
{
TC_LOG_INFO("sql.driver", "Closing down DatabasePool '%s'.", GetDatabaseName());
2010-09-02 17:47:50 +02:00
//! Closes the actualy MySQL connection.
_connections[IDX_ASYNC].clear();
2010-09-02 17:47:50 +02:00
TC_LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '%s' terminated. Proceeding with synchronous connections.",
GetDatabaseName());
2010-09-02 17:47:50 +02:00
//! Shut down the synchronous connections
//! There's no need for locking the connection, because DatabaseWorkerPool<>::Close
//! should only be called after any other thread tasks in the core have exited,
//! meaning there can be no concurrent access at this point.
_connections[IDX_SYNCH].clear();
TC_LOG_INFO("sql.driver", "All connections on DatabasePool '%s' closed.", GetDatabaseName());
2010-09-02 17:47:50 +02:00
}
//! Prepares all prepared statements
bool PrepareStatements()
{
for (auto& connections : _connections)
for (auto& connection : connections)
{
connection->LockIfReady();
if (!connection->PrepareStatements())
{
connection->Unlock();
Close();
return false;
}
else
connection->Unlock();
}
return true;
}
inline MySQLConnectionInfo const* GetConnectionInfo() const
{
return _connectionInfo.get();
}
/**
Delayed one-way statement methods.
*/
//! Enqueues a one-way SQL operation in string format that will be executed asynchronously.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
2010-09-02 17:47:50 +02:00
void Execute(const char* sql)
{
if (Trinity::IsFormatEmptyOrNull(sql))
2010-09-02 17:47:50 +02:00
return;
BasicStatementTask* task = new BasicStatementTask(sql);
Enqueue(task);
}
//! Enqueues a one-way SQL operation in string format -with variable args- that will be executed asynchronously.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
template<typename Format, typename... Args>
void PExecute(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
if (Trinity::IsFormatEmptyOrNull(sql))
2010-09-02 17:47:50 +02:00
return;
Execute(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02:00
}
//! Enqueues a one-way SQL operation in prepared statement format that will be executed asynchronously.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with CONNECTION_ASYNC flag.
void Execute(PreparedStatement* stmt)
{
PreparedStatementTask* task = new PreparedStatementTask(stmt);
Enqueue(task);
}
/**
2012-03-19 18:08:32 +01:00
Direct synchronous one-way statement methods.
*/
//! Directly executes a one-way SQL operation in string format, that will block the calling thread until finished.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
2010-09-02 17:47:50 +02:00
void DirectExecute(const char* sql)
{
2010-09-27 00:20:56 +02:00
if (!sql)
return;
T* connection = GetFreeConnection();
connection->Execute(sql);
connection->Unlock();
2010-09-02 17:47:50 +02:00
}
//! Directly executes a one-way SQL operation in string format -with variable args-, that will block the calling thread until finished.
2012-03-19 18:08:32 +01:00
//! This method should only be used for queries that are only executed once, e.g during startup.
template<typename Format, typename... Args>
void DirectPExecute(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
if (Trinity::IsFormatEmptyOrNull(sql))
2010-09-02 17:47:50 +02:00
return;
DirectExecute(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02:00
}
//! Directly executes a one-way SQL operation in prepared statement format, that will block the calling thread until finished.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with the CONNECTION_SYNCH flag.
void DirectExecute(PreparedStatement* stmt)
{
T* connection = GetFreeConnection();
connection->Execute(stmt);
connection->Unlock();
//! Delete proxy-class. Not needed anymore
delete stmt;
}
/**
2011-12-19 11:11:25 +01:00
Synchronous query (with resultset) methods.
*/
//! Directly executes an SQL query in string format that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
QueryResult Query(const char* sql, T* connection = nullptr)
2010-09-02 17:47:50 +02:00
{
if (!connection)
connection = GetFreeConnection();
2010-09-27 00:20:56 +02:00
ResultSet* result = connection->Query(sql);
connection->Unlock();
2014-03-22 14:54:32 +01:00
if (!result || !result->GetRowCount() || !result->NextRow())
{
delete result;
2010-09-19 12:16:29 +02:00
return QueryResult(NULL);
}
2010-09-19 12:16:29 +02:00
return QueryResult(result);
2010-09-02 17:47:50 +02:00
}
//! Directly executes an SQL query in string format -with variable args- that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
template<typename Format, typename... Args>
QueryResult PQuery(Format&& sql, T* conn, Args&&... args)
2010-09-27 00:20:56 +02:00
{
if (Trinity::IsFormatEmptyOrNull(sql))
return QueryResult(nullptr);
2010-09-27 00:20:56 +02:00
return Query(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str(), conn);
2010-09-27 00:20:56 +02:00
}
//! Directly executes an SQL query in string format -with variable args- that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
template<typename Format, typename... Args>
QueryResult PQuery(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
if (!sql)
return QueryResult(nullptr);
2010-09-02 17:47:50 +02:00
return Query(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02:00
}
//! Directly executes an SQL query in prepared format that will block the calling thread until finished.
//! Returns reference counted auto pointer, no need for manual memory management in upper level code.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with CONNECTION_SYNCH flag.
PreparedQueryResult Query(PreparedStatement* stmt)
{
auto connection = GetFreeConnection();
PreparedResultSet* ret = connection->Query(stmt);
connection->Unlock();
//! Delete proxy-class. Not needed anymore
delete stmt;
if (!ret || !ret->GetRowCount())
{
delete ret;
return PreparedQueryResult(NULL);
}
return PreparedQueryResult(ret);
}
/**
Asynchronous query (with resultset) methods.
*/
//! Enqueues a query in string format that will set the value of the QueryResultFuture return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
QueryResultFuture AsyncQuery(const char* sql)
2010-09-02 17:47:50 +02:00
{
2014-07-02 21:56:40 -05:00
BasicStatementTask* task = new BasicStatementTask(sql, true);
// Store future result before enqueueing - task might get already processed and deleted before returning from this method
QueryResultFuture result = task->GetFuture();
2010-09-02 17:47:50 +02:00
Enqueue(task);
return result;
2010-09-02 17:47:50 +02:00
}
//! Enqueues a query in string format -with variable args- that will set the value of the QueryResultFuture return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
template<typename Format, typename... Args>
QueryResultFuture AsyncPQuery(Format&& sql, Args&&... args)
2010-09-02 17:47:50 +02:00
{
return AsyncQuery(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str());
2010-09-02 17:47:50 +02:00
}
//! Enqueues a query in prepared format that will set the value of the PreparedQueryResultFuture return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
2011-12-19 11:11:25 +01:00
//! Statement must be prepared with CONNECTION_ASYNC flag.
PreparedQueryResultFuture AsyncQuery(PreparedStatement* stmt)
{
2014-07-02 21:56:40 -05:00
PreparedStatementTask* task = new PreparedStatementTask(stmt, true);
// Store future result before enqueueing - task might get already processed and deleted before returning from this method
PreparedQueryResultFuture result = task->GetFuture();
Enqueue(task);
return result;
}
//! Enqueues a vector of SQL operations (can be both adhoc and prepared) that will set the value of the QueryResultHolderFuture
//! return object as soon as the query is executed.
//! The return value is then processed in ProcessQueryCallback methods.
2011-12-19 11:11:25 +01:00
//! Any prepared statements added to this holder need to be prepared with the CONNECTION_ASYNC flag.
2010-09-02 17:47:50 +02:00
QueryResultHolderFuture DelayQueryHolder(SQLQueryHolder* holder)
{
2014-07-02 21:56:40 -05:00
SQLQueryHolderTask* task = new SQLQueryHolderTask(holder);
// Store future result before enqueueing - task might get already processed and deleted before returning from this method
QueryResultHolderFuture result = task->GetFuture();
2010-09-02 17:47:50 +02:00
Enqueue(task);
return result;
2010-09-02 17:47:50 +02:00
}
2010-09-12 01:40:27 +02:00
/**
Transaction context methods.
*/
//! Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0)
2010-09-02 17:47:50 +02:00
SQLTransaction BeginTransaction()
{
return SQLTransaction(new Transaction);
}
//! Enqueues a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations
//! were appended to the transaction will be respected during execution.
2010-09-02 17:47:50 +02:00
void CommitTransaction(SQLTransaction transaction)
{
#ifdef TRINITY_DEBUG
//! Only analyze transaction weaknesses in Debug mode.
//! Ideally we catch the faults in Debug mode and then correct them,
//! so there's no need to waste these CPU cycles in Release mode.
switch (transaction->GetSize())
2010-09-02 17:47:50 +02:00
{
case 0:
TC_LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing.");
return;
case 1:
TC_LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code.");
break;
default:
break;
2010-09-02 17:47:50 +02:00
}
#endif // TRINITY_DEBUG
2010-09-02 17:47:50 +02:00
Enqueue(new TransactionTask(transaction));
}
2010-08-18 02:25:52 +02:00
2011-01-13 20:07:09 +01:00
//! Directly executes a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations
//! were appended to the transaction will be respected during execution.
void DirectCommitTransaction(SQLTransaction& transaction)
{
T* connection = GetFreeConnection();
int errorCode = connection->ExecuteTransaction(transaction);
if (!errorCode)
2011-01-13 20:07:09 +01:00
{
connection->Unlock(); // OK, operation succesful
2011-01-13 20:07:09 +01:00
return;
}
//! Handle MySQL Errno 1213 without extending deadlock to the core itself
/// @todo More elegant way
if (errorCode == ER_LOCK_DEADLOCK)
2011-01-13 20:07:09 +01:00
{
uint8 loopBreaker = 5;
2011-01-13 20:07:09 +01:00
for (uint8 i = 0; i < loopBreaker; ++i)
{
if (!connection->ExecuteTransaction(transaction))
2011-01-13 20:07:09 +01:00
break;
}
}
//! Clean up now.
transaction->Cleanup();
connection->Unlock();
2011-01-13 20:07:09 +01:00
}
//! Method used to execute prepared statements in a diverse context.
//! Will be wrapped in a transaction if valid object is present, otherwise executed standalone.
void ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt)
{
2014-07-01 00:54:09 +02:00
if (!trans)
Execute(stmt);
else
trans->Append(stmt);
}
//! Method used to execute ad-hoc statements in a diverse context.
//! Will be wrapped in a transaction if valid object is present, otherwise executed standalone.
void ExecuteOrAppend(SQLTransaction& trans, const char* sql)
{
2014-07-01 00:54:09 +02:00
if (!trans)
2010-12-13 17:05:01 +01:00
Execute(sql);
else
trans->Append(sql);
}
/**
Other
*/
typedef typename T::Statements PreparedStatementIndex;
//! Automanaged (internally) pointer to a prepared statement object for usage in upper level code.
//! Pointer is deleted in this->DirectExecute(PreparedStatement*), this->Query(PreparedStatement*) or PreparedStatementTask::~PreparedStatementTask.
//! This object is not tied to the prepared statement on the MySQL context yet until execution.
PreparedStatement* GetPreparedStatement(PreparedStatementIndex index)
2010-09-02 20:54:43 +02:00
{
return new PreparedStatement(index);
}
//! Apply escape string'ing for current collation. (utf8)
void EscapeString(std::string& str)
2010-08-18 02:25:52 +02:00
{
if (str.empty())
return;
char* buf = new char[str.size() * 2 + 1];
EscapeString(buf, str.c_str(), uint32(str.length()));
2010-08-18 02:25:52 +02:00
str = buf;
delete[] buf;
}
//! Keeps all our MySQL connections alive, prevent the server from disconnecting us.
2010-09-25 01:05:24 +02:00
void KeepAlive()
{
//! Ping synchronous connections
for (auto& connection : _connections[IDX_SYNCH])
2010-10-31 10:55:29 +01:00
{
if (connection->LockIfReady())
2010-10-31 10:55:29 +01:00
{
connection->Ping();
connection->Unlock();
2010-10-31 10:55:29 +01:00
}
}
//! Assuming all worker threads are free, every worker thread will receive 1 ping operation request
//! If one or more worker threads are busy, the ping operations will not be split evenly, but this doesn't matter
//! as the sole purpose is to prevent connections from idling.
for (auto& connection : _connections[IDX_ASYNC])
2010-12-13 09:18:49 +01:00
Enqueue(new PingOperation);
}
2010-09-25 01:05:24 +02:00
2010-09-03 10:52:32 +02:00
private:
uint32 OpenConnections(InternalIndex type, uint8 numConnections)
{
for (uint8 i = 0; i < numConnections; ++i)
{
// Create the connection
auto connection = [&] {
switch (type)
{
case IDX_ASYNC:
return Trinity::make_unique<T>(_queue.get(), *_connectionInfo);
case IDX_SYNCH:
return Trinity::make_unique<T>(*_connectionInfo);
default:
ABORT();
}
}();
if (uint32 error = connection->Open())
{
// Failed to open a connection or invalid version, abort and cleanup
_connections[type].clear();
return error;
}
else if (mysql_get_server_version(connection->GetHandle()) < MIN_MYSQL_SERVER_VERSION)
{
TC_LOG_ERROR("sql.driver", "TrinityCore does not support MySQL versions below 5.1");
return 1;
}
else
{
_connections[type].push_back(std::move(connection));
}
}
// Everything is fine
return 0;
}
unsigned long EscapeString(char *to, const char *from, unsigned long length)
2010-08-18 02:25:52 +02:00
{
if (!to || !from || !length)
return 0;
return mysql_real_escape_string(
_connections[IDX_SYNCH].front()->GetHandle(), to, from, length);
2010-08-18 02:25:52 +02:00
}
2010-09-12 01:40:27 +02:00
2010-08-18 02:25:52 +02:00
void Enqueue(SQLOperation* op)
{
_queue->Push(op);
2010-08-18 02:25:52 +02:00
}
//! Gets a free connection in the synchronous connection pool.
//! Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks.
2010-12-13 09:18:49 +01:00
T* GetFreeConnection()
{
uint8 i = 0;
auto const num_cons = _connections[IDX_SYNCH].size();
T* connection = nullptr;
//! Block forever until a connection is free
for (;;)
2010-12-13 09:18:49 +01:00
{
connection = _connections[IDX_SYNCH][++i % num_cons].get();
//! Must be matched with t->Unlock() or you will get deadlocks
if (connection->LockIfReady())
break;
2010-12-13 09:18:49 +01:00
}
2010-12-04 21:50:36 +01:00
return connection;
2010-12-13 09:18:49 +01:00
}
char const* GetDatabaseName() const
{
2014-04-20 16:48:35 +02:00
return _connectionInfo->database.c_str();
}
//! Queue shared by async worker threads.
std::unique_ptr<ProducerConsumerQueue<SQLOperation*>> _queue;
std::array<std::vector<std::unique_ptr<T>>, IDX_SIZE> _connections;
std::unique_ptr<MySQLConnectionInfo> _connectionInfo;
uint8 _async_threads, _synch_threads;
2010-08-18 02:25:52 +02:00
};
#endif