~drizzle-trunk/drizzle/development

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Copyright (C) 2011 Stewart Smith
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */


#include <config.h>

#include <unistd.h>
#include <fcntl.h>

#include <drizzled/module/module.h>
#include <drizzled/module/context.h>
#include <drizzled/plugin/plugin.h>
#include <drizzled/plugin.h>
#include <drizzled/plugin/daemon.h>
#include <drizzled/sys_var.h>
#include <drizzled/gettext.h>
#include <drizzled/error.h>
#include <drizzled/query_id.h>
#include <drizzled/session.h>
#include <drizzled/internal/my_sys.h>
#include <drizzled/internal/m_string.h>
#include <algorithm>
#include <iostream>
#include <boost/program_options.hpp>
#include <drizzled/module/option_map.h>
#include <drizzled/constrained_value.h>
#include <evhttp.h>
#include <event.h>
#include <drizzled/execute.h>
#include <drizzled/sql/result_set.h>

#include <drizzled/plugin/listen.h>
#include <drizzled/plugin/client.h>
#include <drizzled/catalog/local.h>

#include <drizzled/pthread_globals.h>
#include <boost/bind.hpp>


#include <drizzled/version.h>
#include <plugin/json_server/json/json.h>

namespace po= boost::program_options;
using namespace drizzled;
using namespace std;

namespace drizzle_plugin
{
namespace json_server
{

static port_constraint port;

static in_port_t getPort(void)
{
  return port.get();
}

extern "C" void process_request(struct evhttp_request *req, void* );
extern "C" void process_root_request(struct evhttp_request *req, void* );
extern "C" void process_api01_version_req(struct evhttp_request *req, void* );
extern "C" void process_api01_sql_req(struct evhttp_request *req, void* );

extern "C" void process_request(struct evhttp_request *req, void* )
{
  struct evbuffer *buf = evbuffer_new();
  if (buf == NULL) return;
  evbuffer_add_printf(buf, "Requested: %s\n", evhttp_request_uri(req));
  evhttp_send_reply(req, HTTP_OK, "OK", buf);
}

extern "C" void process_root_request(struct evhttp_request *req, void* )
{
  struct evbuffer *buf = evbuffer_new();
  if (buf == NULL) return;

  std::string output;

  output.append("<html><head><title>JSON DATABASE interface demo</title></head>"
                "<body>"
                "<script lang=\"javascript\">"
                "function to_table(obj) {"
                " var str = '<table>';"
                "for (var r=0; r< obj.length; r++) {"
                " str+='<tr>';"
                "  for (var c=0; c < obj[r].length; c++) {"
                "    str+= '<td>' + obj[r][c] + '</td>';"
                "  }"
                " str+='</tr>';"
                "}"
                "str+='</table>';"
                "return str;"
                "}"
                "function run_query()\n"
                "{"
                "var url = document.getElementById(\"baseurl\").innerHTML;\n"
                "var query= document.getElementById(\"query\").value;\n"
                "var xmlHttp = new XMLHttpRequest();\n"
                "xmlHttp.onreadystatechange = function () {\n"
                "if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n"
                "var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n"
                "document.getElementById( \"resultset\").innerHTML= to_table(info.result_set);\n"
                "}\n"
                "};\n"
                "xmlHttp.open(\"POST\", url + \"/0.1/sql\", true);"
                "xmlHttp.send(query);"
                "}"
                "\n\n"
                "function update_version()\n"
                "{drizzle_version(document.getElementById(\"baseurl\").innerHTML);}\n\n"
                "function drizzle_version($url)"
                "{"
                "var xmlHttp = new XMLHttpRequest();\n"
                "xmlHttp.onreadystatechange = function () {\n"
                "if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n"
                "var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n"
                "document.getElementById( \"drizzleversion\").innerHTML= info.version;\n"
                "}\n"
                "};\n"
                "xmlHttp.open(\"GET\", $url + \"/0.1/version\", true);"
                "xmlHttp.send(null);"
                "}"
                "</script>"
                "<p>Drizzle Server at: <a id=\"baseurl\">http://localhost:8765</a></p>"
                "<p>Drizzle server version: <a id=\"drizzleversion\"></a></p>"
                "<p><textarea rows=\"3\" cols=\"40\" id=\"query\">"
                "SELECT * from DATA_DICTIONARY.GLOBAL_STATUS;"
                "</textarea>"
                "<button type=\"button\" onclick=\"run_query();\">Execute Query</button>"
                "<div id=\"resultset\"/>"
                "<script lang=\"javascript\">update_version(); run_query();</script>"
                "</body></html>");

  evbuffer_add(buf, output.c_str(), output.length());
  evhttp_send_reply(req, HTTP_OK, "OK", buf);
}

extern "C" void process_api01_version_req(struct evhttp_request *req, void* )
{
  struct evbuffer *buf = evbuffer_new();
  if (buf == NULL) return;

  Json::Value root;
  root["version"]= ::drizzled::version();

  Json::StyledWriter writer;
  std::string output= writer.write(root);

  evbuffer_add(buf, output.c_str(), output.length());
  evhttp_send_reply(req, HTTP_OK, "OK", buf);
}

extern "C" void process_api01_sql_req(struct evhttp_request *req, void* )
{
  struct evbuffer *buf = evbuffer_new();
  if (buf == NULL) return;

  std::string input;
  char buffer[1024];
  int l=0;
  do {
    l= evbuffer_remove(req->input_buffer, buffer, 1024);
    input.append(buffer, l);
  }while(l);

  drizzled::Session::shared_ptr _session= drizzled::Session::make_shared(drizzled::plugin::Listen::getNullClient(),
                                           drizzled::catalog::local());
  drizzled::identifier::user::mptr user_id= identifier::User::make_shared();
  user_id->setUser("");
  _session->setUser(user_id);
  _session->set_schema("test");

  drizzled::Execute execute(*(_session.get()), true);

  drizzled::sql::ResultSet result_set(1);

  /* Execute wraps the SQL to run within a transaction */
  execute.run(input, result_set);
  drizzled::sql::Exception exception= result_set.getException();

  drizzled::error_t err= exception.getErrorCode();

  Json::Value root;
  root["sqlstate"]= exception.getSQLState();

  if ((err != drizzled::EE_OK) && (err != drizzled::ER_EMPTY_QUERY))
  {
    root["error_message"]= exception.getErrorMessage();
    root["error_code"]= exception.getErrorCode();
  }

  while (result_set.next())
  {
    Json::Value json_row;
    for (size_t x= 0; x < result_set.getMetaData().getColumnCount(); x++)
    {
      if (not result_set.isNull(x))
      {
        json_row[x]= result_set.getString(x);
      }
    }
    root["result_set"].append(json_row);
  }

  root["query"]= input;

  Json::StyledWriter writer;
  std::string output= writer.write(root);

  evbuffer_add(buf, output.c_str(), output.length());
  evhttp_send_reply(req, HTTP_OK, "OK", buf);
}

static void shutdown_event(int fd, short, void *arg)
{
  struct event_base *base= (struct event_base *)arg;
  event_base_loopbreak(base);
  close(fd);
}


static void run(struct event_base *base)
{
  internal::my_thread_init();

  event_base_dispatch(base);
}


class JsonServer : public drizzled::plugin::Daemon
{
private:
  JsonServer(const JsonServer &);
  JsonServer& operator=(const JsonServer &);

