using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using log4net; namespace DeviceBroker { /// /// DeviceBroker 宿主入口。 /// 用法: DeviceBroker.exe [--db data.db路径] [--arb arb.db路径] [--broker broker-b01] /// 默认路径与集成测试环境一致(%LOCALAPPDATA%\PluginIntegrationTest)。 /// public static class Program { private static readonly ILog Log = LogManager.GetLogger(typeof(Program)); public static async Task Main(string[] args) { var map = ParseArgs(args); string appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string defaultDir = Path.Combine(appData, "PluginIntegrationTest"); string dbPath = Get(map, "--db", Path.Combine(defaultDir, "data.db")); string arbPath = Get(map, "--arb", Path.Combine(defaultDir, "arb.db")); string brokerId = Get(map, "--broker", "broker-b01"); Console.WriteLine($"DeviceBroker [{brokerId}]"); Console.WriteLine($" 配置库: {dbPath}"); Console.WriteLine($" 仲裁库: {arbPath}"); if (!File.Exists(dbPath)) { Console.WriteLine($"[FATAL] 配置库不存在,请先在注册页保存设备配置。{dbPath}"); Environment.ExitCode = 2; return; } using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; // 优雅退出:租约靠 TTL 过期 + 人工回收,不做进程内强放 cts.Cancel(); Console.WriteLine("[Broker] 收到退出请求,在途片段按 deadline 收口…"); }; try { var server = new BrokerServer(dbPath, arbPath, brokerId); server.LoadDevices(); Console.WriteLine($"[Broker] epoch={server.Epoch},Ctrl+C 退出"); await server.RunAsync(cts.Token).ConfigureAwait(false); } catch (Exception ex) { Log.Fatal("[Broker] 宿主异常退出", ex); Console.WriteLine($"[FATAL] {ex.Message}"); Environment.ExitCode = 1; } } private static string Get(Dictionary map, string key, string fallback) => map.TryGetValue(key, out var v) && !string.IsNullOrWhiteSpace(v) ? v : fallback; private static Dictionary ParseArgs(string[] args) { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); for (int i = 0; i + 1 < args.Length; i++) { if (args[i].StartsWith("--")) { map[args[i]] = args[i + 1]; i++; } } return map; } } }