65 typename Acceptor::endpoint endpoint,
66 std::string server_name = std::string(
"Crow/") + VERSION,
67 std::tuple<Middlewares...>* middlewares =
nullptr,
68 unsigned int concurrency = 1,
70 typename Adaptor::context* adaptor_ctx =
nullptr,
72 concurrency_(concurrency),
73 task_queue_length_pool_(concurrency_ - 1),
74 acceptor_(io_context_),
75 signals_(io_context_),
76 tick_timer_(io_context_),
77 accept_timer_(io_context_),
80 server_name_(server_name),
81 middlewares_(middlewares),
82 adaptor_ctx_(adaptor_ctx),
83 tcp_socket_options_(tcp_socket_options)
85 if (startup_failed_) {
86 CROW_LOG_ERROR <<
"Startup failed; not running server.";
92 acceptor_.raw_acceptor().open(endpoint.protocol(), ec);
94 CROW_LOG_ERROR <<
"Failed to open acceptor: " << ec.message();
95 startup_failed_ =
true;
99 acceptor_.raw_acceptor().set_option(Acceptor::reuse_address_option(), ec);
101 CROW_LOG_ERROR <<
"Failed to set socket option: " << ec.message();
102 startup_failed_ =
true;
106 acceptor_.raw_acceptor().bind(endpoint, ec);
108 CROW_LOG_ERROR <<
"Failed to bind to " << endpoint <<
" - " << ec.message();
109 startup_failed_ =
true;
113 acceptor_.raw_acceptor().listen(tcp::acceptor::max_listen_connections, ec);
115 CROW_LOG_ERROR <<
"Failed to listen on port: " << ec.message();
116 startup_failed_ =
true;
123 void set_tick_function(std::chrono::milliseconds d, std::function<
void()> f)
132 tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
133 tick_timer_.async_wait([
this](
const error_code& ec) {
143 if (startup_failed_) {
144 CROW_LOG_ERROR <<
"Server startup failed. Aborting run().";
148 unsigned int worker_thread_count = concurrency_ - 1;
149 for (
unsigned int i = 0; i < worker_thread_count; i++)
150 io_context_pool_.emplace_back(
new asio::io_context());
151 get_cached_date_str_pool_.resize(worker_thread_count);
152 task_timer_pool_.resize(worker_thread_count);
154 std::vector<std::future<void>> v;
155 std::atomic<unsigned int> init_count(0);
156 for (
unsigned int i = 0; i < worker_thread_count; i++)
159 std::launch::async, [
this, i, &init_count] {
161 auto last = std::chrono::steady_clock::now();
163 std::string date_str;
164 auto update_date_str = [&] {
165 auto last_time_t = time(0);
168#if defined(_MSC_VER) || defined(__MINGW32__)
169 gmtime_s(&my_tm, &last_time_t);
171 gmtime_r(&last_time_t, &my_tm);
173 date_str.resize(100);
174 size_t date_str_sz = strftime(&date_str[0], 99,
"%a, %d %b %Y %H:%M:%S GMT", &my_tm);
175 date_str.resize(date_str_sz);
178 get_cached_date_str_pool_[i] = [&]() -> std::string {
179 if (std::chrono::steady_clock::now() - last >= std::chrono::seconds(1))
181 last = std::chrono::steady_clock::now();
190 task_timer_pool_[i] = &task_timer;
191 task_queue_length_pool_[i] = 0;
198 if (io_context_pool_[i]->run() == 0)
204 catch (std::exception& e)
206 CROW_LOG_ERROR <<
"Worker Crash: An uncaught exception occurred: " << e.what();
211 if (tick_function_ && tick_interval_.count() > 0)
213 tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
214 tick_timer_.async_wait(
215 [
this](
const error_code& ec) {
221 handler_->port(acceptor_.port());
222 handler_->address_is_bound();
223 CROW_LOG_INFO << server_name_
224 <<
" server is running at " << acceptor_.url_display(handler_->ssl_used())
225 <<
" using " << concurrency_ <<
" threads";
226 CROW_LOG_INFO <<
"Call `app.loglevel(crow::LogLevel::Warning)` to hide Info level logs.";
229 [&](
const error_code& ,
int ) {
233 while (worker_thread_count != init_count)
234 std::this_thread::yield();
242 CROW_LOG_INFO <<
"Exiting.";
249 shutting_down_ =
true;
254 if (acceptor_.raw_acceptor().is_open())
256 CROW_LOG_INFO <<
"Closing acceptor. " << &acceptor_;
258 acceptor_.raw_acceptor().close(ec);
261 CROW_LOG_WARNING <<
"Failed to close acceptor: " << ec.message();
265 accept_timer_.cancel();
267 for (
auto& io_context : io_context_pool_)
269 if (io_context !=
nullptr)
271 CROW_LOG_INFO <<
"Closing IO service " << &io_context;
276 CROW_LOG_INFO <<
"Closing main IO service (" << &io_context_ <<
')';
281 uint16_t port()
const {
282 return acceptor_.local_endpoint().port();
288 std::unique_lock<std::mutex> lock(start_mutex_);
290 std::cv_status status = std::cv_status::no_timeout;
291 while (!server_started_ && !startup_failed_ && status == std::cv_status::no_timeout)
292 status = cv_started_.wait_until(lock, wait_until);
302 void signal_add(
int signal_number)
304 signals_.add(signal_number);
308 size_t pick_io_context_idx()
310 size_t min_queue_idx = 0;
315 for (
size_t i = 1; i < task_queue_length_pool_.size() && task_queue_length_pool_[min_queue_idx] > 0; i++)
318 if (task_queue_length_pool_[i] < task_queue_length_pool_[min_queue_idx])
321 return min_queue_idx;
328 size_t context_idx = pick_io_context_idx();
329 asio::io_context& ic = *io_context_pool_[context_idx];
330 auto p = std::make_shared<Connection<Adaptor, Handler, Middlewares...>>(
331 ic, handler_, server_name_, middlewares_,
332 get_cached_date_str_pool_[context_idx], *task_timer_pool_[context_idx], adaptor_ctx_, task_queue_length_pool_[context_idx]);
334 CROW_LOG_DEBUG << &ic <<
" {" << context_idx <<
"} queue length: " << task_queue_length_pool_[context_idx];
336 acceptor_.raw_acceptor().async_accept(
338 [
this, p, &ic](error_code ec) {
341 detail::socket::apply_tcp_socket_options(p->socket(), tcp_socket_options_);
350 if (shutting_down_ || ec == asio::error::operation_aborted)
353 CROW_LOG_ERROR <<
"Failed to accept connection: " << ec.message();
354 if (detail::is_descriptor_exhaustion(ec))
356 accept_timer_.expires_after(std::chrono::milliseconds(100));
357 accept_timer_.async_wait([
this](
const error_code& tec) {
371 std::unique_lock<std::mutex> lock(start_mutex_);
372 server_started_ =
true;
373 cv_started_.notify_all();
377 unsigned int concurrency_{2};
378 std::vector<std::atomic<unsigned int>> task_queue_length_pool_;
379 std::vector<std::unique_ptr<asio::io_context>> io_context_pool_;
380 asio::io_context io_context_;
381 std::vector<detail::task_timer*> task_timer_pool_;
382 std::vector<std::function<std::string()>> get_cached_date_str_pool_;
384 std::atomic<bool> shutting_down_{
false};
385 bool server_started_{
false};
386 bool startup_failed_ =
false;
387 std::condition_variable cv_started_;
388 std::mutex start_mutex_;
389 asio::signal_set signals_;
391 asio::basic_waitable_timer<std::chrono::high_resolution_clock> tick_timer_;
392 asio::steady_timer accept_timer_;
395 std::uint8_t timeout_;
396 std::string server_name_;
399 std::chrono::milliseconds tick_interval_;
400 std::function<void()> tick_function_;
402 std::tuple<Middlewares...>* middlewares_;
404 typename Adaptor::context* adaptor_ctx_;
405 detail::socket::tcp_socket_options tcp_socket_options_;