main.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #include "auth.hpp"
  2. #include "collection_registry.hpp"
  3. #include "config.hpp"
  4. #include <memory>
  5. #include "db_gateway.hpp"
  6. #include "key_store.hpp"
  7. #include "server.hpp"
  8. #include "settings_store.hpp"
  9. #include <svapi/version.hpp>
  10. #include <spdlog/spdlog.h>
  11. #ifdef HAVE_SYSTEMD
  12. #include <systemd/sd-daemon.h>
  13. #else
  14. #define sd_notify(u, s) do {} while (0)
  15. #endif
  16. #include <atomic>
  17. #include <chrono>
  18. #include <csignal>
  19. #include <cstdlib>
  20. #include <cstring>
  21. #include <iostream>
  22. #include <thread>
  23. namespace {
  24. std::atomic<bool> g_running{true};
  25. void onSignal(int) { g_running = false; }
  26. std::string envOr(const char* k, const std::string& dflt = "") { const char* v = std::getenv(k); return v ? std::string(v) : dflt; }
  27. }
  28. int main(int argc, char** argv) {
  29. std::string configPath = "/etc/smartbotic-vectorapi/config.json";
  30. std::string webuiDirOverride;
  31. std::string shareDir = "/usr/share/smartbotic-vectorapi";
  32. for (int i = 1; i < argc; ++i) {
  33. if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i];
  34. else if (std::strcmp(argv[i], "--webui-dir") == 0 && i + 1 < argc) webuiDirOverride = argv[++i];
  35. else if (std::strcmp(argv[i], "--share-dir") == 0 && i + 1 < argc) shareDir = argv[++i];
  36. else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) {
  37. std::cout << "smartbotic-vectorapi " << svapi::VERSION << " (" << svapi::GIT_COMMIT << ")\n";
  38. return 0;
  39. }
  40. }
  41. svapi::Config cfg;
  42. try { cfg = svapi::Config::load(configPath); }
  43. catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; }
  44. spdlog::set_level(spdlog::level::from_str(cfg.logLevel));
  45. if (!webuiDirOverride.empty()) cfg.webuiDir = webuiDirOverride;
  46. std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
  47. svapi::DbGateway db(cfg.dbAddress);
  48. spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
  49. for (int i = 0; i < 30 && !db.connect(); ++i) std::this_thread::sleep_for(std::chrono::seconds(1));
  50. if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; }
  51. svapi::SettingsStore settings(db);
  52. settings.bootstrap(envOr("OPENAI_API_KEY"));
  53. settings.startWatch();
  54. svapi::KeyStore keys(db);
  55. keys.bootstrap(envOr("SMARTBOTIC_VECTORAPI_KEY"));
  56. keys.startWatch();
  57. svapi::CollectionRegistry registry(db);
  58. const std::string defProj = settings.snapshot()->defaultProject;
  59. db.ensureProject(defProj);
  60. // Re-open EVERY project's collection registry at startup. The DB only
  61. // surfaces a collection via find()/list() once it has been opened in the
  62. // current process, so without this a restart makes all collections vanish
  63. // from the API (GET /collections empty, document ops 404) even though the
  64. // data survives on disk. KeyStore::bootstrap already does this for
  65. // vectorapi_keys, which is why keys survive but the registry didn't. (issue #1)
  66. const std::vector<std::string> projects = db.listProjects(); // includes the default
  67. registry.bootstrap(projects);
  68. spdlog::info("opened collection registry for {} project(s) at startup", projects.size());
  69. svapi::FunctionRegistry functions(db);
  70. svapi::FunctionRunLogStore functionRuns(db, cfg.functionRunsKept);
  71. // Same reason CollectionRegistry::bootstrap exists: the database only
  72. // surfaces a collection through find() once it has been opened in this
  73. // process, so without this every project's function registry reads back
  74. // empty after a restart even though the rows are on disk.
  75. for (const std::string& project : projects) {
  76. functions.ensure(project);
  77. functionRuns.ensure(project);
  78. }
  79. // Null when no runners are configured, which the function routes report as
  80. // 503 rather than as a missing feature.
  81. std::unique_ptr<svapi::RunnerPool> runners;
  82. if (!cfg.runnerEndpoints.empty()) {
  83. svapi::RunnerPool::Options ro;
  84. ro.endpoints = cfg.runnerEndpoints;
  85. // Environment over config file: the token is a secret, and
  86. // vectorapi.env can be mode 0640 where config.json is a conffile.
  87. ro.authToken = cfg.runnerToken;
  88. if (const std::string fromEnv = envOr("SVAPI_RUNNER_TOKEN"); !fromEnv.empty())
  89. ro.authToken = fromEnv;
  90. if (ro.authToken.empty())
  91. spdlog::warn("no runner token configured - only a loopback runner will accept us");
  92. runners = std::make_unique<svapi::RunnerPool>(ro);
  93. spdlog::info("function runners configured: {}", cfg.runnerEndpoints.size());
  94. } else {
  95. spdlog::info("no function runners configured - function routes will answer 503");
  96. }
  97. svapi::SessionStore sessions(std::chrono::minutes(settings.snapshot()->sessionTtlMinutes));
  98. svapi::ServerDeps deps{db, settings, keys, registry,
  99. sessions, functions, functionRuns, runners.get(),
  100. cfg.webuiDir, shareDir};
  101. svapi::ApiServer server(std::move(deps));
  102. server.registerRoutes();
  103. std::thread http([&] {
  104. spdlog::info("listening on {}:{}", cfg.httpBind, cfg.httpPort);
  105. if (!server.listen(cfg.httpBind, cfg.httpPort)) { spdlog::error("bind failed"); g_running = false; }
  106. });
  107. sd_notify(0, "READY=1");
  108. while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
  109. sd_notify(0, "STOPPING=1");
  110. server.stop();
  111. if (http.joinable()) http.join();
  112. return 0;
  113. }