1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
26 #include "helperfuncs.h"
29 /* VERSION 2 API: With nonblocking (threaded) requests */
31 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
32 /* $CompileFlags: `mysql_config --include` */
33 /* $LinkerFlags: `mysql_config --libs_r` `perl extra/mysql_rpath.pl` */
35 /* THE NONBLOCKING MYSQL API!
37 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
38 * that instead, you should thread your program. This is what i've done here to allow for
39 * asyncronous SQL requests via mysql. The way this works is as follows:
41 * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
42 * using a queue with priorities. There is a mutex on either end which prevents two threads
43 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
44 * worker thread wakes up, and checks if there is a request at the head of its queue.
45 * If there is, it processes this request, blocking the worker thread but leaving the ircd
46 * thread to go about its business as usual. During this period, the ircd thread is able
47 * to insert futher pending requests into the queue.
49 * Once the processing of a request is complete, it is removed from the incoming queue to
50 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
51 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
52 * connection ID through the connection.
54 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
55 * of the queue, and sends it on its way to the original calling module.
57 * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
58 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
59 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
60 * however, if we were to call a module's OnRequest even from within a thread which was not the
61 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
62 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
63 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
64 * gauranteed threadsafe!)
66 * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
73 extern InspIRCd* ServerInstance;
74 typedef std::map<std::string, SQLConnection*> ConnMap;
76 static Module* SQLModule = NULL;
77 static Notifier* MessagePipe = NULL;
81 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
82 #define mysql_field_count mysql_num_fields
85 typedef std::deque<SQLresult*> ResultQueue;
87 class QueryQueue : public classbase
90 typedef std::deque<SQLrequest> ReqDeque;
92 ReqDeque priority; /* The priority queue */
93 ReqDeque normal; /* The 'normal' queue */
94 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
102 void push(const SQLrequest &q)
104 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
107 priority.push_back(q);
114 if((which == PRI) && priority.size())
116 priority.pop_front();
118 else if((which == NOR) && normal.size())
126 /* Silently do nothing if there was no element to pop() */
134 return priority.front();
136 return normal.front();
141 return priority.front();
147 return normal.front();
150 /* This will probably result in a segfault,
151 * but the caller should have checked totalsize()
152 * first so..meh - moron :p
155 return priority.front();
159 std::pair<int, int> size()
161 return std::make_pair(priority.size(), normal.size());
166 return priority.size() + normal.size();
169 void PurgeModule(Module* mod)
171 DoPurgeModule(mod, priority);
172 DoPurgeModule(mod, normal);
176 void DoPurgeModule(Module* mod, ReqDeque& q)
178 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
180 if(iter->GetSource() == mod)
182 if(iter->id == front().id)
184 /* It's the currently active query.. :x */
185 iter->SetSource(NULL);
189 /* It hasn't been executed yet..just remove it */
190 iter = q.erase(iter);
197 /* A mutex to wrap around queue accesses */
198 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
200 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
202 class MySQLresult : public SQLresult
205 //std::vector<std::map<std::string,std::string> > results;
206 std::vector<std::string> colnames;
207 std::vector<SQLfieldList> fieldlists;
208 SQLfieldMap* fieldmap;
209 SQLfieldMap fieldmap2;
210 SQLfieldList emptyfieldlist;
215 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL)
217 /* A number of affected rows from from mysql_affected_rows.
219 log(DEBUG,"Created new MySQLresult of non-error type");
222 if (affected_rows >= 1)
224 rows = affected_rows;
225 fieldlists.resize(rows);
227 unsigned int field_count = 0;
232 while ((row = mysql_fetch_row(res)))
234 if (fieldlists.size() < (unsigned int)rows+1)
236 fieldlists.resize(fieldlists.size()+1);
239 MYSQL_FIELD *fields = mysql_fetch_fields(res);
240 if(mysql_num_fields(res) == 0)
242 if (fields && mysql_num_fields(res))
245 while (field_count < mysql_num_fields(res))
247 std::string a = (fields[field_count].name ? fields[field_count].name : "");
248 std::string b = (row[field_count] ? row[field_count] : "");
249 SQLfield sqlf(b, !row[field_count]);
250 colnames.push_back(a);
251 fieldlists[n].push_back(sqlf);
252 log(DEBUG,"Inc field count to %d",field_count+1);
259 mysql_free_result(res);
261 log(DEBUG, "Created new MySQL result; %d rows, %d columns", rows, colnames.size());
264 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0)
268 log(DEBUG,"Created new MySQLresult of error type");
282 return colnames.size();
285 virtual std::string ColName(int column)
287 if (column < (int)colnames.size())
289 return colnames[column];
293 throw SQLbadColName();
298 virtual int ColNum(const std::string &column)
300 for (unsigned int i = 0; i < colnames.size(); i++)
302 if (column == colnames[i])
305 throw SQLbadColName();
309 virtual SQLfield GetValue(int row, int column)
311 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
313 return fieldlists[row][column];
316 log(DEBUG,"Danger will robinson, we don't have row %d, column %d!", row, column);
317 throw SQLbadColName();
319 /* XXX: We never actually get here because of the throw */
320 return SQLfield("",true);
323 virtual SQLfieldList& GetRow()
325 if (currentrow < rows)
326 return fieldlists[currentrow];
328 return emptyfieldlist;
331 virtual SQLfieldMap& GetRowMap()
335 if (currentrow < rows)
337 for (int i = 0; i < cols; i++)
339 fieldmap2.insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
347 virtual SQLfieldList* GetRowPtr()
349 SQLfieldList* fieldlist = new SQLfieldList();
351 if (currentrow < rows)
353 for (int i = 0; i < Rows(); i++)
355 fieldlist->push_back(fieldlists[currentrow][i]);
361 virtual SQLfieldMap* GetRowMapPtr()
363 fieldmap = new SQLfieldMap();
365 if (currentrow < rows)
367 for (int i = 0; i < cols; i++)
369 fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
377 virtual void Free(SQLfieldMap* fm)
382 virtual void Free(SQLfieldList* fl)
384 /* XXX: Yes, this is SUPPOSED to do nothing, we
385 * dont want to free our fieldlist until we
386 * destruct the object. Unlike the pgsql module,
387 * we only have the one.
395 void NotifyMainThread(SQLConnection* connection_with_new_result);
397 class SQLConnection : public classbase
408 std::map<std::string,std::string> thisrow;
417 // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
418 // MYSQL struct, but does not connect yet.
419 SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, const std::string &myid)
421 this->Enabled = true;
422 this->host = thishost;
423 this->user = thisuser;
424 this->pass = thispass;
429 // This method connects to the database using the credentials supplied to the constructor, and returns
430 // true upon success.
433 unsigned int timeout = 1;
434 mysql_init(&connection);
435 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
436 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
439 void DoLeadingQuery()
441 if (!CheckConnection())
444 /* Parse the command string and dispatch it to mysql */
445 SQLrequest& req = queue.front();
446 log(DEBUG,"DO QUERY: %s",req.query.q.c_str());
448 /* Pointer to the buffer we screw around with substitution in */
451 /* Pointer to the current end of query, where we append new stuff */
454 /* Total length of the unescaped parameters */
455 unsigned long paramlen;
457 /* Total length of query, used for binary-safety in mysql_real_query */
458 unsigned long querylength = 0;
462 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
464 paramlen += i->size();
467 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
468 * sizeofquery + (totalparamlength*2) + 1
470 * The +1 is for null-terminating the string for mysql_real_escape_string
473 query = new char[req.query.q.length() + (paramlen*2)];
476 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
477 * the parameters into it...
480 for(unsigned long i = 0; i < req.query.q.length(); i++)
482 if(req.query.q[i] == '?')
484 /* We found a place to substitute..what fun.
485 * use mysql calls to escape and write the
486 * escaped string onto the end of our query buffer,
487 * then we "just" need to make sure queryend is
488 * pointing at the right place.
490 if(req.query.p.size())
492 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
495 req.query.p.pop_front();
499 log(DEBUG, "Found a substitution location but no parameter to substitute :|");
505 *queryend = req.query.q[i];
513 log(DEBUG, "Attempting to dispatch query: %s", query);
515 pthread_mutex_lock(&queue_mutex);
517 pthread_mutex_unlock(&queue_mutex);
519 log(DEBUG,"REQUEST ID: %d",req.id);
521 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
523 /* Successfull query */
524 res = mysql_use_result(&connection);
525 unsigned long rows = mysql_affected_rows(&connection);
526 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
527 r->dbid = this->GetID();
528 r->query = req.query.q;
529 /* Put this new result onto the results queue.
530 * XXX: Remember to mutex the queue!
532 pthread_mutex_lock(&results_mutex);
534 pthread_mutex_unlock(&results_mutex);
538 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
539 * possible error numbers and error messages */
540 log(DEBUG,"SQL ERROR: %s",mysql_error(&connection));
541 SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
542 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
543 r->dbid = this->GetID();
544 r->query = req.query.q;
546 pthread_mutex_lock(&results_mutex);
548 pthread_mutex_unlock(&results_mutex);
551 /* Now signal the main thread that we've got a result to process.
552 * Pass them this connection id as what to examine
555 NotifyMainThread(this);
558 bool ConnectionLost()
561 return (mysql_ping(&connection) != 0);
566 bool CheckConnection()
568 if (ConnectionLost()) {
574 std::string GetError()
576 return mysql_error(&connection);
579 const std::string& GetID()
584 std::string GetHost()
589 void SetEnable(bool Enable)
603 void ConnectDatabases(Server* Srv)
605 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
607 i->second->SetEnable(true);
608 if (i->second->Connect())
610 Srv->Log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
614 Srv->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
615 i->second->SetEnable(false);
621 void LoadDatabases(ConfigReader* ThisConf, Server* Srv)
623 Srv->Log(DEFAULT,"SQL: Loading database settings");
625 Srv->Log(DEBUG,"Cleared connections");
626 for (int j =0; j < ThisConf->Enumerate("database"); j++)
628 std::string db = ThisConf->ReadValue("database","name",j);
629 std::string user = ThisConf->ReadValue("database","username",j);
630 std::string pass = ThisConf->ReadValue("database","password",j);
631 std::string host = ThisConf->ReadValue("database","hostname",j);
632 std::string id = ThisConf->ReadValue("database","id",j);
633 Srv->Log(DEBUG,"Read database settings");
634 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
636 SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
637 Srv->Log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
638 Connections[id] = ThisSQL;
639 Srv->Log(DEBUG,"Pushed back connection");
642 ConnectDatabases(Srv);
645 void NotifyMainThread(SQLConnection* connection_with_new_result)
647 /* Here we write() to the socket the main thread has open
648 * and we connect()ed back to before our thread became active.
649 * The main thread is using a nonblocking socket tied into
650 * the socket engine, so they wont block and they'll receive
651 * nearly instant notification. Because we're in a seperate
652 * thread, we can just use standard connect(), and we can
653 * block if we like. We just send the connection id of the
656 log(DEBUG,"Notify of result on connection: %s",connection_with_new_result->GetID().c_str());
657 if (send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0) < 1) // add one for null terminator
659 log(DEBUG,"Error writing to QueueFD: %s",strerror(errno));
661 log(DEBUG,"Sent it on its way via fd=%d",QueueFD);
664 void* DispatcherThread(void* arg);
666 class Notifier : public InspSocket
674 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
675 Notifier(Server* S) : InspSocket("127.0.0.1", 0, true, 3000), Srv(S)
677 uslen = sizeof(sock_us);
678 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
680 throw ModuleException("Could not create random listening port on localhost");
684 Notifier(int newfd, char* ip, Server* S) : InspSocket(newfd, ip), Srv(S)
686 log(DEBUG,"Constructor of new socket");
689 /* Using getsockname and ntohs, we can determine which port number we were allocated */
692 return ntohs(sock_us.sin_port);
695 virtual int OnIncomingConnection(int newsock, char* ip)
697 log(DEBUG,"Inbound connection on fd %d!",newsock);
698 Notifier* n = new Notifier(newsock, ip, Srv);
703 virtual bool OnDataReady()
705 log(DEBUG,"Inbound data!");
706 char* data = this->Read();
707 ConnMap::iterator iter;
711 log(DEBUG,"Looking for connection %s",data);
712 /* We expect to be sent a null terminated string */
713 if((iter = Connections.find(data)) != Connections.end())
715 log(DEBUG,"Found it!");
717 /* Lock the mutex, send back the data */
718 pthread_mutex_lock(&results_mutex);
719 ResultQueue::iterator n = iter->second->rq.begin();
721 iter->second->rq.pop_front();
722 pthread_mutex_unlock(&results_mutex);
731 class ModuleSQL : public Module
736 pthread_t Dispatcher;
739 void Implements(char* List)
741 List[I_OnRehash] = List[I_OnRequest] = 1;
744 unsigned long NewID()
751 char* OnRequest(Request* request)
753 if(strcmp(SQLREQID, request->GetId()) == 0)
755 SQLrequest* req = (SQLrequest*)request;
758 pthread_mutex_lock(&queue_mutex);
760 ConnMap::iterator iter;
762 char* returnval = NULL;
764 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());
766 if((iter = Connections.find(req->dbid)) != Connections.end())
769 iter->second->queue.push(*req);
770 returnval = SQLSUCCESS;
774 req->error.Id(BAD_DBID);
777 pthread_mutex_unlock(&queue_mutex);
783 log(DEBUG, "Got unsupported API version string: %s", request->GetId());
788 ModuleSQL(Server* Me)
792 Conf = new ConfigReader();
796 MessagePipe = new Notifier(Srv);
797 Srv->AddSocket(MessagePipe);
798 log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
800 pthread_attr_t attribs;
801 pthread_attr_init(&attribs);
802 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
803 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
805 throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
807 if (!Srv->PublishFeature("SQL", this))
809 /* Tell worker thread to exit NOW */
811 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
820 virtual void OnRehash(const std::string ¶meter)
822 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
825 virtual Version GetVersion()
827 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
832 void* DispatcherThread(void* arg)
834 log(DEBUG,"Starting Dispatcher thread, mysql version %d",mysql_get_client_version());
835 ModuleSQL* thismodule = (ModuleSQL*)arg;
836 LoadDatabases(thismodule->Conf, thismodule->Srv);
838 /* Connect back to the Notifier */
840 if ((QueueFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
842 /* crap, we're out of sockets... */
843 log(DEBUG,"QueueFD cant be created");
847 log(DEBUG,"Initialize QueueFD to %d",QueueFD);
851 inet_aton("127.0.0.1", &ia);
852 addr.sin_family = AF_INET;
854 addr.sin_port = htons(MessagePipe->GetPort());
856 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
858 /* wtf, we cant connect to it, but we just created it! */
859 log(DEBUG,"QueueFD cant connect!");
863 log(DEBUG,"Connect QUEUE FD");
867 SQLConnection* conn = NULL;
868 /* XXX: Lock here for safety */
869 pthread_mutex_lock(&queue_mutex);
870 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
872 if (i->second->queue.totalsize())
878 pthread_mutex_unlock(&queue_mutex);
881 /* Theres an item! */
884 log(DEBUG,"Process Leading query");
885 conn->DoLeadingQuery();
888 pthread_mutex_lock(&queue_mutex);
890 pthread_mutex_unlock(&queue_mutex);
901 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
903 class ModuleSQLFactory : public ModuleFactory
914 virtual Module * CreateModule(Server* Me)
916 return new ModuleSQL(Me);
922 extern "C" void * init_module( void )
924 return new ModuleSQLFactory;