OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
OdbServerAppBase.cpp
Go to the documentation of this file.
1#include "OdbServerAppBase.h"
2// #include "Logger.h"
4#include <crow_win.h>
5// #include <boost/throw_exception.hpp>
6// #include <boost/system/system_error.hpp>
7#include <App/OdbAppBase.h>
8#include <ExitCode.h>
9#include <memory>
10#include <csignal>
11#include <iostream>
12#include <string>
13#include <thread>
14#include <utility>
15#include <App/DesignCache.h>
16#include <crow/compression.h>
17#include <crow/logging.h>
18
19#if defined(_WIN32)
20#include <io.h>
21#define ISATTY _isatty
22#define FILENO _fileno
23#else
24#include <unistd.h>
25#define ISATTY isatty
26#define FILENO fileno
27#include <sys/select.h>
28#include <sys/time.h>
29#endif
30#include <atomic>
31#include <cctype>
32#include <cstdio>
33#include <crow/app.h>
34#include <crow/http_response.h>
35#include <grpcpp/server.h>
36
37using namespace Utils;
38using namespace std::filesystem;
39
40namespace {
41
42// Interactive console quit helper (TTY-only)
43 std::atomic<bool> s_consoleLoopStarted{ false };
44 std::atomic<bool> s_consoleLoopStop{ false };
45 std::thread s_consoleThread;
46
47 void start_interactive_quit_if_tty()
48 {
49 if (s_consoleLoopStarted.exchange(true)) return;
50 if (!ISATTY(FILENO(stdin)))
51 {
52 return; // non-interactive (containers/k8s) -> no console loop
53 }
54
55 s_consoleLoopStop.store(false);
56 s_consoleThread = std::thread([]
57 {
58 std::fprintf(stderr, "[interactive] Type 'q' then Enter to quit gracefully...\n");
59 std::string line;
60 while (!s_consoleLoopStop.load() && std::getline(std::cin, line))
61 {
62 for (auto& ch : line) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
63 if (line == "q" || line == "quit" || line == "exit" || line == "shutdown")
64 {
65 // Unify with the SIGINT path your class already exposes
67 break;
68 }
69 }
70 });
71 }
72
73 void stop_interactive_quit() { s_consoleLoopStop.store(true); }
74 void join_interactive_quit() { if (s_consoleThread.joinable()) s_consoleThread.join(); }
75
76} // anonymous namespace
77
78namespace Odb::Lib::App
79{
80 std::atomic<OdbServerAppBase *> OdbServerAppBase::s_activeInstance{nullptr};
81
82 OdbServerAppBase::OdbServerAppBase(int argc, char *argv[])
83 : OdbAppBase(argc, argv), m_shutdownFlag(false)
84 {
85 // Initialize the design cache shared pointer to point to the base class's design cache
86 m_pDesignCache = std::shared_ptr<DesignCache>(&m_designCache, [](DesignCache *) {});
87 s_activeInstance.store(this, std::memory_order_release);
88 }
89
91 {
92 // override in extended class to configure server or run custom code
93 return true;
94 }
95
97 {
98 // override in extended class to cleanup server or run custom code
99 return true;
100 }
101
103 {
104 stop_servers();
105 m_vecControllers.clear();
106 s_activeInstance.store(nullptr, std::memory_order_release);
107 }
108
110 {
111 auto *instance = s_activeInstance.load(std::memory_order_acquire);
112 if (instance != nullptr)
113 {
114 instance->signal_handler(signum);
115 }
116 }
117
118 void OdbServerAppBase::RunGrpcServer(const std::string &server_address, std::shared_ptr<DesignCache> cache)
119 {
120 // Default implementation does nothing
121 // Override in subclass to implement gRPC service
122 std::cout << "gRPC server not implemented in base class" << std::endl;
123 }
124
125 void OdbServerAppBase::start_grpc_server()
126 {
127 if (args().grpcPort() > 0 && m_pDesignCache)
128 {
129 // honor the bind address for gRPC too (default "0.0.0.0"), so e.g.
130 // loopback-locked builds cannot be exposed via the gRPC port
131 auto grpcBindAddress = args().bindAddress();
132 // bracket a bare IPv6 literal so "<addr>:<port>" stays parseable
133 // (e.g. "::1" -> "[::1]:<port>"); IPv4 addresses and hostnames unchanged
134 if (!grpcBindAddress.empty() && grpcBindAddress.front() != '[' && grpcBindAddress.find(':') != std::string::npos)
135 {
136 grpcBindAddress = "[" + grpcBindAddress + "]";
137 }
138 std::string grpc_server_address = grpcBindAddress + ":" + std::to_string(args().grpcPort());
139 m_grpcThread = std::make_unique<std::thread>(&OdbServerAppBase::RunGrpcServer, this, grpc_server_address, m_pDesignCache);
140 std::cout << "gRPC server thread started on port " << args().grpcPort() << std::endl;
141 }
142 }
143
144 void OdbServerAppBase::set_grpc_server(std::shared_ptr<grpc::Server> server) {
145 m_grpcServer = std::move(server);
146 }
147
148 // Accessor if needed by controllers/services
149 inline std::shared_ptr<grpc::Server> OdbServerAppBase::grpc_server() const { return m_grpcServer; }
150
151 void OdbServerAppBase::stop_servers()
152 {
153 if (m_shutdownFlag.exchange(true))
154 {
155 return; // Already shutting down
156 }
157
158 std::cout << "Shutting down servers..." << std::endl;
159
160 // Stop Crow
161 m_crowApp.stop();
162
163 // Stop gRPC
164 if (m_grpcServer)
165 {
166 m_grpcServer->Shutdown();
167 }
168
169 // Wait for gRPC thread to finish
170 if (m_grpcThread && m_grpcThread->joinable())
171 {
172 m_grpcThread->join();
173 }
174
175 std::cout << "All servers shut down." << std::endl;
176 }
177
179 {
180 // print usage and exit w/ success
181 if (args().help())
182 {
183 args().printUsage();
184 return ExitCode::Success;
185 }
186
187 // call base class
188 if (ExitCode::Success != OdbAppBase::Run())
189 return ExitCode::FailedInit;
190
191 // set Crow's log level
192 m_crowApp.loglevel(crow::LogLevel::Info);
193
194 // enable HTTP compression
195 m_crowApp.use_compression(crow::compression::algorithm::GZIP);
196
197 // let subclasses add controller types
199
200 // register all added controllers' routes
201 register_routes();
202
203 // minimal health/readiness routes
204 CROW_ROUTE(m_crowApp, "/healthz")([] {
205 return crow::response{ 200, "ok" };
206 });
207 CROW_ROUTE(m_crowApp, "/ready")([this] {
208 if (m_shutdownFlag.load()) return crow::response{ 503, "not ready" };
209 return crow::response{ 200, "ready" };
210 });
211
212 // enable optional per-request HTTP tracing
214
215 // make the bind address explicit (avoid ambiguity across platforms/containers)
216 m_crowApp.bindaddr(args().bindAddress());
217
218 // set port to passed-in port or default if none supplied
219 m_crowApp.port(static_cast<unsigned short>(args().port()));
220
221 // set server to use multiple threads
222 m_crowApp.multithreaded();
223
224 if (!preServerRun())
225 return ExitCode::PreServerRunFailed;
226
227 // Start gRPC server in a separate thread
228 start_grpc_server();
229
230 // Start interactive quit (TTY only). Type 'q' + Enter to stop.
231 start_interactive_quit_if_tty();
232
233 // run the Crow server (blocks until stop() is called)
234 std::cout << "Crow REST server starting on " << args().bindAddress() << ":" << args().port()
235 << " (http-trace=" << (args().httpTrace() ? "true" : "false") << ")" << std::endl;
236 m_crowApp.run();
237
238 // Stop interactive watcher and join
239 stop_interactive_quit();
240 join_interactive_quit();
241
242 // Stop gRPC
243 if (m_grpcServer)
244 {
245 m_grpcServer->Shutdown();
246 }
247
248 // Wait for gRPC thread to finish
249 if (m_grpcThread && m_grpcThread->joinable())
250 {
251 m_grpcThread->join();
252 }
253
254 if (!postServerRun())
255 return ExitCode::PostServerRunFailed;
256
257 // success!
258 return ExitCode::Success;
259 }
260
262 {
263 return m_crowApp;
264 }
265
267 {
268 return *m_pRequestAuthentication;
269 }
270
271 void OdbServerAppBase::request_auth(std::unique_ptr<RequestAuthenticationBase> pRequestAuthentication)
272 {
273 m_pRequestAuthentication = std::move(pRequestAuthentication);
274 }
275
276 std::shared_ptr<DesignCache> OdbServerAppBase::design_cache()
277 {
278 return m_pDesignCache;
279 }
280
281 void OdbServerAppBase::design_cache(std::shared_ptr<DesignCache> pDesignCache)
282 {
283 m_pDesignCache = pDesignCache;
284 }
285
286 void OdbServerAppBase::register_routes()
287 {
288 for (const auto &pController : m_vecControllers)
289 {
290 pController->register_routes();
291 }
292 }
293
294 void OdbServerAppBase::signal_handler(int signum)
295 {
296 std::cout << "\nSignal " << signum << " received. Initiating graceful shutdown..." << std::endl;
297 stop_servers();
298 }
299}
#define ISATTY
#define FILENO
const OdbDesignArgs & args() const override
virtual Utils::ExitCode Run() override
std::string bindAddress() const
std::shared_ptr< DesignCache > design_cache() override
RequestAuthenticationBase & request_auth() override
std::shared_ptr< grpc::Server > m_grpcServer
std::unique_ptr< std::thread > m_grpcThread
RouteController::Vector m_vecControllers
virtual void RunGrpcServer(const std::string &server_address, std::shared_ptr< DesignCache > cache)
void set_grpc_server(std::shared_ptr< grpc::Server > server)
static void HandleSignal(int signum)
Utils::ExitCode Run() override
OdbServerAppBase(int argc, char *argv[])
virtual void add_controllers()=0
std::shared_ptr< grpc::Server > grpc_server() const
static void SetEnabled(bool enabled) noexcept
crow::Crow< crow::CORSHandler > CrowApp
Definition crow_win.h:19
ExitCode
Definition ExitCode.h:7