drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
json_server.cc
1/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2 * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 *
4 * Copyright (C) 2011-2013 Stewart Smith, Henrik Ingo, Mohit Srivastava
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
23
24#include <config.h>
25
26#include <unistd.h>
27#include <fcntl.h>
28
29#include <drizzled/module/module.h>
30#include <drizzled/module/context.h>
31#include <drizzled/plugin/plugin.h>
32#include <drizzled/plugin.h>
33#include <drizzled/plugin/daemon.h>
34#include <drizzled/sys_var.h>
35#include <drizzled/gettext.h>
36#include <drizzled/error.h>
37#include <drizzled/session.h>
38#include <drizzled/internal/my_sys.h>
39#include <drizzled/internal/m_string.h>
40#include <algorithm>
41#include <iostream>
42#include <boost/program_options.hpp>
44#include <drizzled/constrained_value.h>
45#include <evhttp.h>
46#include <event.h>
47#include <drizzled/execute.h>
48#include <drizzled/sql/result_set.h>
49#include <drizzled/diagnostics_area.h>
50#include <drizzled/plugin/listen.h>
51#include <drizzled/plugin/client.h>
52#include <drizzled/catalog/local.h>
53#include <drizzled/current_session.h>
54
55#include <drizzled/pthread_globals.h>
56#include <boost/bind/bind.hpp>
57#include <memory>
58#include <stdexcept>
59
60
61#include <drizzled/version.h>
62#include <json/json.h>
63#include <plugin/json_server/db_access.h>
64#include <plugin/json_server/http_handler.h>
65#include <plugin/json_server/http_server.h>
66#include <plugin/json_server/ddl/schema.h>
67#include <plugin/json_server/json_handler.h>
68
69namespace po= boost::program_options;
70using namespace drizzled;
71using namespace std;
72
73namespace drizzle_plugin
74{
75namespace json_server
76{
77static const string DEFAULT_SCHEMA = "test";
78static const string DEFAULT_TABLE = "";
79static const string JSON_SERVER_VERSION = "0.3";
80static const uint32_t DEFAULT_MAX_THREADS= 32;
81static const bool DEFAULT_ALLOW_DROP_TABLE=false;
82bool allow_drop_table;
83string default_schema;
84string default_table;
85uint32_t max_threads;
86uint32_t clone_max_threads=0;
87bool updateSchema(Session *, set_var* var);
88bool updateTable(Session *, set_var* var);
89void updateMaxThreads(Session *, sql_var_t);
90static port_constraint port;
91
92static in_port_t getPort(void)
93{
94 return port.get();
95}
96
97extern "C" void process_request(struct evhttp_request *req, void* );
98extern "C" void process_root_request(struct evhttp_request *req, void* );
99extern "C" void process_api01_version_req(struct evhttp_request *req, void* );
100extern "C" void process_version_req(struct evhttp_request *req, void* );
101extern "C" void process_sql_req(struct evhttp_request *req, void* );
102extern "C" void process_json_req(struct evhttp_request *req, void* );
103extern "C" void process_json_ddl_schema_create_req(struct evhttp_request *req, void* );
104extern "C" void process_json_ddl_schema_drop_req(struct evhttp_request *req, void* );
105extern "C" void process_request(struct evhttp_request *req, void* )
106{
107 struct evbuffer *buf = evbuffer_new();
108 if (buf == NULL) return;
109 evbuffer_add_printf(buf, "Requested: %s\n", evhttp_request_uri(req));
110 evhttp_send_reply(req, HTTP_OK, "OK", buf);
111}
112
113extern "C" void process_root_request(struct evhttp_request *req, void* )
114{
115 struct evbuffer *buf = evbuffer_new();
116 if (buf == NULL) return;
117
118 std::string output;
119
120 output.append("<html><head><title>JSON DATABASE interface demo</title></head>\n"
121 "<body>\n"
122 "<script lang=\"javascript\">\n"
123 "function to_table(obj) {\n"
124 " var str = '<table border=\"1\">';\n"
125 "for (var r=0; r< obj.length; r++) {\n"
126 " str+='<tr>';\n"
127 " for (var c=0; c < obj[r].length; c++) {\n"
128 " str+= '<td>' + obj[r][c] + '</td>';\n"
129 " }\n"
130 " str+='</tr>';\n"
131 "}\n"
132 "str+='</table>';\n"
133 "return str;\n"
134 "}\n"
135 "function to_table_from_json(obj) {\n"
136 " var str = '<table border=\"1\">';\n"
137 "for (var r=0; r< obj.length; r++) {\n"
138 " str+='<tr>';\n"
139 " str+='<td>' + obj[r]['_id'] + '</td>';\n"
140 " str+='<td>' + JSON.stringify(obj[r]['document']) + '</td>';\n"
141 " str+='</tr>';\n"
142 "}\n"
143 "str+='</table>';\n"
144 "return str;\n"
145 "}\n"
146 "function run_sql_query()\n"
147 "{\n"
148 "var url = window.location;\n"
149 "var query= document.getElementById(\"sql_query\").value;\n"
150 "var xmlHttp = new XMLHttpRequest();\n"
151 "xmlHttp.onreadystatechange = function () {\n"
152 "document.getElementById(\"responseText\").value = xmlHttp.responseText;\n"
153 "if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n"
154 "var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n"
155 "document.getElementById( \"resultset\").innerHTML= to_table(info.result_set);\n"
156 "}\n"
157 "};\n"
158 "xmlHttp.open(\"POST\", url + \"sql\", true);\n"
159 "xmlHttp.send(query);\n"
160 "}\n"
161 "\n\n"
162 "function run_json_query()\n"
163 "{\n"
164//"alert('run_json_query');"
165 "var url = window.location;\n"
166 "var method= document.getElementById(\"json_method\").value;\n"
167 "var query= document.getElementById(\"json_query\").value;\n"
168 "var schema= document.getElementById(\"schema\").value;\n"
169 "var table= document.getElementById(\"table\").value;\n"
170 "var xmlHttp = new XMLHttpRequest();\n"
171 "xmlHttp.onreadystatechange = function () {\n"
172//"alert(xmlHttp.responseText);"
173 "document.getElementById(\"responseText\").value = xmlHttp.responseText;\n"
174 "if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n"
175 "var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n"
176 "document.getElementById( \"resultset\").innerHTML= to_table_from_json(info.result_set);\n"
177 "}\n"
178 "};\n"
179 "if( method == \"POST\" ) {\n"
180 "xmlHttp.open(method, url + \"json?schema=\" + schema + \"&table=\" + table, true);\n"
181 "xmlHttp.send(query);\n"
182 "} else {\n"
183 "xmlHttp.open(method, url + \"json?schema=\" + schema + \"&table=\" + table + \"&query=\" + encodeURIComponent(query), true);\n"
184 "xmlHttp.send();\n"
185 "}\n"
186 "}\n"
187 "\n\n"
188 "function update_version()\n"
189 "{drizzle_version(window.location);}\n\n"
190 "function drizzle_version($url)\n"
191 "{\n"
192 "var xmlHttp = new XMLHttpRequest();\n"
193 "xmlHttp.onreadystatechange = function () {\n"
194 "if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n"
195 "var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n"
196 "document.getElementById( \"drizzleversion\").innerHTML= info.version;\n"
197 "}\n"
198 "};\n"
199 "xmlHttp.open(\"GET\", $url + \"version\", true);\n"
200 "xmlHttp.send(null);\n"
201 "}\n"
202 "</script>\n"
203 "<p>Drizzle server version: <a id=\"drizzleversion\"></a></p>\n"
204 "<p><textarea rows=\"3\" cols=\"80\" id=\"sql_query\">\n"
205 "SELECT * from DATA_DICTIONARY.GLOBAL_STATUS;\n"
206 "</textarea>\n"
207 "<button type=\"button\" onclick=\"run_sql_query();\">Execute SQL Query</button>\n"
208 "</p><p>\n"
209 "<textarea rows=\"8\" cols=\"80\" id=\"json_query\">\n"
210 "{\"_id\" : 1}\n"
211 "</textarea>\n"
212 "<button type=\"button\" onclick=\"run_json_query();\">Execute JSON Query</button>\n"
213 "<br />\n"
214 "<select id=\"json_method\"><option value=\"GET\">GET</option>"
215 "<option value=\"POST\">POST</option>"
216 "<option value=\"PUT\">PUT</option>"
217 "<option value=\"DELETE\">DELETE</option></select>"
218 "<script lang=\"javascript\">document.write(window.location);</script>json?schema=\n"
219 "<input type=\"text\" id=\"schema\" value=\"test\"/>"
220 "&amp;table=<input type=\"text\" id=\"table\" value=\"jsonkv\"/>\n"
221 "</p><hr />\n<div id=\"resultset\"></div>\n"
222 "<hr /><p><textarea rows=\"12\" cols=\"80\" id=\"responseText\" ></textarea></p>"
223 "<script lang=\"javascript\">update_version(); run_sql_query();</script>\n"
224 "</body></html>\n");
225
226 evbuffer_add(buf, output.c_str(), output.length());
227 evhttp_send_reply(req, HTTP_OK, "OK", buf);
228}
229
230extern "C" void process_api01_version_req(struct evhttp_request *req, void* )
231{
232 struct evbuffer *buf = evbuffer_new();
233 if (buf == NULL) return;
234
235 Json::Value root;
236 root["version"]= ::drizzled::version();
237
238 Json::StyledWriter writer;
239 std::string output= writer.write(root);
240
241 evbuffer_add(buf, output.c_str(), output.length());
242 evhttp_send_reply(req, HTTP_OK, "OK", buf);
243}
244
245extern "C" void process_version_req(struct evhttp_request *req, void* )
246{
247 struct evbuffer *buf = evbuffer_new();
248 if (buf == NULL) return;
249
250 Json::Value root;
251 root["version"]= ::drizzled::version();
252 root["json_server_version"]=JSON_SERVER_VERSION;
253
254 Json::StyledWriter writer;
255 std::string output= writer.write(root);
256
257 evbuffer_add(buf, output.c_str(), output.length());
258 evhttp_send_reply(req, HTTP_OK, "OK", buf);
259}
260
261extern "C" void process_sql_req(struct evhttp_request *req, void* )
262{
263 struct evbuffer *buf = evbuffer_new();
264 if (buf == NULL) return;
265
266 std::string input;
267 char buffer[1024];
268 int l=0;
269 do {
270 l= evbuffer_remove(req->input_buffer, buffer, 1024);
271 input.append(buffer, l);
272 }while(l);
273
274 drizzled::Session::shared_ptr _session= drizzled::Session::make_shared(drizzled::plugin::Listen::getNullClient(),
275 drizzled::catalog::local());
276 drizzled::identifier::user::mptr user_id= identifier::User::make_shared();
277 user_id->setUser("");
278 _session->setUser(user_id);
279 _session->set_schema("test");
280
281 drizzled::Execute execute(*(_session.get()), true);
282
283 drizzled::sql::ResultSet result_set(1);
284
285 /* Execute wraps the SQL to run within a transaction */
286 execute.run(input, result_set);
287 drizzled::sql::Exception exception= result_set.getException();
288
289 drizzled::error_t err= exception.getErrorCode();
290
291 Json::Value root;
292 root["sqlstate"]= exception.getSQLState();
293
294 if ((err != drizzled::EE_OK) && (err != drizzled::ER_EMPTY_QUERY))
295 {
296 root["error_message"]= exception.getErrorMessage();
297 root["error_code"]= exception.getErrorCode();
298 root["schema"]= "test";
299 }
300
301 while (result_set.next())
302 {
303 Json::Value json_row;
304 for (size_t x= 0; x < result_set.getMetaData().getColumnCount(); x++)
305 {
306 if (not result_set.isNull(x))
307 {
308 json_row[static_cast<Json::Value::ArrayIndex>(x)]= result_set.getString(x);
309 }
310 }
311 root["result_set"].append(json_row);
312 }
313
314 root["query"]= input;
315
316 Json::StyledWriter writer;
317 std::string output= writer.write(root);
318
319 evbuffer_add(buf, output.c_str(), output.length());
320 evhttp_send_reply(req, HTTP_OK, "OK", buf);
321}
322
323
331extern "C" void process_json_req(struct evhttp_request *req, void* )
332{
333 Json::Value json_out;
334 Json::Value json_in;
335 std::string sql;
336 const char* schema;
337 const char* table;
338
339 HttpHandler* handler = new HttpHandler(json_out,json_in,req);
340 if(!handler->handleRequest())
341 {
342 if(!handler->validate(default_schema,default_table,allow_drop_table))
343 {
344 json_in= handler->getInputJson();
345 schema=handler->getSchema();
346 table=handler->getTable();
347
348 DBAccess* dbAccess = new DBAccess(json_in,json_out,req->type,schema,table);
349 dbAccess->execute();
350 json_out= dbAccess->getOutputJson();
351 delete(dbAccess);
352 }
353 else
354 {
355 json_out= handler->getOutputJson();
356 }
357 }
358 else
359 {
360 json_out= handler->getOutputJson();
361 }
362 handler->setOutputJson(json_out);
363 handler->sendResponse();
364 delete(handler);
365}
366
373
374extern "C" void process_json_ddl_schema_create_req(struct evhttp_request *req, void* )
375{
376 drizzled::Session::shared_ptr _session= drizzled::Session::make_shared(drizzled::plugin::Listen::getNullClient(),
377 drizzled::catalog::local());
378 drizzled::identifier::user::mptr user_id= identifier::User::make_shared();
379 _session->main_da().reset_diagnostics_area();
380 setCurrentSession(_session.get());
381
382 std::string query;
383 std::string db_name;
384 std::string output;
385 Json::Value json_out;
386 Json::Value json_in;
387 const char *http_response_text="OK";
388 int http_response_code=HTTP_OK;
389
390 JsonErrorArea _json_error;
391 JsonHandler* _json_handler = new JsonHandler();
392
393 _json_handler->generate_input_json(req,_json_error);
394 if(!_json_error.is_jsonerror())
395 {
396 json_in = _json_handler->get_input_json();
397 db_name=json_in["query"]["name"].asString();
398 Schema *_schema = new Schema(_session.get(),db_name);
399 _schema->createSchema();
400 if(_session->main_da().is_error())
401 {
402 _json_error.set_error(JsonErrorArea::ER_SQL,_session->main_da().sql_errno(),_session->main_da().message());
403 }
404 }
405 _json_handler->generate_output_query(_json_error);
406 output = _json_handler->get_output_query();
407 struct evbuffer *buf = evbuffer_new();
408 if(buf == NULL)
409 {
410 return;
411 }
412 evbuffer_add(buf, output.c_str(), output.length());
413 evhttp_send_reply( req, http_response_code, http_response_text, buf);
414}
415
421extern "C" void process_json_ddl_schema_drop_req(struct evhttp_request *req, void* )
422{
423 drizzled::Session::shared_ptr _session= drizzled::Session::make_shared(drizzled::plugin::Listen::getNullClient(),
424 drizzled::catalog::local());
425 drizzled::identifier::user::mptr user_id= identifier::User::make_shared();
426 _session->main_da().reset_diagnostics_area();
427 setCurrentSession(_session.get());
428
429 std::string query;
430 std::string db_name;
431 std::string output;
432 Json::Value json_out;
433 Json::Value json_in;
434 const char *http_response_text="OK";
435 int http_response_code=HTTP_OK;
436
437 JsonErrorArea _json_error;
438 JsonHandler* _json_handler = new JsonHandler();
439
440 _json_handler->generate_input_json(req,_json_error);
441 if(!_json_error.is_jsonerror())
442 {
443 json_in = _json_handler->get_input_json();
444
445 db_name=json_in["query"]["name"].asString();
446 Schema *_schema = new Schema(_session.get(),db_name);
447 _schema->dropSchema();
448 if(_session->main_da().is_error())
449 {
450 _json_error.set_error(JsonErrorArea::ER_SQL,_session->main_da().sql_errno(),_session->main_da().message());
451 }
452 }
453 _json_handler->generate_output_query(_json_error);
454 output = _json_handler->get_output_query();
455 struct evbuffer *buf = evbuffer_new();
456 if(buf == NULL)
457 {
458 return;
459 }
460 evbuffer_add(buf, output.c_str(), output.length());
461 evhttp_send_reply( req, http_response_code, http_response_text, buf);
462}
463
464
465static void shutdown_event(int, short, void *arg)
466{
467 struct event_base *base= (struct event_base *)arg;
468 event_base_loopbreak(base);
469}
470
471static void run(struct event_base *base)
472{
473 internal::my_thread_init();
474
475 event_base_dispatch(base);
476}
477
478
479// Owns one file descriptor; closes it on destruction.
480class FileDescriptor
481{
482public:
483 explicit FileDescriptor(int fd= -1) : fd_(fd) { }
484 ~FileDescriptor() { reset(); }
485
486 int get() const { return fd_; }
487 bool valid() const { return fd_ != -1; }
488
489 void reset(int fd= -1)
490 {
491 if (fd_ != -1)
492 close(fd_);
493 fd_= fd;
494 }
495
496 // Hand the fd to a caller that will close it itself.
497 int release()
498 {
499 int fd= fd_;
500 fd_= -1;
501 return fd;
502 }
503
504private:
505 int fd_;
506 FileDescriptor(const FileDescriptor&);
507 FileDescriptor& operator=(const FileDescriptor&);
508};
509
510// Self-pipe used to wake the worker event loops at shutdown.
511class WakeupPipe
512{
513public:
514 WakeupPipe()
515 {
516 int fds[2];
517 if (pipe(fds) < 0)
518 {
519 sql_perror("pipe");
520 return;
521 }
522 read_.reset(fds[0]);
523 write_.reset(fds[1]);
524 }
525
526 bool valid() const { return read_.valid(); }
527 int read_fd() const { return read_.get(); }
528
529 bool makeReadNonBlocking()
530 {
531 int flags= fcntl(read_.get(), F_GETFL, 0);
532 if (flags < 0)
533 {
534 sql_perror("fcntl:F_GETFL");
535 return false;
536 }
537 if (fcntl(read_.get(), F_SETFL, flags | O_NONBLOCK) < 0)
538 {
539 sql_perror("fcntl:F_SETFL");
540 return false;
541 }
542 return true;
543 }
544
545 // Wake every loop watching the read end. The byte is never read
546 // back out, so the descriptor stays readable for all of them.
547 void signal()
548 {
549 char buffer= 4;
550 if (write(write_.get(), &buffer, 1) != 1)
551 sql_perror("write");
552 }
553
554private:
555 FileDescriptor read_;
556 FileDescriptor write_;
557};
558
559typedef std::shared_ptr<struct event_base> event_base_ptr;
560typedef std::shared_ptr<struct evhttp> evhttp_ptr;
561
562// One worker: its own event base, HTTP listener, wakeup event and
563// dispatch thread. Construction either yields a fully wired worker or
564// throws; the shared_ptr deleters release libevent's objects, in
565// reverse order, with no explicit free.
566class JsonWorker
567{
568public:
569 JsonWorker(int listen_fd, int wakeup_fd)
570 {
571 struct event_base *base= event_init();
572 if (base == NULL)
573 throw std::runtime_error("event_init() failed");
574 base_.reset(base, event_base_free);
575
576 struct evhttp *httpd= evhttp_new(base);
577 if (httpd == NULL)
578 throw std::runtime_error("evhttp_new() failed");
579 httpd_.reset(httpd, evhttp_free);
580
581 // evhttp_free() closes the accept socket, so each worker takes its
582 // own descriptor for the shared listening socket.
583 FileDescriptor accept_fd(dup(listen_fd));
584 if (not accept_fd.valid())
585 throw std::runtime_error("dup() of listening socket failed");
586
587 if (evhttp_accept_socket(httpd, accept_fd.get()) != 0)
588 throw std::runtime_error("evhttp_accept_socket() failed");
589 accept_fd.release();
590
591 registerRoutes(httpd);
592
593 event_set(&wakeup_event_, wakeup_fd, EV_READ | EV_PERSIST,
594 shutdown_event, base);
595 event_base_set(base, &wakeup_event_);
596 if (event_add(&wakeup_event_, NULL) < 0)
597 throw std::runtime_error("event_add() failed");
598 }
599
600 ~JsonWorker()
601 {
602 event_del(&wakeup_event_);
603 }
604
605 void start()
606 {
607 thread_.reset(new boost::thread(boost::bind(&run, base_.get())));
608 }
609
610 void join()
611 {
612 if (thread_)
613 thread_->join();
614 }
615
616private:
617 static void registerRoutes(struct evhttp *httpd)
618 {
619 evhttp_set_cb(httpd, "/", process_root_request, NULL);
620 evhttp_set_cb(httpd, "/0.1/version", process_api01_version_req, NULL);
621 evhttp_set_cb(httpd, "/0.2/version", process_api01_version_req, NULL);
622 evhttp_set_cb(httpd, "/0.3/version", process_version_req, NULL);
623 evhttp_set_cb(httpd, "/0.3/sql", process_sql_req, NULL);
624 evhttp_set_cb(httpd, "/0.3/json", process_json_req, NULL);
625 evhttp_set_cb(httpd, "/latest/version", process_version_req, NULL);
626 evhttp_set_cb(httpd, "/latest/sql", process_sql_req, NULL);
627 evhttp_set_cb(httpd, "/latest/json", process_json_req, NULL);
628 evhttp_set_cb(httpd, "/version", process_version_req, NULL);
629 evhttp_set_cb(httpd, "/sql", process_sql_req, NULL);
630 evhttp_set_cb(httpd, "/json", process_json_req, NULL);
631 evhttp_set_cb(httpd, "/json/ddl/schema/create",
633 evhttp_set_cb(httpd, "/json/ddl/schema/drop",
635 }
636
637 // Declared so the deleters run httpd before base.
638 event_base_ptr base_;
639 evhttp_ptr httpd_;
640 struct event wakeup_event_;
641 drizzled::thread_ptr thread_;
642
643 JsonWorker(const JsonWorker&);
644 JsonWorker& operator=(const JsonWorker&);
645};
646
647typedef std::shared_ptr<JsonWorker> JsonWorkerPtr;
648
649class JsonServer : public drizzled::plugin::Daemon , public HTTPServer
650{
651public:
652 JsonServer(in_port_t port_arg) :
653 drizzled::plugin::Daemon("json_server"),
654 _port(port_arg)
655 { }
656
657 bool init()
658 {
659 if (not wakeup_pipe_.valid())
660 return false;
661 if (not wakeup_pipe_.makeReadNonBlocking())
662 return false;
663
664 int fd= BindSocket("0.0.0.0", getPort());
665 if (fd == -1)
666 {
667 sql_perror("evhttp_bind_socket()");
668 return false;
669 }
670 listen_fd_.reset(fd);
671
672 return createThreads(max_threads);
673 }
674
675 bool createThreads(uint32_t num_threads)
676 {
677 for (uint32_t i= 0; i < num_threads; i++)
678 {
679 try
680 {
681 JsonWorkerPtr worker(new JsonWorker(listen_fd_.get(),
682 wakeup_pipe_.read_fd()));
683 worker->start();
684 workers_.push_back(worker);
685 }
686 catch (const std::exception &e)
687 {
688 errmsg_printf(error::ERROR,
689 _("json_server: could not start worker: %s"),
690 e.what());
691 return false;
692 }
693 }
694 return true;
695 }
696
697 ~JsonServer()
698 {
699 // Wake every worker loop, then wait for the threads to exit before
700 // the workers_ destructor tears their event bases down.
701 wakeup_pipe_.signal();
702 for (size_t i= 0; i < workers_.size(); i++)
703 workers_[i]->join();
704 }
705
706private:
707 in_port_t _port;
708 WakeupPipe wakeup_pipe_;
709 FileDescriptor listen_fd_;
710 std::vector<JsonWorkerPtr> workers_;
711};
712JsonServer *server=NULL;
713
714void updateMaxThreads(Session *, sql_var_t)
715{
716 if (clone_max_threads < max_threads)
717 {
718 if(server->createThreads(max_threads - clone_max_threads))
719 {
720 clone_max_threads=max_threads;//success
721 }
722 else
723 {
724 //char buf[100];
725 //sprintf(buf,"json_server unable to create more threads");
726 //my_error(ER_SCRIPT,MYF(0),buf);
727 errmsg_printf(error::ERROR,_("json_server unable to create more threads"));
728 }
729 }
730 else
731 {
732 max_threads = clone_max_threads;
733 //my_error(ER_SCRIPT,MYF(0),"json_server_max_threads cannot be smaller than previous configured value");
734 errmsg_printf(error::ERROR, _("json_server_max_threadscannot be smaller than previous configured value"));//error
735 }
736}
737
738
739bool updateSchema(Session *, set_var* var)
740{
741 if (not var->value->str_value.empty())
742 {
743 std::string new_schema(var->value->str_value.data());
744 default_schema=new_schema;
745 return false; //success
746 }
747 errmsg_printf(error::ERROR, _("json_server_schema cannot be NULL"));
748 return true; // error
749}
750
751bool updateTable(Session *, set_var* var)
752{
753 std::string new_table(var->value->str_value.data());
754 default_table=new_table;
755 return false;
756}
757
758static int json_server_init(drizzled::module::Context &context)
759{
760
761 server = new JsonServer(port);
762 context.add(server);
763 context.registerVariable(new sys_var_constrained_value_readonly<in_port_t>("port", port));
764 context.registerVariable(new sys_var_std_string("schema", default_schema, NULL, &updateSchema));
765 context.registerVariable(new sys_var_std_string("table", default_table, NULL, &updateTable));
766 context.registerVariable(new sys_var_bool_ptr("allow_drop_table", &allow_drop_table));
767 context.registerVariable(new sys_var_uint32_t_ptr("max_threads",&max_threads,&updateMaxThreads));
768
769 clone_max_threads=max_threads;
770
771
772 if (server and not server->init())
773 {
774 return -2;
775 }
776
777 return bool(server) ? 0 : 1;
778}
779
780static void init_options(drizzled::module::option_context &context)
781{
782 context("port",
783 po::value<port_constraint>(&port)->default_value(8086),
784 _("Port number to use for connection or 0 for default (port 8086) "));
785 context("schema",
786 po::value<string>(&default_schema)->default_value(DEFAULT_SCHEMA),
787 _("Schema in use by json server"));
788 context("table",
789 po::value<string>(&default_table)->default_value(DEFAULT_TABLE),
790 _("table in use by json server"));
791 context("allow_drop_table",
792 po::value<bool>(&allow_drop_table)->default_value(DEFAULT_ALLOW_DROP_TABLE),
793 _("allow to drop table"));
794 context("max_threads",
795 po::value<uint32_t>(&max_threads)->default_value(DEFAULT_MAX_THREADS),
796 _("Maximum threads in use by json server"));
797
798}
799
800} /* namespace json_server */
801} /* namespace drizzle_plugin */
802
803DRIZZLE_DECLARE_PLUGIN
804{
805 DRIZZLE_VERSION_ID,
806 "json_server",
807 "0.3",
808 "Stewart Smith, Henrik Ingo, Mohit Srivastava",
809 N_("JSON HTTP interface"),
810 PLUGIN_LICENSE_GPL,
811 drizzle_plugin::json_server::json_server_init,
812 NULL,
813 drizzle_plugin::json_server::init_options
814}
815DRIZZLE_DECLARE_PLUGIN_END;
const Json::Value getOutputJson() const
Definition db_access.h:72
int BindSocket(const char *address, int port)
void set_error(enum_error_type type, drizzled::error_t sql_errno_arg, const char *message_arg)
String str_value
Definition item.h:109
void set_schema(const std::string &)
Definition session.cc:1514
static plugin::Client * getNullClient()
Definition listen.cc:184
Defines the event_t struct that encapsulates an event.
void process_json_req(struct evhttp_request *req, void *)
void process_json_ddl_schema_drop_req(struct evhttp_request *req, void *)
void process_json_ddl_schema_create_req(struct evhttp_request *req, void *)
TODO: Rename this file - func.h is stupid.
STL namespace.
An Proxy Wrapper around boost::program_options::variables_map.