techempower.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. * lwan - simple web server
  3. * Copyright (c) 2014 Leandro A. F. Pereira <[email protected]>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License
  7. * as published by the Free Software Foundation; either version 2
  8. * of the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  18. * USA.
  19. */
  20. #include <errno.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include "lwan-private.h"
  24. #include "lwan-cache.h"
  25. #include "lwan-config.h"
  26. #include "lwan-template.h"
  27. #include "lwan-mod-lua.h"
  28. #include "int-to-str.h"
  29. #include "database.h"
  30. #include "json.h"
  31. enum db_connect_type { DB_CONN_MYSQL, DB_CONN_SQLITE };
  32. static struct db_connection_params {
  33. enum db_connect_type type;
  34. union {
  35. struct {
  36. const char *user;
  37. const char *password;
  38. const char *database;
  39. const char *hostname;
  40. } mysql;
  41. struct {
  42. const char *path;
  43. const char **pragmas;
  44. } sqlite;
  45. };
  46. } db_connection_params;
  47. static const char hello_world[] = "Hello, World!";
  48. static const char random_number_query[] =
  49. "SELECT randomNumber, id FROM world WHERE id=?";
  50. static const char cached_random_number_query[] =
  51. "SELECT randomNumber, id FROM world WHERE id=?";
  52. struct Fortune {
  53. struct {
  54. coro_function_t generator;
  55. int id;
  56. char *message;
  57. } item;
  58. };
  59. DEFINE_ARRAY_TYPE_INLINEFIRST(fortune_array, struct Fortune)
  60. static const char fortunes_template_str[] =
  61. "<!DOCTYPE html>"
  62. "<html>"
  63. "<head><title>Fortunes</title></head>"
  64. "<body>"
  65. "<table>"
  66. "<tr><th>id</th><th>message</th></tr>"
  67. "{{#item}}"
  68. "<tr><td>{{item.id}}</td><td>{{item.message}}</td></tr>"
  69. "{{/item}}"
  70. "</table>"
  71. "</body>"
  72. "</html>";
  73. static int fortune_list_generator(struct coro *coro, void *data);
  74. #undef TPL_STRUCT
  75. #define TPL_STRUCT struct Fortune
  76. static const struct lwan_var_descriptor fortune_desc[] = {
  77. TPL_VAR_SEQUENCE(item,
  78. fortune_list_generator,
  79. ((const struct lwan_var_descriptor[]){
  80. TPL_VAR_INT(item.id),
  81. TPL_VAR_STR_ESCAPE(item.message),
  82. TPL_VAR_SENTINEL,
  83. })),
  84. TPL_VAR_SENTINEL,
  85. };
  86. static struct lwan_tpl *fortune_tpl;
  87. struct hello_world_json {
  88. const char *message;
  89. };
  90. static const struct json_obj_descr hello_world_json_desc[] = {
  91. JSON_OBJ_DESCR_PRIM(struct hello_world_json, message, JSON_TOK_STRING),
  92. };
  93. struct db_json {
  94. int id;
  95. int randomNumber;
  96. };
  97. static const struct json_obj_descr db_json_desc[] = {
  98. JSON_OBJ_DESCR_PRIM(struct db_json, id, JSON_TOK_NUMBER),
  99. JSON_OBJ_DESCR_PRIM(struct db_json, randomNumber, JSON_TOK_NUMBER),
  100. };
  101. struct queries_json {
  102. struct db_json queries[500];
  103. size_t queries_len;
  104. };
  105. static const struct json_obj_descr queries_array_desc =
  106. JSON_OBJ_DESCR_OBJ_ARRAY(struct queries_json,
  107. queries,
  108. 500,
  109. queries_len,
  110. db_json_desc,
  111. N_ELEMENTS(db_json_desc));
  112. static struct db *get_db(void)
  113. {
  114. static __thread struct db *database;
  115. if (!database) {
  116. switch (db_connection_params.type) {
  117. case DB_CONN_MYSQL:
  118. database = db_connect_mysql(db_connection_params.mysql.hostname,
  119. db_connection_params.mysql.user,
  120. db_connection_params.mysql.password,
  121. db_connection_params.mysql.database);
  122. break;
  123. case DB_CONN_SQLITE:
  124. database = db_connect_sqlite(db_connection_params.sqlite.path, true,
  125. db_connection_params.sqlite.pragmas);
  126. break;
  127. }
  128. if (!database)
  129. lwan_status_critical("Could not connect to the database");
  130. }
  131. return database;
  132. }
  133. static int append_to_strbuf(const char *bytes, size_t len, void *data)
  134. {
  135. struct lwan_strbuf *strbuf = data;
  136. return !lwan_strbuf_append_str(strbuf, bytes, len);
  137. }
  138. static enum lwan_http_status
  139. json_response_obj(struct lwan_response *response,
  140. const struct json_obj_descr *descr,
  141. size_t descr_len,
  142. const void *data)
  143. {
  144. if (json_obj_encode_full(descr, descr_len, data, append_to_strbuf,
  145. response->buffer, false) != 0)
  146. return HTTP_INTERNAL_ERROR;
  147. response->mime_type = "application/json";
  148. return HTTP_OK;
  149. }
  150. static enum lwan_http_status
  151. json_response_arr(struct lwan_response *response,
  152. const struct json_obj_descr *descr,
  153. const void *data)
  154. {
  155. if (json_arr_encode_full(descr, data, append_to_strbuf, response->buffer,
  156. false) != 0)
  157. return HTTP_INTERNAL_ERROR;
  158. response->mime_type = "application/json";
  159. return HTTP_OK;
  160. }
  161. LWAN_HANDLER(json)
  162. {
  163. struct hello_world_json j = {.message = hello_world};
  164. return json_response_obj(response, hello_world_json_desc,
  165. N_ELEMENTS(hello_world_json_desc), &j);
  166. }
  167. static bool db_query_key(struct db_stmt *stmt, struct db_json *out, int key)
  168. {
  169. struct db_row row = {.kind = 'i', .u.i = key + 1};
  170. if (UNLIKELY(!db_stmt_bind(stmt, &row, 1)))
  171. return false;
  172. long random_number;
  173. long id;
  174. if (UNLIKELY(!db_stmt_step(stmt, "ii", &random_number, &id)))
  175. return false;
  176. out->id = (int)id;
  177. out->randomNumber = (int)random_number;
  178. return true;
  179. }
  180. static inline bool db_query(struct db_stmt *stmt, struct db_json *out)
  181. {
  182. return db_query_key(stmt, out, rand() % 10000);
  183. }
  184. LWAN_HANDLER(db)
  185. {
  186. struct db_stmt *stmt = db_prepare_stmt(get_db(), random_number_query,
  187. sizeof(random_number_query) - 1);
  188. struct db_json db_json;
  189. if (UNLIKELY(!stmt)) {
  190. lwan_status_debug("preparing stmt failed");
  191. return HTTP_INTERNAL_ERROR;
  192. }
  193. bool queried = db_query(stmt, &db_json);
  194. db_stmt_finalize(stmt);
  195. if (!queried)
  196. return HTTP_INTERNAL_ERROR;
  197. return json_response_obj(response, db_json_desc, N_ELEMENTS(db_json_desc),
  198. &db_json);
  199. }
  200. LWAN_HANDLER(queries)
  201. {
  202. enum lwan_http_status ret = HTTP_INTERNAL_ERROR;
  203. const char *queries_str = lwan_request_get_query_param(request, "queries");
  204. long queries;
  205. queries = LIKELY(queries_str)
  206. ? LWAN_MIN(500, LWAN_MAX(1, parse_long(queries_str, -1)))
  207. : 1;
  208. struct db_stmt *stmt = db_prepare_stmt(get_db(), random_number_query,
  209. sizeof(random_number_query) - 1);
  210. if (UNLIKELY(!stmt))
  211. return HTTP_INTERNAL_ERROR;
  212. struct queries_json qj = {.queries_len = (size_t)queries};
  213. for (long i = 0; i < queries; i++) {
  214. if (!db_query(stmt, &qj.queries[i]))
  215. goto out;
  216. }
  217. /* Avoid reallocations/copies while building response. Each response
  218. * has ~32bytes. 500 queries (max) should be less than 16384 bytes,
  219. * so this is a good approximation. */
  220. lwan_strbuf_grow_to(response->buffer, (size_t)(32l * queries));
  221. ret = json_response_arr(response, &queries_array_desc, &qj);
  222. out:
  223. db_stmt_finalize(stmt);
  224. return ret;
  225. }
  226. static struct cache *cached_queries_cache;
  227. struct db_json_cached {
  228. struct cache_entry base;
  229. struct db_json db_json;
  230. };
  231. static struct cache_entry *cached_queries_new(const char *key, void *context)
  232. {
  233. struct db_json_cached *entry;
  234. struct db_stmt *stmt;
  235. entry = malloc(sizeof(*entry));
  236. if (UNLIKELY(!entry))
  237. return NULL;
  238. stmt = db_prepare_stmt(get_db(), cached_random_number_query,
  239. sizeof(cached_random_number_query) - 1);
  240. if (UNLIKELY(!stmt)) {
  241. free(entry);
  242. return NULL;
  243. }
  244. if (!db_query_key(stmt, &entry->db_json, atoi(key))) {
  245. free(entry);
  246. entry = NULL;
  247. }
  248. db_stmt_finalize(stmt);
  249. return (struct cache_entry *)entry;
  250. }
  251. static void cached_queries_free(struct cache_entry *entry, void *context)
  252. {
  253. free(entry);
  254. }
  255. static struct cache_entry *my_cache_coro_get_and_ref_entry(struct cache *cache,
  256. struct lwan_request *request,
  257. const char *key)
  258. {
  259. /* Using this function instead of cache_coro_get_and_ref_entry() will avoid
  260. * calling coro_defer(), which, in cases where the number of cached queries is
  261. * too high, will trigger reallocations of the coro_defer array (and the "demotion"
  262. * from the storage inlined in the coro struct to somewhere in the heap).
  263. *
  264. * For large number of cached elements, too, this will reduce the number of
  265. * indirect calls that are performed every time a request is serviced.
  266. */
  267. for (int tries = 64; tries; tries--) {
  268. int error;
  269. struct cache_entry *ce = cache_get_and_ref_entry(cache, key, &error);
  270. if (LIKELY(ce))
  271. return ce;
  272. if (error != EWOULDBLOCK)
  273. break;
  274. coro_yield(request->conn->coro, CONN_CORO_WANT_WRITE);
  275. if (tries > 16)
  276. lwan_request_sleep(request, (unsigned int)(tries / 8));
  277. }
  278. return NULL;
  279. }
  280. LWAN_HANDLER(cached_queries)
  281. {
  282. const char *queries_str = lwan_request_get_query_param(request, "count");
  283. long queries;
  284. queries = LIKELY(queries_str)
  285. ? LWAN_MIN(500, LWAN_MAX(1, parse_long(queries_str, -1)))
  286. : 1;
  287. struct queries_json qj = {.queries_len = (size_t)queries};
  288. for (long i = 0; i < queries; i++) {
  289. char key_buf[INT_TO_STR_BUFFER_SIZE];
  290. struct db_json_cached *jc;
  291. size_t discard;
  292. jc = (struct db_json_cached *)my_cache_coro_get_and_ref_entry(
  293. cached_queries_cache, request,
  294. int_to_string(rand() % 10000, key_buf, &discard));
  295. if (UNLIKELY(!jc))
  296. return HTTP_INTERNAL_ERROR;
  297. qj.queries[i] = jc->db_json;
  298. cache_entry_unref(cached_queries_cache, (struct cache_entry *)jc);
  299. }
  300. /* Avoid reallocations/copies while building response. Each response
  301. * has ~32bytes. 500 queries (max) should be less than 16384 bytes,
  302. * so this is a good approximation. */
  303. lwan_strbuf_grow_to(response->buffer, (size_t)(32l * queries));
  304. return json_response_arr(response, &queries_array_desc, &qj);
  305. }
  306. LWAN_HANDLER(plaintext)
  307. {
  308. lwan_strbuf_set_static(response->buffer, hello_world,
  309. sizeof(hello_world) - 1);
  310. response->mime_type = "text/plain";
  311. return HTTP_OK;
  312. }
  313. static int fortune_compare(const void *a, const void *b)
  314. {
  315. const struct Fortune *fortune_a = (const struct Fortune *)a;
  316. const struct Fortune *fortune_b = (const struct Fortune *)b;
  317. return strcmp(fortune_a->item.message, fortune_b->item.message);
  318. }
  319. static bool append_fortune(struct coro *coro,
  320. struct fortune_array *fortunes,
  321. int id,
  322. const char *message)
  323. {
  324. struct Fortune *fortune;
  325. char *message_copy;
  326. message_copy = coro_strdup(coro, message);
  327. if (UNLIKELY(!message_copy))
  328. return false;
  329. fortune = fortune_array_append(fortunes);
  330. if (UNLIKELY(!fortune))
  331. return false;
  332. fortune->item.id = id;
  333. fortune->item.message = message_copy;
  334. return true;
  335. }
  336. static int fortune_list_generator(struct coro *coro, void *data)
  337. {
  338. static const char fortune_query[] = "SELECT * FROM Fortune";
  339. struct Fortune *fortune = data;
  340. struct fortune_array fortunes;
  341. struct db_stmt *stmt;
  342. stmt = db_prepare_stmt(get_db(), fortune_query, sizeof(fortune_query) - 1);
  343. if (UNLIKELY(!stmt))
  344. return 0;
  345. fortune_array_init(&fortunes);
  346. long id;
  347. char fortune_buffer[256];
  348. while (db_stmt_step(stmt, "is", &id, &fortune_buffer, sizeof(fortune_buffer))) {
  349. if (!append_fortune(coro, &fortunes, (int)id, fortune_buffer))
  350. goto out;
  351. }
  352. if (!append_fortune(coro, &fortunes, 0,
  353. "Additional fortune added at request time."))
  354. goto out;
  355. fortune_array_sort(&fortunes, fortune_compare);
  356. struct Fortune *iter;
  357. LWAN_ARRAY_FOREACH (&fortunes, iter) {
  358. fortune->item.id = iter->item.id;
  359. fortune->item.message = iter->item.message;
  360. coro_yield(coro, 1);
  361. }
  362. out:
  363. fortune_array_reset(&fortunes);
  364. db_stmt_finalize(stmt);
  365. return 0;
  366. }
  367. LWAN_HANDLER(fortunes)
  368. {
  369. struct Fortune fortune;
  370. lwan_strbuf_grow_to(response->buffer, 1500);
  371. if (UNLIKELY(!lwan_tpl_apply_with_buffer(fortune_tpl, response->buffer,
  372. &fortune)))
  373. return HTTP_INTERNAL_ERROR;
  374. response->mime_type = "text/html; charset=UTF-8";
  375. return HTTP_OK;
  376. }
  377. LWAN_HANDLER(quit_lwan)
  378. {
  379. exit(0);
  380. return HTTP_OK;
  381. }
  382. int main(void)
  383. {
  384. struct lwan l;
  385. lwan_init(&l);
  386. srand((unsigned int)time(NULL));
  387. if (getenv("USE_MYSQL")) {
  388. db_connection_params = (struct db_connection_params){
  389. .type = DB_CONN_MYSQL,
  390. .mysql.user = getenv("MYSQL_USER"),
  391. .mysql.password = getenv("MYSQL_PASS"),
  392. .mysql.hostname = getenv("MYSQL_HOST"),
  393. .mysql.database = getenv("MYSQL_DB"),
  394. };
  395. if (!db_connection_params.mysql.user)
  396. lwan_status_critical("No MySQL user provided");
  397. if (!db_connection_params.mysql.password)
  398. lwan_status_critical("No MySQL password provided");
  399. if (!db_connection_params.mysql.hostname)
  400. lwan_status_critical("No MySQL hostname provided");
  401. if (!db_connection_params.mysql.database)
  402. lwan_status_critical("No MySQL database provided");
  403. } else {
  404. static const char *pragmas[] = {"PRAGMA mmap_size=44040192",
  405. "PRAGMA journal_mode=OFF",
  406. "PRAGMA locking_mode=EXCLUSIVE", NULL};
  407. db_connection_params = (struct db_connection_params){
  408. .type = DB_CONN_SQLITE,
  409. .sqlite.path = "techempower.db",
  410. .sqlite.pragmas = pragmas,
  411. };
  412. }
  413. fortune_tpl = lwan_tpl_compile_string_full(
  414. fortunes_template_str, fortune_desc, LWAN_TPL_FLAG_CONST_TEMPLATE);
  415. if (!fortune_tpl)
  416. lwan_status_critical("Could not compile fortune templates");
  417. cached_queries_cache = cache_create(cached_queries_new,
  418. cached_queries_free,
  419. NULL,
  420. 3600 /* 1 hour */);
  421. if (!cached_queries_cache)
  422. lwan_status_critical("Could not create cached queries cache");
  423. lwan_main_loop(&l);
  424. cache_destroy(cached_queries_cache);
  425. lwan_tpl_free(fortune_tpl);
  426. lwan_shutdown(&l);
  427. return 0;
  428. }