3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "HandleSys.h"
35 #include "sourcemod.h"
36 #include "sm_stringutil.h"
38 #include "ExtensionSys.h"
40 #include "ThreadSupport.h"
42 #define DBPARSE_LEVEL_NONE 0
43 #define DBPARSE_LEVEL_MAIN 1
44 #define DBPARSE_LEVEL_DATABASE 2
47 static bool s_OneTimeThreaderErrorMsg = false;
49 DBManager::DBManager()
50 : m_StrTab(512), m_ParseLevel(0), m_ParseState(0), m_pDefault(NULL)
54 void DBManager::OnSourceModAllInitialized()
58 g_HandleSys.InitAccessDefaults(NULL, &sec);
59 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
60 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
62 m_DriverType = g_HandleSys.CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
63 m_DatabaseType = g_HandleSys.CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
65 g_ShareSys.AddInterface(NULL, this);
67 g_SourceMod.BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
69 m_pConfigLock = g_pThreader->MakeMutex();
70 m_pThinkLock = g_pThreader->MakeMutex();
71 m_pQueueLock = g_pThreader->MakeMutex();
73 g_PluginSys.AddPluginsListener(this);
76 void DBManager::OnSourceModLevelChange(const char *mapName)
79 unsigned int line = 0;
81 /* We lock and don't give up the lock until we're done.
82 * This way the thread's search won't be searching through a
83 * potentially empty/corrupt list, which would be very bad.
85 m_pConfigLock->Lock();
86 if ((err = textparsers->ParseFile_SMC(m_Filename, this, &line, NULL)) != SMCParse_Okay)
88 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
89 if (err != SMCParse_Custom)
91 const char *txt = textparsers->GetSMCErrorString(err);
92 g_Logger.LogError("[SM] Line %d: %s", line, txt);
95 m_pConfigLock->Unlock();
98 void DBManager::OnSourceModShutdown()
101 g_PluginSys.RemovePluginsListener(this);
102 m_pConfigLock->DestroyThis();
103 m_pThinkLock->DestroyThis();
104 m_pQueueLock->DestroyThis();
105 g_HandleSys.RemoveType(m_DatabaseType, g_pCoreIdent);
106 g_HandleSys.RemoveType(m_DriverType, g_pCoreIdent);
109 unsigned int DBManager::GetInterfaceVersion()
111 return SMINTERFACE_DBI_VERSION;
114 const char *DBManager::GetInterfaceName()
116 return SMINTERFACE_DBI_NAME;
119 void DBManager::OnHandleDestroy(HandleType_t type, void *object)
121 if (type == m_DriverType)
127 if (g_HandleSys.TypeCheck(type, m_DatabaseType))
129 IDatabase *pdb = (IDatabase *)object;
134 void DBManager::ReadSMC_ParseStart()
138 m_ParseState = DBPARSE_LEVEL_NONE;
143 ConfDbInfo s_CurInfo;
144 SMCParseResult DBManager::ReadSMC_NewSection(const char *name, bool opt_quotes)
149 return SMCParse_Continue;
152 if (m_ParseState == DBPARSE_LEVEL_NONE)
154 if (strcmp(name, "Databases") == 0)
156 m_ParseState = DBPARSE_LEVEL_MAIN;
160 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
161 s_CurInfo = ConfDbInfo();
162 s_CurInfo.name = m_StrTab.AddString(name);
163 m_ParseState = DBPARSE_LEVEL_DATABASE;
164 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
168 return SMCParse_Continue;
171 SMCParseResult DBManager::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
175 return SMCParse_Continue;
178 if (m_ParseState == DBPARSE_LEVEL_MAIN)
180 if (strcmp(key, "driver_default") == 0)
182 m_DefDriver.assign(value);
184 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
185 if (strcmp(key, "driver") == 0)
187 if (strcmp(value, "default") != 0)
189 s_CurInfo.driver = m_StrTab.AddString(value);
191 } else if (strcmp(key, "database") == 0) {
192 s_CurInfo.database = m_StrTab.AddString(value);
193 } else if (strcmp(key, "host") == 0) {
194 s_CurInfo.host = m_StrTab.AddString(value);
195 } else if (strcmp(key, "user") == 0) {
196 s_CurInfo.user = m_StrTab.AddString(value);
197 } else if (strcmp(key, "pass") == 0) {
198 s_CurInfo.pass = m_StrTab.AddString(value);
199 } else if (strcmp(key, "timeout") == 0) {
200 s_CurInfo.info.maxTimeout = atoi(value);
201 } else if (strcmp(key, "port") == 0) {
202 s_CurInfo.info.port = atoi(value);
206 return SMCParse_Continue;
209 #define ASSIGN_VAR(var) \
210 if (s_CurInfo.var == -1) { \
211 s_CurInfo.info.var = ""; \
213 s_CurInfo.info.var = m_StrTab.GetString(s_CurInfo.var); \
216 SMCParseResult DBManager::ReadSMC_LeavingSection()
221 return SMCParse_Continue;
224 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
226 /* Set all of the info members to either a blank string
227 * or the string pointer from the string table.
230 ASSIGN_VAR(database);
236 m_confs.push_back(s_CurInfo);
238 /* Go up one level */
239 m_ParseState = DBPARSE_LEVEL_MAIN;
240 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
241 m_ParseState = DBPARSE_LEVEL_NONE;
242 return SMCParse_Halt;
245 return SMCParse_Continue;
249 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
253 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
255 ConfDbInfo *pInfo = GetDatabaseConf(name);
264 UTIL_Format(error, maxlength, "Configuration \"%s\" not found", name);
268 const char *dname = pInfo->info.driver;
269 if (!pInfo->realDriver)
271 /* Try to assign a real driver pointer */
272 if (pInfo->info.driver[0] == '\0')
274 if (!m_pDefault && m_DefDriver.size() > 0)
276 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
278 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
279 pInfo->realDriver = m_pDefault;
281 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
285 if (pInfo->realDriver)
289 *pdr = pInfo->realDriver;
291 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
292 return (*pdb != NULL);
301 UTIL_Format(error, maxlength, "Driver \"%s\" not found", dname);
306 void DBManager::AddDriver(IDBDriver *pDriver)
308 /* Let's kill the worker. Join the thread and let the queries flush.
309 * This is kind of stupid but we just want to unload safely.
310 * Rather than recreate the worker, we'll wait until someone throws
311 * another query through.
315 m_drivers.push_back(pDriver);
318 void DBManager::RemoveDriver(IDBDriver *pDriver)
320 /* Again, we're forced to kill the worker. How rude!
321 * Doing this flushes the queue, and thus we don't need to
322 * clean anything else.
326 for (size_t i=0; i<m_drivers.size(); i++)
328 if (m_drivers[i] == pDriver)
330 m_drivers.erase(m_drivers.iterAt(i));
335 /* Make sure NOTHING references this! */
336 List<ConfDbInfo>::iterator iter;
337 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
339 ConfDbInfo &db = (*iter);
340 if (db.realDriver == pDriver)
342 db.realDriver = NULL;
346 /* Now that the driver is gone, we have to test the think queue.
347 * Whatever happens therein is up to the db op!
349 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
350 Queue<IDBThreadOperation *> templist;
351 while (qiter != m_ThinkQueue.end())
353 IDBThreadOperation *op = (*qiter);
354 if (op->GetDriver() == pDriver)
357 qiter = m_ThinkQueue.erase(qiter);
363 for (qiter = templist.begin();
364 qiter != templist.end();
367 IDBThreadOperation *op = (*qiter);
368 op->CancelThinkPart();
373 IDBDriver *DBManager::GetDefaultDriver()
375 if (!m_pDefault && m_DefDriver.size() > 0)
377 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
383 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
385 HandleType_t type = 0;
387 if (dtype == DBHandle_Driver)
390 } else if (dtype == DBHandle_Database) {
391 type = m_DatabaseType;
396 return g_HandleSys.CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
399 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
401 HandleType_t type = 0;
403 if (dtype == DBHandle_Driver)
406 } else if (dtype == DBHandle_Database) {
407 type = m_DatabaseType;
409 return HandleError_Type;
412 HandleSecurity sec(NULL, g_pCoreIdent);
414 return g_HandleSys.ReadHandle(hndl, type, &sec, ptr);
417 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
419 HandleSecurity sec(token, g_pCoreIdent);
420 return g_HandleSys.FreeHandle(hndl, &sec);
423 unsigned int DBManager::GetDriverCount()
425 return (unsigned int)m_drivers.size();
428 IDBDriver *DBManager::GetDriver(unsigned int index)
430 if (index >= m_drivers.size())
435 return m_drivers[index];
438 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
440 ConfDbInfo *info = GetDatabaseConf(name);
449 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
451 List<ConfDbInfo>::iterator iter;
453 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
455 ConfDbInfo &conf = (*iter);
456 if (strcmp(m_StrTab.GetString(conf.name), name) == 0)
465 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
467 size_t last_size = m_drivers.size();
468 for (size_t i=0; i<last_size; i++)
470 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
476 char filename[PLATFORM_MAX_PATH];
477 UTIL_Format(filename, sizeof(filename), "dbi.%s.ext", name);
479 IExtension *pExt = g_Extensions.LoadAutoExtension(filename);
480 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
485 /* last_size is now gauranteed to be a valid index.
486 * The identifier must match the name.
488 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
490 return m_drivers[last_size];
496 void DBManager::KillWorkerThread()
500 m_pWorker->Stop(false);
501 g_pThreader->DestroyWorker(m_pWorker);
503 s_OneTimeThreaderErrorMsg = false;
507 static IdentityToken_t *s_pAddBlock = NULL;
509 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
511 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
518 m_pWorker = g_pThreader->MakeWorker(this, true);
521 if (!s_OneTimeThreaderErrorMsg)
523 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
524 s_OneTimeThreaderErrorMsg = true;
528 if (!m_pWorker->Start())
530 if (!s_OneTimeThreaderErrorMsg)
532 g_Logger.LogError("[SM] Unable to start db threader (error unknown)");
533 s_OneTimeThreaderErrorMsg = true;
535 g_pThreader->DestroyWorker(m_pWorker);
541 /* Add to the queue */
543 m_pQueueLock->Lock();
544 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
546 m_pQueueLock->Unlock();
549 /* Make the thread */
550 m_pWorker->MakeThread(this);
555 void DBManager::OnWorkerStart(IThreadWorker *pWorker)
558 for (size_t i=0; i<m_drivers.size(); i++)
560 if (m_drivers[i]->IsThreadSafe())
562 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
564 m_drSafety.push_back(false);
569 void DBManager::OnWorkerStop(IThreadWorker *pWorker)
571 for (size_t i=0; i<m_drivers.size(); i++)
575 m_drivers[i]->ShutdownThreadSafety();
581 void DBManager::RunThread(IThreadHandle *pThread)
583 IDBThreadOperation *op = NULL;
585 /* Get something from the queue */
587 m_pQueueLock->Lock();
588 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
594 m_pQueueLock->Unlock();
597 /* whoa. hi. did we get something? we should have. */
606 m_pThinkLock->Lock();
607 m_ThinkQueue.push(op);
608 m_pThinkLock->Unlock();
611 void DBManager::RunFrame()
613 /* Don't bother if we're empty */
614 if (!m_ThinkQueue.size())
619 /* Dump one thing per-frame so the server stays sane. */
620 m_pThinkLock->Lock();
621 IDBThreadOperation *op = m_ThinkQueue.first();
623 m_pThinkLock->Unlock();
628 void DBManager::OnTerminate(IThreadHandle *pThread, bool cancel)
633 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
635 s_pAddBlock = pToken;
637 /* Kill the thread so we can flush everything into the think queue... */
640 /* Run all of the think operations.
641 * Unlike the driver unloading example, we'll let these calls go through,
642 * since a plugin unloading is far more normal.
644 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
645 Queue<IDBThreadOperation *> templist;
646 while (iter != m_ThinkQueue.end())
648 IDBThreadOperation *op = (*iter);
649 if (op->GetOwner() == pToken)
652 iter = m_ThinkQueue.erase(iter);
658 for (iter = templist.begin();
659 iter != templist.end();
662 IDBThreadOperation *op = (*iter);
670 void DBManager::OnPluginUnloaded(IPlugin *plugin)
672 /* Kill the thread so we can flush everything into the think queue... */
675 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
676 plugin->SetProperty("DisallowDBThreads", NULL);
678 /* Run all of the think operations.
679 * Unlike the driver unloading example, we'll let these calls go through,
680 * since a plugin unloading is far more normal.
682 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
683 Queue<IDBThreadOperation *> templist;
684 while (iter != m_ThinkQueue.end())
686 IDBThreadOperation *op = (*iter);
687 if (op->GetOwner() == plugin->GetIdentity())
690 iter = m_ThinkQueue.erase(iter);
696 for (iter = templist.begin();
697 iter != templist.end();
700 IDBThreadOperation *op = (*iter);
706 void DBManager::LockConfig()
708 m_pConfigLock->Lock();
711 void DBManager::UnlockConfig()
713 m_pConfigLock->Unlock();
716 const char *DBManager::GetDefaultDriverName()
718 return m_DefDriver.c_str();