HttpServer.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. #ifdef OS_WIN
  143. static void WINAPI loop_thread_stdcall(void* userdata) {
  144. return loop_thread(userdata);
  145. }
  146. #endif
  147. /* @workflow:
  148. * http_server_run -> Listen -> master_workers_run / hthread_create ->
  149. * loop_thread -> accept -> EventLoop::run ->
  150. * on_accept -> new HttpHandler -> hio_read ->
  151. * on_recv -> HttpHandler::FeedRecvData ->
  152. * on_close -> delete HttpHandler
  153. */
  154. int http_server_run(http_server_t* server, int wait) {
  155. // http_port
  156. if (server->port > 0) {
  157. server->listenfd[0] = Listen(server->port, server->host);
  158. if (server->listenfd[0] < 0) return server->listenfd[0];
  159. hlogi("http server listening on %s:%d", server->host, server->port);
  160. }
  161. // https_port
  162. if (server->https_port > 0 && HV_WITH_SSL) {
  163. server->listenfd[1] = Listen(server->https_port, server->host);
  164. if (server->listenfd[1] < 0) return server->listenfd[1];
  165. hlogi("https server listening on %s:%d", server->host, server->https_port);
  166. }
  167. // SSL_CTX
  168. if (server->listenfd[1] >= 0) {
  169. if (server->ssl_ctx == NULL) {
  170. server->ssl_ctx = hssl_ctx_instance();
  171. }
  172. if (server->ssl_ctx == NULL) {
  173. hloge("new SSL_CTX failed!");
  174. return ERR_NEW_SSL_CTX;
  175. }
  176. #ifdef WITH_NGHTTP2
  177. #ifdef WITH_OPENSSL
  178. static unsigned char s_alpn_protos[] = "\x02h2\x08http/1.1\x08http/1.0\x08http/0.9";
  179. hssl_ctx_set_alpn_protos(server->ssl_ctx, s_alpn_protos, sizeof(s_alpn_protos) - 1);
  180. #endif
  181. #endif
  182. }
  183. HttpServerPrivdata* privdata = new HttpServerPrivdata;
  184. server->privdata = privdata;
  185. if (server->service == NULL) {
  186. privdata->service = std::make_shared<HttpService>();
  187. server->service = privdata->service.get();
  188. }
  189. if (server->worker_processes) {
  190. // multi-processes
  191. return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait);
  192. }
  193. else {
  194. // multi-threads
  195. if (server->worker_threads == 0) server->worker_threads = 1;
  196. for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) {
  197. #ifdef OS_WIN
  198. hthread_t thrd = hthread_create((hthread_routine)loop_thread_stdcall, server);
  199. #else
  200. hthread_t thrd = hthread_create((hthread_routine)loop_thread, server);
  201. #endif
  202. privdata->threads.push_back(thrd);
  203. }
  204. if (wait) {
  205. loop_thread(server);
  206. }
  207. return 0;
  208. }
  209. }
  210. /* @workflow:
  211. * http_server_stop -> EventLoop::stop -> hthread_join
  212. */
  213. int http_server_stop(http_server_t* server) {
  214. HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata;
  215. if (privdata == NULL) return 0;
  216. #ifdef OS_UNIX
  217. if (server->worker_processes) {
  218. signal_handle("stop");
  219. return 0;
  220. }
  221. #endif
  222. // wait for all threads started and all loops running
  223. while (1) {
  224. hv_delay(1);
  225. std::lock_guard<std::mutex> locker(privdata->mutex_);
  226. // wait for all loops created
  227. if (privdata->loops.size() < server->worker_threads) {
  228. continue;
  229. }
  230. // wait for all loops running
  231. bool all_loops_running = true;
  232. for (auto& loop : privdata->loops) {
  233. if (loop->status() < hv::Status::kRunning) {
  234. all_loops_running = false;
  235. break;
  236. }
  237. }
  238. if (all_loops_running) break;
  239. }
  240. // stop all loops
  241. for (auto& loop : privdata->loops) {
  242. loop->stop();
  243. }
  244. // join all threads
  245. for (auto& thrd : privdata->threads) {
  246. hthread_join(thrd);
  247. }
  248. if (server->alloced_ssl_ctx && server->ssl_ctx) {
  249. hssl_ctx_free(server->ssl_ctx);
  250. server->alloced_ssl_ctx = 0;
  251. server->ssl_ctx = NULL;
  252. }
  253. delete privdata;
  254. server->privdata = NULL;
  255. return 0;
  256. }
  257. namespace hv {
  258. std::shared_ptr<hv::EventLoop> HttpServer::loop(int idx) {
  259. HttpServerPrivdata* privdata = (HttpServerPrivdata*)this->privdata;
  260. if (privdata == NULL) return NULL;
  261. std::lock_guard<std::mutex> locker(privdata->mutex_);
  262. if (privdata->loops.empty()) return NULL;
  263. if (idx >= 0 && idx < (int)privdata->loops.size()) {
  264. return privdata->loops[idx];
  265. }
  266. EventLoop* cur = currentThreadEventLoop;
  267. for (auto& loop : privdata->loops) {
  268. if (loop.get() == cur) return loop;
  269. }
  270. return NULL;
  271. }
  272. size_t HttpServer::connectionNum() {
  273. HttpServerPrivdata* privdata = (HttpServerPrivdata*)this->privdata;
  274. if (privdata == NULL) return 0;
  275. std::lock_guard<std::mutex> locker(privdata->mutex_);
  276. if (privdata->loops.empty()) return 0;
  277. size_t total = 0;
  278. for (auto& loop : privdata->loops) {
  279. total += loop->connectionNum;
  280. }
  281. return total;
  282. }
  283. }