using System.Globalization; using Febe.Browser.Hosting; using Febe.Core.Abstractions; namespace Febe.Server; /// /// Xvfb and Chromium of the Docker edition (spec §5, §6.1, §11): started by Febe.Server itself, never by a shell /// script. A start that fails (Chromium missing, sandbox refused, port taken) is retried with a growing wait; once /// running, the supervisors of and restart what crashes. /// internal sealed class BrowserSupervisor : IAsyncDisposable { private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)]; private readonly ServerOptions _options; private readonly IClock _clock; private readonly ServerLog _log; private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); private XvfbProcess? _xvfb; private volatile bool _started; private volatile string? _lastError; public BrowserSupervisor(ServerOptions options, string profileDirectory, string homeDirectory, IClock clock, ServerLog log) { _options = options ?? throw new ArgumentNullException(nameof(options)); ArgumentNullException.ThrowIfNull(clock); _log = log ?? throw new ArgumentNullException(nameof(log)); // Processes start, time out and restart in wall-clock time, whatever clock the engine runs on. _clock = new SystemClock(clock.LocalZone); ProfileDirectory = Path.GetFullPath(profileDirectory); HomeDirectory = Path.GetFullPath(homeDirectory); Host = new ChromiumProcessHost(options.LaunchOptions(HomeDirectory), _clock, log.ForBrowser()); BrowserOptions = new BrowserOptions( ProfileDirectory, options.WindowWidth, options.WindowHeight, options.DebugPort, options.ChromiumPath, UsesXvfb ? options.Display : null); } /// The browser: stable for the whole life of the server (a «Scollega» restarts it in place). public ChromiumProcessHost Host { get; } public BrowserOptions BrowserOptions { get; } /// Dati/browser: holds the Instagram session. public string ProfileDirectory { get; } /// HOME of the browser process (certificate database, font cache). public string HomeDirectory { get; } /// Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window. public static bool UsesXvfb => OperatingSystem.IsLinux(); /// True when the browser runs and a page connection is attached. public bool IsAvailable => _started && Host.IsAttached; /// Completes when the browser started the first time. public Task Ready => _ready.Task; /// Why the last start failed, in Italian (for the log and the connection status); null when running. public string? LastError => _lastError; public bool UserIsDriving => Host.UserIsDriving; /// Starts Xvfb and Chromium, retrying until it works or is cancelled. public async Task RunAsync(CancellationToken ct) { for (var attempt = 0; !ct.IsCancellationRequested; attempt++) { try { await StartOnceAsync(ct).ConfigureAwait(false); _started = true; _lastError = null; _ready.TrySetResult(); _log.Info("browser", $"Browser pronto: finestra {_options.WindowWidth.ToString(CultureInfo.InvariantCulture)}×{_options.WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_options.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{(_options.NoSandbox ? ", senza sandbox (FEBE_SENZA_SANDBOX)" : string.Empty)}."); return; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } catch (Exception ex) when (ex is not OutOfMemoryException) { _lastError = Explain(ex); var wait = Retry[Math.Min(attempt, Retry.Length - 1)]; _log.Error("browser", $"Il browser non parte: {_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s."); // A failed start leaves nothing running in the host (it can be started again); Xvfb, if it started, stays. try { await _clock.Delay(wait, ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } } } } /// /// «Scollega» (spec §4.1): stops Chromium (SIGINT, so it closes cleanly), deletes the profile folder with the /// Instagram session, and starts the browser again with an empty profile. /// public async Task RestartWithEmptyProfileAsync(CancellationToken ct) { if (!_started) { DeleteProfile(); return; } await Host.RestartAsync(DeleteProfile, ct).ConfigureAwait(false); _log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto."); } public async ValueTask DisposeAsync() { await StopProcessesAsync().ConfigureAwait(false); } private async Task StartOnceAsync(CancellationToken ct) { Directory.CreateDirectory(HomeDirectory); if (UsesXvfb && _xvfb is null) { RemoveStaleDisplayLock(_options.Display); var xvfb = new XvfbProcess(_options.Display, _options.WindowWidth, _options.WindowHeight, clock: _clock, log: _log.ForBrowser()); await xvfb.StartAsync(ct).ConfigureAwait(false); _xvfb = xvfb; } RemoveStaleProfileLocks(ProfileDirectory); await Host.StartAsync(BrowserOptions, ct).ConfigureAwait(false); } private async Task StopProcessesAsync() { try { await Host.StopAsync().ConfigureAwait(false); } catch (Exception ex) when (ex is InvalidOperationException or IOException) { } if (_xvfb is { } xvfb) { _xvfb = null; await xvfb.DisposeAsync().ConfigureAwait(false); } } private void DeleteProfile() { if (Directory.Exists(ProfileDirectory)) { Directory.Delete(ProfileDirectory, recursive: true); } } /// /// Chromium's «profile in use on another computer» lock: after the container is recreated the host name changes and /// Chromium would refuse the profile with a dialog nobody sees. Only Febe starts this browser, and it is not running /// now, so the lock files are stale by definition. /// internal static void RemoveStaleProfileLocks(string profileDirectory) { foreach (var name in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" }) { var path = Path.Combine(profileDirectory, name); try { if (File.Exists(path) || new FileInfo(path).LinkTarget is not null) { File.Delete(path); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } } } /// /// A display lock left by an Xvfb of an earlier run of the same container (restart after a crash): its process /// number may now belong to another process, so a lock whose owner is not an Xvfb is removed. /// internal static void RemoveStaleDisplayLock(string display) { if (!OperatingSystem.IsLinux() || !int.TryParse(display.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var number)) { return; } var id = number.ToString(CultureInfo.InvariantCulture); var lockFile = $"/tmp/.X{id}-lock"; try { if (!File.Exists(lockFile)) { return; } var owner = int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid) ? pid : 0; var comm = owner > 0 && File.Exists($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm") ? File.ReadAllText($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm").Trim() : string.Empty; if (comm.Equals("Xvfb", StringComparison.Ordinal)) { return; } File.Delete(lockFile); var socket = $"/tmp/.X11-unix/X{id}"; if (File.Exists(socket)) { File.Delete(socket); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } } private static string Explain(Exception ex) => ex switch { FileNotFoundException => ex.Message, PlatformNotSupportedException => ex.Message, TimeoutException => ex.Message, InvalidOperationException when ex.Message.Contains("sandbox", StringComparison.OrdinalIgnoreCase) => ex.Message + " Se il registro parla della sandbox, vedi docs/docker.md: profilo seccomp oppure FEBE_SENZA_SANDBOX=1.", _ => $"{ex.GetType().Name}: {ex.Message}", }; }