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"
37 #include "TextParsers.h"
39 #include "ExtensionSys.h"
41 #include "ThreadSupport.h"
43 #define DBPARSE_LEVEL_NONE 0
44 #define DBPARSE_LEVEL_MAIN 1
45 #define DBPARSE_LEVEL_DATABASE 2
48 static bool s_OneTimeThreaderErrorMsg = false;
50 DBManager::DBManager()
51 : m_StrTab(512), m_ParseLevel(0), m_ParseState(0), m_pDefault(NULL)
55 void DBManager::OnSourceModAllInitialized()
59 g_HandleSys.InitAccessDefaults(NULL, &sec);
60 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
61 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
63 m_DriverType = g_HandleSys.CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
64 m_DatabaseType = g_HandleSys.CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
66 g_ShareSys.AddInterface(NULL, this);
68 g_SourceMod.BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
70 m_pConfigLock = g_pThreader->MakeMutex();
71 m_pThinkLock = g_pThreader->MakeMutex();
72 m_pQueueLock = g_pThreader->MakeMutex();
74 g_PluginSys.AddPluginsListener(this);
77 void DBManager::OnSourceModLevelChange(const char *mapName)
80 unsigned int line = 0;
82 /* We lock and don't give up the lock until we're done.
83 * This way the thread's search won't be searching through a
84 * potentially empty/corrupt list, which would be very bad.
86 m_pConfigLock->Lock();
87 if ((err = g_TextParser.ParseFile_SMC(m_Filename, this, &line, NULL)) != SMCParse_Okay)
89 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
90 if (err != SMCParse_Custom)
92 const char *txt = g_TextParser.GetSMCErrorString(err);
93 g_Logger.LogError("[SM] Line %d: %s", line, txt);
96 m_pConfigLock->Unlock();
99 void DBManager::OnSourceModShutdown()
102 g_PluginSys.RemovePluginsListener(this);
103 m_pConfigLock->DestroyThis();
104 m_pThinkLock->DestroyThis();
105 m_pQueueLock->DestroyThis();
106 g_HandleSys.RemoveType(m_DatabaseType, g_pCoreIdent);
107 g_HandleSys.RemoveType(m_DriverType, g_pCoreIdent);
110 unsigned int DBManager::GetInterfaceVersion()
112 return SMINTERFACE_DBI_VERSION;
115 const char *DBManager::GetInterfaceName()
117 return SMINTERFACE_DBI_NAME;
120 void DBManager::OnHandleDestroy(HandleType_t type, void *object)
122 if (type == m_DriverType)
128 if (g_HandleSys.TypeCheck(type, m_DatabaseType))
130 IDatabase *pdb = (IDatabase *)object;
135 void DBManager::ReadSMC_ParseStart()
139 m_ParseState = DBPARSE_LEVEL_NONE;
144 ConfDbInfo s_CurInfo;
145 SMCParseResult DBManager::ReadSMC_NewSection(const char *name, bool opt_quotes)
150 return SMCParse_Continue;
153 if (m_ParseState == DBPARSE_LEVEL_NONE)
155 if (strcmp(name, "Databases") == 0)
157 m_ParseState = DBPARSE_LEVEL_MAIN;
161 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
162 s_CurInfo = ConfDbInfo();
163 s_CurInfo.name = m_StrTab.AddString(name);
164 m_ParseState = DBPARSE_LEVEL_DATABASE;
165 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
169 return SMCParse_Continue;
172 SMCParseResult DBManager::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
176 return SMCParse_Continue;
179 if (m_ParseState == DBPARSE_LEVEL_MAIN)
181 if (strcmp(key, "driver_default") == 0)
183 m_DefDriver.assign(value);
185 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
186 if (strcmp(key, "driver") == 0)
188 if (strcmp(value, "default") != 0)
190 s_CurInfo.driver = m_StrTab.AddString(value);
192 } else if (strcmp(key, "database") == 0) {
193 s_CurInfo.database = m_StrTab.AddString(value);
194 } else if (strcmp(key, "host") == 0) {
195 s_CurInfo.host = m_StrTab.AddString(value);
196 } else if (strcmp(key, "user") == 0) {
197 s_CurInfo.user = m_StrTab.AddString(value);
198 } else if (strcmp(key, "pass") == 0) {
199 s_CurInfo.pass = m_StrTab.AddString(value);
200 } else if (strcmp(key, "timeout") == 0) {
201 s_CurInfo.info.maxTimeout = atoi(value);
202 } else if (strcmp(key, "port") == 0) {
203 s_CurInfo.info.port = atoi(value);
207 return SMCParse_Continue;
210 #define ASSIGN_VAR(var) \
211 if (s_CurInfo.var == -1) { \
212 s_CurInfo.info.var = ""; \
214 s_CurInfo.info.var = m_StrTab.GetString(s_CurInfo.var); \
217 SMCParseResult DBManager::ReadSMC_LeavingSection()
222 return SMCParse_Continue;
225 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
227 /* Set all of the info members to either a blank string
228 * or the string pointer from the string table.
231 ASSIGN_VAR(database);
237 m_confs.push_back(s_CurInfo);
239 /* Go up one level */
240 m_ParseState = DBPARSE_LEVEL_MAIN;
241 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
242 m_ParseState = DBPARSE_LEVEL_NONE;
243 return SMCParse_Halt;
246 return SMCParse_Continue;
250 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
254 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
256 ConfDbInfo *pInfo = GetDatabaseConf(name);
265 UTIL_Format(error, maxlength, "Configuration \"%s\" not found", name);
269 const char *dname = pInfo->info.driver;
270 if (!pInfo->realDriver)
272 /* Try to assign a real driver pointer */
273 if (pInfo->info.driver[0] == '\0')
275 if (!m_pDefault && m_DefDriver.size() > 0)
277 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
279 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
280 pInfo->realDriver = m_pDefault;
282 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
286 if (pInfo->realDriver)
290 *pdr = pInfo->realDriver;
292 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
293 return (*pdb != NULL);
302 UTIL_Format(error, maxlength, "Driver \"%s\" not found", dname);
307 void DBManager::AddDriver(IDBDriver *pDriver)
309 /* Let's kill the worker. Join the thread and let the queries flush.
310 * This is kind of stupid but we just want to unload safely.
311 * Rather than recreate the worker, we'll wait until someone throws
312 * another query through.
316 m_drivers.push_back(pDriver);
319 void DBManager::RemoveDriver(IDBDriver *pDriver)
321 /* Again, we're forced to kill the worker. How rude!
322 * Doing this flushes the queue, and thus we don't need to
323 * clean anything else.
327 for (size_t i=0; i<m_drivers.size(); i++)
329 if (m_drivers[i] == pDriver)
331 m_drivers.erase(m_drivers.iterAt(i));
336 /* Make sure NOTHING references this! */
337 List<ConfDbInfo>::iterator iter;
338 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
340 ConfDbInfo &db = (*iter);
341 if (db.realDriver == pDriver)
343 db.realDriver = NULL;
347 /* Now that the driver is gone, we have to test the think queue.
348 * Whatever happens therein is up to the db op!
350 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
351 Queue<IDBThreadOperation *> templist;
352 while (qiter != m_ThinkQueue.end())
354 IDBThreadOperation *op = (*qiter);
355 if (op->GetDriver() == pDriver)
358 qiter = m_ThinkQueue.erase(qiter);
364 for (qiter = templist.begin();
365 qiter != templist.end();
368 IDBThreadOperation *op = (*qiter);
369 op->CancelThinkPart();
374 IDBDriver *DBManager::GetDefaultDriver()
376 if (!m_pDefault && m_DefDriver.size() > 0)
378 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
384 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
386 HandleType_t type = 0;
388 if (dtype == DBHandle_Driver)
391 } else if (dtype == DBHandle_Database) {
392 type = m_DatabaseType;
397 return g_HandleSys.CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
400 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
402 HandleType_t type = 0;
404 if (dtype == DBHandle_Driver)
407 } else if (dtype == DBHandle_Database) {
408 type = m_DatabaseType;
410 return HandleError_Type;
413 HandleSecurity sec(NULL, g_pCoreIdent);
415 return g_HandleSys.ReadHandle(hndl, type, &sec, ptr);
418 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
420 HandleSecurity sec(token, g_pCoreIdent);
421 return g_HandleSys.FreeHandle(hndl, &sec);
424 unsigned int DBManager::GetDriverCount()
426 return (unsigned int)m_drivers.size();
429 IDBDriver *DBManager::GetDriver(unsigned int index)
431 if (index >= m_drivers.size())
436 return m_drivers[index];
439 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
441 ConfDbInfo *info = GetDatabaseConf(name);
450 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
452 List<ConfDbInfo>::iterator iter;
454 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
456 ConfDbInfo &conf = (*iter);
457 if (strcmp(m_StrTab.GetString(conf.name), name) == 0)
466 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
468 size_t last_size = m_drivers.size();
469 for (size_t i=0; i<last_size; i++)
471 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
477 char filename[PLATFORM_MAX_PATH];
478 UTIL_Format(filename, sizeof(filename), "dbi.%s.ext", name);
480 IExtension *pExt = g_Extensions.LoadAutoExtension(filename);
481 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
486 /* last_size is now gauranteed to be a valid index.
487 * The identifier must match the name.
489 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
491 return m_drivers[last_size];
497 void DBManager::KillWorkerThread()
501 m_pWorker->Stop(false);
502 g_pThreader->DestroyWorker(m_pWorker);
504 s_OneTimeThreaderErrorMsg = false;
508 static IdentityToken_t *s_pAddBlock = NULL;
510 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
512 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
519 m_pWorker = g_pThreader->MakeWorker(this, true);
522 if (!s_OneTimeThreaderErrorMsg)
524 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
525 s_OneTimeThreaderErrorMsg = true;
529 if (!m_pWorker->Start())
531 if (!s_OneTimeThreaderErrorMsg)
533 g_Logger.LogError("[SM] Unable to start db threader (error unknown)");
534 s_OneTimeThreaderErrorMsg = true;
536 g_pThreader->DestroyWorker(m_pWorker);
542 /* Add to the queue */
544 m_pQueueLock->Lock();
545 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
547 m_pQueueLock->Unlock();
550 /* Make the thread */
551 m_pWorker->MakeThread(this);
556 void DBManager::OnWorkerStart(IThreadWorker *pWorker)
559 for (size_t i=0; i<m_drivers.size(); i++)
561 if (m_drivers[i]->IsThreadSafe())
563 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
565 m_drSafety.push_back(false);
570 void DBManager::OnWorkerStop(IThreadWorker *pWorker)
572 for (size_t i=0; i<m_drivers.size(); i++)
576 m_drivers[i]->ShutdownThreadSafety();
582 void DBManager::RunThread(IThreadHandle *pThread)
584 IDBThreadOperation *op = NULL;
586 /* Get something from the queue */
588 m_pQueueLock->Lock();
589 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
595 m_pQueueLock->Unlock();
598 /* whoa. hi. did we get something? we should have. */
607 m_pThinkLock->Lock();
608 m_ThinkQueue.push(op);
609 m_pThinkLock->Unlock();
612 void DBManager::RunFrame()
614 /* Don't bother if we're empty */
615 if (!m_ThinkQueue.size())
620 /* Dump one thing per-frame so the server stays sane. */
621 m_pThinkLock->Lock();
622 IDBThreadOperation *op = m_ThinkQueue.first();
624 m_pThinkLock->Unlock();
629 void DBManager::OnTerminate(IThreadHandle *pThread, bool cancel)
634 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
636 s_pAddBlock = pToken;
638 /* Kill the thread so we can flush everything into the think queue... */
641 /* Run all of the think operations.
642 * Unlike the driver unloading example, we'll let these calls go through,
643 * since a plugin unloading is far more normal.
645 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
646 Queue<IDBThreadOperation *> templist;
647 while (iter != m_ThinkQueue.end())
649 IDBThreadOperation *op = (*iter);
650 if (op->GetOwner() == pToken)
653 iter = m_ThinkQueue.erase(iter);
659 for (iter = templist.begin();
660 iter != templist.end();
663 IDBThreadOperation *op = (*iter);
671 void DBManager::OnPluginUnloaded(IPlugin *plugin)
673 /* Kill the thread so we can flush everything into the think queue... */
676 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
677 plugin->SetProperty("DisallowDBThreads", NULL);
679 /* Run all of the think operations.
680 * Unlike the driver unloading example, we'll let these calls go through,
681 * since a plugin unloading is far more normal.
683 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
684 Queue<IDBThreadOperation *> templist;
685 while (iter != m_ThinkQueue.end())
687 IDBThreadOperation *op = (*iter);
688 if (op->GetOwner() == plugin->GetIdentity())
691 iter = m_ThinkQueue.erase(iter);
697 for (iter = templist.begin();
698 iter != templist.end();
701 IDBThreadOperation *op = (*iter);
707 void DBManager::LockConfig()
709 m_pConfigLock->Lock();
712 void DBManager::UnlockConfig()
714 m_pConfigLock->Unlock();
717 const char *DBManager::GetDefaultDriverName()
719 return m_DefDriver.c_str();