2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2007, 2009 Dennis Friis <peavey@inspircd.org>
6 * Copyright (C) 2006-2009 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 /* Stop mysql wanting to use long long */
24 #define NO_CLIENT_LONG_LONG
31 # pragma comment(lib, "libmysql.lib")
34 /* VERSION 3 API: With nonblocking (threaded) requests */
36 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
37 /* $CompileFlags: exec("mysql_config --include") */
38 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
40 /* THE NONBLOCKING MYSQL API!
42 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
43 * that instead, you should thread your program. This is what i've done here to allow for
44 * asyncronous SQL requests via mysql. The way this works is as follows:
46 * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
47 * using a queue with priorities. There is a mutex on either end which prevents two threads
48 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
49 * worker thread wakes up, and checks if there is a request at the head of its queue.
50 * If there is, it processes this request, blocking the worker thread but leaving the ircd
51 * thread to go about its business as usual. During this period, the ircd thread is able
52 * to insert futher pending requests into the queue.
54 * Once the processing of a request is complete, it is removed from the incoming queue to
55 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
56 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
57 * connection ID through the connection.
59 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
60 * of the queue, and sends it on its way to the original calling module.
62 * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
63 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
64 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
65 * however, if we were to call a module's OnRequest even from within a thread which was not the
66 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
67 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
68 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
69 * gauranteed threadsafe!)
71 * For a diagram of this system please see http://wiki.inspircd.org/Mysql2
76 class DispatcherThread;
83 QQueueItem(SQLQuery* Q, const std::string& S, SQLConnection* C) : q(Q), query(S), c(C) {}
90 RQueueItem(SQLQuery* Q, MySQLresult* R) : q(Q), r(R) {}
93 typedef std::map<std::string, SQLConnection*> ConnMap;
94 typedef std::deque<QQueueItem> QueryQueue;
95 typedef std::deque<RQueueItem> ResultQueue;
99 class ModuleSQL : public Module
102 DispatcherThread* Dispatcher;
103 QueryQueue qq; // MUST HOLD MUTEX
104 ResultQueue rq; // MUST HOLD MUTEX
105 ConnMap connections; // main thread only
110 void OnRehash(User* user);
111 void OnUnloadModule(Module* mod);
112 Version GetVersion();
115 class DispatcherThread : public SocketThread
118 ModuleSQL* const Parent;
120 DispatcherThread(ModuleSQL* CreatorModule) : Parent(CreatorModule) { }
121 ~DispatcherThread() { }
123 virtual void OnNotify();
126 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
127 #define mysql_field_count mysql_num_fields
130 /** Represents a mysql result set
132 class MySQLresult : public SQLResult
138 std::vector<std::string> colnames;
139 std::vector<SQLEntries> fieldlists;
141 MySQLresult(MYSQL_RES* res, int affected_rows) : err(SQL_NO_ERROR), currentrow(0), rows(0)
143 if (affected_rows >= 1)
145 rows = affected_rows;
146 fieldlists.resize(rows);
148 unsigned int field_count = 0;
153 while ((row = mysql_fetch_row(res)))
155 if (fieldlists.size() < (unsigned int)rows+1)
157 fieldlists.resize(fieldlists.size()+1);
160 MYSQL_FIELD *fields = mysql_fetch_fields(res);
161 if(mysql_num_fields(res) == 0)
163 if (fields && mysql_num_fields(res))
166 while (field_count < mysql_num_fields(res))
168 std::string a = (fields[field_count].name ? fields[field_count].name : "");
169 if (row[field_count])
170 fieldlists[n].push_back(SQLEntry(row[field_count]));
172 fieldlists[n].push_back(SQLEntry());
173 colnames.push_back(a);
180 mysql_free_result(res);
184 MySQLresult(SQLerror& e) : err(e)
198 virtual void GetCols(std::vector<std::string>& result)
200 result.assign(colnames.begin(), colnames.end());
203 virtual SQLEntry GetValue(int row, int column)
205 if ((row >= 0) && (row < rows) && (column >= 0) && (column < (int)fieldlists[row].size()))
207 return fieldlists[row][column];
212 virtual bool GetRow(SQLEntries& result)
214 if (currentrow < rows)
216 result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
228 /** Represents a connection to a mysql database
230 class SQLConnection : public SQLProvider
233 reference<ConfigTag> config;
237 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
238 SQLConnection(Module* p, ConfigTag* tag) : SQLProvider(p, "SQL/" + tag->getString("id")),
239 config(tag), connection(NULL)
248 // This method connects to the database using the credentials supplied to the constructor, and returns
249 // true upon success.
252 unsigned int timeout = 1;
253 connection = mysql_init(connection);
254 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
255 std::string host = config->getString("host");
256 std::string user = config->getString("user");
257 std::string pass = config->getString("pass");
258 std::string dbname = config->getString("name");
259 int port = config->getInt("port");
260 bool rv = mysql_real_connect(connection, host.c_str(), user.c_str(), pass.c_str(), dbname.c_str(), port, NULL, 0);
263 std::string initquery;
264 if (config->readString("initialquery", initquery))
266 mysql_query(connection,initquery.c_str());
273 return (ModuleSQL*)(Module*)creator;
276 MySQLresult* DoBlockingQuery(const std::string& query)
279 /* Parse the command string and dispatch it to mysql */
280 if (CheckConnection() && !mysql_real_query(connection, query.data(), query.length()))
282 /* Successfull query */
283 MYSQL_RES* res = mysql_use_result(connection);
284 unsigned long rows = mysql_affected_rows(connection);
285 return new MySQLresult(res, rows);
289 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
290 * possible error numbers and error messages */
291 SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + ": " + mysql_error(connection));
292 return new MySQLresult(e);
296 bool CheckConnection()
298 if (!connection || mysql_ping(connection) != 0)
303 std::string GetError()
305 return mysql_error(connection);
310 mysql_close(connection);
313 void submit(SQLQuery* q, const std::string& qs)
315 Parent()->Dispatcher->LockQueue();
316 Parent()->qq.push_back(QQueueItem(q, qs, this));
317 Parent()->Dispatcher->UnlockQueueWakeup();
320 void submit(SQLQuery* call, const std::string& q, const ParamL& p)
323 unsigned int param = 0;
324 for(std::string::size_type i = 0; i < q.length(); i++)
330 if (param < p.size())
332 std::string parm = p[param++];
333 // In the worst case, each character may need to be encoded as using two bytes,
334 // and one byte is the terminating null
335 std::vector<char> buffer(parm.length() * 2 + 1);
337 // The return value of mysql_escape_string() is the length of the encoded string,
338 // not including the terminating null
339 unsigned long escapedsize = mysql_escape_string(&buffer[0], parm.c_str(), parm.length());
340 // mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
341 res.append(&buffer[0], escapedsize);
348 void submit(SQLQuery* call, const std::string& q, const ParamM& p)
351 for(std::string::size_type i = 0; i < q.length(); i++)
359 while (i < q.length() && isalnum(q[i]))
360 field.push_back(q[i++]);
363 ParamM::const_iterator it = p.find(field);
366 std::string parm = it->second;
368 std::vector<char> buffer(parm.length() * 2 + 1);
369 unsigned long escapedsize = mysql_escape_string(&buffer[0], parm.c_str(), parm.length());
370 res.append(&buffer[0], escapedsize);
378 ModuleSQL::ModuleSQL()
383 void ModuleSQL::init()
385 Dispatcher = new DispatcherThread(this);
386 ServerInstance->Threads->Start(Dispatcher);
388 Implementation eventlist[] = { I_OnRehash, I_OnUnloadModule };
389 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
394 ModuleSQL::~ModuleSQL()
399 Dispatcher->OnNotify();
402 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
408 void ModuleSQL::OnRehash(User* user)
411 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
412 for(ConfigIter i = tags.first; i != tags.second; i++)
414 if (i->second->getString("module", "mysql") != "mysql")
416 std::string id = i->second->getString("id");
417 ConnMap::iterator curr = connections.find(id);
418 if (curr == connections.end())
420 SQLConnection* conn = new SQLConnection(this, i->second);
421 conns.insert(std::make_pair(id, conn));
422 ServerInstance->Modules->AddService(*conn);
427 connections.erase(curr);
431 // now clean up the deleted databases
432 Dispatcher->LockQueue();
433 SQLerror err(SQL_BAD_DBID);
434 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
436 ServerInstance->Modules->DelService(*i->second);
437 // it might be running a query on this database. Wait for that to complete
438 i->second->lock.Lock();
439 i->second->lock.Unlock();
440 // now remove all active queries to this DB
441 for (size_t j = qq.size(); j > 0; j--)
444 if (qq[k].c == i->second)
446 qq[k].q->OnError(err);
448 qq.erase(qq.begin() + k);
451 // finally, nuke the connection
454 Dispatcher->UnlockQueue();
455 connections.swap(conns);
458 void ModuleSQL::OnUnloadModule(Module* mod)
460 SQLerror err(SQL_BAD_DBID);
461 Dispatcher->LockQueue();
462 unsigned int i = qq.size();
466 if (qq[i].q->creator == mod)
470 // need to wait until the query is done
471 // (the result will be discarded)
472 qq[i].c->lock.Lock();
473 qq[i].c->lock.Unlock();
475 qq[i].q->OnError(err);
477 qq.erase(qq.begin() + i);
480 Dispatcher->UnlockQueue();
481 // clean up any result queue entries
482 Dispatcher->OnNotify();
485 Version ModuleSQL::GetVersion()
487 return Version("MySQL support", VF_VENDOR);
490 void DispatcherThread::Run()
493 while (!this->GetExitFlag())
495 if (!Parent->qq.empty())
497 QQueueItem i = Parent->qq.front();
500 MySQLresult* res = i.c->DoBlockingQuery(i.query);
504 * At this point, the main thread could be working on:
505 * Rehash - delete i.c out from under us. We don't care about that.
506 * UnloadModule - delete i.q and the qq item. Need to avoid reporting results.
510 if (!Parent->qq.empty() && Parent->qq.front().q == i.q)
512 Parent->qq.pop_front();
513 Parent->rq.push_back(RQueueItem(i.q, res));
518 // UnloadModule ate the query
524 /* We know the queue is empty, we can safely hang this thread until
527 this->WaitForQueue();
533 void DispatcherThread::OnNotify()
535 // this could unlock during the dispatch, but OnResult isn't expected to take that long
537 for(ResultQueue::iterator i = Parent->rq.begin(); i != Parent->rq.end(); i++)
539 MySQLresult* res = i->r;
540 if (res->err.id == SQL_NO_ERROR)
541 i->q->OnResult(*res);
543 i->q->OnError(res->err);
551 MODULE_INIT(ModuleSQL)