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/>.
22 /// $CompilerFlags: execute("mysql_config --include" "MYSQL_CXXFLAGS")
23 /// $LinkerFlags: execute("mysql_config --libs_r" "MYSQL_LDFLAGS" "-lmysqlclient")
25 /// $PackageInfo: require_system("centos" "6.0" "6.99") mysql-devel
26 /// $PackageInfo: require_system("centos" "7.0") mariadb-devel
27 /// $PackageInfo: require_system("darwin") mysql-connector-c
28 /// $PackageInfo: require_system("debian") libmysqlclient-dev
29 /// $PackageInfo: require_system("ubuntu") libmysqlclient-dev
32 // Fix warnings about the use of `long long` on C++03.
34 # pragma clang diagnostic ignored "-Wc++11-long-long"
35 #elif defined __GNUC__
36 # pragma GCC diagnostic ignored "-Wlong-long"
41 #include "modules/sql.h"
44 # pragma comment(lib, "libmysql.lib")
47 /* VERSION 3 API: With nonblocking (threaded) requests */
49 /* THE NONBLOCKING MYSQL API!
51 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
52 * that instead, you should thread your program. This is what i've done here to allow for
53 * asyncronous SQL requests via mysql. The way this works is as follows:
55 * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
56 * using a queue with priorities. There is a mutex on either end which prevents two threads
57 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
58 * worker thread wakes up, and checks if there is a request at the head of its queue.
59 * If there is, it processes this request, blocking the worker thread but leaving the ircd
60 * thread to go about its business as usual. During this period, the ircd thread is able
61 * to insert futher pending requests into the queue.
63 * Once the processing of a request is complete, it is removed from the incoming queue to
64 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
65 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
66 * connection ID through the connection.
68 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
69 * of the queue, and sends it on its way to the original calling module.
71 * XXX: You might be asking "why doesnt it just send the response from within the worker thread?"
72 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
73 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
74 * however, if we were to call a module's OnRequest even from within a thread which was not the
75 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
76 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
77 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
78 * gauranteed threadsafe!)
83 class DispatcherThread;
90 QQueueItem(SQL::Query* Q, const std::string& S, SQLConnection* C) : q(Q), query(S), c(C) {}
97 RQueueItem(SQL::Query* Q, MySQLresult* R) : q(Q), r(R) {}
100 typedef insp::flat_map<std::string, SQLConnection*> ConnMap;
101 typedef std::deque<QQueueItem> QueryQueue;
102 typedef std::deque<RQueueItem> ResultQueue;
106 class ModuleSQL : public Module
109 DispatcherThread* Dispatcher;
110 QueryQueue qq; // MUST HOLD MUTEX
111 ResultQueue rq; // MUST HOLD MUTEX
112 ConnMap connections; // main thread only
115 void init() CXX11_OVERRIDE;
117 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE;
118 void OnUnloadModule(Module* mod) CXX11_OVERRIDE;
119 Version GetVersion() CXX11_OVERRIDE;
122 class DispatcherThread : public SocketThread
125 ModuleSQL* const Parent;
127 DispatcherThread(ModuleSQL* CreatorModule) : Parent(CreatorModule) { }
128 ~DispatcherThread() { }
129 void Run() CXX11_OVERRIDE;
130 void OnNotify() CXX11_OVERRIDE;
133 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
134 #define mysql_field_count mysql_num_fields
137 /** Represents a mysql result set
139 class MySQLresult : public SQL::Result
145 std::vector<std::string> colnames;
146 std::vector<SQL::Row> fieldlists;
148 MySQLresult(MYSQL_RES* res, int affected_rows) : err(SQL::SUCCESS), currentrow(0), rows(0)
150 if (affected_rows >= 1)
152 rows = affected_rows;
153 fieldlists.resize(rows);
155 unsigned int field_count = 0;
160 while ((row = mysql_fetch_row(res)))
162 if (fieldlists.size() < (unsigned int)rows+1)
164 fieldlists.resize(fieldlists.size()+1);
167 MYSQL_FIELD *fields = mysql_fetch_fields(res);
168 if(mysql_num_fields(res) == 0)
170 if (fields && mysql_num_fields(res))
173 while (field_count < mysql_num_fields(res))
175 std::string a = (fields[field_count].name ? fields[field_count].name : "");
176 if (row[field_count])
177 fieldlists[n].push_back(SQL::Field(row[field_count]));
179 fieldlists[n].push_back(SQL::Field());
180 colnames.push_back(a);
187 mysql_free_result(res);
191 MySQLresult(SQL::Error& e) : err(e)
196 int Rows() CXX11_OVERRIDE
201 void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
203 result.assign(colnames.begin(), colnames.end());
206 bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
208 for (size_t i = 0; i < colnames.size(); ++i)
210 if (colnames[i] == column)
219 SQL::Field GetValue(int row, int column)
221 if ((row >= 0) && (row < rows) && (column >= 0) && (column < (int)fieldlists[row].size()))
223 return fieldlists[row][column];
228 bool GetRow(SQL::Row& result) CXX11_OVERRIDE
230 if (currentrow < rows)
232 result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
244 /** Represents a connection to a mysql database
246 class SQLConnection : public SQL::Provider
249 reference<ConfigTag> config;
253 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
254 SQLConnection(Module* p, ConfigTag* tag) : SQL::Provider(p, "SQL/" + tag->getString("id")),
255 config(tag), connection(NULL)
264 // This method connects to the database using the credentials supplied to the constructor, and returns
265 // true upon success.
268 unsigned int timeout = 1;
269 connection = mysql_init(connection);
270 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
271 std::string host = config->getString("host");
272 std::string user = config->getString("user");
273 std::string pass = config->getString("pass");
274 std::string dbname = config->getString("name");
275 unsigned int port = config->getUInt("port", 3306);
276 bool rv = mysql_real_connect(connection, host.c_str(), user.c_str(), pass.c_str(), dbname.c_str(), port, NULL, 0);
280 // Enable character set settings
281 std::string charset = config->getString("charset");
282 if ((!charset.empty()) && (mysql_set_character_set(connection, charset.c_str())))
283 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not set character set to \"%s\"", charset.c_str());
285 std::string initquery;
286 if (config->readString("initialquery", initquery))
288 mysql_query(connection,initquery.c_str());
295 return (ModuleSQL*)(Module*)creator;
298 MySQLresult* DoBlockingQuery(const std::string& query)
301 /* Parse the command string and dispatch it to mysql */
302 if (CheckConnection() && !mysql_real_query(connection, query.data(), query.length()))
304 /* Successfull query */
305 MYSQL_RES* res = mysql_use_result(connection);
306 unsigned long rows = mysql_affected_rows(connection);
307 return new MySQLresult(res, rows);
311 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
312 * possible error numbers and error messages */
313 SQL::Error e(SQL::QREPLY_FAIL, InspIRCd::Format("%u: %s", mysql_errno(connection), mysql_error(connection)));
314 return new MySQLresult(e);
318 bool CheckConnection()
320 if (!connection || mysql_ping(connection) != 0)
325 std::string GetError()
327 return mysql_error(connection);
332 mysql_close(connection);
335 void Submit(SQL::Query* q, const std::string& qs) CXX11_OVERRIDE
337 Parent()->Dispatcher->LockQueue();
338 Parent()->qq.push_back(QQueueItem(q, qs, this));
339 Parent()->Dispatcher->UnlockQueueWakeup();
342 void Submit(SQL::Query* call, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
345 unsigned int param = 0;
346 for(std::string::size_type i = 0; i < q.length(); i++)
352 if (param < p.size())
354 std::string parm = p[param++];
355 // In the worst case, each character may need to be encoded as using two bytes,
356 // and one byte is the terminating null
357 std::vector<char> buffer(parm.length() * 2 + 1);
359 // The return value of mysql_real_escape_string() is the length of the encoded string,
360 // not including the terminating null
361 unsigned long escapedsize = mysql_real_escape_string(connection, &buffer[0], parm.c_str(), parm.length());
362 res.append(&buffer[0], escapedsize);
369 void Submit(SQL::Query* call, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
372 for(std::string::size_type i = 0; i < q.length(); i++)
380 while (i < q.length() && isalnum(q[i]))
381 field.push_back(q[i++]);
384 SQL::ParamMap::const_iterator it = p.find(field);
387 std::string parm = it->second;
389 std::vector<char> buffer(parm.length() * 2 + 1);
390 unsigned long escapedsize = mysql_escape_string(&buffer[0], parm.c_str(), parm.length());
391 res.append(&buffer[0], escapedsize);
399 ModuleSQL::ModuleSQL()
404 void ModuleSQL::init()
406 Dispatcher = new DispatcherThread(this);
407 ServerInstance->Threads.Start(Dispatcher);
410 ModuleSQL::~ModuleSQL()
415 Dispatcher->OnNotify();
418 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
424 void ModuleSQL::ReadConfig(ConfigStatus& status)
427 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
428 for(ConfigIter i = tags.first; i != tags.second; i++)
430 if (!stdalgo::string::equalsci(i->second->getString("module"), "mysql"))
432 std::string id = i->second->getString("id");
433 ConnMap::iterator curr = connections.find(id);
434 if (curr == connections.end())
436 SQLConnection* conn = new SQLConnection(this, i->second);
437 conns.insert(std::make_pair(id, conn));
438 ServerInstance->Modules->AddService(*conn);
443 connections.erase(curr);
447 // now clean up the deleted databases
448 Dispatcher->LockQueue();
449 SQL::Error err(SQL::BAD_DBID);
450 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
452 ServerInstance->Modules->DelService(*i->second);
453 // it might be running a query on this database. Wait for that to complete
454 i->second->lock.Lock();
455 i->second->lock.Unlock();
456 // now remove all active queries to this DB
457 for (size_t j = qq.size(); j > 0; j--)
460 if (qq[k].c == i->second)
462 qq[k].q->OnError(err);
464 qq.erase(qq.begin() + k);
467 // finally, nuke the connection
470 Dispatcher->UnlockQueue();
471 connections.swap(conns);
474 void ModuleSQL::OnUnloadModule(Module* mod)
476 SQL::Error err(SQL::BAD_DBID);
477 Dispatcher->LockQueue();
478 unsigned int i = qq.size();
482 if (qq[i].q->creator == mod)
486 // need to wait until the query is done
487 // (the result will be discarded)
488 qq[i].c->lock.Lock();
489 qq[i].c->lock.Unlock();
491 qq[i].q->OnError(err);
493 qq.erase(qq.begin() + i);
496 Dispatcher->UnlockQueue();
497 // clean up any result queue entries
498 Dispatcher->OnNotify();
501 Version ModuleSQL::GetVersion()
503 return Version("Provides MySQL support", VF_VENDOR);
506 void DispatcherThread::Run()
509 while (!this->GetExitFlag())
511 if (!Parent->qq.empty())
513 QQueueItem i = Parent->qq.front();
516 MySQLresult* res = i.c->DoBlockingQuery(i.query);
520 * At this point, the main thread could be working on:
521 * Rehash - delete i.c out from under us. We don't care about that.
522 * UnloadModule - delete i.q and the qq item. Need to avoid reporting results.
526 if (!Parent->qq.empty() && Parent->qq.front().q == i.q)
528 Parent->qq.pop_front();
529 Parent->rq.push_back(RQueueItem(i.q, res));
534 // UnloadModule ate the query
540 /* We know the queue is empty, we can safely hang this thread until
543 this->WaitForQueue();
549 void DispatcherThread::OnNotify()
551 // this could unlock during the dispatch, but OnResult isn't expected to take that long
553 for(ResultQueue::iterator i = Parent->rq.begin(); i != Parent->rq.end(); i++)
555 MySQLresult* res = i->r;
556 if (res->err.code == SQL::SUCCESS)
557 i->q->OnResult(*res);
559 i->q->OnError(res->err);
567 MODULE_INIT(ModuleSQL)