main.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #include "database_service.hpp"
  2. #include <spdlog/spdlog.h>
  3. #include <spdlog/sinks/stdout_color_sinks.h>
  4. #include <csignal>
  5. #include <cstdlib>
  6. #include <filesystem>
  7. #include <iostream>
  8. #ifdef HAVE_SYSTEMD
  9. #include <systemd/sd-daemon.h>
  10. #endif
  11. namespace {
  12. smartbotic::database::DatabaseService* g_service = nullptr;
  13. void signalHandler(int signal) {
  14. spdlog::info("Received signal {}", signal);
  15. if (g_service) {
  16. g_service->signalStop();
  17. }
  18. }
  19. void printUsage(const char* programName) {
  20. std::cout << "Usage: " << programName << " [OPTIONS]\n"
  21. << "\n"
  22. << "Options:\n"
  23. << " --config, -c PATH Configuration file path\n"
  24. << " --help, -h Show this help message\n"
  25. << " --version, -v Show version information\n"
  26. << "\n"
  27. << "Environment variables:\n"
  28. << " DATABASE_NODE_ID Override node ID from config\n"
  29. << " DATABASE_MASTER_KEY Encryption master key (hex-encoded)\n"
  30. << std::endl;
  31. }
  32. void printVersion() {
  33. std::cout << "smartbotic-database version 1.0.0\n"
  34. << "Smartbotic Database Service\n"
  35. << std::endl;
  36. }
  37. void initLogging(const std::string& serviceName) {
  38. try {
  39. // Create console sink
  40. auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  41. console_sink->set_level(spdlog::level::debug);
  42. // Create default logger with console sink
  43. auto logger = std::make_shared<spdlog::logger>(serviceName, console_sink);
  44. logger->set_level(spdlog::level::info);
  45. // Check environment for log level
  46. if (const char* logLevel = std::getenv("LOG_LEVEL")) {
  47. std::string level(logLevel);
  48. if (level == "trace") logger->set_level(spdlog::level::trace);
  49. else if (level == "debug") logger->set_level(spdlog::level::debug);
  50. else if (level == "info") logger->set_level(spdlog::level::info);
  51. else if (level == "warn") logger->set_level(spdlog::level::warn);
  52. else if (level == "error") logger->set_level(spdlog::level::err);
  53. }
  54. spdlog::set_default_logger(logger);
  55. spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [%n] %v");
  56. } catch (const spdlog::spdlog_ex& ex) {
  57. std::cerr << "Log initialization failed: " << ex.what() << std::endl;
  58. }
  59. }
  60. std::filesystem::path findConfigFile(int argc, char* argv[]) {
  61. // Check command line arguments
  62. for (int i = 1; i < argc; ++i) {
  63. std::string arg = argv[i];
  64. if ((arg == "--config" || arg == "-c") && i + 1 < argc) {
  65. return argv[i + 1];
  66. }
  67. }
  68. // Check environment variable
  69. if (const char* configPath = std::getenv("DATABASE_CONFIG")) {
  70. return configPath;
  71. }
  72. // Default paths
  73. std::vector<std::filesystem::path> defaultPaths = {
  74. "./config/database.json",
  75. "./config/storage.json", // Backward compatibility
  76. "/etc/smartbotic/database.json",
  77. "/etc/callerai/storage.json", // Backward compatibility
  78. std::filesystem::path(std::getenv("HOME") ? std::getenv("HOME") : "") / ".config/smartbotic/database.json"
  79. };
  80. for (const auto& path : defaultPaths) {
  81. if (std::filesystem::exists(path)) {
  82. return path;
  83. }
  84. }
  85. return "./config/database.json";
  86. }
  87. } // anonymous namespace
  88. int main(int argc, char* argv[]) {
  89. // Parse command line arguments
  90. for (int i = 1; i < argc; ++i) {
  91. std::string arg = argv[i];
  92. if (arg == "--help" || arg == "-h") {
  93. printUsage(argv[0]);
  94. return 0;
  95. }
  96. if (arg == "--version" || arg == "-v") {
  97. printVersion();
  98. return 0;
  99. }
  100. }
  101. try {
  102. // Initialize logging
  103. initLogging("database");
  104. // Find configuration file
  105. auto configPath = findConfigFile(argc, argv);
  106. spdlog::info("Loading configuration from {}", configPath.string());
  107. // Load configuration
  108. smartbotic::database::DatabaseService::Config config;
  109. if (std::filesystem::exists(configPath)) {
  110. config = smartbotic::database::DatabaseService::loadConfig(configPath);
  111. } else {
  112. spdlog::warn("Configuration file not found, using defaults");
  113. // Set default data directory
  114. const char* home = std::getenv("HOME");
  115. if (home) {
  116. config.dataDirectory = std::filesystem::path(home) / ".local/share/smartbotic/database";
  117. config.keyFilePath = std::filesystem::path(home) / ".config/smartbotic/database.key";
  118. } else {
  119. config.dataDirectory = "/var/lib/smartbotic/database";
  120. config.keyFilePath = "/etc/smartbotic/database.key";
  121. }
  122. }
  123. // Override node ID from environment if set
  124. if (const char* nodeId = std::getenv("DATABASE_NODE_ID")) {
  125. config.nodeId = nodeId;
  126. }
  127. // Create service
  128. smartbotic::database::DatabaseService service(config);
  129. g_service = &service;
  130. // Set up signal handlers
  131. std::signal(SIGINT, signalHandler);
  132. std::signal(SIGTERM, signalHandler);
  133. // Initialize service
  134. if (!service.initialize()) {
  135. spdlog::error("Failed to initialize database service");
  136. return 1;
  137. }
  138. // Start service
  139. service.start();
  140. #ifdef HAVE_SYSTEMD
  141. // Notify systemd we're ready
  142. sd_notify(0, "READY=1");
  143. spdlog::info("Notified systemd: READY");
  144. #endif
  145. // Wait for shutdown
  146. int watchdogCounter = 0;
  147. while (service.isRunning()) {
  148. std::this_thread::sleep_for(std::chrono::seconds(1));
  149. #ifdef HAVE_SYSTEMD
  150. // Send watchdog notification every 30 seconds (half of WatchdogSec=60)
  151. if (++watchdogCounter >= 30) {
  152. sd_notify(0, "WATCHDOG=1");
  153. watchdogCounter = 0;
  154. }
  155. #endif
  156. }
  157. #ifdef HAVE_SYSTEMD
  158. sd_notify(0, "STOPPING=1");
  159. #endif
  160. // Stop service
  161. service.stop();
  162. g_service = nullptr;
  163. spdlog::info("Database service exited cleanly");
  164. return 0;
  165. } catch (const std::exception& e) {
  166. spdlog::error("Fatal error: {}", e.what());
  167. return 1;
  168. }
  169. }