main.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. #include "database_service.hpp"
  2. #include "config/config_loader.hpp"
  3. #include "persistence/persistence_manager.hpp"
  4. #include "storage/document_store_lmdb.hpp"
  5. #include "storage/lmdb_env.hpp"
  6. #include "storage/migrate_v1_to_v2.hpp"
  7. #include <spdlog/spdlog.h>
  8. #include <spdlog/sinks/stdout_color_sinks.h>
  9. #include <csignal>
  10. #include <cstdio>
  11. #include <cstdlib>
  12. #include <filesystem>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <optional>
  16. #include <string>
  17. #include <vector>
  18. #if defined(__GLIBC__) && !defined(__APPLE__)
  19. #include <malloc.h>
  20. #endif
  21. #ifdef HAVE_SYSTEMD
  22. #include <systemd/sd-daemon.h>
  23. #endif
  24. namespace {
  25. smartbotic::database::DatabaseService* g_service = nullptr;
  26. void signalHandler(int signal) {
  27. spdlog::info("Received signal {}", signal);
  28. if (g_service) {
  29. g_service->signalStop();
  30. }
  31. }
  32. // v1.8.3: diagnostic handlers for hunting the untracked RSS leak observed
  33. // on Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md, "Update 2026-05-13 10:05"). Both are
  34. // async-signal-unsafe under the spec (they call into glibc allocator
  35. // state), but `malloc_info` / `malloc_trim` are well-known to work from
  36. // signal handlers in practice on glibc — and we'd rather have the
  37. // diagnostic than be pedantic about it.
  38. //
  39. // kill -USR1 $PID → write malloc_info(0) XML to stderr (and journal)
  40. // — captures arena stats: blocks in use, fastbin
  41. // caches, mmap'd regions. Compare two samples
  42. // over time to find which arena is growing.
  43. // kill -USR2 $PID → call malloc_trim(0), then log before/after RSS
  44. // — if RSS drops sharply, the gap is allocator
  45. // retention (madvise(DONTNEED) not happening
  46. // autonomously). If it doesn't drop, the leak
  47. // is genuinely held by the application.
  48. void mallocInfoHandler(int) {
  49. #if defined(__GLIBC__) && !defined(__APPLE__)
  50. std::fprintf(stderr, "=== malloc_info dump (SIGUSR1) ===\n");
  51. ::malloc_info(0, stderr);
  52. std::fprintf(stderr, "=== end malloc_info ===\n");
  53. std::fflush(stderr);
  54. #endif
  55. }
  56. void mallocTrimHandler(int) {
  57. #if defined(__GLIBC__) && !defined(__APPLE__)
  58. auto readRssKb = []() -> long {
  59. std::ifstream s("/proc/self/status");
  60. std::string line;
  61. while (std::getline(s, line)) {
  62. if (line.rfind("VmRSS:", 0) == 0) {
  63. long kb = 0;
  64. std::sscanf(line.c_str(), "VmRSS: %ld kB", &kb);
  65. return kb;
  66. }
  67. }
  68. return 0;
  69. };
  70. long before = readRssKb();
  71. int released = ::malloc_trim(0);
  72. long after = readRssKb();
  73. std::fprintf(stderr,
  74. "=== malloc_trim(0) (SIGUSR2): returned=%d, VmRSS %ld kB -> %ld kB (delta %+ld kB) ===\n",
  75. released, before, after, after - before);
  76. std::fflush(stderr);
  77. #endif
  78. }
  79. void printUsage(const char* programName) {
  80. std::cout << "Usage: " << programName << " [OPTIONS]\n"
  81. << "\n"
  82. << "Options:\n"
  83. << " --config, -c PATH Configuration file path\n"
  84. << " --help, -h Show this help message\n"
  85. << " --version, -v Show version information\n"
  86. << " --read-only Start in read-only mode (reject all writes)\n"
  87. << " --force-readwrite Accept non-trivial recovery state; start writable\n"
  88. << " --recovery-mode=MODE Override recovery mode for this boot\n"
  89. << " Values: normal, snapshot_fallback, wal_only,\n"
  90. << " best_effort, force_empty\n"
  91. << " --migrate-from-v1 Force one-shot v1.x → v2.0 migration even\n"
  92. << " if heuristics don't fire (operator escape hatch)\n"
  93. << " --no-auto-migrate Refuse to auto-migrate. If v1.x data is detected\n"
  94. << " at the data directory, exit non-zero.\n"
  95. << "\n"
  96. << "Environment variables:\n"
  97. << " DATABASE_NODE_ID Override node ID from config\n"
  98. << " DATABASE_MASTER_KEY Encryption master key (hex-encoded)\n"
  99. << std::endl;
  100. }
  101. // Injected by service/CMakeLists.txt from the top-level VERSION file. The
  102. // fallback reports "unknown" rather than a plausible-looking literal: an
  103. // honest "unknown" is debuggable, a stale version string is not.
  104. #ifndef SMARTBOTIC_DB_VERSION_STRING
  105. #define SMARTBOTIC_DB_VERSION_STRING "unknown"
  106. #endif
  107. #ifndef SMARTBOTIC_DB_GIT_COMMIT_STRING
  108. // Mirrors the SMARTBOTIC_DB_VERSION_STRING fallback: report the absence rather
  109. // than baking in a literal that could drift.
  110. #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown"
  111. #endif
  112. void printVersion() {
  113. // v2.8.0 — report the build commit too. It was computed and passed as a
  114. // Docker build-arg since v2.4 but never consumed, so packages carried no
  115. // provenance and `--version` could not tell two builds of the same version
  116. // apart.
  117. std::cout << "smartbotic-database version " << SMARTBOTIC_DB_VERSION_STRING
  118. << " (commit " << SMARTBOTIC_DB_GIT_COMMIT_STRING << ")\n"
  119. << "Smartbotic Database Service\n"
  120. << std::endl;
  121. }
  122. void initLogging(const std::string& serviceName) {
  123. try {
  124. // Create console sink
  125. auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  126. console_sink->set_level(spdlog::level::debug);
  127. // Create default logger with console sink
  128. auto logger = std::make_shared<spdlog::logger>(serviceName, console_sink);
  129. logger->set_level(spdlog::level::info);
  130. // Check environment for log level
  131. if (const char* logLevel = std::getenv("LOG_LEVEL")) {
  132. std::string level(logLevel);
  133. if (level == "trace") logger->set_level(spdlog::level::trace);
  134. else if (level == "debug") logger->set_level(spdlog::level::debug);
  135. else if (level == "info") logger->set_level(spdlog::level::info);
  136. else if (level == "warn") logger->set_level(spdlog::level::warn);
  137. else if (level == "error") logger->set_level(spdlog::level::err);
  138. }
  139. spdlog::set_default_logger(logger);
  140. spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [%n] %v");
  141. } catch (const spdlog::spdlog_ex& ex) {
  142. std::cerr << "Log initialization failed: " << ex.what() << std::endl;
  143. }
  144. }
  145. struct CliOverrides {
  146. bool readOnly = false;
  147. bool forceReadwrite = false;
  148. std::optional<smartbotic::database::RecoveryMode> recoveryMode;
  149. // One-shot v1.x → v2.0 migration toggles.
  150. bool migrateFromV1 = false; // --migrate-from-v1 (force, escape hatch)
  151. bool noAutoMigrate = false; // --no-auto-migrate (refuse auto-detect)
  152. };
  153. CliOverrides parseCliOverrides(int argc, char* argv[]) {
  154. CliOverrides ov;
  155. for (int i = 1; i < argc; i++) {
  156. std::string arg = argv[i];
  157. if (arg == "--read-only") {
  158. ov.readOnly = true;
  159. } else if (arg == "--force-readwrite") {
  160. ov.forceReadwrite = true;
  161. } else if (arg == "--migrate-from-v1") {
  162. ov.migrateFromV1 = true;
  163. } else if (arg == "--no-auto-migrate") {
  164. ov.noAutoMigrate = true;
  165. } else if (arg.rfind("--recovery-mode=", 0) == 0) {
  166. std::string mode = arg.substr(std::string("--recovery-mode=").size());
  167. try {
  168. ov.recoveryMode = smartbotic::database::recoveryModeFromString(mode);
  169. } catch (const std::exception& e) {
  170. std::cerr << "ERROR: " << e.what() << std::endl;
  171. std::exit(11);
  172. }
  173. }
  174. }
  175. return ov;
  176. }
  177. // Run the v1.x → v2.0 auto-detect-and-migrate phase. Called from main()
  178. // before service.initialize() so the heavy v1.x recovery sequence doesn't
  179. // run twice. Returns 0 on success or on a clean "no migration needed"
  180. // decision; non-zero on a refused migration (operator must intervene).
  181. //
  182. // On success, the v2.0 schema_version=2 marker is set in the env's _meta
  183. // sub-db, so subsequent boots short-circuit on the migration_complete()
  184. // check inside should_run_migration().
  185. int runV1MigrationIfNeeded(const std::filesystem::path& dataDir,
  186. bool forceMigrate, bool noAutoMigrate) {
  187. using namespace smartbotic::db::storage;
  188. // Already on the v2.3 multi-project layout? Then this instance is well past
  189. // any v1.x → v2.0 migration. Skip the check entirely — crucially without
  190. // create_directories(<dataDir>/env), which would re-create the legacy env
  191. // dir on every boot and trip the v2.3 ambiguous-layout guard in
  192. // migrateLegacyEnvToDefaultProject() (it refuses to start when both
  193. // <dataDir>/env and <dataDir>/projects/default/env exist). That made any
  194. // restart of a migrated instance fatal.
  195. {
  196. std::error_code ec23;
  197. if (std::filesystem::exists(dataDir / "projects" / "default" / "env", ec23)) {
  198. spdlog::info("v2.0 migration: v2.3 layout present (projects/default/env) — "
  199. "skipping v1 check (not creating legacy env/)");
  200. return 0;
  201. }
  202. }
  203. // v2.0 env lives at <dataDir>/env/ — separate from v1.x's snapshots/
  204. // and wal/. Open via the Stage 1 RAII wrapper.
  205. LmdbEnvOpts envOpts;
  206. envOpts.path = (dataDir / "env").string();
  207. envOpts.map_size_bytes = 4ULL << 30; // 4 GiB initial; LMDB grows lazily.
  208. envOpts.max_dbs = 1024;
  209. std::error_code ec;
  210. std::filesystem::create_directories(envOpts.path, ec);
  211. std::unique_ptr<LmdbEnv> env;
  212. try {
  213. env = std::make_unique<LmdbEnv>(envOpts);
  214. } catch (const std::exception& e) {
  215. spdlog::error("Failed to open v2.0 LMDB env at {}: {}", envOpts.path, e.what());
  216. // Pre-Stage-4: this isn't a hard failure path yet because the
  217. // service still boots from v1.x. Treat as "skip migration, log it"
  218. // and let the rest of boot proceed. Once Stage 4 lands, this
  219. // becomes a hard exit.
  220. return 0;
  221. }
  222. AutoMigrateOptions opts;
  223. opts.force = forceMigrate;
  224. opts.disabled = noAutoMigrate;
  225. AutoMigrateDecision decision =
  226. should_run_migration(dataDir.string(), *env, opts);
  227. switch (decision.action) {
  228. case AutoMigrateDecision::Action::SkipNoV1Data:
  229. spdlog::info("v2.0 migration: {}", decision.message);
  230. return 0;
  231. case AutoMigrateDecision::Action::SkipAlreadyMigrated:
  232. spdlog::info("v2.0 migration: {}", decision.message);
  233. return 0;
  234. case AutoMigrateDecision::Action::BlockedByFlag:
  235. spdlog::error("v2.0 migration BLOCKED: {}", decision.message);
  236. std::cerr << "ERROR: " << decision.message << std::endl;
  237. return 12; // exit code 12 = migration refused by operator
  238. case AutoMigrateDecision::Action::RunMigration:
  239. break;
  240. }
  241. // Loud banner — operators reading the journal need to know exactly
  242. // what's about to happen.
  243. spdlog::info("================================================================");
  244. spdlog::info("v2.0 storage migration starting");
  245. spdlog::info(" Source v1.x data dir: {}", dataDir.string());
  246. spdlog::info(" Target v2.0 LMDB env: {}", envOpts.path);
  247. spdlog::info(" This is a one-shot operation. The v1.x data dir is");
  248. spdlog::info(" read-only and will not be modified. Rollback path:");
  249. spdlog::info(" restore /var/backups/smartbotic-database/pre-upgrade-*/.");
  250. spdlog::info("================================================================");
  251. #ifdef HAVE_SYSTEMD
  252. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  253. sd_notify(0, "STATUS=Migrating from v1.x");
  254. #endif
  255. LmdbDocumentStore target(*env);
  256. auto progressCb = [](const MigrationProgress& p) {
  257. #ifdef HAVE_SYSTEMD
  258. std::string status = "STATUS=Migrating from v1.x: " +
  259. std::to_string(p.docs_migrated) + "/" +
  260. std::to_string(p.docs_total);
  261. if (!p.current_collection.empty()) {
  262. status += " in '" + p.current_collection + "'";
  263. }
  264. sd_notify(0, status.c_str());
  265. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  266. #endif
  267. if (p.docs_migrated > 0 && (p.docs_migrated % 5000) == 0) {
  268. spdlog::info("v2.0 migration progress: {}/{} docs (collection '{}')",
  269. p.docs_migrated, p.docs_total, p.current_collection);
  270. }
  271. };
  272. MigrationResult result =
  273. migrate_v1_to_v2(dataDir.string(), target, *env, progressCb);
  274. if (!result.success) {
  275. #ifdef HAVE_SYSTEMD
  276. sd_notify(0, "STATUS=Migration failed");
  277. #endif
  278. spdlog::error("v2.0 migration FAILED: {}", result.error);
  279. std::cerr << "ERROR: v2.0 migration failed:\n " << result.error << std::endl;
  280. return 13; // exit code 13 = migration failure
  281. }
  282. spdlog::info("v2.0 migration complete: {} docs across {} collections",
  283. result.docs_migrated, result.collections_migrated);
  284. return 0;
  285. }
  286. std::filesystem::path findConfigFile(int argc, char* argv[]) {
  287. // Check command line arguments
  288. for (int i = 1; i < argc; ++i) {
  289. std::string arg = argv[i];
  290. if ((arg == "--config" || arg == "-c") && i + 1 < argc) {
  291. return argv[i + 1];
  292. }
  293. }
  294. // Check environment variable
  295. if (const char* configPath = std::getenv("DATABASE_CONFIG")) {
  296. return configPath;
  297. }
  298. // Default paths
  299. std::vector<std::filesystem::path> defaultPaths = {
  300. "./config/database.json",
  301. "./config/storage.json", // Backward compatibility
  302. "/etc/smartbotic/database.json",
  303. "/etc/callerai/storage.json", // Backward compatibility
  304. std::filesystem::path(std::getenv("HOME") ? std::getenv("HOME") : "") / ".config/smartbotic/database.json"
  305. };
  306. for (const auto& path : defaultPaths) {
  307. if (std::filesystem::exists(path)) {
  308. return path;
  309. }
  310. }
  311. return "./config/database.json";
  312. }
  313. } // anonymous namespace
  314. // v1.8.1: Cap glibc per-thread malloc arenas. With ~20+ threads
  315. // (eviction / WAL sync / snapshot / gRPC pool / replication apply +
  316. // connection loop), the default `8 × num_cpus` arenas fragment heap
  317. // pages so they're never returned to the OS, drifting RSS far above
  318. // the DB's tracked working set (Zoe: 6.5 GB gap, OOM every ~3h until
  319. // MALLOC_ARENA_MAX=2 was set). The systemd unit sets the env var as
  320. // the primary control; this programmatic call covers non-systemd
  321. // deployments (docker, ad-hoc launches). Skip if the env var is
  322. // already set, so operators can override.
  323. static void capGlibcArenas() {
  324. #if defined(__GLIBC__) && !defined(__APPLE__)
  325. if (const char* v = std::getenv("MALLOC_ARENA_MAX"); v && *v) {
  326. return; // Operator override in effect — respect it.
  327. }
  328. if (::mallopt(M_ARENA_MAX, 2) == 0) {
  329. // mallopt returns nonzero on success; silent — the worst case is
  330. // we run with default arenas and observe the historical drift.
  331. }
  332. #endif
  333. }
  334. int main(int argc, char* argv[]) {
  335. capGlibcArenas();
  336. // Parse command line arguments
  337. for (int i = 1; i < argc; ++i) {
  338. std::string arg = argv[i];
  339. if (arg == "--help" || arg == "-h") {
  340. printUsage(argv[0]);
  341. return 0;
  342. }
  343. if (arg == "--version" || arg == "-v") {
  344. printVersion();
  345. return 0;
  346. }
  347. }
  348. try {
  349. // Initialize logging
  350. initLogging("database");
  351. // Find configuration file (base) + sibling conf.d/ drop-in directory
  352. auto configPath = findConfigFile(argc, argv);
  353. auto confDir = configPath.parent_path() / "conf.d";
  354. spdlog::info("Loading configuration from {} (drop-ins: {})",
  355. configPath.string(), confDir.string());
  356. // Load configuration. The loader accepts a missing base file (empty {})
  357. // and a missing conf.d/. If either exists we parse it; syntax errors
  358. // in any file are fatal with exit code 11 (config invalid).
  359. smartbotic::database::DatabaseService::Config config;
  360. const bool baseExists = std::filesystem::exists(configPath);
  361. const bool dropinsExist = std::filesystem::exists(confDir);
  362. if (baseExists || dropinsExist) {
  363. try {
  364. std::vector<std::filesystem::path> mergedFiles;
  365. nlohmann::json merged = smartbotic::database::loadLayeredConfig(
  366. configPath, confDir, &mergedFiles);
  367. config = smartbotic::database::DatabaseService::parseConfig(merged);
  368. } catch (const std::exception& e) {
  369. std::cerr << "Config error: " << e.what() << std::endl;
  370. spdlog::error("Config error: {}", e.what());
  371. return 11;
  372. }
  373. } else {
  374. spdlog::warn("Configuration file not found, using defaults");
  375. // Set default data directory
  376. const char* home = std::getenv("HOME");
  377. if (home) {
  378. config.dataDirectory = std::filesystem::path(home) / ".local/share/smartbotic/database";
  379. config.keyFilePath = std::filesystem::path(home) / ".config/smartbotic/database.key";
  380. } else {
  381. config.dataDirectory = "/var/lib/smartbotic/database";
  382. config.keyFilePath = "/etc/smartbotic/database.key";
  383. }
  384. }
  385. // Override node ID from environment if set
  386. if (const char* nodeId = std::getenv("DATABASE_NODE_ID")) {
  387. config.nodeId = nodeId;
  388. }
  389. // Parse CLI overrides (--read-only, --force-readwrite, --recovery-mode=...,
  390. // --migrate-from-v1, --no-auto-migrate)
  391. auto cli = parseCliOverrides(argc, argv);
  392. // Apply --recovery-mode to persistence config before service construction
  393. if (cli.recoveryMode) {
  394. config.persistenceConfig.recoveryMode = *cli.recoveryMode;
  395. }
  396. // Auto-detect-and-migrate v1.x data before the
  397. // service initialises. Runs against <dataDir>/env/ (the v2.0 LMDB
  398. // env). On success, sets the schema_version=2 marker so subsequent
  399. // boots short-circuit. On a refused migration (--no-auto-migrate +
  400. // v1.x data present, or migration failure) we exit non-zero before
  401. // the service starts.
  402. if (int rc = runV1MigrationIfNeeded(config.dataDirectory,
  403. cli.migrateFromV1,
  404. cli.noAutoMigrate);
  405. rc != 0) {
  406. return rc;
  407. }
  408. // Create service
  409. smartbotic::database::DatabaseService service(config);
  410. g_service = &service;
  411. // Apply --force-readwrite BEFORE initialize() so auto-readonly check respects it
  412. if (cli.forceReadwrite) {
  413. service.setForceReadwrite(true);
  414. }
  415. // Set up signal handlers
  416. std::signal(SIGINT, signalHandler);
  417. std::signal(SIGTERM, signalHandler);
  418. // v1.8.3: SIGUSR1 / SIGUSR2 for live heap-state probing on Zoe. Both
  419. // log to stderr (caught by the systemd journal), do not interrupt
  420. // service operation. Documented in CLAUDE.md.
  421. std::signal(SIGUSR1, mallocInfoHandler);
  422. std::signal(SIGUSR2, mallocTrimHandler);
  423. #ifdef HAVE_SYSTEMD
  424. // v1.7.5: extend the systemd start timeout while recovery is
  425. // running. Default TimeoutStartSec=90s + a 5-min unit cap is
  426. // enough for most datasets, but very large databases (millions
  427. // of docs, multi-GB WAL) can exceed that. EXTEND_TIMEOUT_USEC
  428. // pushes systemd's clock back a fixed interval — we re-issue
  429. // it on each major step so the watchdog never fires mid-replay.
  430. // 600 seconds (10 min) per step is generous and only affects
  431. // the start phase; once READY is sent, normal WatchdogSec
  432. // semantics take over.
  433. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  434. sd_notify(0, "STATUS=Initializing — running recovery and migrations");
  435. #endif
  436. // Initialize service. Recovery-refused is reported via the
  437. // recovery_outcome_ state (banner printed by DatabaseService) and
  438. // maps to exit code 10.
  439. if (!service.initialize()) {
  440. if (service.recoveryOutcome().isFailure()) {
  441. // Banner was already printed by DatabaseService; just exit with code 10.
  442. return 10;
  443. }
  444. spdlog::error("Failed to initialize database service");
  445. return 1;
  446. }
  447. // Apply --read-only after initialize() succeeds, before start() accepts connections
  448. if (cli.readOnly) {
  449. service.setReadOnly(true, "started with --read-only flag");
  450. }
  451. #ifdef HAVE_SYSTEMD
  452. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  453. sd_notify(0, "STATUS=Starting gRPC server");
  454. #endif
  455. // Start service
  456. service.start();
  457. #ifdef HAVE_SYSTEMD
  458. // v1.7.5: only notify READY *after* full initialization +
  459. // service.start() — recovery is done, migrations are applied,
  460. // gRPC is listening. With the unit set to Type=notify,
  461. // dependents (shadowman-tools, -gateway, -server) block in
  462. // their own systemd start until this READY arrives, so they
  463. // can never observe an in-recovery DB and silently fall back
  464. // to defaults. Pre-1.7.5 the unit was Type=simple — sd_notify
  465. // was effectively decoration.
  466. sd_notify(0, "READY=1");
  467. sd_notify(0, "STATUS=Ready");
  468. spdlog::info("Notified systemd: READY");
  469. #endif
  470. // Wait for shutdown
  471. int watchdogCounter = 0;
  472. while (service.isRunning()) {
  473. std::this_thread::sleep_for(std::chrono::seconds(1));
  474. #ifdef HAVE_SYSTEMD
  475. // Send watchdog notification every 30 seconds (half of WatchdogSec=60)
  476. if (++watchdogCounter >= 30) {
  477. sd_notify(0, "WATCHDOG=1");
  478. watchdogCounter = 0;
  479. }
  480. #endif
  481. }
  482. #ifdef HAVE_SYSTEMD
  483. sd_notify(0, "STOPPING=1");
  484. #endif
  485. // Stop service
  486. service.stop();
  487. g_service = nullptr;
  488. spdlog::info("Database service exited cleanly");
  489. return 0;
  490. } catch (const std::exception& e) {
  491. spdlog::error("Fatal error: {}", e.what());
  492. return 1;
  493. }
  494. }