1
0

HttpServer.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #include "HttpServer.h"
  2. #include "hmain.h" // import master_workers_run
  3. #include "herr.h"
  4. #include "hlog.h"
  5. #include "htime.h"
  6. #include "EventLoop.h"
  7. using namespace hv;
  8. #include "HttpHandler.h"
  9. static void on_accept(hio_t* io);
  10. static void on_recv(hio_t* io, void* _buf, int readbytes);
  11. static void on_close(hio_t* io);
  12. struct HttpServerPrivdata {
  13. std::vector<EventLoopPtr> loops;
  14. std::vector<hthread_t> threads;
  15. std::mutex mutex_;
  16. std::shared_ptr<HttpService> service;
  17. FileCache filecache;
  18. };
  19. static void on_recv(hio_t* io, void* buf, int readbytes) {
  20. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  21. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  22. assert(handler != NULL);
  23. int nfeed = handler->FeedRecvData((const char*)buf, readbytes);
  24. if (nfeed != readbytes) {
  25. hio_close(io);
  26. return;
  27. }
  28. }
  29. static void on_close(hio_t* io) {
  30. HttpHandler* handler = (HttpHandler*)hevent_userdata(io);
  31. if (handler == NULL) return;
  32. hevent_set_userdata(io, NULL);
  33. delete handler;
  34. EventLoop* loop = currentThreadEventLoop;
  35. if (loop) {
  36. --loop->connectionNum;
  37. }
  38. }
  39. static void on_accept(hio_t* io) {
  40. http_server_t* server = (http_server_t*)hevent_userdata(io);
  41. HttpService* service = server->service;
  42. /*
  43. printf("on_accept connfd=%d\n", hio_fd(io));
  44. char localaddrstr[SOCKADDR_STRLEN] = {0};
  45. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  46. printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
  47. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  48. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  49. */
  50. EventLoop* loop = currentThreadEventLoop;
  51. if (loop->connectionNum >= server->worker_connections) {
  52. hlogw("over worker_connections");
  53. hio_close(io);
  54. return;
  55. }
  56. ++loop->connectionNum;
  57. hio_setcb_close(io, on_close);
  58. hio_setcb_read(io, on_recv);
  59. hio_read(io);
  60. if (service->keepalive_timeout > 0) {
  61. hio_set_keepalive_timeout(io, service->keepalive_timeout);
  62. }
  63. // new HttpHandler, delete on_close
  64. HttpHandler* handler = new HttpHandler(io);
  65. // ssl
  66. handler->ssl = hio_is_ssl(io);
  67. // ip:port
  68. sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io);
  69. sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip));
  70. handler->port = sockaddr_port(peeraddr);
  71. // http service
  72. handler->service = service;
  73. // websocket service
  74. handler->ws_service = server->ws;
  75. // FileCache
  76. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  77. handler->files = &privdata->filecache;
  78. hevent_set_userdata(io, handler);
  79. }
  80. static void loop_thread(void* userdata) {
  81. http_server_t* server = (http_server_t*)userdata;
  82. HttpService* service = server->service;
  83. auto loop = std::make_shared<EventLoop>();
  84. hloop_t* hloop = loop->loop();
  85. // http
  86. if (server->listenfd[0] >= 0) {
  87. hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept);
  88. hevent_set_userdata(listenio, server);
  89. }
  90. // https
  91. if (server->listenfd[1] >= 0) {
  92. hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept);
  93. hevent_set_userdata(listenio, server);
  94. hio_enable_ssl(listenio);
  95. if (server->ssl_ctx) {
  96. hio_set_ssl_ctx(listenio, server->ssl_ctx);
  97. }
  98. }
  99. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  100. privdata->mutex_.lock();
  101. if (privdata->loops.size() == 0) {
  102. // NOTE: fsync logfile when idle
  103. hlog_disable_fsync();
  104. hidle_add(hloop, [](hidle_t*) {
  105. hlog_fsync();
  106. }, INFINITE);
  107. // NOTE: add timer to update s_date every 1s
  108. htimer_add(hloop, [](htimer_t* timer) {
  109. gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date);
  110. }, 1000);
  111. // document_root
  112. if (service->document_root.size() > 0 && service->GetStaticFilepath("/").empty()) {
  113. service->Static("/", service->document_root.c_str());
  114. }
  115. // FileCache
  116. FileCache* filecache = &privdata->filecache;
  117. filecache->stat_interval = service->file_cache_stat_interval;
  118. filecache->expired_time = service->file_cache_expired_time;
  119. if (filecache->expired_time > 0) {
  120. // NOTE: add timer to remove expired file cache
  121. htimer_t* timer = htimer_add(hloop, [](htimer_t* timer) {
  122. FileCache* filecache = (FileCache*)hevent_userdata(timer);
  123. filecache->RemoveExpiredFileCache();
  124. }, filecache->expired_time * 1000);
  125. hevent_set_userdata(timer, filecache);
  126. }
  127. }
  128. privdata->loops.push_back(loop);
  129. privdata->mutex_.unlock();
  130. hlogi("EventLoop started, pid=%ld tid=%ld", hv_getpid(), hv_gettid());
  131. if (server->onWorkerStart) {
  132. loop->queueInLoop([server](){
  133. server->onWorkerStart();
  134. });
  135. }
  136. loop->run();
  137. if (server->onWorkerStop) {
  138. server->onWorkerStop();
  139. }
  140. hlogi("EventLoop stopped, pid=%ld tid=%ld", hv_getpid(), hv_gettid());
  141. }
  142. /* @workflow:
  143. * http_server_run -> Listen -> master_workers_run / hthread_create ->
  144. * loop_thread -> accept -> EventLoop::run ->
  145. * on_accept -> new HttpHandler -> hio_read ->
  146. * on_recv -> HttpHandler::FeedRecvData ->
  147. * on_close -> delete HttpHandler
  148. */
  149. int http_server_run(http_server_t* server, int wait) {
  150. // http_port
  151. if (server->port > 0) {
  152. server->listenfd[0] = Listen(server->port, server->host);
  153. if (server->listenfd[0] < 0) return server->listenfd[0];
  154. hlogi("http server listening on %s:%d", server->host, server->port);
  155. }
  156. // https_port
  157. if (server->https_port > 0 && HV_WITH_SSL) {
  158. server->listenfd[1] = Listen(server->https_port, server->host);
  159. if (server->listenfd[1] < 0) return server->listenfd[1];
  160. hlogi("https server listening on %s:%d", server->host, server->https_port);
  161. }
  162. // SSL_CTX
  163. if (server->listenfd[1] >= 0) {
  164. if (server->ssl_ctx == NULL) {
  165. server->ssl_ctx = hssl_ctx_instance();
  166. }
  167. if (server->ssl_ctx == NULL) {
  168. hloge("new SSL_CTX failed!");
  169. return ERR_NEW_SSL_CTX;
  170. }
  171. #ifdef WITH_NGHTTP2
  172. #ifdef WITH_OPENSSL
  173. static unsigned char s_alpn_protos[] = "\x02h2\x08http/1.1\x08http/1.0\x08http/0.9";
  174. hssl_ctx_set_alpn_protos(server->ssl_ctx, s_alpn_protos, sizeof(s_alpn_protos) - 1);
  175. #endif
  176. #endif
  177. }
  178. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  179. server->privdata = privdata;
  180. if (server->service == NULL) {
  181. privdata->service = std::make_shared<HttpService>();
  182. server->service = privdata->service.get();
  183. }
  184. if (server->worker_processes) {
  185. // multi-processes
  186. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  187. }
  188. else {
  189. // multi-threads
  190. if (server->worker_threads == 0) server->worker_threads = 1;
  191. for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) {
  192. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  193. privdata->threads.push_back(thrd);
  194. }
  195. if (wait) {
  196. loop_thread(server);
  197. }
  198. return 0;
  199. }
  200. }
  201. /* @workflow:
  202. * http_server_stop -> EventLoop::stop -> hthread_join
  203. */
  204. int http_server_stop(http_server_t* server) {
  205. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  206. if (privdata == NULL) return 0;
  207. #ifdef OS_UNIX
  208. if (server->worker_processes) {
  209. signal_handle("stop");
  210. return 0;
  211. }
  212. #endif
  213. // wait for all threads started and all loops running
  214. while (1) {
  215. hv_delay(1);
  216. std::lock_guard<std::mutex> locker(privdata->mutex_);
  217. // wait for all loops created
  218. if (privdata->loops.size() < server->worker_threads) {
  219. continue;
  220. }
  221. // wait for all loops running
  222. bool all_loops_running = true;
  223. for (auto& loop : privdata->loops) {
  224. if (loop->status() < hv::Status::kRunning) {
  225. all_loops_running = false;
  226. break;
  227. }
  228. }
  229. if (all_loops_running) break;
  230. }
  231. // stop all loops
  232. for (auto& loop : privdata->loops) {
  233. loop->stop();
  234. }
  235. // join all threads
  236. for (auto& thrd : privdata->threads) {
  237. hthread_join(thrd);
  238. }
  239. if (server->alloced_ssl_ctx && server->ssl_ctx) {
  240. hssl_ctx_free(server->ssl_ctx);
  241. server->alloced_ssl_ctx = 0;
  242. server->ssl_ctx = NULL;
  243. }
  244. delete privdata;
  245. server->privdata = NULL;
  246. return 0;
  247. }