Update CS:GO team score gamedata.
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 "ISourceMod.h"
34 #include "HandleSys.h"
35 #include "ExtensionSys.h"
36 #include "PluginSys.h"
38 #include <IThreader.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 static void FrameHook(bool simulating)
60 void DBManager::OnSourceModAllInitialized()
64 g_HandleSys.InitAccessDefaults(NULL, &sec);
65 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
66 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
68 m_DriverType = g_HandleSys.CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
69 m_DatabaseType = g_HandleSys.CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
71 g_ShareSys.AddInterface(NULL, this);
73 g_pSM->BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
75 g_PluginSys.AddPluginsListener(this);
77 g_pSM->AddGameFrameHook(&FrameHook);
80 void DBManager::OnSourceModLevelChange(const char *mapName)
83 SMCStates states = {0, 0};
85 /* We lock and don't give up the lock until we're done.
86 * This way the thread's search won't be searching through a
87 * potentially empty/corrupt list, which would be very bad.
89 ke::AutoLock lock(&m_ConfigLock);
90 if ((err = textparsers->ParseFile_SMC(m_Filename, this, &states)) != SMCError_Okay)
92 smcore.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
93 if (err != SMCError_Custom)
95 const char *txt = textparsers->GetSMCErrorString(err);
96 smcore.LogError("[SM] Line %d: %s", states.line, txt);
101 void DBManager::OnSourceModShutdown()
103 g_pSM->RemoveGameFrameHook(&FrameHook);
105 g_PluginSys.RemovePluginsListener(this);
106 g_HandleSys.RemoveType(m_DatabaseType, g_pCoreIdent);
107 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;
144 void DBManager::ClearConfigs()
146 List<ConfDbInfo *>::iterator iter;
147 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
152 ConfDbInfo s_CurInfo;
153 SMCResult DBManager::ReadSMC_NewSection(const SMCStates *states, const char *name)
158 return SMCResult_Continue;
161 if (m_ParseState == DBPARSE_LEVEL_NONE)
163 if (strcmp(name, "Databases") == 0)
165 m_ParseState = DBPARSE_LEVEL_MAIN;
169 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
170 s_CurInfo = ConfDbInfo();
171 s_CurInfo.name = name;
172 m_ParseState = DBPARSE_LEVEL_DATABASE;
173 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
177 return SMCResult_Continue;
180 SMCResult DBManager::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
184 return SMCResult_Continue;
187 if (m_ParseState == DBPARSE_LEVEL_MAIN)
189 if (strcmp(key, "driver_default") == 0)
191 m_DefDriver.assign(value);
193 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
194 if (strcmp(key, "driver") == 0)
196 if (strcmp(value, "default") != 0)
198 s_CurInfo.driver = value;
200 } else if (strcmp(key, "database") == 0) {
201 s_CurInfo.database = value;
202 } else if (strcmp(key, "host") == 0) {
203 s_CurInfo.host = value;
204 } else if (strcmp(key, "user") == 0) {
205 s_CurInfo.user = value;
206 } else if (strcmp(key, "pass") == 0) {
207 s_CurInfo.pass = value;
208 } else if (strcmp(key, "timeout") == 0) {
209 s_CurInfo.info.maxTimeout = atoi(value);
210 } else if (strcmp(key, "port") == 0) {
211 s_CurInfo.info.port = atoi(value);
215 return SMCResult_Continue;
218 SMCResult DBManager::ReadSMC_LeavingSection(const SMCStates *states)
223 return SMCResult_Continue;
226 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
228 ConfDbInfo *cdb = new ConfDbInfo();
230 cdb->name = s_CurInfo.name;
231 cdb->driver = s_CurInfo.driver;
232 cdb->host = s_CurInfo.host;
233 cdb->user = s_CurInfo.user;
234 cdb->pass = s_CurInfo.pass;
235 cdb->database = s_CurInfo.database;
236 cdb->realDriver = s_CurInfo.realDriver;
237 cdb->info.maxTimeout = s_CurInfo.info.maxTimeout;
238 cdb->info.port = s_CurInfo.info.port;
240 cdb->info.driver = cdb->driver.c_str();
241 cdb->info.database = cdb->database.c_str();
242 cdb->info.host = cdb->host.c_str();
243 cdb->info.user = cdb->user.c_str();
244 cdb->info.pass = cdb->pass.c_str();
247 m_confs.push_back(cdb);
249 /* Go up one level */
250 m_ParseState = DBPARSE_LEVEL_MAIN;
251 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
252 m_ParseState = DBPARSE_LEVEL_NONE;
253 return SMCResult_Halt;
256 return SMCResult_Continue;
259 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
263 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
265 ConfDbInfo *pInfo = GetDatabaseConf(name);
274 g_pSM->Format(error, maxlength, "Configuration \"%s\" not found", name);
278 const char *dname = pInfo->info.driver;
279 if (!pInfo->realDriver)
281 /* Try to assign a real driver pointer */
282 if (pInfo->info.driver[0] == '\0')
284 if (!m_pDefault && m_DefDriver.size() > 0)
286 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
288 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
289 pInfo->realDriver = m_pDefault;
291 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
295 if (pInfo->realDriver)
299 *pdr = pInfo->realDriver;
301 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
302 return (*pdb != NULL);
311 g_pSM->Format(error, maxlength, "Driver \"%s\" not found", dname);
316 void DBManager::AddDriver(IDBDriver *pDriver)
318 /* Let's kill the worker. Join the thread and let the queries flush.
319 * This is kind of stupid but we just want to unload safely.
320 * Rather than recreate the worker, we'll wait until someone throws
321 * another query through.
325 m_drivers.push_back(pDriver);
328 void DBManager::RemoveDriver(IDBDriver *pDriver)
330 /* Again, we're forced to kill the worker. How rude!
331 * Doing this flushes the queue, and thus we don't need to
332 * clean anything else.
336 for (size_t i=0; i<m_drivers.size(); i++)
338 if (m_drivers[i] == pDriver)
340 m_drivers.erase(m_drivers.iterAt(i));
345 /* Make sure NOTHING references this! */
346 List<ConfDbInfo *>::iterator iter;
347 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
349 ConfDbInfo &db = *(*iter);
350 if (db.realDriver == pDriver)
352 db.realDriver = NULL;
356 /* Someone unloaded the default driver? Silly.. */
357 if (pDriver == m_pDefault)
362 /* Now that the driver is gone, we have to test the think queue.
363 * Whatever happens therein is up to the db op!
365 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
366 Queue<IDBThreadOperation *> templist;
367 while (qiter != m_ThinkQueue.end())
369 IDBThreadOperation *op = (*qiter);
370 if (op->GetDriver() == pDriver)
373 qiter = m_ThinkQueue.erase(qiter);
379 for (qiter = templist.begin();
380 qiter != templist.end();
383 IDBThreadOperation *op = (*qiter);
384 op->CancelThinkPart();
389 IDBDriver *DBManager::GetDefaultDriver()
391 if (!m_pDefault && m_DefDriver.size() > 0)
393 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
399 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
401 HandleType_t type = 0;
403 if (dtype == DBHandle_Driver)
406 } else if (dtype == DBHandle_Database) {
407 type = m_DatabaseType;
412 return g_HandleSys.CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
415 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
417 HandleType_t type = 0;
419 if (dtype == DBHandle_Driver)
422 } else if (dtype == DBHandle_Database) {
423 type = m_DatabaseType;
425 return HandleError_Type;
428 HandleSecurity sec(NULL, g_pCoreIdent);
430 return g_HandleSys.ReadHandle(hndl, type, &sec, ptr);
433 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
435 HandleSecurity sec(token, g_pCoreIdent);
436 return g_HandleSys.FreeHandle(hndl, &sec);
439 unsigned int DBManager::GetDriverCount()
441 return (unsigned int)m_drivers.size();
444 IDBDriver *DBManager::GetDriver(unsigned int index)
446 if (index >= m_drivers.size())
451 return m_drivers[index];
454 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
456 ConfDbInfo *info = GetDatabaseConf(name);
465 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
467 List<ConfDbInfo *>::iterator iter;
469 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
471 ConfDbInfo &conf = *(*iter);
472 if (conf.name == name)
481 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
483 size_t last_size = m_drivers.size();
484 for (size_t i=0; i<last_size; i++)
486 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
492 char filename[PLATFORM_MAX_PATH];
493 g_pSM->Format(filename, sizeof(filename), "dbi.%s.ext", name);
495 IExtension *pExt = g_Extensions.LoadAutoExtension(filename);
496 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
501 /* last_size is now gauranteed to be a valid index.
502 * The identifier must match the name.
504 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
506 return m_drivers[last_size];
512 void DBManager::KillWorkerThread()
517 ke::AutoLock lock(&m_QueueEvent);
519 m_QueueEvent.Notify();
523 s_OneTimeThreaderErrorMsg = false;
528 static IdentityToken_t *s_pAddBlock = NULL;
530 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
532 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
539 m_Worker = new ke::Thread(this, "SM SQL Worker");
540 if (!m_Worker->Succeeded())
542 if (!s_OneTimeThreaderErrorMsg)
544 smcore.LogError("[SM] Unable to create db threader (error unknown)");
545 s_OneTimeThreaderErrorMsg = true;
552 /* Add to the queue */
554 ke::AutoLock lock(&m_QueueEvent);
555 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
557 m_QueueEvent.Notify();
563 void DBManager::Run()
565 // Initialize DB threadsafety.
566 for (size_t i=0; i < m_drivers.size(); i++)
568 if (m_drivers[i]->IsThreadSafe())
569 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
571 m_drSafety.push_back(false);
574 // Run actual worker thread logic.
577 // Shutdown DB threadsafety.
578 for (size_t i=0; i<m_drivers.size(); i++)
581 m_drivers[i]->ShutdownThreadSafety();
586 void DBManager::ThreadMain()
588 ke::AutoLock lock(&m_QueueEvent);
591 // The lock has been acquired. Grab everything we can out of the
592 // queue. Since we want to flush the queue even if we're terminated,
593 // we process all operations we can before checking to terminate.
594 // There's no risk of starvation since the main thread blocks on us
598 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
602 IDBThreadOperation *op = queue.first();
605 // Unlock the queue when we run the query, so the main thread can
606 // keep pumping events. We re-acquire the lock to check for more
607 // items. It's okay if we terminate while unlocked; the main
608 // thread would be blocked and we'd need to flush the queue
609 // anyway, so after we've depleted the queue here, we'll just
610 // reach the terminate at the top of the loop.
612 ke::AutoUnlock unlock(&m_QueueEvent);
615 ke::AutoLock lock(&m_ThinkLock);
616 m_ThinkQueue.push(op);
623 // Release the lock and wait for a signal.
628 void DBManager::RunFrame()
630 /* Don't bother if we're empty */
631 if (!m_ThinkQueue.size())
636 /* Dump one thing per-frame so the server stays sane. */
637 IDBThreadOperation *op;
639 ke::AutoLock lock(&m_ThinkLock);
640 op = m_ThinkQueue.first();
647 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
649 s_pAddBlock = pToken;
651 /* Kill the thread so we can flush everything into the think queue... */
654 /* Run all of the think operations.
655 * Unlike the driver unloading example, we'll let these calls go through,
656 * since a plugin unloading is far more normal.
658 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
659 Queue<IDBThreadOperation *> templist;
660 while (iter != m_ThinkQueue.end())
662 IDBThreadOperation *op = (*iter);
663 if (op->GetOwner() == pToken)
666 iter = m_ThinkQueue.erase(iter);
672 for (iter = templist.begin();
673 iter != templist.end();
676 IDBThreadOperation *op = (*iter);
684 void DBManager::OnPluginUnloaded(IPlugin *plugin)
686 /* Kill the thread so we can flush everything into the think queue... */
689 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
690 plugin->SetProperty("DisallowDBThreads", NULL);
692 /* Run all of the think operations.
693 * Unlike the driver unloading example, we'll let these calls go through,
694 * since a plugin unloading is far more normal.
696 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
697 Queue<IDBThreadOperation *> templist;
698 while (iter != m_ThinkQueue.end())
700 IDBThreadOperation *op = (*iter);
701 if (op->GetOwner() == plugin->GetIdentity())
704 iter = m_ThinkQueue.erase(iter);
710 for (iter = templist.begin();
711 iter != templist.end();
714 IDBThreadOperation *op = (*iter);
720 void DBManager::LockConfig()
725 void DBManager::UnlockConfig()
727 m_ConfigLock.Unlock();
730 const char *DBManager::GetDefaultDriverName()
732 return m_DefDriver.c_str();
735 void DBManager::AddDependency(IExtension *myself, IDBDriver *driver)
737 g_Extensions.AddRawDependency(myself, driver->GetIdentity(), driver);