config.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #include "smartbotic/database/config.hpp"
  2. #include <nlohmann/json.hpp>
  3. #include <spdlog/spdlog.h>
  4. #include <algorithm>
  5. #include <cctype>
  6. #include <cstdlib>
  7. #include <filesystem>
  8. #include <fstream>
  9. namespace smartbotic::database {
  10. auto LogLevelToString(LogLevel level) -> std::string {
  11. switch (level) {
  12. case LogLevel::kTrace:
  13. return "trace";
  14. case LogLevel::kDebug:
  15. return "debug";
  16. case LogLevel::kInfo:
  17. return "info";
  18. case LogLevel::kWarn:
  19. return "warn";
  20. case LogLevel::kError:
  21. return "error";
  22. case LogLevel::kCritical:
  23. return "critical";
  24. case LogLevel::kOff:
  25. return "off";
  26. }
  27. return "info";
  28. }
  29. auto ParseLogLevel(const std::string& str) -> std::optional<LogLevel> {
  30. std::string lower;
  31. lower.reserve(str.size());
  32. std::transform(str.begin(), str.end(), std::back_inserter(lower),
  33. [](unsigned char c) { return std::tolower(c); });
  34. if (lower == "trace") return LogLevel::kTrace;
  35. if (lower == "debug") return LogLevel::kDebug;
  36. if (lower == "info") return LogLevel::kInfo;
  37. if (lower == "warn" || lower == "warning") return LogLevel::kWarn;
  38. if (lower == "error" || lower == "err") return LogLevel::kError;
  39. if (lower == "critical" || lower == "crit" || lower == "fatal") return LogLevel::kCritical;
  40. if (lower == "off" || lower == "none") return LogLevel::kOff;
  41. return std::nullopt;
  42. }
  43. namespace {
  44. auto GetEnvOrDefault(const char* name, const std::string& default_value) -> std::string {
  45. const char* value = std::getenv(name);
  46. return value != nullptr ? std::string(value) : default_value;
  47. }
  48. auto GetEnvOrDefault(const char* name, uint16_t default_value) -> uint16_t {
  49. const char* value = std::getenv(name);
  50. if (value == nullptr) {
  51. return default_value;
  52. }
  53. try {
  54. return static_cast<uint16_t>(std::stoi(value));
  55. } catch (...) {
  56. return default_value;
  57. }
  58. }
  59. auto GetEnvOrDefault(const char* name, int64_t default_value) -> int64_t {
  60. const char* value = std::getenv(name);
  61. if (value == nullptr) {
  62. return default_value;
  63. }
  64. try {
  65. return std::stoll(value);
  66. } catch (...) {
  67. return default_value;
  68. }
  69. }
  70. } // namespace
  71. auto ConfigLoader::GetDefaultConfigPaths() -> std::vector<std::string> {
  72. std::vector<std::string> paths;
  73. // Current directory
  74. paths.emplace_back("./smartbotic-db.json");
  75. // Config subdirectory
  76. paths.emplace_back("./config/smartbotic-db.json");
  77. // /etc for system-wide config
  78. paths.emplace_back("/etc/smartbotic/smartbotic-db.json");
  79. // Home directory
  80. const char* home = std::getenv("HOME");
  81. if (home != nullptr) {
  82. paths.push_back(std::string(home) + "/.config/smartbotic/smartbotic-db.json");
  83. }
  84. return paths;
  85. }
  86. auto ConfigLoader::FindConfigFile() -> std::optional<std::string> {
  87. // Check environment variable for explicit config path
  88. const char* config_path_env = std::getenv("SMARTBOTIC_CRM_DB_CONFIG");
  89. if (config_path_env != nullptr && std::filesystem::exists(config_path_env)) {
  90. return std::string(config_path_env);
  91. }
  92. // Search default paths
  93. for (const auto& path : GetDefaultConfigPaths()) {
  94. if (std::filesystem::exists(path)) {
  95. return path;
  96. }
  97. }
  98. return std::nullopt;
  99. }
  100. auto ConfigLoader::LoadFromFile(const std::string& path) -> std::optional<DatabaseConfig> {
  101. try {
  102. if (!std::filesystem::exists(path)) {
  103. spdlog::warn("Config file not found: {}", path);
  104. return std::nullopt;
  105. }
  106. std::ifstream file(path);
  107. if (!file.is_open()) {
  108. spdlog::error("Failed to open config file: {}", path);
  109. return std::nullopt;
  110. }
  111. nlohmann::json json = nlohmann::json::parse(file);
  112. DatabaseConfig config;
  113. // Server section
  114. if (json.contains("server")) {
  115. const auto& server = json["server"];
  116. if (server.contains("address")) {
  117. config.address = server["address"].get<std::string>();
  118. }
  119. if (server.contains("port")) {
  120. config.port = server["port"].get<uint16_t>();
  121. }
  122. }
  123. // Storage section
  124. if (json.contains("storage")) {
  125. const auto& storage = json["storage"];
  126. if (storage.contains("data_dir")) {
  127. config.data_dir = storage["data_dir"].get<std::string>();
  128. }
  129. }
  130. // Snapshot section
  131. if (json.contains("snapshot")) {
  132. const auto& snapshot = json["snapshot"];
  133. if (snapshot.contains("enabled")) {
  134. config.snapshot_enabled = snapshot["enabled"].get<bool>();
  135. }
  136. if (snapshot.contains("interval_seconds")) {
  137. config.snapshot_interval_seconds = snapshot["interval_seconds"].get<int64_t>();
  138. }
  139. if (snapshot.contains("change_threshold")) {
  140. config.snapshot_change_threshold = snapshot["change_threshold"].get<uint64_t>();
  141. }
  142. }
  143. // Logging section
  144. if (json.contains("logging")) {
  145. const auto& logging = json["logging"];
  146. if (logging.contains("level")) {
  147. auto level_str = logging["level"].get<std::string>();
  148. auto level = ParseLogLevel(level_str);
  149. if (level) {
  150. config.log_level = *level;
  151. } else {
  152. spdlog::warn("Invalid log level '{}', using default", level_str);
  153. }
  154. }
  155. }
  156. // Security section
  157. if (json.contains("security")) {
  158. const auto& security = json["security"];
  159. if (security.contains("encryption_key_path")) {
  160. config.encryption_key_path = security["encryption_key_path"].get<std::string>();
  161. }
  162. }
  163. spdlog::info("Loaded configuration from: {}", path);
  164. return config;
  165. } catch (const nlohmann::json::exception& e) {
  166. spdlog::error("Failed to parse config file {}: {}", path, e.what());
  167. return std::nullopt;
  168. } catch (const std::exception& e) {
  169. spdlog::error("Error loading config file {}: {}", path, e.what());
  170. return std::nullopt;
  171. }
  172. }
  173. void ConfigLoader::ApplyEnvironment(DatabaseConfig& config) {
  174. // Server settings from environment (can override config file)
  175. config.address = GetEnvOrDefault("SMARTBOTIC_CRM_DB_ADDRESS", config.address);
  176. config.port = GetEnvOrDefault("SMARTBOTIC_CRM_DB_PORT", config.port);
  177. config.data_dir = GetEnvOrDefault("SMARTBOTIC_CRM_DB_DATA_DIR", config.data_dir);
  178. // Snapshot settings from environment
  179. config.snapshot_interval_seconds =
  180. GetEnvOrDefault("SMARTBOTIC_CRM_DB_SNAPSHOT_INTERVAL", config.snapshot_interval_seconds);
  181. // Log level from environment
  182. const char* log_level_env = std::getenv("SMARTBOTIC_CRM_DB_LOG_LEVEL");
  183. if (log_level_env != nullptr) {
  184. auto level = ParseLogLevel(log_level_env);
  185. if (level) {
  186. config.log_level = *level;
  187. }
  188. }
  189. // Encryption key path from environment (for secrets)
  190. const char* key_path_env = std::getenv("SMARTBOTIC_CRM_DB_ENCRYPTION_KEY_PATH");
  191. if (key_path_env != nullptr) {
  192. config.encryption_key_path = key_path_env;
  193. }
  194. }
  195. auto ConfigLoader::ParseCommandLine(int argc, char* argv[], DatabaseConfig& config)
  196. -> std::optional<bool> {
  197. std::string config_file_override;
  198. for (int i = 1; i < argc; ++i) {
  199. std::string arg = argv[i];
  200. if (arg == "--help" || arg == "-h") {
  201. PrintHelp(argv[0]);
  202. return std::nullopt; // Help requested, exit
  203. }
  204. if (arg == "--version" || arg == "-v") {
  205. spdlog::info("SmartBotic Database v0.1.0");
  206. return std::nullopt; // Version requested, exit
  207. }
  208. if (arg == "--config" || arg == "-c") {
  209. if (i + 1 < argc) {
  210. config_file_override = argv[++i];
  211. } else {
  212. spdlog::error("--config requires a path argument");
  213. return false;
  214. }
  215. continue;
  216. }
  217. if (arg == "--port" || arg == "-p") {
  218. if (i + 1 < argc) {
  219. try {
  220. config.port = static_cast<uint16_t>(std::stoi(argv[++i]));
  221. } catch (...) {
  222. spdlog::error("Invalid port number: {}", argv[i]);
  223. return false;
  224. }
  225. } else {
  226. spdlog::error("--port requires a number argument");
  227. return false;
  228. }
  229. continue;
  230. }
  231. if (arg == "--address" || arg == "-a") {
  232. if (i + 1 < argc) {
  233. config.address = argv[++i];
  234. } else {
  235. spdlog::error("--address requires an address argument");
  236. return false;
  237. }
  238. continue;
  239. }
  240. if (arg == "--data-dir" || arg == "-d") {
  241. if (i + 1 < argc) {
  242. config.data_dir = argv[++i];
  243. } else {
  244. spdlog::error("--data-dir requires a path argument");
  245. return false;
  246. }
  247. continue;
  248. }
  249. if (arg == "--snapshot-interval") {
  250. if (i + 1 < argc) {
  251. try {
  252. config.snapshot_interval_seconds = std::stoll(argv[++i]);
  253. } catch (...) {
  254. spdlog::error("Invalid snapshot interval: {}", argv[i]);
  255. return false;
  256. }
  257. } else {
  258. spdlog::error("--snapshot-interval requires a number argument");
  259. return false;
  260. }
  261. continue;
  262. }
  263. if (arg == "--log-level" || arg == "-l") {
  264. if (i + 1 < argc) {
  265. auto level = ParseLogLevel(argv[++i]);
  266. if (level) {
  267. config.log_level = *level;
  268. } else {
  269. spdlog::error("Invalid log level: {}", argv[i]);
  270. return false;
  271. }
  272. } else {
  273. spdlog::error("--log-level requires a level argument");
  274. return false;
  275. }
  276. continue;
  277. }
  278. if (arg == "--encryption-key-path") {
  279. if (i + 1 < argc) {
  280. config.encryption_key_path = argv[++i];
  281. } else {
  282. spdlog::error("--encryption-key-path requires a path argument");
  283. return false;
  284. }
  285. continue;
  286. }
  287. spdlog::error("Unknown argument: {}", arg);
  288. PrintHelp(argv[0]);
  289. return false;
  290. }
  291. // If config file was specified on command line, load it
  292. if (!config_file_override.empty()) {
  293. auto file_config = LoadFromFile(config_file_override);
  294. if (!file_config) {
  295. spdlog::error("Failed to load specified config file: {}", config_file_override);
  296. return false;
  297. }
  298. // Start with file config, then re-apply command line args below
  299. config = *file_config;
  300. // Re-parse command line to override file settings
  301. // (Skip the config file argument this time)
  302. for (int i = 1; i < argc; ++i) {
  303. std::string arg = argv[i];
  304. if (arg == "--config" || arg == "-c") {
  305. ++i; // Skip the config path
  306. continue;
  307. }
  308. if ((arg == "--port" || arg == "-p") && i + 1 < argc) {
  309. config.port = static_cast<uint16_t>(std::stoi(argv[++i]));
  310. } else if ((arg == "--address" || arg == "-a") && i + 1 < argc) {
  311. config.address = argv[++i];
  312. } else if ((arg == "--data-dir" || arg == "-d") && i + 1 < argc) {
  313. config.data_dir = argv[++i];
  314. } else if (arg == "--snapshot-interval" && i + 1 < argc) {
  315. config.snapshot_interval_seconds = std::stoll(argv[++i]);
  316. } else if ((arg == "--log-level" || arg == "-l") && i + 1 < argc) {
  317. auto level = ParseLogLevel(argv[++i]);
  318. if (level) config.log_level = *level;
  319. } else if (arg == "--encryption-key-path" && i + 1 < argc) {
  320. config.encryption_key_path = argv[++i];
  321. }
  322. }
  323. }
  324. return true;
  325. }
  326. auto ConfigLoader::Load(int argc, char* argv[]) -> DatabaseConfig {
  327. DatabaseConfig config = DatabaseConfig::Default();
  328. // 1. Try to find and load config file (lowest priority for non-secrets)
  329. auto config_file = FindConfigFile();
  330. if (config_file) {
  331. auto file_config = LoadFromFile(*config_file);
  332. if (file_config) {
  333. config = *file_config;
  334. }
  335. }
  336. // 2. Apply environment variables (can override config file)
  337. ApplyEnvironment(config);
  338. // 3. Parse command-line arguments (highest priority)
  339. auto result = ParseCommandLine(argc, argv, config);
  340. if (!result.has_value()) {
  341. // Help or version was requested, exit cleanly
  342. std::exit(0);
  343. }
  344. if (!result.value()) {
  345. // Error parsing arguments
  346. std::exit(1);
  347. }
  348. return config;
  349. }
  350. void ConfigLoader::PrintHelp(const char* program_name) {
  351. spdlog::info("Usage: {} [options]", program_name);
  352. spdlog::info("");
  353. spdlog::info("SmartBotic Database Service");
  354. spdlog::info("");
  355. spdlog::info("Options:");
  356. spdlog::info(" -h, --help Show this help message");
  357. spdlog::info(" -v, --version Show version information");
  358. spdlog::info(" -c, --config <path> Path to config file (default: smartbotic-db.json)");
  359. spdlog::info(" -p, --port <port> Port to listen on (default: 50051)");
  360. spdlog::info(" -a, --address <addr> Address to bind to (default: 0.0.0.0)");
  361. spdlog::info(" -d, --data-dir <path> Data directory (default: ./data)");
  362. spdlog::info(" --snapshot-interval <sec> Snapshot interval in seconds (default: 300)");
  363. spdlog::info(" -l, --log-level <level> Log level: trace, debug, info, warn, error, critical, off");
  364. spdlog::info(" --encryption-key-path <p> Path to encryption key file");
  365. spdlog::info("");
  366. spdlog::info("Environment Variables:");
  367. spdlog::info(" SMARTBOTIC_CRM_DB_CONFIG Path to config file");
  368. spdlog::info(" SMARTBOTIC_CRM_DB_ADDRESS Address to bind to");
  369. spdlog::info(" SMARTBOTIC_CRM_DB_PORT Port to listen on");
  370. spdlog::info(" SMARTBOTIC_CRM_DB_DATA_DIR Data directory");
  371. spdlog::info(" SMARTBOTIC_CRM_DB_SNAPSHOT_INTERVAL Snapshot interval in seconds");
  372. spdlog::info(" SMARTBOTIC_CRM_DB_LOG_LEVEL Log level");
  373. spdlog::info(" SMARTBOTIC_CRM_DB_ENCRYPTION_KEY_PATH Path to encryption key file");
  374. spdlog::info(" SMARTBOTIC_CRM_DB_ENCRYPTION_KEY Encryption key (base64 encoded) - for secrets");
  375. spdlog::info("");
  376. spdlog::info("Config File Search Order:");
  377. for (const auto& path : GetDefaultConfigPaths()) {
  378. spdlog::info(" {}", path);
  379. }
  380. }
  381. void ConfigLoader::PrintConfig(const DatabaseConfig& config) {
  382. spdlog::info("Configuration:");
  383. spdlog::info(" Address: {}", config.address);
  384. spdlog::info(" Port: {}", config.port);
  385. spdlog::info(" Data Directory: {}", config.data_dir);
  386. spdlog::info(" Snapshot Interval: {} seconds", config.snapshot_interval_seconds);
  387. spdlog::info(" Snapshot Enabled: {}", config.snapshot_enabled ? "yes" : "no");
  388. spdlog::info(" Log Level: {}", LogLevelToString(config.log_level));
  389. if (!config.encryption_key_path.empty()) {
  390. spdlog::info(" Encryption Key: {} (path configured)", config.encryption_key_path);
  391. } else {
  392. const char* key_env = std::getenv("SMARTBOTIC_CRM_DB_ENCRYPTION_KEY");
  393. if (key_env != nullptr) {
  394. spdlog::info(" Encryption Key: (from environment variable)");
  395. } else {
  396. spdlog::info(" Encryption Key: (not configured)");
  397. }
  398. }
  399. }
  400. } // namespace smartbotic::database