1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
24 /* VERSION 2 API: With nonblocking (threaded) requests */
26 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
27 /* $CompileFlags: `mysql_config --include` */
28 /* $LinkerFlags: `mysql_config --libs_r` `perl extra/mysql_rpath.pl` */
29 /* $ModDep: m_sqlv2.h */
31 /* THE NONBLOCKING MYSQL API!
33 * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
34 * that instead, you should thread your program. This is what i've done here to allow for
35 * asyncronous SQL requests via mysql. The way this works is as follows:
37 * The module spawns a thread via pthreads, and performs its mysql queries in this thread,
38 * using a queue with priorities. There is a mutex on either end which prevents two threads
39 * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
40 * worker thread wakes up, and checks if there is a request at the head of its queue.
41 * If there is, it processes this request, blocking the worker thread but leaving the ircd
42 * thread to go about its business as usual. During this period, the ircd thread is able
43 * to insert futher pending requests into the queue.
45 * Once the processing of a request is complete, it is removed from the incoming queue to
46 * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
47 * ircd thread (via a loopback socket) of the fact a result is available, by sending the
48 * connection ID through the connection.
50 * The ircd thread then mutexes the queue once more, reads the outbound response off the head
51 * of the queue, and sends it on its way to the original calling module.
53 * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
54 * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
55 * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
56 * however, if we were to call a module's OnRequest even from within a thread which was not the
57 * one the module was originally instantiated upon, there is a chance of all hell breaking loose
58 * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
59 * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
60 * gauranteed threadsafe!)
62 * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2
70 typedef std::map<std::string, SQLConnection*> ConnMap;
72 static Module* SQLModule = NULL;
73 static Notifier* MessagePipe = NULL;
77 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
78 #define mysql_field_count mysql_num_fields
81 typedef std::deque<SQLresult*> ResultQueue;
83 /** Represents a mysql query queue
85 class QueryQueue : public classbase
88 typedef std::deque<SQLrequest> ReqDeque;
90 ReqDeque priority; /* The priority queue */
91 ReqDeque normal; /* The 'normal' queue */
92 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
100 void push(const SQLrequest &q)
103 priority.push_back(q);
110 if((which == PRI) && priority.size())
112 priority.pop_front();
114 else if((which == NOR) && normal.size())
122 /* Silently do nothing if there was no element to pop() */
130 return priority.front();
132 return normal.front();
137 return priority.front();
143 return normal.front();
146 /* This will probably result in a segfault,
147 * but the caller should have checked totalsize()
148 * first so..meh - moron :p
151 return priority.front();
155 std::pair<int, int> size()
157 return std::make_pair(priority.size(), normal.size());
162 return priority.size() + normal.size();
165 void PurgeModule(Module* mod)
167 DoPurgeModule(mod, priority);
168 DoPurgeModule(mod, normal);
172 void DoPurgeModule(Module* mod, ReqDeque& q)
174 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
176 if(iter->GetSource() == mod)
178 if(iter->id == front().id)
180 /* It's the currently active query.. :x */
181 iter->SetSource(NULL);
185 /* It hasn't been executed yet..just remove it */
186 iter = q.erase(iter);
193 /* A mutex to wrap around queue accesses */
194 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
196 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
198 pthread_mutex_t logging_mutex = PTHREAD_MUTEX_INITIALIZER;
200 /** Represents a mysql result set
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;
214 MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL)
216 /* A number of affected rows from from mysql_affected_rows.
220 if (affected_rows >= 1)
222 rows = affected_rows;
223 fieldlists.resize(rows);
225 unsigned int field_count = 0;
230 while ((row = mysql_fetch_row(res)))
232 if (fieldlists.size() < (unsigned int)rows+1)
234 fieldlists.resize(fieldlists.size()+1);
237 MYSQL_FIELD *fields = mysql_fetch_fields(res);
238 if(mysql_num_fields(res) == 0)
240 if (fields && mysql_num_fields(res))
243 while (field_count < mysql_num_fields(res))
245 std::string a = (fields[field_count].name ? fields[field_count].name : "");
246 std::string b = (row[field_count] ? row[field_count] : "");
247 SQLfield sqlf(b, !row[field_count]);
248 colnames.push_back(a);
249 fieldlists[n].push_back(sqlf);
256 mysql_free_result(res);
260 MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0)
277 return colnames.size();
280 virtual std::string ColName(int column)
282 if (column < (int)colnames.size())
284 return colnames[column];
288 throw SQLbadColName();
293 virtual int ColNum(const std::string &column)
295 for (unsigned int i = 0; i < colnames.size(); i++)
297 if (column == colnames[i])
300 throw SQLbadColName();
304 virtual SQLfield GetValue(int row, int column)
306 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
308 return fieldlists[row][column];
311 throw SQLbadColName();
313 /* XXX: We never actually get here because of the throw */
314 return SQLfield("",true);
317 virtual SQLfieldList& GetRow()
319 if (currentrow < rows)
320 return fieldlists[currentrow];
322 return emptyfieldlist;
325 virtual SQLfieldMap& GetRowMap()
329 if (currentrow < rows)
331 for (int i = 0; i < Cols(); i++)
333 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
341 virtual SQLfieldList* GetRowPtr()
343 SQLfieldList* fieldlist = new SQLfieldList();
345 if (currentrow < rows)
347 for (int i = 0; i < Rows(); i++)
349 fieldlist->push_back(fieldlists[currentrow][i]);
356 virtual SQLfieldMap* GetRowMapPtr()
358 fieldmap = new SQLfieldMap();
360 if (currentrow < rows)
362 for (int i = 0; i < Cols(); i++)
364 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
372 virtual void Free(SQLfieldMap* fm)
377 virtual void Free(SQLfieldList* fl)
385 void NotifyMainThread(SQLConnection* connection_with_new_result);
387 /** Represents a connection to a mysql database
389 class SQLConnection : public classbase
397 std::map<std::string,std::string> thisrow;
405 // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
406 SQLConnection(const SQLhost &hi) : host(hi), Enabled(true)
415 // This method connects to the database using the credentials supplied to the constructor, and returns
416 // true upon success.
419 unsigned int timeout = 1;
420 mysql_init(&connection);
421 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
422 return mysql_real_connect(&connection, host.host.c_str(), host.user.c_str(), host.pass.c_str(), host.name.c_str(), host.port, NULL, 0);
425 void DoLeadingQuery()
427 if (!CheckConnection())
430 /* Parse the command string and dispatch it to mysql */
431 SQLrequest& req = queue.front();
433 /* Pointer to the buffer we screw around with substitution in */
436 /* Pointer to the current end of query, where we append new stuff */
439 /* Total length of the unescaped parameters */
440 unsigned long paramlen;
442 /* Total length of query, used for binary-safety in mysql_real_query */
443 unsigned long querylength = 0;
447 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
449 paramlen += i->size();
452 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
453 * sizeofquery + (totalparamlength*2) + 1
455 * The +1 is for null-terminating the string for mysql_real_escape_string
458 query = new char[req.query.q.length() + (paramlen*2) + 1];
461 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
462 * the parameters into it...
465 for(unsigned long i = 0; i < req.query.q.length(); i++)
467 if(req.query.q[i] == '?')
469 /* We found a place to substitute..what fun.
470 * use mysql calls to escape and write the
471 * escaped string onto the end of our query buffer,
472 * then we "just" need to make sure queryend is
473 * pointing at the right place.
475 if(req.query.p.size())
477 unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
480 req.query.p.pop_front();
487 *queryend = req.query.q[i];
495 pthread_mutex_lock(&queue_mutex);
497 pthread_mutex_unlock(&queue_mutex);
499 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
501 /* Successfull query */
502 res = mysql_use_result(&connection);
503 unsigned long rows = mysql_affected_rows(&connection);
504 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id);
505 r->dbid = this->GetID();
506 r->query = req.query.q;
507 /* Put this new result onto the results queue.
508 * XXX: Remember to mutex the queue!
510 pthread_mutex_lock(&results_mutex);
512 pthread_mutex_unlock(&results_mutex);
516 /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
517 * possible error numbers and error messages */
518 SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection));
519 MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id);
520 r->dbid = this->GetID();
521 r->query = req.query.q;
523 pthread_mutex_lock(&results_mutex);
525 pthread_mutex_unlock(&results_mutex);
528 /* Now signal the main thread that we've got a result to process.
529 * Pass them this connection id as what to examine
534 NotifyMainThread(this);
537 bool ConnectionLost()
540 return (mysql_ping(&connection) != 0);
545 bool CheckConnection()
547 if (ConnectionLost()) {
553 std::string GetError()
555 return mysql_error(&connection);
558 const std::string& GetID()
563 std::string GetHost()
568 void SetEnable(bool Enable)
580 mysql_close(&connection);
587 void ConnectDatabases(InspIRCd* ServerInstance)
589 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
591 i->second->SetEnable(true);
592 if (!i->second->Connect())
595 pthread_mutex_lock(&logging_mutex);
596 ServerInstance->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
597 i->second->SetEnable(false);
598 pthread_mutex_unlock(&logging_mutex);
603 void ClearDatabases()
606 while ((i = Connections.begin()) != Connections.end())
608 Connections.erase(i);
613 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance)
616 for (int j =0; j < conf->Enumerate("database"); j++)
619 host.id = conf->ReadValue("database", "id", j);
620 host.host = conf->ReadValue("database", "hostname", j);
621 host.port = conf->ReadInteger("database", "port", j, true);
622 host.name = conf->ReadValue("database", "name", j);
623 host.user = conf->ReadValue("database", "username", j);
624 host.pass = conf->ReadValue("database", "password", j);
626 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
628 SQLConnection* ThisSQL = new SQLConnection(host);
629 Connections[host.id] = ThisSQL;
632 ConnectDatabases(ServerInstance);
635 void NotifyMainThread(SQLConnection* connection_with_new_result)
637 /* Here we write() to the socket the main thread has open
638 * and we connect()ed back to before our thread became active.
639 * The main thread is using a nonblocking socket tied into
640 * the socket engine, so they wont block and they'll receive
641 * nearly instant notification. Because we're in a seperate
642 * thread, we can just use standard connect(), and we can
643 * block if we like. We just send the connection id of the
646 send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0);
649 void* DispatcherThread(void* arg);
651 /** Used by m_mysql to notify one thread when the other has a result
653 class Notifier : public InspSocket
655 insp_sockaddr sock_us;
661 /* Create a socket on a random port. Let the tcp stack allocate us an available port */
663 Notifier(InspIRCd* SI) : InspSocket(SI, "::1", 0, true, 3000)
665 Notifier(InspIRCd* SI) : InspSocket(SI, "127.0.0.1", 0, true, 3000)
668 uslen = sizeof(sock_us);
669 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
671 throw ModuleException("Could not create random listening port on localhost");
675 Notifier(InspIRCd* SI, int newfd, char* ip) : InspSocket(SI, newfd, ip)
677 Instance->Log(DEBUG,"Constructor of new socket");
680 /* Using getsockname and ntohs, we can determine which port number we were allocated */
684 return ntohs(sock_us.sin6_port);
686 return ntohs(sock_us.sin_port);
690 virtual int OnIncomingConnection(int newsock, char* ip)
692 Instance->Log(DEBUG,"Inbound connection on fd %d!",newsock);
693 Notifier* n = new Notifier(this->Instance, newsock, ip);
694 n = n; /* Stop bitching at me, GCC */
698 virtual bool OnDataReady()
700 Instance->Log(DEBUG,"Inbound data!");
701 char* data = this->Read();
702 ConnMap::iterator iter;
706 Instance->Log(DEBUG,"Looking for connection %s",data);
707 /* We expect to be sent a null terminated string */
708 if((iter = Connections.find(data)) != Connections.end())
710 Instance->Log(DEBUG,"Found it!");
712 /* Lock the mutex, send back the data */
713 pthread_mutex_lock(&results_mutex);
714 ResultQueue::iterator n = iter->second->rq.begin();
716 iter->second->rq.pop_front();
717 pthread_mutex_unlock(&results_mutex);
728 class ModuleSQL : public Module
733 InspIRCd* PublicServerInstance;
734 pthread_t Dispatcher;
737 ModuleSQL(InspIRCd* Me)
740 ServerInstance->UseInterface("SQLutils");
742 Conf = new ConfigReader(ServerInstance);
743 PublicServerInstance = ServerInstance;
747 MessagePipe = new Notifier(ServerInstance);
748 ServerInstance->Log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
750 pthread_attr_t attribs;
751 pthread_attr_init(&attribs);
752 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
753 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
755 throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
758 if (!ServerInstance->PublishFeature("SQL", this))
760 /* Tell worker thread to exit NOW */
762 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
765 ServerInstance->PublishInterface("SQL", this);
773 ServerInstance->UnpublishInterface("SQL", this);
774 ServerInstance->UnpublishFeature("SQL");
775 ServerInstance->DoneWithInterface("SQLutils");
779 void Implements(char* List)
781 List[I_OnRehash] = List[I_OnRequest] = 1;
784 unsigned long NewID()
791 char* OnRequest(Request* request)
793 if(strcmp(SQLREQID, request->GetId()) == 0)
795 SQLrequest* req = (SQLrequest*)request;
798 pthread_mutex_lock(&queue_mutex);
800 ConnMap::iterator iter;
802 char* returnval = NULL;
804 ServerInstance->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());
806 if((iter = Connections.find(req->dbid)) != Connections.end())
809 iter->second->queue.push(*req);
810 returnval = SQLSUCCESS;
814 req->error.Id(BAD_DBID);
817 pthread_mutex_unlock(&queue_mutex);
823 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
828 virtual void OnRehash(userrec* user, const std::string ¶meter)
830 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
833 virtual Version GetVersion()
835 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
840 void* DispatcherThread(void* arg)
842 ModuleSQL* thismodule = (ModuleSQL*)arg;
843 LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance);
845 /* Connect back to the Notifier */
847 if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1)
849 /* crap, we're out of sockets... */
856 insp_aton("::1", &addr.sin6_addr);
857 addr.sin6_family = AF_FAMILY;
858 addr.sin6_port = htons(MessagePipe->GetPort());
861 insp_aton("127.0.0.1", &ia);
862 addr.sin_family = AF_FAMILY;
864 addr.sin_port = htons(MessagePipe->GetPort());
867 if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
869 /* wtf, we cant connect to it, but we just created it! */
875 SQLConnection* conn = NULL;
876 /* XXX: Lock here for safety */
877 pthread_mutex_lock(&queue_mutex);
878 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
880 if (i->second->queue.totalsize())
886 pthread_mutex_unlock(&queue_mutex);
889 /* Theres an item! */
892 conn->DoLeadingQuery();
895 pthread_mutex_lock(&queue_mutex);
897 pthread_mutex_unlock(&queue_mutex);
908 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
910 class ModuleSQLFactory : public ModuleFactory
921 virtual Module * CreateModule(InspIRCd* Me)
923 return new ModuleSQL(Me);
929 extern "C" void * init_module( void )
931 return new ModuleSQLFactory;