using System.Collections; using System.Runtime.InteropServices; using Anubis.Core; using Anubis.Platform; using Anubis.Supervision; // The guard (SPEC 9.3, ADR 0012): the main process of the container and the parent of the engine. Its arguments go to // the engine as they are. "drill" runs the guard drill in a temporary folder instead. if (args is ["drill", ..]) { return await GuardDrill.RunAsync(GuardLaunch.Server(), Console.Out, CancellationToken.None).ConfigureAwait(false); } var environment = Environment.GetEnvironmentVariables().Cast() .ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); var paths = new GuardPaths(DataRoot(args, environment)); var logger = new LineLogger(Console.Out.WriteLine); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }; var clock = SystemClock.Instance; var guardian = new Guardian(paths, clock, new GuardOptions(), start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start), (account, keys) => GuardBrokers.Create(http, clock, account, keys), (text, keys, ct) => GuardBrokers.AlertAsync(http, logger, keys, text, ct), logger); // The stop of the container (SIGTERM) or Ctrl+C: passed on to the engine, which closes in order and is not restarted. using var shutdown = new CancellationTokenSource(); using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Stop); using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Stop); return await guardian.RunAsync(shutdown.Token).ConfigureAwait(false); void Stop(PosixSignalContext context) { context.Cancel = true; shutdown.Cancel(); } // The engine's data folder: --data-dir when given, /data in Docker, the user's folder on desktop (SPEC 15.2, 15.6). static string DataRoot(string[] args, Dictionary environment) { var index = Array.IndexOf(args, "--data-dir"); if (index >= 0 && index + 1 < args.Length) { return Path.GetFullPath(args[index + 1]); } var platform = Array.IndexOf(args, "--platform") is var p and >= 0 && p + 1 < args.Length ? args[p + 1] : environment.GetValueOrDefault("ANUBIS_PLATFORM"); return platform == "docker" ? "/data" : DataDirectory.ForCurrentUser().Root; }