| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559 |
- #include "database_service.hpp"
- #include "config/config_loader.hpp"
- #include "persistence/persistence_manager.hpp"
- #include "storage/document_store_lmdb.hpp"
- #include "storage/lmdb_env.hpp"
- #include "storage/migrate_v1_to_v2.hpp"
- #include <spdlog/spdlog.h>
- #include <spdlog/sinks/stdout_color_sinks.h>
- #include <csignal>
- #include <cstdio>
- #include <cstdlib>
- #include <filesystem>
- #include <fstream>
- #include <iostream>
- #include <optional>
- #include <string>
- #include <vector>
- #if defined(__GLIBC__) && !defined(__APPLE__)
- #include <malloc.h>
- #endif
- #ifdef HAVE_SYSTEMD
- #include <systemd/sd-daemon.h>
- #endif
- namespace {
- smartbotic::database::DatabaseService* g_service = nullptr;
- void signalHandler(int signal) {
- spdlog::info("Received signal {}", signal);
- if (g_service) {
- g_service->signalStop();
- }
- }
- // v1.8.3: diagnostic handlers for hunting the untracked RSS leak observed
- // on Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md, "Update 2026-05-13 10:05"). Both are
- // async-signal-unsafe under the spec (they call into glibc allocator
- // state), but `malloc_info` / `malloc_trim` are well-known to work from
- // signal handlers in practice on glibc — and we'd rather have the
- // diagnostic than be pedantic about it.
- //
- // kill -USR1 $PID → write malloc_info(0) XML to stderr (and journal)
- // — captures arena stats: blocks in use, fastbin
- // caches, mmap'd regions. Compare two samples
- // over time to find which arena is growing.
- // kill -USR2 $PID → call malloc_trim(0), then log before/after RSS
- // — if RSS drops sharply, the gap is allocator
- // retention (madvise(DONTNEED) not happening
- // autonomously). If it doesn't drop, the leak
- // is genuinely held by the application.
- void mallocInfoHandler(int) {
- #if defined(__GLIBC__) && !defined(__APPLE__)
- std::fprintf(stderr, "=== malloc_info dump (SIGUSR1) ===\n");
- ::malloc_info(0, stderr);
- std::fprintf(stderr, "=== end malloc_info ===\n");
- std::fflush(stderr);
- #endif
- }
- void mallocTrimHandler(int) {
- #if defined(__GLIBC__) && !defined(__APPLE__)
- auto readRssKb = []() -> long {
- std::ifstream s("/proc/self/status");
- std::string line;
- while (std::getline(s, line)) {
- if (line.rfind("VmRSS:", 0) == 0) {
- long kb = 0;
- std::sscanf(line.c_str(), "VmRSS: %ld kB", &kb);
- return kb;
- }
- }
- return 0;
- };
- long before = readRssKb();
- int released = ::malloc_trim(0);
- long after = readRssKb();
- std::fprintf(stderr,
- "=== malloc_trim(0) (SIGUSR2): returned=%d, VmRSS %ld kB -> %ld kB (delta %+ld kB) ===\n",
- released, before, after, after - before);
- std::fflush(stderr);
- #endif
- }
- void printUsage(const char* programName) {
- std::cout << "Usage: " << programName << " [OPTIONS]\n"
- << "\n"
- << "Options:\n"
- << " --config, -c PATH Configuration file path\n"
- << " --help, -h Show this help message\n"
- << " --version, -v Show version information\n"
- << " --read-only Start in read-only mode (reject all writes)\n"
- << " --force-readwrite Accept non-trivial recovery state; start writable\n"
- << " --recovery-mode=MODE Override recovery mode for this boot\n"
- << " Values: normal, snapshot_fallback, wal_only,\n"
- << " best_effort, force_empty\n"
- << " --migrate-from-v1 Force one-shot v1.x → v2.0 migration even\n"
- << " if heuristics don't fire (operator escape hatch)\n"
- << " --no-auto-migrate Refuse to auto-migrate. If v1.x data is detected\n"
- << " at the data directory, exit non-zero.\n"
- << "\n"
- << "Environment variables:\n"
- << " DATABASE_NODE_ID Override node ID from config\n"
- << " DATABASE_MASTER_KEY Encryption master key (hex-encoded)\n"
- << std::endl;
- }
- // Injected by service/CMakeLists.txt from the top-level VERSION file. The
- // fallback reports "unknown" rather than a plausible-looking literal: an
- // honest "unknown" is debuggable, a stale version string is not.
- #ifndef SMARTBOTIC_DB_VERSION_STRING
- #define SMARTBOTIC_DB_VERSION_STRING "unknown"
- #endif
- #ifndef SMARTBOTIC_DB_GIT_COMMIT_STRING
- // Mirrors the SMARTBOTIC_DB_VERSION_STRING fallback: report the absence rather
- // than baking in a literal that could drift.
- #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown"
- #endif
- void printVersion() {
- // v2.8.0 — report the build commit too. It was computed and passed as a
- // Docker build-arg since v2.4 but never consumed, so packages carried no
- // provenance and `--version` could not tell two builds of the same version
- // apart.
- std::cout << "smartbotic-database version " << SMARTBOTIC_DB_VERSION_STRING
- << " (commit " << SMARTBOTIC_DB_GIT_COMMIT_STRING << ")\n"
- << "Smartbotic Database Service\n"
- << std::endl;
- }
- void initLogging(const std::string& serviceName) {
- try {
- // Create console sink
- auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
- console_sink->set_level(spdlog::level::debug);
- // Create default logger with console sink
- auto logger = std::make_shared<spdlog::logger>(serviceName, console_sink);
- logger->set_level(spdlog::level::info);
- // Check environment for log level
- if (const char* logLevel = std::getenv("LOG_LEVEL")) {
- std::string level(logLevel);
- if (level == "trace") logger->set_level(spdlog::level::trace);
- else if (level == "debug") logger->set_level(spdlog::level::debug);
- else if (level == "info") logger->set_level(spdlog::level::info);
- else if (level == "warn") logger->set_level(spdlog::level::warn);
- else if (level == "error") logger->set_level(spdlog::level::err);
- }
- spdlog::set_default_logger(logger);
- spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [%n] %v");
- } catch (const spdlog::spdlog_ex& ex) {
- std::cerr << "Log initialization failed: " << ex.what() << std::endl;
- }
- }
- struct CliOverrides {
- bool readOnly = false;
- bool forceReadwrite = false;
- std::optional<smartbotic::database::RecoveryMode> recoveryMode;
- // One-shot v1.x → v2.0 migration toggles.
- bool migrateFromV1 = false; // --migrate-from-v1 (force, escape hatch)
- bool noAutoMigrate = false; // --no-auto-migrate (refuse auto-detect)
- };
- CliOverrides parseCliOverrides(int argc, char* argv[]) {
- CliOverrides ov;
- for (int i = 1; i < argc; i++) {
- std::string arg = argv[i];
- if (arg == "--read-only") {
- ov.readOnly = true;
- } else if (arg == "--force-readwrite") {
- ov.forceReadwrite = true;
- } else if (arg == "--migrate-from-v1") {
- ov.migrateFromV1 = true;
- } else if (arg == "--no-auto-migrate") {
- ov.noAutoMigrate = true;
- } else if (arg.rfind("--recovery-mode=", 0) == 0) {
- std::string mode = arg.substr(std::string("--recovery-mode=").size());
- try {
- ov.recoveryMode = smartbotic::database::recoveryModeFromString(mode);
- } catch (const std::exception& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- std::exit(11);
- }
- }
- }
- return ov;
- }
- // Run the v1.x → v2.0 auto-detect-and-migrate phase. Called from main()
- // before service.initialize() so the heavy v1.x recovery sequence doesn't
- // run twice. Returns 0 on success or on a clean "no migration needed"
- // decision; non-zero on a refused migration (operator must intervene).
- //
- // On success, the v2.0 schema_version=2 marker is set in the env's _meta
- // sub-db, so subsequent boots short-circuit on the migration_complete()
- // check inside should_run_migration().
- int runV1MigrationIfNeeded(const std::filesystem::path& dataDir,
- bool forceMigrate, bool noAutoMigrate) {
- using namespace smartbotic::db::storage;
- // Already on the v2.3 multi-project layout? Then this instance is well past
- // any v1.x → v2.0 migration. Skip the check entirely — crucially without
- // create_directories(<dataDir>/env), which would re-create the legacy env
- // dir on every boot and trip the v2.3 ambiguous-layout guard in
- // migrateLegacyEnvToDefaultProject() (it refuses to start when both
- // <dataDir>/env and <dataDir>/projects/default/env exist). That made any
- // restart of a migrated instance fatal.
- {
- std::error_code ec23;
- if (std::filesystem::exists(dataDir / "projects" / "default" / "env", ec23)) {
- spdlog::info("v2.0 migration: v2.3 layout present (projects/default/env) — "
- "skipping v1 check (not creating legacy env/)");
- return 0;
- }
- }
- // v2.0 env lives at <dataDir>/env/ — separate from v1.x's snapshots/
- // and wal/. Open via the Stage 1 RAII wrapper.
- LmdbEnvOpts envOpts;
- envOpts.path = (dataDir / "env").string();
- envOpts.map_size_bytes = 4ULL << 30; // 4 GiB initial; LMDB grows lazily.
- envOpts.max_dbs = 1024;
- std::error_code ec;
- std::filesystem::create_directories(envOpts.path, ec);
- std::unique_ptr<LmdbEnv> env;
- try {
- env = std::make_unique<LmdbEnv>(envOpts);
- } catch (const std::exception& e) {
- spdlog::error("Failed to open v2.0 LMDB env at {}: {}", envOpts.path, e.what());
- // Pre-Stage-4: this isn't a hard failure path yet because the
- // service still boots from v1.x. Treat as "skip migration, log it"
- // and let the rest of boot proceed. Once Stage 4 lands, this
- // becomes a hard exit.
- return 0;
- }
- AutoMigrateOptions opts;
- opts.force = forceMigrate;
- opts.disabled = noAutoMigrate;
- AutoMigrateDecision decision =
- should_run_migration(dataDir.string(), *env, opts);
- switch (decision.action) {
- case AutoMigrateDecision::Action::SkipNoV1Data:
- spdlog::info("v2.0 migration: {}", decision.message);
- return 0;
- case AutoMigrateDecision::Action::SkipAlreadyMigrated:
- spdlog::info("v2.0 migration: {}", decision.message);
- return 0;
- case AutoMigrateDecision::Action::BlockedByFlag:
- spdlog::error("v2.0 migration BLOCKED: {}", decision.message);
- std::cerr << "ERROR: " << decision.message << std::endl;
- return 12; // exit code 12 = migration refused by operator
- case AutoMigrateDecision::Action::RunMigration:
- break;
- }
- // Loud banner — operators reading the journal need to know exactly
- // what's about to happen.
- spdlog::info("================================================================");
- spdlog::info("v2.0 storage migration starting");
- spdlog::info(" Source v1.x data dir: {}", dataDir.string());
- spdlog::info(" Target v2.0 LMDB env: {}", envOpts.path);
- spdlog::info(" This is a one-shot operation. The v1.x data dir is");
- spdlog::info(" read-only and will not be modified. Rollback path:");
- spdlog::info(" restore /var/backups/smartbotic-database/pre-upgrade-*/.");
- spdlog::info("================================================================");
- #ifdef HAVE_SYSTEMD
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- sd_notify(0, "STATUS=Migrating from v1.x");
- #endif
- LmdbDocumentStore target(*env);
- auto progressCb = [](const MigrationProgress& p) {
- #ifdef HAVE_SYSTEMD
- std::string status = "STATUS=Migrating from v1.x: " +
- std::to_string(p.docs_migrated) + "/" +
- std::to_string(p.docs_total);
- if (!p.current_collection.empty()) {
- status += " in '" + p.current_collection + "'";
- }
- sd_notify(0, status.c_str());
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- #endif
- if (p.docs_migrated > 0 && (p.docs_migrated % 5000) == 0) {
- spdlog::info("v2.0 migration progress: {}/{} docs (collection '{}')",
- p.docs_migrated, p.docs_total, p.current_collection);
- }
- };
- MigrationResult result =
- migrate_v1_to_v2(dataDir.string(), target, *env, progressCb);
- if (!result.success) {
- #ifdef HAVE_SYSTEMD
- sd_notify(0, "STATUS=Migration failed");
- #endif
- spdlog::error("v2.0 migration FAILED: {}", result.error);
- std::cerr << "ERROR: v2.0 migration failed:\n " << result.error << std::endl;
- return 13; // exit code 13 = migration failure
- }
- spdlog::info("v2.0 migration complete: {} docs across {} collections",
- result.docs_migrated, result.collections_migrated);
- return 0;
- }
- std::filesystem::path findConfigFile(int argc, char* argv[]) {
- // Check command line arguments
- for (int i = 1; i < argc; ++i) {
- std::string arg = argv[i];
- if ((arg == "--config" || arg == "-c") && i + 1 < argc) {
- return argv[i + 1];
- }
- }
- // Check environment variable
- if (const char* configPath = std::getenv("DATABASE_CONFIG")) {
- return configPath;
- }
- // Default paths
- std::vector<std::filesystem::path> defaultPaths = {
- "./config/database.json",
- "./config/storage.json", // Backward compatibility
- "/etc/smartbotic/database.json",
- "/etc/callerai/storage.json", // Backward compatibility
- std::filesystem::path(std::getenv("HOME") ? std::getenv("HOME") : "") / ".config/smartbotic/database.json"
- };
- for (const auto& path : defaultPaths) {
- if (std::filesystem::exists(path)) {
- return path;
- }
- }
- return "./config/database.json";
- }
- } // anonymous namespace
- // v1.8.1: Cap glibc per-thread malloc arenas. With ~20+ threads
- // (eviction / WAL sync / snapshot / gRPC pool / replication apply +
- // connection loop), the default `8 × num_cpus` arenas fragment heap
- // pages so they're never returned to the OS, drifting RSS far above
- // the DB's tracked working set (Zoe: 6.5 GB gap, OOM every ~3h until
- // MALLOC_ARENA_MAX=2 was set). The systemd unit sets the env var as
- // the primary control; this programmatic call covers non-systemd
- // deployments (docker, ad-hoc launches). Skip if the env var is
- // already set, so operators can override.
- static void capGlibcArenas() {
- #if defined(__GLIBC__) && !defined(__APPLE__)
- if (const char* v = std::getenv("MALLOC_ARENA_MAX"); v && *v) {
- return; // Operator override in effect — respect it.
- }
- if (::mallopt(M_ARENA_MAX, 2) == 0) {
- // mallopt returns nonzero on success; silent — the worst case is
- // we run with default arenas and observe the historical drift.
- }
- #endif
- }
- int main(int argc, char* argv[]) {
- capGlibcArenas();
- // Parse command line arguments
- for (int i = 1; i < argc; ++i) {
- std::string arg = argv[i];
- if (arg == "--help" || arg == "-h") {
- printUsage(argv[0]);
- return 0;
- }
- if (arg == "--version" || arg == "-v") {
- printVersion();
- return 0;
- }
- }
- try {
- // Initialize logging
- initLogging("database");
- // Find configuration file (base) + sibling conf.d/ drop-in directory
- auto configPath = findConfigFile(argc, argv);
- auto confDir = configPath.parent_path() / "conf.d";
- spdlog::info("Loading configuration from {} (drop-ins: {})",
- configPath.string(), confDir.string());
- // Load configuration. The loader accepts a missing base file (empty {})
- // and a missing conf.d/. If either exists we parse it; syntax errors
- // in any file are fatal with exit code 11 (config invalid).
- smartbotic::database::DatabaseService::Config config;
- const bool baseExists = std::filesystem::exists(configPath);
- const bool dropinsExist = std::filesystem::exists(confDir);
- if (baseExists || dropinsExist) {
- try {
- std::vector<std::filesystem::path> mergedFiles;
- nlohmann::json merged = smartbotic::database::loadLayeredConfig(
- configPath, confDir, &mergedFiles);
- config = smartbotic::database::DatabaseService::parseConfig(merged);
- } catch (const std::exception& e) {
- std::cerr << "Config error: " << e.what() << std::endl;
- spdlog::error("Config error: {}", e.what());
- return 11;
- }
- } else {
- spdlog::warn("Configuration file not found, using defaults");
- // Set default data directory
- const char* home = std::getenv("HOME");
- if (home) {
- config.dataDirectory = std::filesystem::path(home) / ".local/share/smartbotic/database";
- config.keyFilePath = std::filesystem::path(home) / ".config/smartbotic/database.key";
- } else {
- config.dataDirectory = "/var/lib/smartbotic/database";
- config.keyFilePath = "/etc/smartbotic/database.key";
- }
- }
- // Override node ID from environment if set
- if (const char* nodeId = std::getenv("DATABASE_NODE_ID")) {
- config.nodeId = nodeId;
- }
- // Parse CLI overrides (--read-only, --force-readwrite, --recovery-mode=...,
- // --migrate-from-v1, --no-auto-migrate)
- auto cli = parseCliOverrides(argc, argv);
- // Apply --recovery-mode to persistence config before service construction
- if (cli.recoveryMode) {
- config.persistenceConfig.recoveryMode = *cli.recoveryMode;
- }
- // Auto-detect-and-migrate v1.x data before the
- // service initialises. Runs against <dataDir>/env/ (the v2.0 LMDB
- // env). On success, sets the schema_version=2 marker so subsequent
- // boots short-circuit. On a refused migration (--no-auto-migrate +
- // v1.x data present, or migration failure) we exit non-zero before
- // the service starts.
- if (int rc = runV1MigrationIfNeeded(config.dataDirectory,
- cli.migrateFromV1,
- cli.noAutoMigrate);
- rc != 0) {
- return rc;
- }
- // Create service
- smartbotic::database::DatabaseService service(config);
- g_service = &service;
- // Apply --force-readwrite BEFORE initialize() so auto-readonly check respects it
- if (cli.forceReadwrite) {
- service.setForceReadwrite(true);
- }
- // Set up signal handlers
- std::signal(SIGINT, signalHandler);
- std::signal(SIGTERM, signalHandler);
- // v1.8.3: SIGUSR1 / SIGUSR2 for live heap-state probing on Zoe. Both
- // log to stderr (caught by the systemd journal), do not interrupt
- // service operation. Documented in CLAUDE.md.
- std::signal(SIGUSR1, mallocInfoHandler);
- std::signal(SIGUSR2, mallocTrimHandler);
- #ifdef HAVE_SYSTEMD
- // v1.7.5: extend the systemd start timeout while recovery is
- // running. Default TimeoutStartSec=90s + a 5-min unit cap is
- // enough for most datasets, but very large databases (millions
- // of docs, multi-GB WAL) can exceed that. EXTEND_TIMEOUT_USEC
- // pushes systemd's clock back a fixed interval — we re-issue
- // it on each major step so the watchdog never fires mid-replay.
- // 600 seconds (10 min) per step is generous and only affects
- // the start phase; once READY is sent, normal WatchdogSec
- // semantics take over.
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- sd_notify(0, "STATUS=Initializing — running recovery and migrations");
- #endif
- // Initialize service. Recovery-refused is reported via the
- // recovery_outcome_ state (banner printed by DatabaseService) and
- // maps to exit code 10.
- if (!service.initialize()) {
- if (service.recoveryOutcome().isFailure()) {
- // Banner was already printed by DatabaseService; just exit with code 10.
- return 10;
- }
- spdlog::error("Failed to initialize database service");
- return 1;
- }
- // Apply --read-only after initialize() succeeds, before start() accepts connections
- if (cli.readOnly) {
- service.setReadOnly(true, "started with --read-only flag");
- }
- #ifdef HAVE_SYSTEMD
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- sd_notify(0, "STATUS=Starting gRPC server");
- #endif
- // Start service
- service.start();
- #ifdef HAVE_SYSTEMD
- // v1.7.5: only notify READY *after* full initialization +
- // service.start() — recovery is done, migrations are applied,
- // gRPC is listening. With the unit set to Type=notify,
- // dependents (shadowman-tools, -gateway, -server) block in
- // their own systemd start until this READY arrives, so they
- // can never observe an in-recovery DB and silently fall back
- // to defaults. Pre-1.7.5 the unit was Type=simple — sd_notify
- // was effectively decoration.
- sd_notify(0, "READY=1");
- sd_notify(0, "STATUS=Ready");
- spdlog::info("Notified systemd: READY");
- #endif
- // Wait for shutdown
- int watchdogCounter = 0;
- while (service.isRunning()) {
- std::this_thread::sleep_for(std::chrono::seconds(1));
- #ifdef HAVE_SYSTEMD
- // Send watchdog notification every 30 seconds (half of WatchdogSec=60)
- if (++watchdogCounter >= 30) {
- sd_notify(0, "WATCHDOG=1");
- watchdogCounter = 0;
- }
- #endif
- }
- #ifdef HAVE_SYSTEMD
- sd_notify(0, "STOPPING=1");
- #endif
- // Stop service
- service.stop();
- g_service = nullptr;
- spdlog::info("Database service exited cleanly");
- return 0;
- } catch (const std::exception& e) {
- spdlog::error("Fatal error: {}", e.what());
- return 1;
- }
- }
|