server: refactor server entrypoint (#31113)

* server_role

* cont
This commit is contained in:
Xuan-Son Nguyen authored and GitHub committed 2026-10-24 20:04:28 +02:00
1 parent 3f03b17724
commit f3269ef96a
7 files changed
+651 -527

No files matched your search

+63
View File
@@ -16,7 +16,9 @@
#include <limits>
#include <cstring>
#include <type_traits>
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
#ifdef _WIN32
@@ -2210,3 +2212,64 @@ void server_subproc::waiter::wait(const std::vector<server_subproc *> & procs, s
}
#endif
}
//
// server_role
//
server_role::server_role() {
if (is_managed_by_router()) {
cmd_out = server_reserve_stdout();
}
}
server_role::~server_role() {
if (cmd_out) {
fclose(cmd_out);
}
}
bool server_role::is_managed_by_router() {
return std::getenv(SERVER_ENV_ROUTER_PORT) != nullptr;
}
server_role_type server_role::get_role() {
const char * role = std::getenv(SERVER_ENV_CHILD_ROLE);
return server_role_type_from_str(role ? role : "");
}
std::thread server_role::setup(const std::function<void(int)> & shutdown_handler) {
// setup thread for monitoring stdin
return std::thread([shutdown_handler]() {
// wait for EOF on stdin
SRV_INF("%s", "child server monitoring thread started, waiting for EOF on stdin...\n");
bool eof = false;
while (true) {
std::string line;
if (!std::getline(std::cin, line)) {
// EOF detected, that means the router server is unexpectedly exit or killed
eof = true;
break;
}
if (line.find(CMD_ROUTER_TO_CHILD_EXIT) != std::string::npos) {
SRV_INF("%s", "exit command received, exiting...\n");
shutdown_handler(0);
break;
}
}
if (eof) {
SRV_INF("%s", "EOF on stdin detected, forcing shutdown...\n");
exit(1);
}
});
}
void server_role::notify_to_router(const std::string & state, const json & payload) {
json data = {
{"state", state},
{"payload", payload},
};
std::lock_guard<std::mutex> lk(mtx_stdout);
fprintf(cmd_out, "%s%s\n", CMD_CHILD_TO_ROUTER_STATE, safe_json_to_str(data).c_str());
fflush(cmd_out);
}