]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Huge ass comment about how this works
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 using namespace std;
18
19 #include <stdio.h>
20 #include <string>
21 #include <mysql.h>
22 #include <pthread.h>
23 #include "users.h"
24 #include "channels.h"
25 #include "modules.h"
26 #include "helperfuncs.h"
27 #include "m_sqlv2.h"
28
29 /* VERSION 2 API: With nonblocking (threaded) requests */
30
31 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
32 /* $CompileFlags: `mysql_config --include` */
33 /* $LinkerFlags: `mysql_config --libs_r` `perl ../mysql_rpath.pl` */
34
35
36 /* THE NONBLOCKING MYSQL API!
37  * 
38  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
39  * that instead, you should thread your program. This is what i've done here to allow for
40  * asyncronous SQL requests via mysql. The way this works is as follows:
41  *
42  * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
43  * using a queue with priorities. There is a mutex on either end which prevents two threads
44  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
45  * worker thread wakes up, and checks if there is a request at the head of its queue.
46  * If there is, it processes this request, blocking the worker thread but leaving the ircd
47  * thread to go about its business as usual. During this period, the ircd thread is able
48  * to insert futher pending requests into the queue.
49  *
50  * Once the processing of a request is complete, it is removed from the incoming queue to
51  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
52  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
53  * connection ID through the connection.
54  *
55  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
56  * of the queue, and sends it on its way to the original calling module.
57  *
58  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
59  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
60  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
61  * however, if we were to call a module's OnRequest even from within a thread which was not the
62  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
63  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
64  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
65  * gauranteed threadsafe!)
66  *
67  * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
68  */
69
70
71 class SQLConnection;
72 class Notifier;
73
74 extern InspIRCd* ServerInstance;
75 typedef std::map<std::string, SQLConnection*> ConnMap;
76 bool giveup = false;
77 static Module* SQLModule = NULL;
78 static Notifier* MessagePipe = NULL;
79 int QueueFD = -1;
80
81
82 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
83 #define mysql_field_count mysql_num_fields
84 #endif
85
86 typedef std::deque<SQLresult*> ResultQueue;
87
88 class QueryQueue : public classbase
89 {
90 private:
91         typedef std::deque<SQLrequest> ReqDeque;
92
93         ReqDeque priority;      /* The priority queue */
94         ReqDeque normal;        /* The 'normal' queue */
95         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
96
97 public:
98         QueryQueue()
99         : which(NON)
100         {
101         }
102
103         void push(const SQLrequest &q)
104         {
105                 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
106
107                 if(q.pri)
108                         priority.push_back(q);
109                 else
110                         normal.push_back(q);
111         }
112
113         void pop()
114         {
115                 if((which == PRI) && priority.size())
116                 {
117                         priority.pop_front();
118                 }
119                 else if((which == NOR) && normal.size())
120                 {
121                         normal.pop_front();
122                 }
123
124                 /* Reset this */
125                 which = NON;
126
127                 /* Silently do nothing if there was no element to pop() */
128         }
129
130         SQLrequest& front()
131         {
132                 switch(which)
133                 {
134                         case PRI:
135                                 return priority.front();
136                         case NOR:
137                                 return normal.front();
138                         default:
139                                 if(priority.size())
140                                 {
141                                         which = PRI;
142                                         return priority.front();
143                                 }
144
145                                 if(normal.size())
146                                 {
147                                         which = NOR;
148                                         return normal.front();
149                                 }
150
151                                 /* This will probably result in a segfault,
152                                  * but the caller should have checked totalsize()
153                                  * first so..meh - moron :p
154                                  */
155
156                                 return priority.front();
157                 }
158         }
159
160         std::pair<int, int> size()
161         {
162                 return std::make_pair(priority.size(), normal.size());
163         }
164
165         int totalsize()
166         {
167                 return priority.size() + normal.size();
168         }
169
170         void PurgeModule(Module* mod)
171         {
172                 DoPurgeModule(mod, priority);
173                 DoPurgeModule(mod, normal);
174         }
175
176 private:
177         void DoPurgeModule(Module* mod, ReqDeque& q)
178         {
179                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
180                 {
181                         if(iter->GetSource() == mod)
182                         {
183                                 if(iter->id == front().id)
184                                 {
185                                         /* It's the currently active query.. :x */
186                                         iter->SetSource(NULL);
187                                 }
188                                 else
189                                 {
190                                         /* It hasn't been executed yet..just remove it */
191                                         iter = q.erase(iter);
192                                 }
193                         }
194                 }
195         }
196 };
197
198 /* A mutex to wrap around queue accesses */
199 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
200
201 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
202
203 class MySQLresult : public SQLresult
204 {
205         int currentrow;
206         //std::vector<std::map<std::string,std::string> > results;
207         std::vector<std::string> colnames;
208         std::vector<SQLfieldList> fieldlists;
209         SQLfieldMap* fieldmap;
210         int rows;
211         int cols;
212  public:
213
214         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows) : SQLresult(self, to), currentrow(0), fieldmap(NULL)
215         {
216                 /* A number of affected rows from from mysql_affected_rows.
217                  */
218                 log(DEBUG,"Created new MySQLresult of non-error type");
219                 fieldlists.clear();
220                 rows = 0;
221                 if (affected_rows >= 1)
222                 {
223                         rows = affected_rows;
224                         fieldlists.resize(rows);
225                 }
226                 unsigned int field_count;
227                 if (res)
228                 {
229                         MYSQL_ROW row;
230                         int n = 0;
231                         while ((row = mysql_fetch_row(res)))
232                         {
233                                 if (fieldlists.size() < (unsigned int)rows+1)
234                                 {
235                                         fieldlists.resize(fieldlists.size()+1);
236                                 }
237                                 field_count = 0;
238                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
239                                 if(mysql_num_fields(res) == 0)
240                                         break;
241                                 if (fields && mysql_num_fields(res))
242                                 {
243                                         colnames.clear();
244                                         while (field_count < mysql_num_fields(res))
245                                         {
246                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
247                                                 std::string b = (row[field_count] ? row[field_count] : "");
248                                                 SQLfield sqlf(b, !row[field_count]);
249                                                 colnames.push_back(a);
250                                                 fieldlists[n].push_back(sqlf); 
251                                                 field_count++;
252                                         }
253                                         n++;
254                                 }
255                                 rows++;
256                         }
257                         cols = mysql_num_fields(res);
258                         mysql_free_result(res);
259                 }
260                 cols = field_count;
261                 log(DEBUG, "Created new MySQL result; %d rows, %d columns", rows, cols);
262         }
263
264         MySQLresult(Module* self, Module* to, SQLerror e) : SQLresult(self, to), currentrow(0)
265         {
266                 rows = 0;
267                 cols = 0;
268                 error = e;
269                 log(DEBUG,"Created new MySQLresult of error type");
270         }
271
272         ~MySQLresult()
273         {
274         }
275
276         virtual int Rows()
277         {
278                 return rows;
279         }
280
281         virtual int Cols()
282         {
283                 return cols;
284         }
285
286         virtual std::string ColName(int column)
287         {
288                 if (column < (int)colnames.size())
289                 {
290                         return colnames[column];
291                 }
292                 else
293                 {
294                         throw SQLbadColName();
295                 }
296                 return "";
297         }
298
299         virtual int ColNum(const std::string &column)
300         {
301                 for (unsigned int i = 0; i < colnames.size(); i++)
302                 {
303                         if (column == colnames[i])
304                                 return i;
305                 }
306                 throw SQLbadColName();
307                 return 0;
308         }
309
310         virtual SQLfield GetValue(int row, int column)
311         {
312                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < cols))
313                 {
314                         return fieldlists[row][column];
315                 }
316
317                 log(DEBUG,"Danger will robinson, we don't have row %d, column %d!", row, column);
318                 throw SQLbadColName();
319
320                 /* XXX: We never actually get here because of the throw */
321                 return SQLfield("",true);
322         }
323
324         virtual SQLfieldList& GetRow()
325         {
326                 return fieldlists[currentrow];
327         }
328
329         virtual SQLfieldMap& GetRowMap()
330         {
331                 fieldmap = new SQLfieldMap();
332                 
333                 for (int i = 0; i < cols; i++)
334                 {
335                         fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
336                 }
337                 currentrow++;
338
339                 return *fieldmap;
340         }
341
342         virtual SQLfieldList* GetRowPtr()
343         {
344                 return &fieldlists[currentrow++];
345         }
346
347         virtual SQLfieldMap* GetRowMapPtr()
348         {
349                 fieldmap = new SQLfieldMap();
350
351                 for (int i = 0; i < cols; i++)
352                 {
353                         fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
354                 }
355                 currentrow++;
356
357                 return fieldmap;
358         }
359
360         virtual void Free(SQLfieldMap* fm)
361         {
362                 delete fm;
363         }
364
365         virtual void Free(SQLfieldList* fl)
366         {
367                 /* XXX: Yes, this is SUPPOSED to do nothing, we
368                  * dont want to free our fieldlist until we
369                  * destruct the object. Unlike the pgsql module,
370                  * we only have the one.
371                  */
372         }
373 };
374
375 class SQLConnection;
376
377 void NotifyMainThread(SQLConnection* connection_with_new_result);
378
379 class SQLConnection : public classbase
380 {
381  protected:
382
383         MYSQL connection;
384         MYSQL_RES *res;
385         MYSQL_ROW row;
386         std::string host;
387         std::string user;
388         std::string pass;
389         std::string db;
390         std::map<std::string,std::string> thisrow;
391         bool Enabled;
392         std::string id;
393
394  public:
395
396         QueryQueue queue;
397         ResultQueue rq;
398
399         // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
400         // MYSQL struct, but does not connect yet.
401         SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, const std::string &myid)
402         {
403                 this->Enabled = true;
404                 this->host = thishost;
405                 this->user = thisuser;
406                 this->pass = thispass;
407                 this->db = thisdb;
408                 this->id = myid;
409         }
410
411         // This method connects to the database using the credentials supplied to the constructor, and returns
412         // true upon success.
413         bool Connect()
414         {
415                 unsigned int timeout = 1;
416                 mysql_init(&connection);
417                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
418                 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
419         }
420
421         void DoLeadingQuery()
422         {
423                 /* Parse the command string and dispatch it to mysql */
424                 SQLrequest& req = queue.front();
425                 log(DEBUG,"DO QUERY: %s",req.query.q.c_str());
426
427                 /* Pointer to the buffer we screw around with substitution in */
428                 char* query;
429
430                 /* Pointer to the current end of query, where we append new stuff */
431                 char* queryend;
432
433                 /* Total length of the unescaped parameters */
434                 unsigned long paramlen;
435
436                 /* Total length of query, used for binary-safety in mysql_real_query */
437                 unsigned long querylength = 0;
438
439                 paramlen = 0;
440
441                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
442                 {
443                         paramlen += i->size();
444                 }
445
446                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
447                  * sizeofquery + (totalparamlength*2) + 1
448                  *
449                  * The +1 is for null-terminating the string for mysql_real_escape_string
450                  */
451
452                 query = new char[req.query.q.length() + (paramlen*2)];
453                 queryend = query;
454
455                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
456                  * the parameters into it...
457                  */
458
459                 for(unsigned long i = 0; i < req.query.q.length(); i++)
460                 {
461                         if(req.query.q[i] == '?')
462                         {
463                                 /* We found a place to substitute..what fun.
464                                  * use mysql calls to escape and write the
465                                  * escaped string onto the end of our query buffer,
466                                  * then we "just" need to make sure queryend is
467                                  * pointing at the right place.
468                                  */
469                                 if(req.query.p.size())
470                                 {
471                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
472
473                                         queryend += len;
474                                         req.query.p.pop_front();
475                                 }
476                                 else
477                                 {
478                                         log(DEBUG, "Found a substitution location but no parameter to substitute :|");
479                                         break;
480                                 }
481                         }
482                         else
483                         {
484                                 *queryend = req.query.q[i];
485                                 queryend++;
486                         }
487                         querylength++;
488                 }
489
490                 *queryend = 0;
491
492                 log(DEBUG, "Attempting to dispatch query: %s", query);
493
494                 pthread_mutex_lock(&queue_mutex);
495                 req.query.q = query;
496                 pthread_mutex_unlock(&queue_mutex);
497
498                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
499                 {
500                         /* Successfull query */
501                         res = mysql_use_result(&connection);
502                         unsigned long rows = mysql_affected_rows(&connection);
503                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows);
504                         r->dbid = this->GetID();
505                         r->query = req.query.q;
506                         /* Put this new result onto the results queue.
507                          * XXX: Remember to mutex the queue!
508                          */
509                         pthread_mutex_lock(&results_mutex);
510                         rq.push_back(r);
511                         pthread_mutex_unlock(&results_mutex);
512                 }
513                 else
514                 {
515                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
516                          * possible error numbers and error messages */
517                         log(DEBUG,"SQL ERROR: %s",mysql_error(&connection));
518                         SQLerror e((SQLerrorNum)mysql_errno(&connection), mysql_error(&connection));
519                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e);
520                         r->dbid = this->GetID();
521                         r->query = req.query.q;
522
523                         pthread_mutex_lock(&results_mutex);
524                         rq.push_back(r);
525                         pthread_mutex_unlock(&results_mutex);
526                 }
527
528                 /* Now signal the main thread that we've got a result to process.
529                  * Pass them this connection id as what to examine
530                  */
531
532                 NotifyMainThread(this);
533         }
534
535         bool ConnectionLost()
536         {
537                 if (&connection) {
538                         return (mysql_ping(&connection) != 0);
539                 }
540                 else return false;
541         }
542
543         bool CheckConnection()
544         {
545                 if (ConnectionLost()) {
546                         return Connect();
547                 }
548                 else return true;
549         }
550
551         std::string GetError()
552         {
553                 return mysql_error(&connection);
554         }
555
556         const std::string& GetID()
557         {
558                 return id;
559         }
560
561         std::string GetHost()
562         {
563                 return host;
564         }
565
566         void SetEnable(bool Enable)
567         {
568                 Enabled = Enable;
569         }
570
571         bool IsEnabled()
572         {
573                 return Enabled;
574         }
575
576 };
577
578 ConnMap Connections;
579
580 void ConnectDatabases(Server* Srv)
581 {
582         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
583         {
584                 i->second->SetEnable(true);
585                 if (i->second->Connect())
586                 {
587                         Srv->Log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
588                 }
589                 else
590                 {
591                         Srv->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
592                         i->second->SetEnable(false);
593                 }
594         }
595 }
596
597
598 void LoadDatabases(ConfigReader* ThisConf, Server* Srv)
599 {
600         Srv->Log(DEFAULT,"SQL: Loading database settings");
601         Connections.clear();
602         Srv->Log(DEBUG,"Cleared connections");
603         for (int j =0; j < ThisConf->Enumerate("database"); j++)
604         {
605                 std::string db = ThisConf->ReadValue("database","name",j);
606                 std::string user = ThisConf->ReadValue("database","username",j);
607                 std::string pass = ThisConf->ReadValue("database","password",j);
608                 std::string host = ThisConf->ReadValue("database","hostname",j);
609                 std::string id = ThisConf->ReadValue("database","id",j);
610                 Srv->Log(DEBUG,"Read database settings");
611                 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
612                 {
613                         SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
614                         Srv->Log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
615                         Connections[id] = ThisSQL;
616                         Srv->Log(DEBUG,"Pushed back connection");
617                 }
618         }
619         ConnectDatabases(Srv);
620 }
621
622 void NotifyMainThread(SQLConnection* connection_with_new_result)
623 {
624         /* Here we write() to the socket the main thread has open
625          * and we connect()ed back to before our thread became active.
626          * The main thread is using a nonblocking socket tied into
627          * the socket engine, so they wont block and they'll receive
628          * nearly instant notification. Because we're in a seperate
629          * thread, we can just use standard connect(), and we can
630          * block if we like. We just send the connection id of the
631          * connection back.
632          */
633         log(DEBUG,"Notify of result on connection: %s",connection_with_new_result->GetID().c_str());
634         if (send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0) < 1) // add one for null terminator
635         {
636                 log(DEBUG,"Error writing to QueueFD: %s",strerror(errno));
637         }
638         log(DEBUG,"Sent it on its way via fd=%d",QueueFD);
639 }
640
641 void* DispatcherThread(void* arg);
642
643 class Notifier : public InspSocket
644 {
645         sockaddr_in sock_us;
646         socklen_t uslen;
647         Server* Srv;
648
649  public:
650
651         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
652         Notifier(Server* S) : InspSocket("127.0.0.1", 0, true, 3000), Srv(S)
653         {
654                 uslen = sizeof(sock_us);
655                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
656                 {
657                         throw ModuleException("Could not create random listening port on localhost");
658                 }
659         }
660
661         Notifier(int newfd, char* ip, Server* S) : InspSocket(newfd, ip), Srv(S)
662         {
663                 log(DEBUG,"Constructor of new socket");
664         }
665
666         /* Using getsockname and ntohs, we can determine which port number we were allocated */
667         int GetPort()
668         {
669                 return ntohs(sock_us.sin_port);
670         }
671
672         virtual int OnIncomingConnection(int newsock, char* ip)
673         {
674                 log(DEBUG,"Inbound connection on fd %d!",newsock);
675                 Notifier* n = new Notifier(newsock, ip, Srv);
676                 Srv->AddSocket(n);
677                 return true;
678         }
679
680         virtual bool OnDataReady()
681         {
682                 log(DEBUG,"Inbound data!");
683                 char* data = this->Read();
684                 ConnMap::iterator iter;
685
686                 if (data && *data)
687                 {
688                         log(DEBUG,"Looking for connection %s",data);
689                         /* We expect to be sent a null terminated string */
690                         if((iter = Connections.find(data)) != Connections.end())
691                         {
692                                 log(DEBUG,"Found it!");
693
694                                 /* Lock the mutex, send back the data */
695                                 pthread_mutex_lock(&results_mutex);
696                                 ResultQueue::iterator n = iter->second->rq.begin();
697                                 (*n)->Send();
698                                 iter->second->rq.pop_front();
699                                 pthread_mutex_unlock(&results_mutex);
700                                 return true;
701                         }
702                 }
703
704                 return false;
705         }
706 };
707
708 class ModuleSQL : public Module
709 {
710  public:
711         Server *Srv;
712         ConfigReader *Conf;
713         pthread_t Dispatcher;
714         int currid;
715
716         void Implements(char* List)
717         {
718                 List[I_OnRehash] = List[I_OnRequest] = 1;
719         }
720
721         unsigned long NewID()
722         {
723                 if (currid+1 == 0)
724                         currid++;
725                 return ++currid;
726         }
727
728         char* OnRequest(Request* request)
729         {
730                 if(strcmp(SQLREQID, request->GetData()) == 0)
731                 {
732                         SQLrequest* req = (SQLrequest*)request;
733
734                         /* XXX: Lock */
735                         pthread_mutex_lock(&queue_mutex);
736
737                         ConnMap::iterator iter;
738
739                         char* returnval = NULL;
740
741                         log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
742
743                         if((iter = Connections.find(req->dbid)) != Connections.end())
744                         {
745                                 iter->second->queue.push(*req);
746                                 req->id = NewID();
747                                 returnval = SQLSUCCESS;
748                         }
749                         else
750                         {
751                                 req->error.Id(BAD_DBID);
752                         }
753
754                         pthread_mutex_unlock(&queue_mutex);
755                         /* XXX: Unlock */
756
757                         return returnval;
758                 }
759
760                 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
761
762                 return NULL;
763         }
764
765         ModuleSQL(Server* Me)
766                 : Module::Module(Me)
767         {
768                 Srv = Me;
769                 Conf = new ConfigReader();
770                 currid = 0;
771                 SQLModule = this;
772
773                 MessagePipe = new Notifier(Srv);
774                 Srv->AddSocket(MessagePipe);
775                 log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
776                 
777                 pthread_attr_t attribs;
778                 pthread_attr_init(&attribs);
779                 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
780                 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
781                 {
782                         throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
783                 }
784                 Srv->PublishFeature("SQL", this);
785                 Srv->PublishFeature("MySQL", this);
786         }
787         
788         virtual ~ModuleSQL()
789         {
790                 DELETE(Conf);
791         }
792         
793         virtual void OnRehash(const std::string &parameter)
794         {
795                 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
796         }
797         
798         virtual Version GetVersion()
799         {
800                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
801         }
802         
803 };
804
805 void* DispatcherThread(void* arg)
806 {
807         log(DEBUG,"Starting Dispatcher thread, mysql version %d",mysql_get_client_version());
808         ModuleSQL* thismodule = (ModuleSQL*)arg;
809         LoadDatabases(thismodule->Conf, thismodule->Srv);
810
811         /* Connect back to the Notifier */
812
813         if ((QueueFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
814         {
815                 /* crap, we're out of sockets... */
816                 log(DEBUG,"QueueFD cant be created");
817                 return NULL;
818         }
819
820         log(DEBUG,"Initialize QueueFD to %d",QueueFD);
821
822         sockaddr_in addr;
823         in_addr ia;
824         inet_aton("127.0.0.1", &ia);
825         addr.sin_family = AF_INET;
826         addr.sin_addr = ia;
827         addr.sin_port = htons(MessagePipe->GetPort());
828
829         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
830         {
831                 /* wtf, we cant connect to it, but we just created it! */
832                 log(DEBUG,"QueueFD cant connect!");
833                 return NULL;
834         }
835
836         log(DEBUG,"Connect QUEUE FD");
837
838         while (!giveup)
839         {
840                 SQLConnection* conn = NULL;
841                 /* XXX: Lock here for safety */
842                 pthread_mutex_lock(&queue_mutex);
843                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
844                 {
845                         if (i->second->queue.totalsize())
846                         {
847                                 conn = i->second;
848                                 break;
849                         }
850                 }
851                 pthread_mutex_unlock(&queue_mutex);
852                 /* XXX: Unlock */
853
854                 /* Theres an item! */
855                 if (conn)
856                 {
857                         log(DEBUG,"Process Leading query");
858                         conn->DoLeadingQuery();
859
860                         /* XXX: Lock */
861                         pthread_mutex_lock(&queue_mutex);
862                         conn->queue.pop();
863                         pthread_mutex_unlock(&queue_mutex);
864                         /* XXX: Unlock */
865                 }
866
867                 usleep(50);
868         }
869
870         return NULL;
871 }
872
873
874 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
875
876 class ModuleSQLFactory : public ModuleFactory
877 {
878  public:
879         ModuleSQLFactory()
880         {
881         }
882         
883         ~ModuleSQLFactory()
884         {
885         }
886         
887         virtual Module * CreateModule(Server* Me)
888         {
889                 return new ModuleSQL(Me);
890         }
891         
892 };
893
894
895 extern "C" void * init_module( void )
896 {
897         return new ModuleSQLFactory;
898 }
899