| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- using System.Net;
- using System.Security.Cryptography;
- using Admin.NET.DataPlatform.Edge;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
- if (args is ["--stage-release", var dataPath, var publisherKey, var manifest, var signature, var archive])
- {
- try
- {
- Console.WriteLine(EdgeRelease.Stage(Path.GetFullPath(dataPath), publisherKey, manifest, signature, archive));
- return 0;
- }
- catch (Exception error)
- {
- Console.Error.WriteLine(error is EdgeContractException edge ? edge.Code : error.GetType().Name);
- return 1;
- }
- }
- var mode = args.Length == 0 ? "--run" : args[0];
- var configPath = args.Length == 2 ? args[1] : Environment.GetEnvironmentVariable("MDP_EDGE_CONFIG");
- if (mode is not ("--run" or "--enroll" or "--once" or "--status" or "--rotate") || args.Length > 2)
- {
- Console.Error.WriteLine("Usage: edge [--run|--enroll|--once|--status|--rotate] [config-path]");
- return 2;
- }
- var settings = new ConfigurationBuilder();
- if (!string.IsNullOrWhiteSpace(configPath)) settings.AddJsonFile(Path.GetFullPath(configPath), optional: false);
- var config = settings.AddEnvironmentVariables().Build();
- using var stopping = new CancellationTokenSource();
- Console.CancelKeyPress += (_, eventArgs) => { eventArgs.Cancel = true; stopping.Cancel(); };
- try
- {
- var local = new EdgeLocalState(config["Edge:DataDirectory"] ?? throw new EdgeContractException("EDGE_DATA_PATH_REQUIRED"));
- local.Initialize();
- using var ownership = new FileStream(Path.Combine(local.DirectoryPath, "device.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
- var key = local.ReadKey();
- try
- {
- var queue = new EdgeQueue(Path.Combine(local.DirectoryPath, "outbox.db"), key, config.GetValue("Edge:MaxBufferedBytes", 268435456L),
- config.GetValue("Edge:MinimumFreeBytes", 67108864L));
- if (mode == "--status")
- {
- using var certificate = local.ReadCertificate(key);
- var usage = queue.Usage();
- Console.WriteLine($"registered={certificate is not null} backlog={usage.Pending} bytes={usage.Bytes} free={usage.FreeBytes}");
- return 0;
- }
- var transport = new EdgeTransport(new Uri(config["Edge:Platform"] ?? throw new EdgeContractException("EDGE_PLATFORM_URL_REQUIRED")));
- if (mode == "--enroll")
- {
- var activation = Environment.GetEnvironmentVariable("MDP_EDGE_ACTIVATION")
- ?? Console.ReadLine() ?? throw new EdgeContractException("EDGE_ACTIVATION_REQUIRED");
- await transport.EnrollAsync(local, key, activation, stopping.Token);
- Console.WriteLine("EDGE_REGISTERED");
- return 0;
- }
- if (mode == "--rotate")
- {
- using var certificate = local.ReadCertificate(key) ?? throw new EdgeContractException("EDGE_NOT_REGISTERED");
- await transport.RotateAsync(local, key, certificate, stopping.Token);
- return 0;
- }
- if (mode == "--run" && !File.Exists(Path.Combine(local.DirectoryPath, "certificate")))
- {
- var credentials = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
- var bootstrap = config["Edge:ActivationFile"] ??
- (string.IsNullOrEmpty(credentials) ? null : Path.Combine(credentials, "edge-activation"));
- if (!string.IsNullOrEmpty(bootstrap) && File.Exists(bootstrap))
- {
- await transport.EnrollAsync(local, key, File.ReadAllText(bootstrap).Trim(), stopping.Token);
- if (config["Edge:ActivationFile"] is not null) File.Delete(bootstrap);
- }
- }
- var engine = new EdgeEngine(local, key, queue, transport, config);
- if (mode == "--once") return await engine.WorkAsync(stopping.Token) ? 0 : 1;
- if (config["Edge:PushListen"] is { } listener)
- {
- var uri = new Uri(listener);
- if (uri.Scheme != "https" || !IPAddress.TryParse(uri.Host, out var ip) || ip.Equals(IPAddress.Any)
- || ip.Equals(IPAddress.IPv6Any) || uri.AbsolutePath != "/" || uri.Query.Length != 0 || uri.UserInfo.Length != 0)
- throw new EdgeContractException("EDGE_PUSH_LISTENER_INVALID");
- var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = [] });
- builder.Configuration.AddConfiguration(config);
- builder.Host.UseWindowsService();
- builder.WebHost.UseUrls(listener);
- builder.Services.AddHostedService(_ => new EdgeWorker(engine));
- var app = builder.Build();
- EdgePush.Map(app, engine, queue, config);
- await app.RunAsync(stopping.Token);
- }
- else
- {
- using var host = Host.CreateDefaultBuilder([]).UseWindowsService()
- .ConfigureServices(services => services.AddHostedService(_ => new EdgeWorker(engine))).Build();
- await host.RunAsync(stopping.Token);
- }
- return 0;
- }
- finally { CryptographicOperations.ZeroMemory(key); }
- }
- catch (OperationCanceledException) when (stopping.IsCancellationRequested) { return 0; }
- catch (Exception error)
- {
- Console.Error.WriteLine(error is EdgeContractException edge ? edge.Code : error.GetType().Name);
- return 1;
- }
- internal sealed class EdgeWorker(EdgeEngine engine) : BackgroundService
- {
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- while (!stoppingToken.IsCancellationRequested)
- {
- await engine.WorkAsync(stoppingToken);
- await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
- }
- }
- }
|