Files
Chronos/src/Chronos.Setup/Engine/SilentSetup.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

165 lines
8.4 KiB
C#

using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Packaging;
using Chronos.Setup.Cli;
namespace Chronos.Setup.Engine;
/// <summary>
/// <c>/S</c>: install or uninstall without a window, reporting only through the exit code and the setup log.
/// Running programs are asked to close; if they do not, setup stops with <see cref="SetupExitCode.ProgramRunning"/>
/// before touching anything. Then the services of the installed programs are stopped (and started again after the
/// upgrade, or when it fails) or deleted with the uninstall, which asks for administrator approval when setup runs
/// without it. Silent uninstall never removes user data.
/// </summary>
internal static class SilentSetup
{
public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(20);
public static async Task<SetupExitCode> RunAsync(SetupArguments arguments)
{
try
{
return arguments.Uninstall ? await UninstallAsync(arguments).ConfigureAwait(false) : await InstallAsync(arguments).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Error("setup", "Silent setup failed", ex);
return CodeFor(ex);
}
}
/// <summary>Exit code for a failure.</summary>
public static SetupExitCode CodeFor(Exception ex) => ex switch
{
SetupException s => s.Code,
PayloadException => SetupExitCode.PayloadInvalid,
// ERROR_DISK_FULL / ERROR_HANDLE_DISK_FULL
IOException { HResult: unchecked((int)0x80070070) or unchecked((int)0x80070027) } => SetupExitCode.DiskFull,
_ => SetupExitCode.Failed,
};
private static async Task<SetupExitCode> InstallAsync(SetupArguments arguments)
{
using var payload = PayloadReader.OpenCurrentProcess();
var engine = new InstallEngine(payload);
var plan = InstallPlan.Resolve(engine.Manifest, arguments);
if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory))
Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'");
if (!InstallPlan.IsValidDirectory(engine.Manifest, plan.Scope, plan.Directory, plan.Components))
{
Log.Error("setup", $"'{plan.Directory}' cannot take {string.Join(", ", plan.Components)} for {plan.Scope}");
return SetupExitCode.InvalidArguments;
}
if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments;
var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null;
if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false);
// Read before the upgrade rewrites the log, so a program it drops still names its service.
var programs = InstallPlan.Programs(engine.Manifest, plan.Directory).ToList();
var owned = CommandProgram.FullPaths(plan.Directory, programs);
var closed = await CloseProgramsAsync(plan.Directory, programs, owned).ConfigureAwait(false);
if (closed.Code != SetupExitCode.Success) return closed.Code;
var stopped = closed.Services;
try
{
var code = await InstalledServices.ApplyAsync(plan.Directory, stopped, ServiceActions.Stop, IntPtr.Zero).ConfigureAwait(false);
if (code != SetupExitCode.Success)
{
await StartAgainAsync(plan.Directory, stopped).ConfigureAwait(false);
return code;
}
var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu);
engine.Install(request, null, CancellationToken.None);
}
catch
{
await StartAgainAsync(plan.Directory, stopped).ConfigureAwait(false);
throw;
}
// Services whose program the upgrade removed go; the ones stopped for it run again.
var after = InstalledServices.Find(owned).Where(s => !File.Exists(s.Program)).UnionBy(stopped, s => s.Name, StringComparer.OrdinalIgnoreCase).ToList();
var services = await InstalledServices.ApplyAsync(plan.Directory, after, ServiceActions.Prune | ServiceActions.Start, IntPtr.Zero).ConfigureAwait(false);
if (services != SetupExitCode.Success) return services;
if (launch is null) return SetupExitCode.Success;
if (arguments.Elevated) return SetupExitCode.LaunchRequested;
Launcher.Start(launch);
return SetupExitCode.Success;
}
private static async Task<SetupExitCode> UninstallAsync(SetupArguments arguments)
{
var product = UninstallEngine.Locate(arguments.Directory, PayloadProduct());
if (product is null) return SetupExitCode.NotInstalled;
if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated)
return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false);
var owned = CommandProgram.FullPaths(product.Directory, product.Log.Files);
var closed = await CloseProgramsAsync(product.Directory, product.Log.Files, owned).ConfigureAwait(false);
if (closed.Code != SetupExitCode.Success) return closed.Code;
// Only now that the programs are closed. Services that were not running are still registered: no service may
// outlive its program. If one cannot be deleted, the ones stopped here run again.
var services = await InstalledServices.ApplyAsync(product.Directory, InstalledServices.Find(owned), ServiceActions.Remove, IntPtr.Zero).ConfigureAwait(false);
if (services != SetupExitCode.Success)
{
await StartAgainAsync(product.Directory, closed.Services).ConfigureAwait(false);
return services;
}
UninstallEngine.Uninstall(product, userData: null, null);
return SetupExitCode.Success;
}
/// <summary>The product named by this program's payload, when it has one (a full installer run with /uninstall).</summary>
public static string? PayloadProduct()
{
try
{
using var payload = PayloadReader.OpenCurrentProcess();
return payload.Manifest.Product;
}
catch (PayloadException)
{
return null;
}
}
/// <summary>
/// Asks the running programs of <paramref name="directory"/> to close and returns the running services of
/// <paramref name="owned"/>, which the caller stops or deletes: a program that does not close stops setup before
/// any service is touched.
/// </summary>
private static async Task<(SetupExitCode Code, IReadOnlyList<InstalledService> Services)> CloseProgramsAsync(string directory, IEnumerable<string> programs, IReadOnlySet<string> owned)
{
var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList();
var running = RunningPrograms.Find(directory, programs, services);
try
{
if (running.Count == 0) return (SetupExitCode.Success, services);
Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close");
var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false);
return (still.Count == 0 ? SetupExitCode.Success : SetupExitCode.ProgramRunning, services);
}
finally
{
foreach (var p in running) p.Dispose();
}
}
/// <summary>After a failure, starts again the services setup stopped, so a failed upgrade does not leave the server down.</summary>
private static async Task StartAgainAsync(string directory, IReadOnlyList<InstalledService> stopped)
{
if (stopped.Count == 0) return;
try
{
var code = await InstalledServices.ApplyAsync(directory, stopped, ServiceActions.Start, IntPtr.Zero).ConfigureAwait(false);
if (code != SetupExitCode.Success) Log.Warning("setup", $"Stopped services not started again: {code}");
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException)
{
Log.Warning("setup", "Stopped services not started again", ex);
}
}
}