http_server.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. #pragma once
  2. #ifdef CROW_USE_BOOST
  3. #include <boost/asio.hpp>
  4. #ifdef CROW_ENABLE_SSL
  5. #include <boost/asio/ssl.hpp>
  6. #endif
  7. #else
  8. #ifndef ASIO_STANDALONE
  9. #define ASIO_STANDALONE
  10. #endif
  11. #include <asio.hpp>
  12. #ifdef CROW_ENABLE_SSL
  13. #include <asio/ssl.hpp>
  14. #endif
  15. #endif
  16. #include <atomic>
  17. #include <chrono>
  18. #include <cstdint>
  19. #include <future>
  20. #include <memory>
  21. #include <vector>
  22. #include "version.h"
  23. #include "http_connection.h"
  24. #include "logging.h"
  25. #include "task_timer.h"
  26. namespace crow // NOTE: Already documented in "crow/app.h"
  27. {
  28. #ifdef CROW_USE_BOOST
  29. namespace asio = boost::asio;
  30. using error_code = boost::system::error_code;
  31. #else
  32. using error_code = asio::error_code;
  33. #endif
  34. using tcp = asio::ip::tcp;
  35. template<typename Handler, typename Adaptor = SocketAdaptor, typename... Middlewares>
  36. class Server
  37. {
  38. public:
  39. Server(Handler* handler, std::string bindaddr, uint16_t port, std::string server_name = std::string("Crow/") + VERSION, std::tuple<Middlewares...>* middlewares = nullptr, uint16_t concurrency = 1, uint8_t timeout = 5, typename Adaptor::context* adaptor_ctx = nullptr):
  40. acceptor_(io_context_, tcp::endpoint(asio::ip::make_address(bindaddr), port)),
  41. signals_(io_context_),
  42. tick_timer_(io_context_),
  43. handler_(handler),
  44. concurrency_(concurrency),
  45. timeout_(timeout),
  46. server_name_(server_name),
  47. port_(port),
  48. bindaddr_(bindaddr),
  49. task_queue_length_pool_(concurrency_ - 1),
  50. middlewares_(middlewares),
  51. adaptor_ctx_(adaptor_ctx)
  52. {}
  53. void set_tick_function(std::chrono::milliseconds d, std::function<void()> f)
  54. {
  55. tick_interval_ = d;
  56. tick_function_ = f;
  57. }
  58. void on_tick()
  59. {
  60. tick_function_();
  61. tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
  62. tick_timer_.async_wait([this](const error_code& ec) {
  63. if (ec)
  64. return;
  65. on_tick();
  66. });
  67. }
  68. void run()
  69. {
  70. uint16_t worker_thread_count = concurrency_ - 1;
  71. for (int i = 0; i < worker_thread_count; i++)
  72. io_context_pool_.emplace_back(new asio::io_context());
  73. get_cached_date_str_pool_.resize(worker_thread_count);
  74. task_timer_pool_.resize(worker_thread_count);
  75. std::vector<std::future<void>> v;
  76. std::atomic<int> init_count(0);
  77. for (uint16_t i = 0; i < worker_thread_count; i++)
  78. v.push_back(
  79. std::async(
  80. std::launch::async, [this, i, &init_count] {
  81. // thread local date string get function
  82. auto last = std::chrono::steady_clock::now();
  83. std::string date_str;
  84. auto update_date_str = [&] {
  85. auto last_time_t = time(0);
  86. tm my_tm;
  87. #if defined(_MSC_VER) || defined(__MINGW32__)
  88. gmtime_s(&my_tm, &last_time_t);
  89. #else
  90. gmtime_r(&last_time_t, &my_tm);
  91. #endif
  92. date_str.resize(100);
  93. size_t date_str_sz = strftime(&date_str[0], 99, "%a, %d %b %Y %H:%M:%S GMT", &my_tm);
  94. date_str.resize(date_str_sz);
  95. };
  96. update_date_str();
  97. get_cached_date_str_pool_[i] = [&]() -> std::string {
  98. if (std::chrono::steady_clock::now() - last >= std::chrono::seconds(1))
  99. {
  100. last = std::chrono::steady_clock::now();
  101. update_date_str();
  102. }
  103. return date_str;
  104. };
  105. // initializing task timers
  106. detail::task_timer task_timer(*io_context_pool_[i]);
  107. task_timer.set_default_timeout(timeout_);
  108. task_timer_pool_[i] = &task_timer;
  109. task_queue_length_pool_[i] = 0;
  110. init_count++;
  111. while (1)
  112. {
  113. try
  114. {
  115. if (io_context_pool_[i]->run() == 0)
  116. {
  117. // when io_service.run returns 0, there are no more works to do.
  118. break;
  119. }
  120. }
  121. catch (std::exception& e)
  122. {
  123. CROW_LOG_ERROR << "Worker Crash: An uncaught exception occurred: " << e.what();
  124. }
  125. }
  126. }));
  127. if (tick_function_ && tick_interval_.count() > 0)
  128. {
  129. tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
  130. tick_timer_.async_wait(
  131. [this](const error_code& ec) {
  132. if (ec)
  133. return;
  134. on_tick();
  135. });
  136. }
  137. port_ = acceptor_.local_endpoint().port();
  138. handler_->port(port_);
  139. CROW_LOG_INFO << server_name_ << " server is running at " << (handler_->ssl_used() ? "https://" : "http://") << bindaddr_ << ":" << acceptor_.local_endpoint().port() << " using " << concurrency_ << " threads";
  140. CROW_LOG_INFO << "Call `app.loglevel(crow::LogLevel::Warning)` to hide Info level logs.";
  141. signals_.async_wait(
  142. [&](const error_code& /*error*/, int /*signal_number*/) {
  143. stop();
  144. });
  145. while (worker_thread_count != init_count)
  146. std::this_thread::yield();
  147. do_accept();
  148. std::thread(
  149. [this] {
  150. notify_start();
  151. io_context_.run();
  152. CROW_LOG_INFO << "Exiting.";
  153. })
  154. .join();
  155. }
  156. void stop()
  157. {
  158. shutting_down_ = true; // Prevent the acceptor from taking new connections
  159. for (auto& io_context : io_context_pool_)
  160. {
  161. if (io_context != nullptr)
  162. {
  163. CROW_LOG_INFO << "Closing IO service " << &io_context;
  164. io_context->stop(); // Close all io_services (and HTTP connections)
  165. }
  166. }
  167. CROW_LOG_INFO << "Closing main IO service (" << &io_context_ << ')';
  168. io_context_.stop(); // Close main io_service
  169. }
  170. uint16_t port(){
  171. return acceptor_.local_endpoint().port();
  172. }
  173. /// Wait until the server has properly started
  174. void wait_for_start()
  175. {
  176. std::unique_lock<std::mutex> lock(start_mutex_);
  177. while (!server_started_)
  178. cv_started_.wait(lock);
  179. }
  180. void signal_clear()
  181. {
  182. signals_.clear();
  183. }
  184. void signal_add(int signal_number)
  185. {
  186. signals_.add(signal_number);
  187. }
  188. private:
  189. uint16_t pick_io_context_idx()
  190. {
  191. uint16_t min_queue_idx = 0;
  192. // TODO improve load balancing
  193. // size_t is used here to avoid the security issue https://codeql.github.com/codeql-query-help/cpp/cpp-comparison-with-wider-type/
  194. // even though the max value of this can be only uint16_t as concurrency is uint16_t.
  195. for (size_t i = 1; i < task_queue_length_pool_.size() && task_queue_length_pool_[min_queue_idx] > 0; i++)
  196. // No need to check other io_services if the current one has no tasks
  197. {
  198. if (task_queue_length_pool_[i] < task_queue_length_pool_[min_queue_idx])
  199. min_queue_idx = i;
  200. }
  201. return min_queue_idx;
  202. }
  203. void do_accept()
  204. {
  205. if (!shutting_down_)
  206. {
  207. uint16_t context_idx = pick_io_context_idx();
  208. asio::io_context& ic = *io_context_pool_[context_idx];
  209. task_queue_length_pool_[context_idx]++;
  210. CROW_LOG_DEBUG << &ic << " {" << context_idx << "} queue length: " << task_queue_length_pool_[context_idx];
  211. auto p = std::make_shared<Connection<Adaptor, Handler, Middlewares...>>(
  212. ic, handler_, server_name_, middlewares_,
  213. get_cached_date_str_pool_[context_idx], *task_timer_pool_[context_idx], adaptor_ctx_, task_queue_length_pool_[context_idx]);
  214. acceptor_.async_accept(
  215. p->socket(),
  216. [this, p, &ic, context_idx](error_code ec) {
  217. if (!ec)
  218. {
  219. asio::post(ic,
  220. [p] {
  221. p->start();
  222. });
  223. }
  224. else
  225. {
  226. task_queue_length_pool_[context_idx]--;
  227. CROW_LOG_DEBUG << &ic << " {" << context_idx << "} queue length: " << task_queue_length_pool_[context_idx];
  228. }
  229. do_accept();
  230. });
  231. }
  232. }
  233. /// Notify anything using `wait_for_start()` to proceed
  234. void notify_start()
  235. {
  236. std::unique_lock<std::mutex> lock(start_mutex_);
  237. server_started_ = true;
  238. cv_started_.notify_all();
  239. }
  240. private:
  241. std::vector<std::unique_ptr<asio::io_context>> io_context_pool_;
  242. asio::io_context io_context_;
  243. std::vector<detail::task_timer*> task_timer_pool_;
  244. std::vector<std::function<std::string()>> get_cached_date_str_pool_;
  245. tcp::acceptor acceptor_;
  246. bool shutting_down_ = false;
  247. bool server_started_{false};
  248. std::condition_variable cv_started_;
  249. std::mutex start_mutex_;
  250. asio::signal_set signals_;
  251. asio::basic_waitable_timer<std::chrono::high_resolution_clock> tick_timer_;
  252. Handler* handler_;
  253. uint16_t concurrency_{2};
  254. std::uint8_t timeout_;
  255. std::string server_name_;
  256. uint16_t port_;
  257. std::string bindaddr_;
  258. std::vector<std::atomic<unsigned int>> task_queue_length_pool_;
  259. std::chrono::milliseconds tick_interval_;
  260. std::function<void()> tick_function_;
  261. std::tuple<Middlewares...>* middlewares_;
  262. typename Adaptor::context* adaptor_ctx_;
  263. };
  264. } // namespace crow