50 typename Acceptor::endpoint endpoint,
51 std::string server_name = std::string(
"Crow/") + VERSION,
52 std::tuple<Middlewares...>* middlewares =
nullptr,
53 unsigned int concurrency = 1,
55 typename Adaptor::context* adaptor_ctx =
nullptr,
57 concurrency_(concurrency),
58 task_queue_length_pool_(concurrency_ - 1),
59 acceptor_(io_context_),
60 signals_(io_context_),
61 tick_timer_(io_context_),
64 server_name_(server_name),
65 middlewares_(middlewares),
66 adaptor_ctx_(adaptor_ctx),
67 tcp_socket_options_(tcp_socket_options)
69 if (startup_failed_) {
70 CROW_LOG_ERROR <<
"Startup failed; not running server.";
76 acceptor_.raw_acceptor().open(endpoint.protocol(), ec);
78 CROW_LOG_ERROR <<
"Failed to open acceptor: " << ec.message();
79 startup_failed_ =
true;
83 acceptor_.raw_acceptor().set_option(Acceptor::reuse_address_option(), ec);
85 CROW_LOG_ERROR <<
"Failed to set socket option: " << ec.message();
86 startup_failed_ =
true;
90 acceptor_.raw_acceptor().bind(endpoint, ec);
92 CROW_LOG_ERROR <<
"Failed to bind to " << acceptor_.address()
93 <<
":" << acceptor_.port() <<
" - " << ec.message();
94 startup_failed_ =
true;
98 acceptor_.raw_acceptor().listen(tcp::acceptor::max_listen_connections, ec);
100 CROW_LOG_ERROR <<
"Failed to listen on port: " << ec.message();
101 startup_failed_ =
true;
108 void set_tick_function(std::chrono::milliseconds d, std::function<
void()> f)
117 tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
118 tick_timer_.async_wait([
this](
const error_code& ec) {
128 if (startup_failed_) {
129 CROW_LOG_ERROR <<
"Server startup failed. Aborting run().";
133 uint16_t worker_thread_count = concurrency_ - 1;
134 for (
int i = 0; i < worker_thread_count; i++)
135 io_context_pool_.emplace_back(
new asio::io_context());
136 get_cached_date_str_pool_.resize(worker_thread_count);
137 task_timer_pool_.resize(worker_thread_count);
139 std::vector<std::future<void>> v;
140 std::atomic<int> init_count(0);
141 for (uint16_t i = 0; i < worker_thread_count; i++)
144 std::launch::async, [
this, i, &init_count] {
146 auto last = std::chrono::steady_clock::now();
148 std::string date_str;
149 auto update_date_str = [&] {
150 auto last_time_t = time(0);
153#if defined(_MSC_VER) || defined(__MINGW32__)
154 gmtime_s(&my_tm, &last_time_t);
156 gmtime_r(&last_time_t, &my_tm);
158 date_str.resize(100);
159 size_t date_str_sz = strftime(&date_str[0], 99,
"%a, %d %b %Y %H:%M:%S GMT", &my_tm);
160 date_str.resize(date_str_sz);
163 get_cached_date_str_pool_[i] = [&]() -> std::string {
164 if (std::chrono::steady_clock::now() - last >= std::chrono::seconds(1))
166 last = std::chrono::steady_clock::now();
175 task_timer_pool_[i] = &task_timer;
176 task_queue_length_pool_[i] = 0;
183 if (io_context_pool_[i]->run() == 0)
189 catch (std::exception& e)
191 CROW_LOG_ERROR <<
"Worker Crash: An uncaught exception occurred: " << e.what();
196 if (tick_function_ && tick_interval_.count() > 0)
198 tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
199 tick_timer_.async_wait(
200 [
this](
const error_code& ec) {
206 handler_->port(acceptor_.port());
207 handler_->address_is_bound();
208 CROW_LOG_INFO << server_name_
209 <<
" server is running at " << acceptor_.url_display(handler_->ssl_used())
210 <<
" using " << concurrency_ <<
" threads";
211 CROW_LOG_INFO <<
"Call `app.loglevel(crow::LogLevel::Warning)` to hide Info level logs.";
214 [&](
const error_code& ,
int ) {
218 while (worker_thread_count != init_count)
219 std::this_thread::yield();
227 CROW_LOG_INFO <<
"Exiting.";
234 shutting_down_ =
true;
239 if (acceptor_.raw_acceptor().is_open())
241 CROW_LOG_INFO <<
"Closing acceptor. " << &acceptor_;
243 acceptor_.raw_acceptor().close(ec);
246 CROW_LOG_WARNING <<
"Failed to close acceptor: " << ec.message();
250 for (
auto& io_context : io_context_pool_)
252 if (io_context !=
nullptr)
254 CROW_LOG_INFO <<
"Closing IO service " << &io_context;
259 CROW_LOG_INFO <<
"Closing main IO service (" << &io_context_ <<
')';
264 uint16_t port()
const {
265 return acceptor_.local_endpoint().port();
271 std::unique_lock<std::mutex> lock(start_mutex_);
273 std::cv_status status = std::cv_status::no_timeout;
274 while (!server_started_ && !startup_failed_ && status == std::cv_status::no_timeout)
275 status = cv_started_.wait_until(lock, wait_until);
285 void signal_add(
int signal_number)
287 signals_.add(signal_number);
291 size_t pick_io_context_idx()
293 size_t min_queue_idx = 0;
298 for (
size_t i = 1; i < task_queue_length_pool_.size() && task_queue_length_pool_[min_queue_idx] > 0; i++)
301 if (task_queue_length_pool_[i] < task_queue_length_pool_[min_queue_idx])
304 return min_queue_idx;
311 size_t context_idx = pick_io_context_idx();
312 asio::io_context& ic = *io_context_pool_[context_idx];
313 auto p = std::make_shared<Connection<Adaptor, Handler, Middlewares...>>(
314 ic, handler_, server_name_, middlewares_,
315 get_cached_date_str_pool_[context_idx], *task_timer_pool_[context_idx], adaptor_ctx_, task_queue_length_pool_[context_idx]);
317 CROW_LOG_DEBUG << &ic <<
" {" << context_idx <<
"} queue length: " << task_queue_length_pool_[context_idx];
319 acceptor_.raw_acceptor().async_accept(
321 [
this, p, &ic](error_code ec) {
324 detail::socket::apply_tcp_socket_options(p->socket(), tcp_socket_options_);
338 std::unique_lock<std::mutex> lock(start_mutex_);
339 server_started_ =
true;
340 cv_started_.notify_all();
344 unsigned int concurrency_{2};
345 std::vector<std::atomic<unsigned int>> task_queue_length_pool_;
346 std::vector<std::unique_ptr<asio::io_context>> io_context_pool_;
347 asio::io_context io_context_;
348 std::vector<detail::task_timer*> task_timer_pool_;
349 std::vector<std::function<std::string()>> get_cached_date_str_pool_;
351 bool shutting_down_ =
false;
352 bool server_started_{
false};
353 bool startup_failed_ =
false;
354 std::condition_variable cv_started_;
355 std::mutex start_mutex_;
356 asio::signal_set signals_;
358 asio::basic_waitable_timer<std::chrono::high_resolution_clock> tick_timer_;
361 std::uint8_t timeout_;
362 std::string server_name_;
365 std::chrono::milliseconds tick_interval_;
366 std::function<void()> tick_function_;
368 std::tuple<Middlewares...>* middlewares_;
370 typename Adaptor::context* adaptor_ctx_;
371 detail::socket::tcp_socket_options tcp_socket_options_;