Program.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using System.Net;
  2. using System.Security.Cryptography;
  3. using Admin.NET.DataPlatform.Edge;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  5. if (args is ["--stage-release", var dataPath, var publisherKey, var manifest, var signature, var archive])
  6. {
  7. try
  8. {
  9. Console.WriteLine(EdgeRelease.Stage(Path.GetFullPath(dataPath), publisherKey, manifest, signature, archive));
  10. return 0;
  11. }
  12. catch (Exception error)
  13. {
  14. Console.Error.WriteLine(error is EdgeContractException edge ? edge.Code : error.GetType().Name);
  15. return 1;
  16. }
  17. }
  18. var mode = args.Length == 0 ? "--run" : args[0];
  19. var configPath = args.Length == 2 ? args[1] : Environment.GetEnvironmentVariable("MDP_EDGE_CONFIG");
  20. if (mode is not ("--run" or "--enroll" or "--once" or "--status" or "--rotate") || args.Length > 2)
  21. {
  22. Console.Error.WriteLine("Usage: edge [--run|--enroll|--once|--status|--rotate] [config-path]");
  23. return 2;
  24. }
  25. var settings = new ConfigurationBuilder();
  26. if (!string.IsNullOrWhiteSpace(configPath)) settings.AddJsonFile(Path.GetFullPath(configPath), optional: false);
  27. var config = settings.AddEnvironmentVariables().Build();
  28. using var stopping = new CancellationTokenSource();
  29. Console.CancelKeyPress += (_, eventArgs) => { eventArgs.Cancel = true; stopping.Cancel(); };
  30. try
  31. {
  32. var local = new EdgeLocalState(config["Edge:DataDirectory"] ?? throw new EdgeContractException("EDGE_DATA_PATH_REQUIRED"));
  33. local.Initialize();
  34. using var ownership = new FileStream(Path.Combine(local.DirectoryPath, "device.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
  35. var key = local.ReadKey();
  36. try
  37. {
  38. var queue = new EdgeQueue(Path.Combine(local.DirectoryPath, "outbox.db"), key, config.GetValue("Edge:MaxBufferedBytes", 268435456L),
  39. config.GetValue("Edge:MinimumFreeBytes", 67108864L));
  40. if (mode == "--status")
  41. {
  42. using var certificate = local.ReadCertificate(key);
  43. var usage = queue.Usage();
  44. Console.WriteLine($"registered={certificate is not null} backlog={usage.Pending} bytes={usage.Bytes} free={usage.FreeBytes}");
  45. return 0;
  46. }
  47. var transport = new EdgeTransport(new Uri(config["Edge:Platform"] ?? throw new EdgeContractException("EDGE_PLATFORM_URL_REQUIRED")));
  48. if (mode == "--enroll")
  49. {
  50. var activation = Environment.GetEnvironmentVariable("MDP_EDGE_ACTIVATION")
  51. ?? Console.ReadLine() ?? throw new EdgeContractException("EDGE_ACTIVATION_REQUIRED");
  52. await transport.EnrollAsync(local, key, activation, stopping.Token);
  53. Console.WriteLine("EDGE_REGISTERED");
  54. return 0;
  55. }
  56. if (mode == "--rotate")
  57. {
  58. using var certificate = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
  59. await transport.RotateAsync(local, key, certificate, stopping.Token);
  60. return 0;
  61. }
  62. if (mode == "--run" && !File.Exists(Path.Combine(local.DirectoryPath, "certificate")))
  63. {
  64. var credentials = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
  65. var bootstrap = config["Edge:ActivationFile"] ??
  66. (string.IsNullOrEmpty(credentials) ? null : Path.Combine(credentials, "edge-activation"));
  67. if (!string.IsNullOrEmpty(bootstrap) && File.Exists(bootstrap))
  68. {
  69. await transport.EnrollAsync(local, key, File.ReadAllText(bootstrap).Trim(), stopping.Token);
  70. if (config["Edge:ActivationFile"] is not null) File.Delete(bootstrap);
  71. }
  72. }
  73. var engine = new EdgeEngine(local, key, queue, transport, config);
  74. if (mode == "--once") return await engine.WorkAsync(stopping.Token) ? 0 : 1;
  75. if (config["Edge:PushListen"] is { } listener)
  76. {
  77. var uri = new Uri(listener);
  78. if (uri.Scheme != "https" || !IPAddress.TryParse(uri.Host, out var ip) || ip.Equals(IPAddress.Any)
  79. || ip.Equals(IPAddress.IPv6Any) || uri.AbsolutePath != "/" || uri.Query.Length != 0 || uri.UserInfo.Length != 0)
  80. throw new EdgeContractException("EDGE_PUSH_LISTENER_INVALID");
  81. var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = [] });
  82. builder.Configuration.AddConfiguration(config);
  83. builder.Host.UseWindowsService();
  84. builder.WebHost.UseUrls(listener);
  85. builder.Services.AddHostedService(_ => new EdgeWorker(engine));
  86. var app = builder.Build();
  87. EdgePush.Map(app, engine, queue, config);
  88. await app.RunAsync(stopping.Token);
  89. }
  90. else
  91. {
  92. using var host = Host.CreateDefaultBuilder([]).UseWindowsService()
  93. .ConfigureServices(services => services.AddHostedService(_ => new EdgeWorker(engine))).Build();
  94. await host.RunAsync(stopping.Token);
  95. }
  96. return 0;
  97. }
  98. finally { CryptographicOperations.ZeroMemory(key); }
  99. }
  100. catch (OperationCanceledException) when (stopping.IsCancellationRequested) { return 0; }
  101. catch (Exception error)
  102. {
  103. Console.Error.WriteLine(error is EdgeContractException edge ? edge.Code : error.GetType().Name);
  104. return 1;
  105. }
  106. internal sealed class EdgeWorker(EdgeEngine engine) : BackgroundService
  107. {
  108. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  109. {
  110. while (!stoppingToken.IsCancellationRequested)
  111. {
  112. await engine.WorkAsync(stoppingToken);
  113. await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
  114. }
  115. }
  116. }