2 * vim: set ts=4 sw=4 tw=99 noet :
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 "sourcemod.h"
34 #include "sm_stringutil.h"
37 #include <IThreader.h>
38 #include "logic_bridge.h"
40 #define DBPARSE_LEVEL_NONE 0
41 #define DBPARSE_LEVEL_MAIN 1
42 #define DBPARSE_LEVEL_DATABASE 2
45 static bool s_OneTimeThreaderErrorMsg = false;
47 DBManager::DBManager()
55 void DBManager::OnSourceModAllInitialized()
59 handlesys->InitAccessDefaults(NULL, &sec);
60 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
61 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
63 m_DriverType = handlesys->CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
64 m_DatabaseType = handlesys->CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
66 sharesys->AddInterface(NULL, this);
68 g_SourceMod.BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
70 scripts->AddPluginsListener(this);
73 void DBManager::OnSourceModLevelChange(const char *mapName)
76 SMCStates states = {0, 0};
78 /* We lock and don't give up the lock until we're done.
79 * This way the thread's search won't be searching through a
80 * potentially empty/corrupt list, which would be very bad.
82 ke::AutoLock lock(&m_ConfigLock);
83 if ((err = textparsers->ParseFile_SMC(m_Filename, this, &states)) != SMCError_Okay)
85 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
86 if (err != SMCError_Custom)
88 const char *txt = textparsers->GetSMCErrorString(err);
89 g_Logger.LogError("[SM] Line %d: %s", states.line, txt);
94 void DBManager::OnSourceModShutdown()
97 scripts->RemovePluginsListener(this);
98 handlesys->RemoveType(m_DatabaseType, g_pCoreIdent);
99 handlesys->RemoveType(m_DriverType, g_pCoreIdent);
103 unsigned int DBManager::GetInterfaceVersion()
105 return SMINTERFACE_DBI_VERSION;
108 const char *DBManager::GetInterfaceName()
110 return SMINTERFACE_DBI_NAME;
113 void DBManager::OnHandleDestroy(HandleType_t type, void *object)
115 if (type == m_DriverType)
121 if (handlesys->TypeCheck(type, m_DatabaseType))
123 IDatabase *pdb = (IDatabase *)object;
128 void DBManager::ReadSMC_ParseStart()
132 m_ParseState = DBPARSE_LEVEL_NONE;
136 void DBManager::ClearConfigs()
138 List<ConfDbInfo *>::iterator iter;
139 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
144 ConfDbInfo s_CurInfo;
145 SMCResult DBManager::ReadSMC_NewSection(const SMCStates *states, const char *name)
150 return SMCResult_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 = name;
164 m_ParseState = DBPARSE_LEVEL_DATABASE;
165 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
169 return SMCResult_Continue;
172 SMCResult DBManager::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
176 return SMCResult_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 = value;
192 } else if (strcmp(key, "database") == 0) {
193 s_CurInfo.database = value;
194 } else if (strcmp(key, "host") == 0) {
195 s_CurInfo.host = value;
196 } else if (strcmp(key, "user") == 0) {
197 s_CurInfo.user = value;
198 } else if (strcmp(key, "pass") == 0) {
199 s_CurInfo.pass = 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 SMCResult_Continue;
210 SMCResult DBManager::ReadSMC_LeavingSection(const SMCStates *states)
215 return SMCResult_Continue;
218 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
220 ConfDbInfo *cdb = new ConfDbInfo();
222 cdb->name = s_CurInfo.name;
223 cdb->driver = s_CurInfo.driver;
224 cdb->host = s_CurInfo.host;
225 cdb->user = s_CurInfo.user;
226 cdb->pass = s_CurInfo.pass;
227 cdb->database = s_CurInfo.database;
228 cdb->realDriver = s_CurInfo.realDriver;
229 cdb->info.maxTimeout = s_CurInfo.info.maxTimeout;
230 cdb->info.port = s_CurInfo.info.port;
232 cdb->info.driver = cdb->driver.c_str();
233 cdb->info.database = cdb->database.c_str();
234 cdb->info.host = cdb->host.c_str();
235 cdb->info.user = cdb->user.c_str();
236 cdb->info.pass = cdb->pass.c_str();
239 m_confs.push_back(cdb);
241 /* Go up one level */
242 m_ParseState = DBPARSE_LEVEL_MAIN;
243 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
244 m_ParseState = DBPARSE_LEVEL_NONE;
245 return SMCResult_Halt;
248 return SMCResult_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 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 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 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 (conf.name == name)
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 = extsys->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()
503 ke::AutoLock lock(&m_QueueEvent);
505 m_QueueEvent.Notify();
509 s_OneTimeThreaderErrorMsg = false;
514 static IdentityToken_t *s_pAddBlock = NULL;
516 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
518 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
525 m_Worker = new ke::Thread(this, "SM SQL Worker");
526 if (!m_Worker->Succeeded())
528 if (!s_OneTimeThreaderErrorMsg)
530 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
531 s_OneTimeThreaderErrorMsg = true;
538 /* Add to the queue */
540 ke::AutoLock lock(&m_QueueEvent);
541 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
543 m_QueueEvent.Notify();
549 void DBManager::Run()
551 // Initialize DB threadsafety.
552 for (size_t i=0; i < m_drivers.size(); i++)
554 if (m_drivers[i]->IsThreadSafe())
555 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
557 m_drSafety.push_back(false);
560 // Run actual worker thread logic.
563 // Shutdown DB threadsafety.
564 for (size_t i=0; i<m_drivers.size(); i++)
567 m_drivers[i]->ShutdownThreadSafety();
572 void DBManager::ThreadMain()
574 ke::AutoLock lock(&m_QueueEvent);
577 // The lock has been acquired. Grab everything we can out of the
578 // queue. Since we want to flush the queue even if we're terminated,
579 // we process all operations we can before checking to terminate.
580 // There's no risk of starvation since the main thread blocks on us
584 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
588 IDBThreadOperation *op = queue.first();
591 // Unlock the queue when we run the query, so the main thread can
592 // keep pumping events. We re-acquire the lock to check for more
593 // items. It's okay if we terminate while unlocked; the main
594 // thread would be blocked and we'd need to flush the queue
595 // anyway, so after we've depleted the queue here, we'll just
596 // reach the terminate at the top of the loop.
598 ke::AutoUnlock unlock(&m_QueueEvent);
601 ke::AutoLock lock(&m_ThinkLock);
602 m_ThinkQueue.push(op);
609 // Release the lock and wait for a signal.
614 void DBManager::RunFrame()
616 /* Don't bother if we're empty */
617 if (!m_ThinkQueue.size())
622 /* Dump one thing per-frame so the server stays sane. */
623 IDBThreadOperation *op;
625 ke::AutoLock lock(&m_ThinkLock);
626 op = m_ThinkQueue.first();
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()
711 void DBManager::UnlockConfig()
713 m_ConfigLock.Unlock();
716 const char *DBManager::GetDefaultDriverName()
718 return m_DefDriver.c_str();
721 void DBManager::AddDependency(IExtension *myself, IDBDriver *driver)
723 extsys->AddRawDependency(myself, driver->GetIdentity(), driver);