3 * ================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * ================================================================
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License,
10 * version 3.0, as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to
21 * link the code of this program (as well as its derivative works) to
22 * "Half-Life 2," the "Source Engine," the "SourcePawn JIT," and any
23 * Game MODs that run on software by the Valve Corporation. You must
24 * obey the GNU General Public License in all respects for all other
25 * code used. Additionally, AlliedModders LLC grants this exception
26 * to all derivative works. AlliedModders LLC defines further
27 * exceptions, found in LICENSE.txt (as of this writing, version
28 * JULY-31-2007), or <http://www.sourcemod.net/license.php>.
34 #include "HandleSys.h"
36 #include "sourcemod.h"
37 #include "sm_stringutil.h"
38 #include "TextParsers.h"
40 #include "ExtensionSys.h"
42 #include "ThreadSupport.h"
44 #define DBPARSE_LEVEL_NONE 0
45 #define DBPARSE_LEVEL_MAIN 1
46 #define DBPARSE_LEVEL_DATABASE 2
49 static bool s_OneTimeThreaderErrorMsg = false;
51 DBManager::DBManager()
52 : m_StrTab(512), m_ParseLevel(0), m_ParseState(0), m_pDefault(NULL)
56 void DBManager::OnSourceModAllInitialized()
60 g_HandleSys.InitAccessDefaults(NULL, &sec);
61 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
62 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
64 m_DriverType = g_HandleSys.CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
65 m_DatabaseType = g_HandleSys.CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
67 g_ShareSys.AddInterface(NULL, this);
69 g_SourceMod.BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
71 m_pConfigLock = g_pThreader->MakeMutex();
72 m_pThinkLock = g_pThreader->MakeMutex();
73 m_pQueueLock = g_pThreader->MakeMutex();
75 g_PluginSys.AddPluginsListener(this);
78 void DBManager::OnSourceModLevelChange(const char *mapName)
81 unsigned int line = 0;
83 /* We lock and don't give up the lock until we're done.
84 * This way the thread's search won't be searching through a
85 * potentially empty/corrupt list, which would be very bad.
87 m_pConfigLock->Lock();
88 if ((err = g_TextParser.ParseFile_SMC(m_Filename, this, &line, NULL)) != SMCParse_Okay)
90 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
91 if (err != SMCParse_Custom)
93 const char *txt = g_TextParser.GetSMCErrorString(err);
94 g_Logger.LogError("[SM] Line %d: %s", line, txt);
97 m_pConfigLock->Unlock();
100 void DBManager::OnSourceModShutdown()
103 g_PluginSys.RemovePluginsListener(this);
104 m_pConfigLock->DestroyThis();
105 m_pThinkLock->DestroyThis();
106 m_pQueueLock->DestroyThis();
107 g_HandleSys.RemoveType(m_DatabaseType, g_pCoreIdent);
108 g_HandleSys.RemoveType(m_DriverType, g_pCoreIdent);
111 unsigned int DBManager::GetInterfaceVersion()
113 return SMINTERFACE_DBI_VERSION;
116 const char *DBManager::GetInterfaceName()
118 return SMINTERFACE_DBI_NAME;
121 void DBManager::OnHandleDestroy(HandleType_t type, void *object)
123 if (type == m_DriverType)
129 if (g_HandleSys.TypeCheck(type, m_DatabaseType))
131 IDatabase *pdb = (IDatabase *)object;
136 void DBManager::ReadSMC_ParseStart()
140 m_ParseState = DBPARSE_LEVEL_NONE;
145 ConfDbInfo s_CurInfo;
146 SMCParseResult DBManager::ReadSMC_NewSection(const char *name, bool opt_quotes)
151 return SMCParse_Continue;
154 if (m_ParseState == DBPARSE_LEVEL_NONE)
156 if (strcmp(name, "Databases") == 0)
158 m_ParseState = DBPARSE_LEVEL_MAIN;
162 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
163 s_CurInfo = ConfDbInfo();
164 s_CurInfo.name = m_StrTab.AddString(name);
165 m_ParseState = DBPARSE_LEVEL_DATABASE;
166 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
170 return SMCParse_Continue;
173 SMCParseResult DBManager::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
177 return SMCParse_Continue;
180 if (m_ParseState == DBPARSE_LEVEL_MAIN)
182 if (strcmp(key, "driver_default") == 0)
184 m_DefDriver.assign(value);
186 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
187 if (strcmp(key, "driver") == 0)
189 if (strcmp(value, "default") != 0)
191 s_CurInfo.driver = m_StrTab.AddString(value);
193 } else if (strcmp(key, "database") == 0) {
194 s_CurInfo.database = m_StrTab.AddString(value);
195 } else if (strcmp(key, "host") == 0) {
196 s_CurInfo.host = m_StrTab.AddString(value);
197 } else if (strcmp(key, "user") == 0) {
198 s_CurInfo.user = m_StrTab.AddString(value);
199 } else if (strcmp(key, "pass") == 0) {
200 s_CurInfo.pass = m_StrTab.AddString(value);
201 } else if (strcmp(key, "timeout") == 0) {
202 s_CurInfo.info.maxTimeout = atoi(value);
203 } else if (strcmp(key, "port") == 0) {
204 s_CurInfo.info.port = atoi(value);
208 return SMCParse_Continue;
211 #define ASSIGN_VAR(var) \
212 if (s_CurInfo.var == -1) { \
213 s_CurInfo.info.var = ""; \
215 s_CurInfo.info.var = m_StrTab.GetString(s_CurInfo.var); \
218 SMCParseResult DBManager::ReadSMC_LeavingSection()
223 return SMCParse_Continue;
226 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
228 /* Set all of the info members to either a blank string
229 * or the string pointer from the string table.
232 ASSIGN_VAR(database);
238 m_confs.push_back(s_CurInfo);
240 /* Go up one level */
241 m_ParseState = DBPARSE_LEVEL_MAIN;
242 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
243 m_ParseState = DBPARSE_LEVEL_NONE;
244 return SMCParse_Halt;
247 return SMCParse_Continue;
251 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
255 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
257 ConfDbInfo *pInfo = GetDatabaseConf(name);
266 UTIL_Format(error, maxlength, "Configuration \"%s\" not found", name);
270 const char *dname = pInfo->info.driver;
271 if (!pInfo->realDriver)
273 /* Try to assign a real driver pointer */
274 if (pInfo->info.driver[0] == '\0')
276 if (!m_pDefault && m_DefDriver.size() > 0)
278 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
280 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
281 pInfo->realDriver = m_pDefault;
283 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
287 if (pInfo->realDriver)
291 *pdr = pInfo->realDriver;
293 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
294 return (*pdb != NULL);
303 UTIL_Format(error, maxlength, "Driver \"%s\" not found", dname);
308 void DBManager::AddDriver(IDBDriver *pDriver)
310 /* Let's kill the worker. Join the thread and let the queries flush.
311 * This is kind of stupid but we just want to unload safely.
312 * Rather than recreate the worker, we'll wait until someone throws
313 * another query through.
317 m_drivers.push_back(pDriver);
320 void DBManager::RemoveDriver(IDBDriver *pDriver)
322 /* Again, we're forced to kill the worker. How rude!
323 * Doing this flushes the queue, and thus we don't need to
324 * clean anything else.
328 for (size_t i=0; i<m_drivers.size(); i++)
330 if (m_drivers[i] == pDriver)
332 m_drivers.erase(m_drivers.iterAt(i));
337 /* Make sure NOTHING references this! */
338 List<ConfDbInfo>::iterator iter;
339 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
341 ConfDbInfo &db = (*iter);
342 if (db.realDriver == pDriver)
344 db.realDriver = NULL;
348 /* Now that the driver is gone, we have to test the think queue.
349 * Whatever happens therein is up to the db op!
351 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
352 Queue<IDBThreadOperation *> templist;
353 while (qiter != m_ThinkQueue.end())
355 IDBThreadOperation *op = (*qiter);
356 if (op->GetDriver() == pDriver)
359 qiter = m_ThinkQueue.erase(qiter);
365 for (qiter = templist.begin();
366 qiter != templist.end();
369 IDBThreadOperation *op = (*qiter);
370 op->CancelThinkPart();
375 IDBDriver *DBManager::GetDefaultDriver()
377 if (!m_pDefault && m_DefDriver.size() > 0)
379 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
385 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
387 HandleType_t type = 0;
389 if (dtype == DBHandle_Driver)
392 } else if (dtype == DBHandle_Database) {
393 type = m_DatabaseType;
398 return g_HandleSys.CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
401 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
403 HandleType_t type = 0;
405 if (dtype == DBHandle_Driver)
408 } else if (dtype == DBHandle_Database) {
409 type = m_DatabaseType;
411 return HandleError_Type;
414 HandleSecurity sec(NULL, g_pCoreIdent);
416 return g_HandleSys.ReadHandle(hndl, type, &sec, ptr);
419 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
421 HandleSecurity sec(token, g_pCoreIdent);
422 return g_HandleSys.FreeHandle(hndl, &sec);
425 unsigned int DBManager::GetDriverCount()
427 return (unsigned int)m_drivers.size();
430 IDBDriver *DBManager::GetDriver(unsigned int index)
432 if (index >= m_drivers.size())
437 return m_drivers[index];
440 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
442 ConfDbInfo *info = GetDatabaseConf(name);
451 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
453 List<ConfDbInfo>::iterator iter;
455 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
457 ConfDbInfo &conf = (*iter);
458 if (strcmp(m_StrTab.GetString(conf.name), name) == 0)
467 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
469 size_t last_size = m_drivers.size();
470 for (size_t i=0; i<last_size; i++)
472 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
478 char filename[PLATFORM_MAX_PATH];
479 UTIL_Format(filename, sizeof(filename), "dbi.%s.ext", name);
481 IExtension *pExt = g_Extensions.LoadAutoExtension(filename);
482 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
487 /* last_size is now gauranteed to be a valid index.
488 * The identifier must match the name.
490 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
492 return m_drivers[last_size];
498 void DBManager::KillWorkerThread()
502 m_pWorker->Stop(false);
503 g_pThreader->DestroyWorker(m_pWorker);
505 s_OneTimeThreaderErrorMsg = false;
509 static IdentityToken_t *s_pAddBlock = NULL;
511 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
513 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
520 m_pWorker = g_pThreader->MakeWorker(this, true);
523 if (!s_OneTimeThreaderErrorMsg)
525 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
526 s_OneTimeThreaderErrorMsg = true;
530 if (!m_pWorker->Start())
532 if (!s_OneTimeThreaderErrorMsg)
534 g_Logger.LogError("[SM] Unable to start db threader (error unknown)");
535 s_OneTimeThreaderErrorMsg = true;
537 g_pThreader->DestroyWorker(m_pWorker);
543 /* Add to the queue */
545 m_pQueueLock->Lock();
546 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
548 m_pQueueLock->Unlock();
551 /* Make the thread */
552 m_pWorker->MakeThread(this);
557 void DBManager::OnWorkerStart(IThreadWorker *pWorker)
560 for (size_t i=0; i<m_drivers.size(); i++)
562 if (m_drivers[i]->IsThreadSafe())
564 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
566 m_drSafety.push_back(false);
571 void DBManager::OnWorkerStop(IThreadWorker *pWorker)
573 for (size_t i=0; i<m_drivers.size(); i++)
577 m_drivers[i]->ShutdownThreadSafety();
583 void DBManager::RunThread(IThreadHandle *pThread)
585 IDBThreadOperation *op = NULL;
587 /* Get something from the queue */
589 m_pQueueLock->Lock();
590 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
596 m_pQueueLock->Unlock();
599 /* whoa. hi. did we get something? we should have. */
608 m_pThinkLock->Lock();
609 m_ThinkQueue.push(op);
610 m_pThinkLock->Unlock();
613 void DBManager::RunFrame()
615 /* Don't bother if we're empty */
616 if (!m_ThinkQueue.size())
621 /* Dump one thing per-frame so the server stays sane. */
622 m_pThinkLock->Lock();
623 IDBThreadOperation *op = m_ThinkQueue.first();
625 m_pThinkLock->Unlock();
630 void DBManager::OnTerminate(IThreadHandle *pThread, bool cancel)
635 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
637 s_pAddBlock = pToken;
639 /* Kill the thread so we can flush everything into the think queue... */
642 /* Run all of the think operations.
643 * Unlike the driver unloading example, we'll let these calls go through,
644 * since a plugin unloading is far more normal.
646 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
647 Queue<IDBThreadOperation *> templist;
648 while (iter != m_ThinkQueue.end())
650 IDBThreadOperation *op = (*iter);
651 if (op->GetOwner() == pToken)
654 iter = m_ThinkQueue.erase(iter);
660 for (iter = templist.begin();
661 iter != templist.end();
664 IDBThreadOperation *op = (*iter);
672 void DBManager::OnPluginUnloaded(IPlugin *plugin)
674 /* Kill the thread so we can flush everything into the think queue... */
677 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
678 plugin->SetProperty("DisallowDBThreads", NULL);
680 /* Run all of the think operations.
681 * Unlike the driver unloading example, we'll let these calls go through,
682 * since a plugin unloading is far more normal.
684 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
685 Queue<IDBThreadOperation *> templist;
686 while (iter != m_ThinkQueue.end())
688 IDBThreadOperation *op = (*iter);
689 if (op->GetOwner() == plugin->GetIdentity())
692 iter = m_ThinkQueue.erase(iter);
698 for (iter = templist.begin();
699 iter != templist.end();
702 IDBThreadOperation *op = (*iter);
708 void DBManager::LockConfig()
710 m_pConfigLock->Lock();
713 void DBManager::UnlockConfig()
715 m_pConfigLock->Unlock();
718 const char *DBManager::GetDefaultDriverName()
720 return m_DefDriver.c_str();