3 * =============================================================================
5 * Copyright (C) 2004-2008 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 <IThreader.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_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 SMCStates states = {0, 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, &states)) != SMCError_Okay)
88 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
89 if (err != SMCError_Custom)
91 const char *txt = textparsers->GetSMCErrorString(err);
92 g_Logger.LogError("[SM] Line %d: %s", states.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;
142 ConfDbInfo s_CurInfo;
143 SMCResult DBManager::ReadSMC_NewSection(const SMCStates *states, const char *name)
148 return SMCResult_Continue;
151 if (m_ParseState == DBPARSE_LEVEL_NONE)
153 if (strcmp(name, "Databases") == 0)
155 m_ParseState = DBPARSE_LEVEL_MAIN;
159 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
160 s_CurInfo = ConfDbInfo();
161 s_CurInfo.name = name;
162 m_ParseState = DBPARSE_LEVEL_DATABASE;
163 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
167 return SMCResult_Continue;
170 SMCResult DBManager::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
174 return SMCResult_Continue;
177 if (m_ParseState == DBPARSE_LEVEL_MAIN)
179 if (strcmp(key, "driver_default") == 0)
181 m_DefDriver.assign(value);
183 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
184 if (strcmp(key, "driver") == 0)
186 if (strcmp(value, "default") != 0)
188 s_CurInfo.driver = value;
190 } else if (strcmp(key, "database") == 0) {
191 s_CurInfo.database = value;
192 } else if (strcmp(key, "host") == 0) {
193 s_CurInfo.host = value;
194 } else if (strcmp(key, "user") == 0) {
195 s_CurInfo.user = value;
196 } else if (strcmp(key, "pass") == 0) {
197 s_CurInfo.pass = value;
198 } else if (strcmp(key, "timeout") == 0) {
199 s_CurInfo.info.maxTimeout = atoi(value);
200 } else if (strcmp(key, "port") == 0) {
201 s_CurInfo.info.port = atoi(value);
205 return SMCResult_Continue;
208 #define ASSIGN_VAR(var) \
209 if (s_CurInfo.var == "") { \
210 s_CurInfo.info.var = ""; \
212 s_CurInfo.info.var = s_CurInfo.var.c_str(); \
215 SMCResult DBManager::ReadSMC_LeavingSection(const SMCStates *states)
220 return SMCResult_Continue;
223 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
225 /* Set all of the info members to either a blank string
226 * or the string pointer from the string table.
229 ASSIGN_VAR(database);
235 m_confs.push_back(s_CurInfo);
237 /* Go up one level */
238 m_ParseState = DBPARSE_LEVEL_MAIN;
239 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
240 m_ParseState = DBPARSE_LEVEL_NONE;
241 return SMCResult_Halt;
244 return SMCResult_Continue;
248 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
252 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
254 ConfDbInfo *pInfo = GetDatabaseConf(name);
263 UTIL_Format(error, maxlength, "Configuration \"%s\" not found", name);
267 const char *dname = pInfo->info.driver;
268 if (!pInfo->realDriver)
270 /* Try to assign a real driver pointer */
271 if (pInfo->info.driver[0] == '\0')
273 if (!m_pDefault && m_DefDriver.size() > 0)
275 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
277 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
278 pInfo->realDriver = m_pDefault;
280 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
284 if (pInfo->realDriver)
288 *pdr = pInfo->realDriver;
290 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
291 return (*pdb != NULL);
300 UTIL_Format(error, maxlength, "Driver \"%s\" not found", dname);
305 void DBManager::AddDriver(IDBDriver *pDriver)
307 /* Let's kill the worker. Join the thread and let the queries flush.
308 * This is kind of stupid but we just want to unload safely.
309 * Rather than recreate the worker, we'll wait until someone throws
310 * another query through.
314 m_drivers.push_back(pDriver);
317 void DBManager::RemoveDriver(IDBDriver *pDriver)
319 /* Again, we're forced to kill the worker. How rude!
320 * Doing this flushes the queue, and thus we don't need to
321 * clean anything else.
325 for (size_t i=0; i<m_drivers.size(); i++)
327 if (m_drivers[i] == pDriver)
329 m_drivers.erase(m_drivers.iterAt(i));
334 /* Make sure NOTHING references this! */
335 List<ConfDbInfo>::iterator iter;
336 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
338 ConfDbInfo &db = (*iter);
339 if (db.realDriver == pDriver)
341 db.realDriver = NULL;
345 /* Now that the driver is gone, we have to test the think queue.
346 * Whatever happens therein is up to the db op!
348 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
349 Queue<IDBThreadOperation *> templist;
350 while (qiter != m_ThinkQueue.end())
352 IDBThreadOperation *op = (*qiter);
353 if (op->GetDriver() == pDriver)
356 qiter = m_ThinkQueue.erase(qiter);
362 for (qiter = templist.begin();
363 qiter != templist.end();
366 IDBThreadOperation *op = (*qiter);
367 op->CancelThinkPart();
372 IDBDriver *DBManager::GetDefaultDriver()
374 if (!m_pDefault && m_DefDriver.size() > 0)
376 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
382 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
384 HandleType_t type = 0;
386 if (dtype == DBHandle_Driver)
389 } else if (dtype == DBHandle_Database) {
390 type = m_DatabaseType;
395 return g_HandleSys.CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
398 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
400 HandleType_t type = 0;
402 if (dtype == DBHandle_Driver)
405 } else if (dtype == DBHandle_Database) {
406 type = m_DatabaseType;
408 return HandleError_Type;
411 HandleSecurity sec(NULL, g_pCoreIdent);
413 return g_HandleSys.ReadHandle(hndl, type, &sec, ptr);
416 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
418 HandleSecurity sec(token, g_pCoreIdent);
419 return g_HandleSys.FreeHandle(hndl, &sec);
422 unsigned int DBManager::GetDriverCount()
424 return (unsigned int)m_drivers.size();
427 IDBDriver *DBManager::GetDriver(unsigned int index)
429 if (index >= m_drivers.size())
434 return m_drivers[index];
437 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
439 ConfDbInfo *info = GetDatabaseConf(name);
448 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
450 List<ConfDbInfo>::iterator iter;
452 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
454 ConfDbInfo &conf = (*iter);
455 if (conf.name == name)
464 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
466 size_t last_size = m_drivers.size();
467 for (size_t i=0; i<last_size; i++)
469 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
475 char filename[PLATFORM_MAX_PATH];
476 UTIL_Format(filename, sizeof(filename), "dbi.%s.ext", name);
478 IExtension *pExt = g_Extensions.LoadAutoExtension(filename);
479 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
484 /* last_size is now gauranteed to be a valid index.
485 * The identifier must match the name.
487 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
489 return m_drivers[last_size];
495 void DBManager::KillWorkerThread()
499 m_pWorker->Stop(false);
500 g_pThreader->DestroyWorker(m_pWorker);
502 s_OneTimeThreaderErrorMsg = false;
506 static IdentityToken_t *s_pAddBlock = NULL;
508 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
510 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
517 m_pWorker = g_pThreader->MakeWorker(this, true);
520 if (!s_OneTimeThreaderErrorMsg)
522 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
523 s_OneTimeThreaderErrorMsg = true;
527 if (!m_pWorker->Start())
529 if (!s_OneTimeThreaderErrorMsg)
531 g_Logger.LogError("[SM] Unable to start db threader (error unknown)");
532 s_OneTimeThreaderErrorMsg = true;
534 g_pThreader->DestroyWorker(m_pWorker);
540 /* Add to the queue */
542 m_pQueueLock->Lock();
543 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
545 m_pQueueLock->Unlock();
548 /* Make the thread */
549 m_pWorker->MakeThread(this);
554 void DBManager::OnWorkerStart(IThreadWorker *pWorker)
557 for (size_t i=0; i<m_drivers.size(); i++)
559 if (m_drivers[i]->IsThreadSafe())
561 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
563 m_drSafety.push_back(false);
568 void DBManager::OnWorkerStop(IThreadWorker *pWorker)
570 for (size_t i=0; i<m_drivers.size(); i++)
574 m_drivers[i]->ShutdownThreadSafety();
580 void DBManager::RunThread(IThreadHandle *pThread)
582 IDBThreadOperation *op = NULL;
584 /* Get something from the queue */
586 m_pQueueLock->Lock();
587 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
593 m_pQueueLock->Unlock();
596 /* whoa. hi. did we get something? we should have. */
605 m_pThinkLock->Lock();
606 m_ThinkQueue.push(op);
607 m_pThinkLock->Unlock();
610 void DBManager::RunFrame()
612 /* Don't bother if we're empty */
613 if (!m_ThinkQueue.size())
618 /* Dump one thing per-frame so the server stays sane. */
619 m_pThinkLock->Lock();
620 IDBThreadOperation *op = m_ThinkQueue.first();
622 m_pThinkLock->Unlock();
627 void DBManager::OnTerminate(IThreadHandle *pThread, bool cancel)
632 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
634 s_pAddBlock = pToken;
636 /* Kill the thread so we can flush everything into the think queue... */
639 /* Run all of the think operations.
640 * Unlike the driver unloading example, we'll let these calls go through,
641 * since a plugin unloading is far more normal.
643 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
644 Queue<IDBThreadOperation *> templist;
645 while (iter != m_ThinkQueue.end())
647 IDBThreadOperation *op = (*iter);
648 if (op->GetOwner() == pToken)
651 iter = m_ThinkQueue.erase(iter);
657 for (iter = templist.begin();
658 iter != templist.end();
661 IDBThreadOperation *op = (*iter);
669 void DBManager::OnPluginUnloaded(IPlugin *plugin)
671 /* Kill the thread so we can flush everything into the think queue... */
674 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
675 plugin->SetProperty("DisallowDBThreads", NULL);
677 /* Run all of the think operations.
678 * Unlike the driver unloading example, we'll let these calls go through,
679 * since a plugin unloading is far more normal.
681 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
682 Queue<IDBThreadOperation *> templist;
683 while (iter != m_ThinkQueue.end())
685 IDBThreadOperation *op = (*iter);
686 if (op->GetOwner() == plugin->GetIdentity())
689 iter = m_ThinkQueue.erase(iter);
695 for (iter = templist.begin();
696 iter != templist.end();
699 IDBThreadOperation *op = (*iter);
705 void DBManager::LockConfig()
707 m_pConfigLock->Lock();
710 void DBManager::UnlockConfig()
712 m_pConfigLock->Unlock();
715 const char *DBManager::GetDefaultDriverName()
717 return m_DefDriver.c_str();
720 void DBManager::AddDependency(IExtension *myself, IDBDriver *driver)
722 g_Extensions.AddRawDependency(myself, driver->GetIdentity(), driver);