  drizzled::thread_ptr json_thread;
  in_port_t _port;
  struct evhttp *httpd;
  struct event_base *base;
  int wakeup_fd[2];
  struct event wakeup_event;

public:
  JsonServer(in_port_t port_arg) :
    drizzled::plugin::Daemon("JSON Server"),
    _port(port_arg),
    httpd(NULL),
    base(NULL)
  { }

  bool init()
  {
    if (pipe(wakeup_fd) < 0)
    {
      sql_perror("pipe");
      return false;
    }

    int returned_flags;
    if ((returned_flags= fcntl(wakeup_fd[0], F_GETFL, 0)) < 0)
    {
      sql_perror("fcntl:F_GETFL");
      return false;
    }

    if (fcntl(wakeup_fd[0], F_SETFL, returned_flags | O_NONBLOCK) < 0)

    {
      sql_perror("F_SETFL");
      return false;
    }

    if ((base= event_init()) == NULL)
    {
      sql_perror("event_init()");
      return false;
    }

    if ((httpd= evhttp_new(base)) == NULL)
    {
      sql_perror("evhttp_new()");
      return false;
    }


    if ((evhttp_bind_socket(httpd, "0.0.0.0", getPort())) == -1)
    {
      sql_perror("evhttp_bind_socket()");
      return false;
    }

    evhttp_set_cb(httpd, "/", process_root_request, NULL);
    evhttp_set_cb(httpd, "/0.1/version", process_api01_version_req, NULL);
    evhttp_set_cb(httpd, "/0.1/sql", process_api01_sql_req, NULL);
    evhttp_set_gencb(httpd, process_request, NULL);

    event_set(&wakeup_event, wakeup_fd[0], EV_READ | EV_PERSIST, shutdown_event, base);
    event_base_set(base, &wakeup_event);
    if (event_add(&wakeup_event, NULL) < 0)
    {
      sql_perror("event_add");
      return false;
    }

    json_thread.reset(new boost::thread((boost::bind(&run, base))));

    if (not json_thread)
      return false;

    return true;
  }

  ~JsonServer()
  {
    // If we can't write(), we will just muddle our way through the shutdown
    char buffer[1];
    buffer[0]= 4;
    if ((write(wakeup_fd[1], &buffer, 1)) == 1)
    {
      json_thread->join();
      evhttp_free(httpd);
      event_base_free(base);
    }
  }
};

static int json_server_init(drizzled::module::Context &context)
{
  context.registerVariable(new sys_var_constrained_value_readonly<in_port_t>("port", port));

  JsonServer *server;
  context.add(server= new JsonServer(port));

  if (server and not server->init())
  {
    return -2;
  }

  return bool(server) ? 0 : 1;
}

static void init_options(drizzled::module::option_context &context)
{
  context("port",
          po::value<port_constraint>(&port)->default_value(8086),
          _("Port number to use for connection or 0 for default (port 8086) "));
}

} /* namespace json_server */
} /* namespace drizzle_plugin */

DRIZZLE_DECLARE_PLUGIN
{
  DRIZZLE_VERSION_ID,
  "json-server",
  "0.1",
  "Stewart Smith",
  "JSON HTTP interface",
  PLUGIN_LICENSE_GPL,
  drizzle_plugin::json_server::json_server_init,             /* Plugin Init */
  NULL, /* depends */
  drizzle_plugin::json_server::init_options    /* config options */
}
DRIZZLE_DECLARE_PLUGIN_END;