]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Fix MySQL crash on module unload with empty query queue
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* Stop mysql wanting to use long long */
15 #define NO_CLIENT_LONG_LONG
16
17 #include "inspircd.h"
18 #include <mysql.h>
19 #include "sql.h"
20
21 #ifdef WINDOWS
22 #pragma comment(lib, "mysqlclient.lib")
23 #endif
24
25 /* VERSION 3 API: With nonblocking (threaded) requests */
26
27 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
28 /* $CompileFlags: exec("mysql_config --include") */
29 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
30 /* $ModDep: m_sqlv2.h */
31
32 /* THE NONBLOCKING MYSQL API!
33  *
34  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
35  * that instead, you should thread your program. This is what i've done here to allow for
36  * asyncronous SQL requests via mysql. The way this works is as follows:
37  *
38  * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
39  * using a queue with priorities. There is a mutex on either end which prevents two threads
40  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
41  * worker thread wakes up, and checks if there is a request at the head of its queue.
42  * If there is, it processes this request, blocking the worker thread but leaving the ircd
43  * thread to go about its business as usual. During this period, the ircd thread is able
44  * to insert futher pending requests into the queue.
45  *
46  * Once the processing of a request is complete, it is removed from the incoming queue to
47  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
48  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
49  * connection ID through the connection.
50  *
51  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
52  * of the queue, and sends it on its way to the original calling module.
53  *
54  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
55  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
56  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
57  * however, if we were to call a module's OnRequest even from within a thread which was not the
58  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
59  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
60  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
61  * gauranteed threadsafe!)
62  *
63  * For a diagram of this system please see http://wiki.inspircd.org/Mysql2
64  */
65
66 class SQLConnection;
67 class MySQLresult;
68 class DispatcherThread;
69
70 struct QQueueItem
71 {
72         SQLQuery* q;
73         std::string query;
74         SQLConnection* c;
75         QQueueItem(SQLQuery* Q, const std::string& S, SQLConnection* C) : q(Q), query(S), c(C) {}
76 };
77
78 struct RQueueItem
79 {
80         SQLQuery* q;
81         MySQLresult* r;
82         RQueueItem(SQLQuery* Q, MySQLresult* R) : q(Q), r(R) {}
83 };
84
85 typedef std::map<std::string, SQLConnection*> ConnMap;
86 typedef std::deque<QQueueItem> QueryQueue;
87 typedef std::deque<RQueueItem> ResultQueue;
88
89 /** MySQL module
90  *  */
91 class ModuleSQL : public Module
92 {
93  public:
94         DispatcherThread* Dispatcher;
95         QueryQueue qq;       // MUST HOLD MUTEX
96         ResultQueue rq;      // MUST HOLD MUTEX
97         ConnMap connections; // main thread only
98
99         ModuleSQL();
100         void init();
101         ~ModuleSQL();
102         void OnRehash(User* user);
103         void OnUnloadModule(Module* mod);
104         Version GetVersion();
105 };
106
107 class DispatcherThread : public SocketThread
108 {
109  private:
110         ModuleSQL* const Parent;
111  public:
112         DispatcherThread(ModuleSQL* CreatorModule) : Parent(CreatorModule) { }
113         ~DispatcherThread() { }
114         virtual void Run();
115         virtual void OnNotify();
116 };
117
118 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
119 #define mysql_field_count mysql_num_fields
120 #endif
121
122 /** Represents a mysql result set
123  */
124 class MySQLresult : public SQLResult
125 {
126  public:
127         SQLerror err;
128         int currentrow;
129         int rows;
130         std::vector<std::string> colnames;
131         std::vector<SQLEntries> fieldlists;
132
133         MySQLresult(MYSQL_RES* res, int affected_rows) : err(SQL_NO_ERROR), currentrow(0), rows(0)
134         {
135                 if (affected_rows >= 1)
136                 {
137                         rows = affected_rows;
138                         fieldlists.resize(rows);
139                 }
140                 unsigned int field_count = 0;
141                 if (res)
142                 {
143                         MYSQL_ROW row;
144                         int n = 0;
145                         while ((row = mysql_fetch_row(res)))
146                         {
147                                 if (fieldlists.size() < (unsigned int)rows+1)
148                                 {
149                                         fieldlists.resize(fieldlists.size()+1);
150                                 }
151                                 field_count = 0;
152                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
153                                 if(mysql_num_fields(res) == 0)
154                                         break;
155                                 if (fields && mysql_num_fields(res))
156                                 {
157                                         colnames.clear();
158                                         while (field_count < mysql_num_fields(res))
159                                         {
160                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
161                                                 if (row[field_count])
162                                                         fieldlists[n].push_back(SQLEntry(row[field_count]));
163                                                 else
164                                                         fieldlists[n].push_back(SQLEntry());
165                                                 colnames.push_back(a);
166                                                 field_count++;
167                                         }
168                                         n++;
169                                 }
170                                 rows++;
171                         }
172                         mysql_free_result(res);
173                         res = NULL;
174                 }
175         }
176
177         MySQLresult(SQLerror& e) : err(e)
178         {
179
180         }
181
182         ~MySQLresult()
183         {
184         }
185
186         virtual int Rows()
187         {
188                 return rows;
189         }
190
191         virtual void GetCols(std::vector<std::string>& result)
192         {
193                 result.assign(colnames.begin(), colnames.end());
194         }
195
196         virtual SQLEntry GetValue(int row, int column)
197         {
198                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < (int)fieldlists[row].size()))
199                 {
200                         return fieldlists[row][column];
201                 }
202                 return SQLEntry();
203         }
204
205         virtual bool GetRow(SQLEntries& result)
206         {
207                 if (currentrow < rows)
208                 {
209                         result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
210                         currentrow++;
211                         return true;
212                 }
213                 else
214                 {
215                         result.clear();
216                         return false;
217                 }
218         }
219 };
220
221 /** Represents a connection to a mysql database
222  */
223 class SQLConnection : public SQLProvider
224 {
225  public:
226         reference<ConfigTag> config;
227         MYSQL *connection;
228         Mutex lock;
229
230         // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
231         SQLConnection(Module* p, ConfigTag* tag) : SQLProvider(p, "SQL/" + tag->getString("id")),
232                 config(tag), connection(NULL)
233         {
234         }
235
236         ~SQLConnection()
237         {
238                 Close();
239         }
240
241         // This method connects to the database using the credentials supplied to the constructor, and returns
242         // true upon success.
243         bool Connect()
244         {
245                 unsigned int timeout = 1;
246                 connection = mysql_init(connection);
247                 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
248                 std::string host = config->getString("host");
249                 std::string user = config->getString("user");
250                 std::string pass = config->getString("pass");
251                 std::string dbname = config->getString("name");
252                 int port = config->getInt("port");
253                 bool rv = mysql_real_connect(connection, host.c_str(), user.c_str(), pass.c_str(), dbname.c_str(), port, NULL, 0);
254                 if (!rv)
255                         return rv;
256                 std::string initquery;
257                 if (config->readString("initialquery", initquery))
258                 {
259                         mysql_query(connection,initquery.c_str());
260                 }
261                 return true;
262         }
263
264         ModuleSQL* Parent()
265         {
266                 return (ModuleSQL*)(Module*)creator;
267         }
268
269         MySQLresult* DoBlockingQuery(const std::string& query)
270         {
271
272                 /* Parse the command string and dispatch it to mysql */
273                 if (CheckConnection() && !mysql_real_query(connection, query.data(), query.length()))
274                 {
275                         /* Successfull query */
276                         MYSQL_RES* res = mysql_use_result(connection);
277                         unsigned long rows = mysql_affected_rows(connection);
278                         return new MySQLresult(res, rows);
279                 }
280                 else
281                 {
282                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
283                          * possible error numbers and error messages */
284                         SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
285                         return new MySQLresult(e);
286                 }
287         }
288
289         bool CheckConnection()
290         {
291                 if (!connection || mysql_ping(connection) != 0)
292                         return Connect();
293                 return true;
294         }
295
296         std::string GetError()
297         {
298                 return mysql_error(connection);
299         }
300
301         void Close()
302         {
303                 mysql_close(connection);
304         }
305
306         void submit(SQLQuery* q, const std::string& qs)
307         {
308                 Parent()->Dispatcher->LockQueue();
309                 Parent()->qq.push_back(QQueueItem(q, qs, this));
310                 Parent()->Dispatcher->UnlockQueueWakeup();
311         }
312
313         void submit(SQLQuery* call, const std::string& q, const ParamL& p)
314         {
315                 std::string res;
316                 unsigned int param = 0;
317                 for(std::string::size_type i = 0; i < q.length(); i++)
318                 {
319                         if (q[i] != '?')
320                                 res.push_back(q[i]);
321                         else
322                         {
323                                 if (param < p.size())
324                                 {
325                                         std::string parm = p[param++];
326                                         char buffer[MAXBUF];
327                                         mysql_escape_string(buffer, parm.c_str(), parm.length());
328 //                                      mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
329                                         res.append(buffer);
330                                 }
331                         }
332                 }
333                 submit(call, res);
334         }
335
336         void submit(SQLQuery* call, const std::string& q, const ParamM& p)
337         {
338                 std::string res;
339                 for(std::string::size_type i = 0; i < q.length(); i++)
340                 {
341                         if (q[i] != '$')
342                                 res.push_back(q[i]);
343                         else
344                         {
345                                 std::string field;
346                                 i++;
347                                 while (i < q.length() && isalpha(q[i]))
348                                         field.push_back(q[i++]);
349                                 i--;
350
351                                 ParamM::const_iterator it = p.find(field);
352                                 if (it != p.end())
353                                 {
354                                         std::string parm = it->second;
355                                         char buffer[MAXBUF];
356                                         mysql_escape_string(buffer, parm.c_str(), parm.length());
357                                         res.append(buffer);
358                                 }
359                         }
360                 }
361                 submit(call, res);
362         }
363 };
364
365 ModuleSQL::ModuleSQL()
366 {
367         Dispatcher = NULL;
368 }
369
370 void ModuleSQL::init()
371 {
372         Dispatcher = new DispatcherThread(this);
373         ServerInstance->Threads->Start(Dispatcher);
374
375         Implementation eventlist[] = { I_OnRehash, I_OnUnloadModule };
376         ServerInstance->Modules->Attach(eventlist, this, 2);
377
378         OnRehash(NULL);
379 }
380
381 ModuleSQL::~ModuleSQL()
382 {
383         if (Dispatcher)
384         {
385                 Dispatcher->join();
386                 Dispatcher->OnNotify();
387                 delete Dispatcher;
388         }
389         for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
390         {
391                 delete i->second;
392         }
393 }
394
395 void ModuleSQL::OnRehash(User* user)
396 {
397         ConnMap conns;
398         ConfigTagList tags = ServerInstance->Config->ConfTags("database");
399         for(ConfigIter i = tags.first; i != tags.second; i++)
400         {
401                 if (i->second->getString("module", "mysql") != "mysql")
402                         continue;
403                 std::string id = i->second->getString("id");
404                 ConnMap::iterator curr = connections.find(id);
405                 if (curr == connections.end())
406                 {
407                         SQLConnection* conn = new SQLConnection(this, i->second);
408                         conns.insert(std::make_pair(id, conn));
409                         ServerInstance->Modules->AddService(*conn);
410                 }
411                 else
412                 {
413                         conns.insert(*curr);
414                         connections.erase(curr);
415                 }
416         }
417
418         // now clean up the deleted databases
419         Dispatcher->LockQueue();
420         SQLerror err(SQL_BAD_DBID);
421         for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
422         {
423                 ServerInstance->Modules->DelService(*i->second);
424                 // it might be running a query on this database. Wait for that to complete
425                 i->second->lock.Lock();
426                 i->second->lock.Unlock();
427                 // now remove all active queries to this DB
428                 for(unsigned int j = qq.size() - 1; j >= 0; j--)
429                 {
430                         if (qq[j].c == i->second)
431                         {
432                                 qq[j].q->OnError(err);
433                                 delete qq[j].q;
434                                 qq.erase(qq.begin() + j);
435                         }
436                 }
437                 // finally, nuke the connection
438                 delete i->second;
439         }
440         Dispatcher->UnlockQueue();
441         connections.swap(conns);
442 }
443
444 void ModuleSQL::OnUnloadModule(Module* mod)
445 {
446         SQLerror err(SQL_BAD_DBID);
447         Dispatcher->LockQueue();
448         unsigned int i = qq.size();
449         while (i > 0)
450         {
451                 i--;
452                 if (qq[i].q->creator == mod)
453                 {
454                         if (i == 0)
455                         {
456                                 // need to wait until the query is done
457                                 // (the result will be discarded)
458                                 qq[i].c->lock.Lock();
459                                 qq[i].c->lock.Unlock();
460                         }
461                         qq[i].q->OnError(err);
462                         delete qq[i].q;
463                         qq.erase(qq.begin() + i);
464                 }
465         }
466         Dispatcher->UnlockQueue();
467         // clean up any result queue entries
468         Dispatcher->OnNotify();
469 }
470
471 Version ModuleSQL::GetVersion()
472 {
473         return Version("MySQL support", VF_VENDOR);
474 }
475
476 void DispatcherThread::Run()
477 {
478         this->LockQueue();
479         while (!this->GetExitFlag())
480         {
481                 if (!Parent->qq.empty())
482                 {
483                         QQueueItem i = Parent->qq.front();
484                         i.c->lock.Lock();
485                         this->UnlockQueue();
486                         MySQLresult* res = i.c->DoBlockingQuery(i.query);
487                         i.c->lock.Unlock();
488
489                         /*
490                          * At this point, the main thread could be working on:
491                          *  Rehash - delete i.c out from under us. We don't care about that.
492                          *  UnloadModule - delete i.q and the qq item. Need to avoid reporting results.
493                          */
494
495                         this->LockQueue();
496                         if (Parent->qq.front().q == i.q)
497                         {
498                                 Parent->qq.pop_front();
499                                 Parent->rq.push_back(RQueueItem(i.q, res));
500                                 NotifyParent();
501                         }
502                         else
503                         {
504                                 // UnloadModule ate the query
505                                 delete res;
506                         }
507                 }
508                 else
509                 {
510                         /* We know the queue is empty, we can safely hang this thread until
511                          * something happens
512                          */
513                         this->WaitForQueue();
514                 }
515         }
516         this->UnlockQueue();
517 }
518
519 void DispatcherThread::OnNotify()
520 {
521         // this could unlock during the dispatch, but OnResult isn't expected to take that long
522         this->LockQueue();
523         for(ResultQueue::iterator i = Parent->rq.begin(); i != Parent->rq.end(); i++)
524         {
525                 MySQLresult* res = i->r;
526                 if (res->err.id == SQL_NO_ERROR)
527                         i->q->OnResult(*res);
528                 else
529                         i->q->OnError(res->err);
530                 delete i->q;
531                 delete i->r;
532         }
533         Parent->rq.clear();
534         this->UnlockQueue();
535 }
536
537 MODULE_INIT(ModuleSQL)