Discard threaded query results on plugin unload (fixes #1647)

This commit is contained in:
Nicholas Hastings
2026-08-02 12:14:04 -04:00
parent 84c633c4da
commit bf0f9986f4
5 changed files with 249 additions and 78 deletions
+10
View File
@@ -117,6 +117,16 @@
*/
"BlockBadPlugins" "yes"
/**
* Controls how plugin unloads handle outstanding threaded database operations.
*
* "discard" - Immediately discard the plugin's outstanding database operations.
* This is the default and keeps the server responsive.
* "wait" - Wait for outstanding operations and run their callbacks before unload.
* Warning: This can stall the server.
*/
"DatabasePluginUnload" "discard"
/**
* If a plugin takes too long to execute, hanging or freezing the game server in the process,
* SourceMod will attempt to terminate that plugin after the specified timeout length has
+151 -41
View File
@@ -51,6 +51,7 @@ DBManager g_DBMan;
DBManager::DBManager()
: m_Terminate(false),
m_ActiveOperation(NULL),
m_pDefault(NULL)
{
}
@@ -243,11 +244,7 @@ void DBManager::RemoveDriver(IDBDriver *pDriver)
for (qiter = templist.begin();
qiter != templist.end();
qiter++)
{
IDBThreadOperation *op = (*qiter);
op->CancelThinkPart();
op->Destroy();
}
FinalizeOperation(*qiter, true);
}
IDBDriver *DBManager::GetDefaultDriver()
@@ -386,11 +383,108 @@ void DBManager::KillWorkerThread()
}
}
void DBManager::FinalizeOperation(IDBThreadOperation *op, bool driver_unloading)
{
bool cancelled = false;
{
std::lock_guard<std::mutex> lock(m_Lock);
m_OperationOwners.erase(op);
auto iter = m_CancelledOperations.find(op);
if (iter != m_CancelledOperations.end())
{
cancelled = true;
m_CancelledOperations.erase(iter);
}
}
if (cancelled)
{
op->Destroy();
}
else
{
if (driver_unloading)
op->CancelThinkPart();
else
op->RunThinkPart();
op->Destroy();
}
}
void DBManager::CancelPluginOperations(IdentityToken_t *identity)
{
Queue<IDBThreadOperation *> cancelled;
bool active_in_think_queue = false;
std::unique_lock<std::mutex> lock(m_Lock);
auto owns = [this, identity](IDBThreadOperation *op) {
auto iter = m_OperationOwners.find(op);
return iter != m_OperationOwners.end() && iter->second == identity;
};
for (PrioQueueLevel priority : {PrioQueue_High, PrioQueue_Normal, PrioQueue_Low})
{
Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(priority);
for (auto iter = queue.begin(); iter != queue.end();)
{
IDBThreadOperation *op = *iter;
if (owns(op))
{
cancelled.push(op);
m_OperationOwners.erase(op);
iter = queue.erase(iter);
}
else
{
iter++;
}
}
}
IDBThreadOperation *active = m_ActiveOperation;
bool cancelling_active = active && owns(active);
{
std::lock_guard<std::mutex> think_lock(m_ThinkLock);
for (auto iter = m_ThinkQueue.begin(); iter != m_ThinkQueue.end();)
{
IDBThreadOperation *op = *iter;
if (owns(op))
{
if (op == active)
active_in_think_queue = true;
cancelled.push(op);
m_OperationOwners.erase(op);
iter = m_ThinkQueue.erase(iter);
}
else
{
iter++;
}
}
}
if (cancelling_active)
{
if (active_in_think_queue)
m_ActiveOperation = nullptr;
else
m_CancelledOperations.insert(active);
}
lock.unlock();
while (!cancelled.empty())
{
IDBThreadOperation *op = cancelled.first();
cancelled.pop();
op->Destroy();
}
}
static IdentityToken_t *s_pAddBlock = NULL;
bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
{
if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
IdentityToken_t *owner = op->GetOwner();
if (s_pAddBlock && owner == s_pAddBlock)
{
return false;
}
@@ -406,6 +500,7 @@ bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
{
std::lock_guard<std::mutex> lock(m_Lock);
Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
m_OperationOwners.emplace(op, owner);
queue.push(op);
m_QueueEvent.notify_one();
}
@@ -459,6 +554,7 @@ void DBManager::ThreadMain()
IDBThreadOperation *op = queue->first();
queue->pop();
m_ActiveOperation = op;
// Unlock the queue when we run the query, so the main thread can
// keep pumping events. We re-acquire the lock to check for more
@@ -476,6 +572,9 @@ void DBManager::ThreadMain()
std::lock_guard<std::mutex> think_lock(m_ThinkLock);
m_ThinkQueue.push(op);
}
lock.lock();
m_ActiveOperation = nullptr;
lock.unlock();
// Note that we add a 20ms delay after processing a query. This is
// questionable but the intent is to avoid starving the game thread.
@@ -488,21 +587,16 @@ void DBManager::ThreadMain()
void DBManager::RunFrame()
{
/* Don't bother if we're empty */
if (!m_ThinkQueue.size())
{
return;
}
/* Dump one thing per-frame so the server stays sane. */
IDBThreadOperation *op;
{
std::lock_guard<std::mutex> lock(m_ThinkLock);
if (m_ThinkQueue.empty())
return;
op = m_ThinkQueue.first();
m_ThinkQueue.pop();
}
op->RunThinkPart();
op->Destroy();
FinalizeOperation(op, false);
}
void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
@@ -521,7 +615,8 @@ void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
while (iter != m_ThinkQueue.end())
{
IDBThreadOperation *op = (*iter);
if (op->GetOwner() == pToken)
auto owner = m_OperationOwners.find(op);
if (owner != m_OperationOwners.end() && owner->second == pToken)
{
templist.push(op);
iter = m_ThinkQueue.erase(iter);
@@ -533,49 +628,64 @@ void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
for (iter = templist.begin();
iter != templist.end();
iter++)
{
IDBThreadOperation *op = (*iter);
op->RunThinkPart();
op->Destroy();
}
FinalizeOperation(*iter, false);
s_pAddBlock = NULL;
}
void DBManager::OnPluginWillUnload(IPlugin *plugin)
bool DBManager::ShouldDiscardPluginOperations()
{
/* Kill the thread so we can flush everything into the think queue... */
KillWorkerThread();
const char *behavior = g_pSM->GetCoreConfigValue("DatabasePluginUnload");
return !behavior || strcasecmp(behavior, "wait") != 0;
}
/* Mark the plugin as being unloaded so future database calls will ignore threading... */
void DBManager::WaitForPluginOperations(IPlugin *plugin)
{
KillWorkerThread();
plugin->SetProperty("DisallowDBThreads", NULL);
/* Run all of the think operations.
* Unlike the driver unloading example, we'll let these calls go through,
* since a plugin unloading is far more normal.
*/
Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
Queue<IDBThreadOperation *> templist;
while (iter != m_ThinkQueue.end())
Queue<IDBThreadOperation *> operations;
{
IDBThreadOperation *op = (*iter);
if (op->GetOwner() == plugin->GetIdentity())
std::lock_guard<std::mutex> lock(m_Lock);
std::lock_guard<std::mutex> think_lock(m_ThinkLock);
for (auto iter = m_ThinkQueue.begin(); iter != m_ThinkQueue.end();)
{
templist.push(op);
iter = m_ThinkQueue.erase(iter);
} else {
iter++;
IDBThreadOperation *op = *iter;
auto owner = m_OperationOwners.find(op);
if (owner != m_OperationOwners.end() && owner->second == plugin->GetIdentity())
{
operations.push(op);
iter = m_ThinkQueue.erase(iter);
}
else
{
iter++;
}
}
}
for (iter = templist.begin(); iter != templist.end(); iter++)
while (!operations.empty())
{
IDBThreadOperation *op = (*iter);
op->RunThinkPart();
op->Destroy();
IDBThreadOperation *op = operations.first();
operations.pop();
FinalizeOperation(op, false);
}
}
void DBManager::DiscardPluginOperations(IPlugin *plugin)
{
plugin->SetProperty("DisallowDBThreads", NULL);
CancelPluginOperations(plugin->GetIdentity());
}
void DBManager::OnPluginWillUnload(IPlugin *plugin)
{
if (ShouldDiscardPluginOperations())
DiscardPluginOperations(plugin);
else
WaitForPluginOperations(plugin);
}
std::string DBManager::GetDefaultDriverName()
{
ConfDbInfoList &list = m_Builder.GetConfigList();
+10
View File
@@ -42,6 +42,8 @@
#include <memory>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include "sm_simple_prioqueue.h"
#include <am-refcounting.h>
#include "DatabaseConfBuilder.h"
@@ -89,6 +91,8 @@ public:
IDBDriver *GetDefaultDriver();
std::string GetDefaultDriverName();
bool AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio);
bool ShouldDiscardPluginOperations();
void DiscardPluginOperations(IPlugin *plugin);
void RunFrame();
inline HandleType_t GetDatabaseType()
{
@@ -97,6 +101,9 @@ public:
private:
void ClearConfigs();
void KillWorkerThread();
void WaitForPluginOperations(IPlugin *plugin);
void CancelPluginOperations(IdentityToken_t *identity);
void FinalizeOperation(IDBThreadOperation *op, bool driver_unloading);
private:
CVector<IDBDriver *> m_drivers;
@@ -109,6 +116,9 @@ private:
std::mutex m_ThinkLock;
std::mutex m_Lock;
bool m_Terminate;
IDBThreadOperation *m_ActiveOperation;
std::unordered_map<IDBThreadOperation *, IdentityToken_t *> m_OperationOwners;
std::unordered_set<IDBThreadOperation *> m_CancelledOperations;
DatabaseConfBuilder m_Builder;
HandleType_t m_DriverType;
+72 -33
View File
@@ -190,7 +190,6 @@ class TQueryOp : public IDBThreadOperation
public:
TQueryOp(IDatabase *db, IPluginFunction *pf, const char *query, cell_t data) :
m_pDatabase(db), m_pFunction(pf), m_Query(query), m_Data(data),
me(scripts->FindPluginByContext(pf->GetParentContext())),
m_pQuery(NULL)
{
/* We always increase the reference count because this is potentially
@@ -198,9 +197,8 @@ public:
* we're still latched onto it.
*/
m_pDatabase->IncReferenceCount();
HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
m_MyHandle = CreateLocalHandle(g_DBMan.GetDatabaseType(), m_pDatabase, &sec);
IPlugin *plugin = scripts->FindPluginByContext(pf->GetParentContext());
m_Identity = plugin->GetIdentity();
}
~TQueryOp()
{
@@ -209,19 +207,11 @@ public:
m_pQuery->Destroy();
}
/* Close our Handle if it's valid. */
if (m_MyHandle != BAD_HANDLE)
{
HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
handlesys->FreeHandle(m_MyHandle, &sec);
} else {
/* Otherwise, there is an open ref to the db */
m_pDatabase->Close();
}
m_pDatabase->Close();
}
IdentityToken_t *GetOwner()
{
return me->GetIdentity();
return m_Identity;
}
IDBDriver *GetDriver()
{
@@ -250,8 +240,11 @@ public:
}
void RunThinkPart()
{
/* Create a Handle for our query */
HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
/* Create handles for the callback. */
HandleSecurity sec(m_Identity, g_pCoreIdent);
Handle_t dbh = CreateLocalHandle(g_DBMan.GetDatabaseType(), m_pDatabase, &sec);
if (dbh != BAD_HANDLE)
m_pDatabase->AddRef();
Handle_t qh = BAD_HANDLE;
@@ -271,7 +264,7 @@ public:
if (m_pFunction->IsRunnable())
{
m_pFunction->PushCell(m_MyHandle);
m_pFunction->PushCell(dbh);
m_pFunction->PushCell(qh);
m_pFunction->PushString(qh == BAD_HANDLE ? error : "");
m_pFunction->PushCell(m_Data);
@@ -282,6 +275,8 @@ public:
{
handlesys->FreeHandle(qh, &sec);
}
if (dbh != BAD_HANDLE)
handlesys->FreeHandle(dbh, &sec);
}
void Destroy()
{
@@ -292,10 +287,9 @@ private:
IPluginFunction *m_pFunction;
String m_Query;
cell_t m_Data;
IPlugin *me;
IdentityToken_t *m_Identity;
IQuery *m_pQuery;
char error[255];
Handle_t m_MyHandle;
};
enum AsyncCallbackMode {
@@ -315,7 +309,8 @@ public:
m_Data = data;
error[0] = '\0';
strncopy(dbname, _dbname, sizeof(dbname));
me = scripts->FindPluginByContext(m_pFunction->GetParentContext());
IPlugin *plugin = scripts->FindPluginByContext(m_pFunction->GetParentContext());
m_Identity = plugin->GetIdentity();
m_pInfo = g_DBMan.GetDatabaseConf(dbname);
if (!m_pInfo)
@@ -323,9 +318,14 @@ public:
g_pSM->Format(error, sizeof(error), "Could not find database config \"%s\"", dbname);
}
}
~TConnectOp()
{
if (m_pDatabase)
m_pDatabase->Close();
}
IdentityToken_t *GetOwner()
{
return me->GetIdentity();
return m_Identity;
}
IDBDriver *GetDriver()
{
@@ -341,7 +341,10 @@ public:
void CancelThinkPart()
{
if (m_pDatabase)
{
m_pDatabase->Close();
m_pDatabase = NULL;
}
if (!m_pFunction->IsRunnable())
return;
@@ -358,20 +361,19 @@ public:
Handle_t hndl = BAD_HANDLE;
if (!m_pFunction->IsRunnable())
{
if (m_pDatabase)
m_pDatabase->Close();
return;
}
if (m_pDatabase)
{
if ((hndl = g_DBMan.CreateHandle(DBHandle_Database, m_pDatabase, me->GetIdentity()))
if ((hndl = g_DBMan.CreateHandle(DBHandle_Database, m_pDatabase, m_Identity))
== BAD_HANDLE)
{
m_pDatabase->Close();
g_pSM->Format(error, sizeof(error), "Unable to allocate Handle");
}
else
{
m_pDatabase = NULL;
}
}
if (m_ACM == ACM_Old)
@@ -387,7 +389,7 @@ public:
}
private:
ke::RefPtr<ConfDbInfo> m_pInfo;
IPlugin *me;
IdentityToken_t *m_Identity;
IPluginFunction *m_pFunction;
IDBDriver *m_pDriver;
IDatabase *m_pDatabase;
@@ -489,8 +491,20 @@ static cell_t ConnectToDbAsync(IPluginContext *pContext, const cell_t *params, A
/* Finally, add to the thread if we can */
TConnectOp *op = new TConnectOp(pf, driver, conf, acm, params[3]);
IPlugin *pPlugin = scripts->FindPluginByContext(pContext);
if (pPlugin->GetProperty("DisallowDBThreads", NULL)
|| !g_DBMan.AddToThreadQueue(op, PrioQueue_High))
if (pPlugin->GetProperty("DisallowDBThreads", NULL))
{
if (g_DBMan.ShouldDiscardPluginOperations())
{
op->Destroy();
}
else
{
op->RunThreadPart();
op->RunThinkPart();
op->Destroy();
}
}
else if (!g_DBMan.AddToThreadQueue(op, PrioQueue_High))
{
/* Do everything right now */
op->RunThreadPart();
@@ -868,8 +882,20 @@ static cell_t SQL_TQuery(IPluginContext *pContext, const cell_t *params)
IPlugin *pPlugin = scripts->FindPluginByContext(pContext);
TQueryOp *op = new TQueryOp(db, pf, query, data);
if (pPlugin->GetProperty("DisallowDBThreads", NULL)
|| !g_DBMan.AddToThreadQueue(op, level))
if (pPlugin->GetProperty("DisallowDBThreads", NULL))
{
if (g_DBMan.ShouldDiscardPluginOperations())
{
op->Destroy();
}
else
{
op->RunThreadPart();
op->RunThinkPart();
op->Destroy();
}
}
else if (!g_DBMan.AddToThreadQueue(op, level))
{
/* Do everything right now */
op->RunThreadPart();
@@ -1809,7 +1835,20 @@ static cell_t SQL_ExecuteTransaction(IPluginContext *pContext, const cell_t *par
handlesys->FreeHandle(params[2], &sec);
IPlugin *pPlugin = scripts->FindPluginByContext(pContext);
if (pPlugin->GetProperty("DisallowDBThreads", NULL) || !g_DBMan.AddToThreadQueue(op, priority))
if (pPlugin->GetProperty("DisallowDBThreads", NULL))
{
if (g_DBMan.ShouldDiscardPluginOperations())
{
op->Destroy();
}
else
{
op->RunThreadPart();
op->RunThinkPart();
op->Destroy();
}
}
else if (!g_DBMan.AddToThreadQueue(op, priority))
{
// Do everything right now.
op->RunThreadPart();
+6 -4
View File
@@ -757,7 +757,8 @@ namespace SourceMod
/**
* @brief Called inside the thread; this is where any blocking
* or threaded operations must occur.
* or threaded operations must occur. This is not called if Core is
* configured to discard work when the operation's owner unloads.
*/
virtual void RunThreadPart() =0;
@@ -771,9 +772,10 @@ namespace SourceMod
/**
* @brief If RunThinkPart() is not called, this will be called
* instead. Note that RunThreadPart() is ALWAYS called regardless,
* and this is only called when Core requests that the operation
* be scrapped (for example, the database driver might be unloading).
* instead. This is only called when Core requests that a completed
* operation be scrapped (for example, when the database driver unloads).
* Core may also destroy an operation without a callback when configured
* to discard database work during owner unload.
*/
virtual void CancelThinkPart() =0;