Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

fix(updater): address follow-up review feedback

Alenbosh213bd40f747d
diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.cs
index 71819380..d17609f2 100644
--- a/src/Filee.App/App.axaml.cs
+++ b/src/Filee.App/App.axaml.cs
@@ -137,6 +137,8 @@ public partial class App : Application
_ = Task.Run(() => Filee.Core.Web.WebDrop.DeleteStale(Filee.Core.Web.WebDrop.DefaultWorkRoot, TimeSpan.FromDays(1)));
// Likewise the work folders of conversions that never got to clean up after themselves.
_ = Task.Run(() => JobQueue.DeleteStaleWorkFolders(JobQueue.DefaultWorkRoot, TimeSpan.FromDays(1)));
+ // Leftover update workspaces from cancelled or failed in-app updates.
+ _ = Task.Run(() => UpdateService.DeleteStaleWorkspaces());
// Once LibreOffice is installed: prepare its profiles while the user isn't converting yet.
AppHost.Get<EngineDownloadService>().WarmUpInBackground(TimeSpan.FromSeconds(10));
@@ -212,7 +214,9 @@ public partial class App : Application
store.SaveSettings();
AppHost.Get<WindowService>().ShowUpdateNotice(version);
};
- updates.UpdateFailed += async (_, _) => await AppHost.Get<WindowService>().ShowUpdateFailedAsync();
+ updates.UpdateFailed += async (_, _) => await AppHost.Get<WindowService>().ShowUpdateFailedAsync(updates.LastFailureLogPath);
+ if (updates.CheckPendingFailure(store.Directory))
+ Dispatcher.UIThread.Post(async () => await AppHost.Get<WindowService>().ShowUpdateFailedAsync(updates.LastFailureLogPath));
updates.StartPeriodicChecks(() => store.Settings.CheckForUpdates, TimeSpan.FromSeconds(20));
DispatcherTimer.RunOnce(() => NotifyEngineUpdates(store), TimeSpan.FromSeconds(25));
}
diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.cs
index 834dd562..174a9241 100644
--- a/src/Filee.App/Services/UpdateService.cs
+++ b/src/Filee.App/Services/UpdateService.cs
@@ -154,6 +154,12 @@ public sealed partial class UpdateService : ObservableObject
/// <summary>Allows tests to redirect Linux installation target directory to an isolated temporary folder.</summary>
internal string? LinuxInstallDirectoryOverride { get; set; }
+ /// <summary>Allows tests to redirect update failure marker path to an isolated temporary location.</summary>
+ internal string? FailureMarkerPathOverride { get; set; }
+
+ /// <summary>The log file path recorded in the update failure marker from the previous run, if any.</summary>
+ internal string? LastFailureLogPath { get; private set; }
+
/// <summary>Whether <see cref="UpdateAsync"/> installs by itself (<see cref="IsInstalled"/>; tests set it).</summary>
internal bool InstallsItself { get; init; } = IsInstalled;
@@ -410,6 +416,7 @@ public sealed partial class UpdateService : ObservableObject
var logDir = Path.Combine(UserDataStore.DefaultDirectory, "logs");
Directory.CreateDirectory(logDir);
var logFile = Path.Combine(logDir, $"filee-{DateTime.Now:yyyyMMdd}.log");
+ var markerFile = FailureMarkerPathOverride ?? Path.Combine(UserDataStore.DefaultDirectory, ".update-failed");
Process? helper;
try
@@ -422,11 +429,17 @@ public sealed partial class UpdateService : ObservableObject
startInfo.ArgumentList.Add("-c");
startInfo.ArgumentList.Add(
"for _ in $(seq 1 600); do if ! kill -0 \"$1\" 2>/dev/null; then break; fi; sleep 0.1; done; " +
- "if kill -0 \"$1\" 2>/dev/null; then echo \"Update aborted: Filee (PID $1) did not exit within timeout\" >> \"$4\"; exit 1; fi; " +
+ "if kill -0 \"$1\" 2>/dev/null; then echo \"Update aborted: Filee (PID $1) did not exit within timeout\" >> \"$4\"; rm -rf \"$5\" 2>/dev/null; exit 1; fi; " +
"\"$2\" --upgrade >> \"$4\" 2>&1; " +
"status=$?; " +
"rm -rf \"$5\" 2>/dev/null; " +
- "if [ $status -eq 0 ]; then exec \"$3\" --background --whats-new; else echo \"Update failed with status $status\" >> \"$4\"; exit $status; fi"
+ "if [ $status -eq 0 ]; then " +
+ "if [ -x \"$3\" ]; then exec \"$3\" --background --whats-new; else echo \"Update succeeded but '$3' is not executable\" >> \"$4\"; exit 1; fi; " +
+ "else " +
+ "echo \"Update failed with status $status\" >> \"$4\"; " +
+ "echo \"$4\" > \"$6.tmp\" 2>/dev/null && mv -f \"$6.tmp\" \"$6\" 2>/dev/null || true; " +
+ "if [ -x \"$3\" ]; then exec \"$3\" --background; else echo \"Cannot restart Filee: '$3' is not executable after rollback\" >> \"$4\"; exit $status; fi; " +
+ "fi"
);
startInfo.ArgumentList.Add("_");
startInfo.ArgumentList.Add(currentPid.ToString());
@@ -434,6 +447,7 @@ public sealed partial class UpdateService : ObservableObject
startInfo.ArgumentList.Add(newExe);
startInfo.ArgumentList.Add(logFile);
startInfo.ArgumentList.Add(workspace);
+ startInfo.ArgumentList.Add(markerFile);
helper = StartProcess(startInfo);
}
@@ -561,6 +575,51 @@ public sealed partial class UpdateService : ObservableObject
UpdateFailed?.Invoke(this, EventArgs.Empty);
}
+ /// <summary>
+ /// Checks whether a previous in-app update attempt failed before restarting.
+ /// If an update failure marker exists, safely reads the log path, consumes (deletes) the marker,
+ /// logs the failure, sets <see cref="Step"/> to <see cref="UpdateStep.Failed"/>, and returns <c>true</c>.
+ /// </summary>
+ public bool CheckPendingFailure(string? dataDir = null)
+ {
+ var markerPath = FailureMarkerPathOverride ?? Path.Combine(dataDir ?? UserDataStore.DefaultDirectory, ".update-failed");
+ if (!File.Exists(markerPath))
+ return false;
+
+ string? logPath = null;
+ try
+ {
+ var content = File.ReadAllText(markerPath).Trim();
+ if (!string.IsNullOrWhiteSpace(content)
+ && Path.IsPathRooted(content)
+ && !content.Any(char.IsControl)
+ && (File.Exists(content) || content.EndsWith(".log", StringComparison.OrdinalIgnoreCase)))
+ {
+ logPath = content;
+ }
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Failed to read update failure marker at {MarkerPath}", markerPath);
+ }
+ finally
+ {
+ try
+ {
+ File.Delete(markerPath);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Failed to delete update failure marker at {MarkerPath}", markerPath);
+ }
+ }
+
+ LastFailureLogPath = logPath;
+ _log.LogWarning("In-app update failed during previous run. Log: {LogPath}", logPath ?? "(unknown)");
+ Step = UpdateStep.Failed;
+ return true;
+ }
+
private void Publish(string? newer, bool announce)
{
var previous = LatestVersion;
@@ -880,27 +939,27 @@ public sealed partial class UpdateService : ObservableObject
}
}
+ /// <summary>Gets the default root directory where secure workspaces are allocated.</summary>
+ internal static string GetDefaultWorkspaceBaseDirectory()
+ {
+ if (OperatingSystem.IsLinux())
+ {
+ var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
+ var root = !string.IsNullOrWhiteSpace(dataHome)
+ ? dataHome
+ : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+ return Path.Combine(root, "filee");
+ }
+ return Path.GetTempPath();
+ }
+
/// <summary>
/// Creates a private, dedicated temporary workspace for this update instance.
/// Mode 0700 on Unix, inaccessible to other local users, non-predictable, and never reusing pre-existing paths.
/// </summary>
internal static string CreateSecureWorkspace(string? baseDir = null)
{
- if (string.IsNullOrWhiteSpace(baseDir))
- {
- if (OperatingSystem.IsLinux())
- {
- var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
- var root = !string.IsNullOrWhiteSpace(dataHome)
- ? dataHome
- : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- baseDir = Path.Combine(root, "filee");
- }
- else
- {
- baseDir = Path.GetTempPath();
- }
- }
+ baseDir = string.IsNullOrWhiteSpace(baseDir) ? GetDefaultWorkspaceBaseDirectory() : baseDir;
Directory.CreateDirectory(baseDir);
@@ -953,116 +1012,95 @@ public sealed partial class UpdateService : ObservableObject
}
}
- /// <summary>Locates the installation directory on Linux.</summary>
- internal static string GetLinuxInstallDirectory()
+ /// <summary>
+ /// Checks whether a process with the given <paramref name="pid"/> is currently running.
+ /// Used to protect active update workspaces from being swept.
+ /// </summary>
+ internal static bool IsProcessAlive(int pid)
{
- if (IsLinuxInstalled(AppContext.BaseDirectory))
- return AppContext.BaseDirectory;
- var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
- var root = !string.IsNullOrWhiteSpace(dataHome)
- ? dataHome
- : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- return Path.Combine(root, "filee", "application");
- }
+ if (pid <= 0)
+ return false;
- /// <summary>Reads the installed Filee version from the specified installation folder.</summary>
- internal static string? GetInstalledVersion(string installDir)
- {
- var dll = Path.Combine(installDir, "Filee.dll");
- if (File.Exists(dll))
+ try
{
- try
- {
- var info = FileVersionInfo.GetVersionInfo(dll);
- if (!string.IsNullOrWhiteSpace(info.ProductVersion))
- return info.ProductVersion.Split('+')[0].Trim();
- if (!string.IsNullOrWhiteSpace(info.FileVersion))
- return info.FileVersion.Trim();
- }
- catch
- {
- // Fall through
- }
- }
+ if (OperatingSystem.IsLinux())
+ return Directory.Exists($"/proc/{pid}");
- var exe = Path.Combine(installDir, "Filee");
- if (File.Exists(exe))
- {
- try
- {
- var info = FileVersionInfo.GetVersionInfo(exe);
- if (!string.IsNullOrWhiteSpace(info.ProductVersion))
- return info.ProductVersion.Split('+')[0].Trim();
- if (!string.IsNullOrWhiteSpace(info.FileVersion))
- return info.FileVersion.Trim();
- }
- catch
- {
- // Fall through
- }
+ using var proc = Process.GetProcessById(pid);
+ return !proc.HasExited;
}
-
- var cli = Path.Combine(installDir, "filee-cli");
- if (File.Exists(cli))
+ catch (ArgumentException)
{
- try
- {
- using var proc = Process.Start(new ProcessStartInfo(cli, "version")
- {
- RedirectStandardOutput = true,
- UseShellExecute = false,
- });
- if (proc is not null && proc.WaitForExit(3000) && proc.ExitCode == 0)
- {
- var line = proc.StandardOutput.ReadLine()?.Trim();
- if (line?.StartsWith("filee ", StringComparison.OrdinalIgnoreCase) == true)
- return line["filee ".Length..].Trim();
- }
- }
- catch
- {
- // Fall through
- }
+ return false;
}
-
- return null;
- }
-
- /// <summary>Verifies that the version installed in <paramref name="installDir"/> matches <paramref name="expectedVersion"/>.</summary>
- internal static bool VerifyInstalledVersion(string installDir, string expectedVersion, out string? actualVersion)
- {
- actualVersion = GetInstalledVersion(installDir);
- if (actualVersion is null)
+ catch (InvalidOperationException)
+ {
return false;
-
- if (TryParse(expectedVersion, out var expected) && TryParse(actualVersion, out var actual))
- return expected == actual;
-
- return string.Equals(actualVersion.Trim(), expectedVersion.Trim(), StringComparison.OrdinalIgnoreCase);
+ }
+ catch (Exception)
+ {
+ // If in doubt (e.g. access denied), assume alive to safeguard against deleting active workspaces
+ return true;
+ }
}
- internal static string FindLinuxRecoveryInfo(string installDir)
+ /// <summary>
+ /// Deletes stale update workspaces left behind by crashes, forced kills, or aborted updates.
+ /// Protects active workspaces by checking both an age threshold (default 1 day) and process liveness
+ /// (never deleting a workspace belonging to a running PID).
+ /// </summary>
+ public static void DeleteStaleWorkspaces(string? root = null, TimeSpan? age = null, ILogger? log = null)
{
- var cleanInstallDir = Path.TrimEndingDirectorySeparator(installDir);
- var parent = Path.GetDirectoryName(cleanInstallDir);
- if (string.IsNullOrWhiteSpace(parent) || !Directory.Exists(parent))
- return "";
-
+ var threshold = age ?? TimeSpan.FromDays(1);
try
{
- var backups = Directory.GetDirectories(parent, ".backup-*");
- if (backups.Length > 0)
+ var baseDir = root ?? GetDefaultWorkspaceBaseDirectory();
+ var dirInfo = new DirectoryInfo(baseDir);
+ if (!dirInfo.Exists || dirInfo.LinkTarget is not null || dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
+ return;
+
+ foreach (var folder in dirInfo.EnumerateDirectories(".update-*"))
{
- var latestBackup = backups.OrderByDescending(Directory.GetCreationTimeUtc).First();
- return $"Previous installation retained at '{latestBackup}'. To recover manually: mv '{latestBackup}' '{cleanInstallDir}'";
+ if (folder.LinkTarget is not null || folder.Attributes.HasFlag(FileAttributes.ReparsePoint))
+ continue;
+
+ try
+ {
+ var parts = folder.Name.Split('-');
+ if (parts.Length >= 2 && int.TryParse(parts[1], out var pid))
+ {
+ if (IsProcessAlive(pid))
+ continue;
+ }
+
+ if (DateTime.UtcNow - folder.LastWriteTimeUtc > threshold)
+ {
+ DeleteSecureWorkspace(folder.FullName);
+ log?.LogInformation("Deleted stale update workspace {Workspace}", folder.FullName);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ log?.LogWarning(ex, "Could not delete stale update workspace {Workspace}", folder.FullName);
+ }
}
}
- catch
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
- // Ignore directory enumeration failures
+ log?.LogWarning(ex, "Failed to enumerate update workspaces in {Root}", root);
}
+ }
- return "No backup directory found.";
+ /// <summary>Locates the installation directory on Linux.</summary>
+ internal static string GetLinuxInstallDirectory()
+ {
+ if (IsLinuxInstalled(AppContext.BaseDirectory))
+ return AppContext.BaseDirectory;
+ var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
+ var root = !string.IsNullOrWhiteSpace(dataHome)
+ ? dataHome
+ : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+ return Path.Combine(root, "filee", "application");
}
/// <summary>True when release tag <paramref name="tag"/> ("v1.2.0") is a higher version than <paramref name="current"/>.</summary>
diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.cs
index ac4347e7..54fac612 100644
--- a/src/Filee.App/Services/WindowService.cs
+++ b/src/Filee.App/Services/WindowService.cs
@@ -321,10 +321,13 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services, Mem
public Task MessageAsync(Window? owner, string message) => ShowMessageAsync(owner, message, destructive: false, withCancel: false);
/// <summary>The in-app update failed: say so, then open the website to download the new version there.</summary>
- public async Task ShowUpdateFailedAsync()
+ public async Task ShowUpdateFailedAsync(string? logPath = null)
{
_updateNotice?.Close();
- await MessageAsync(_main is { IsVisible: true } main ? main : null, loc["update.failed_alert"]);
+ var message = loc["update.failed_alert"];
+ if (!string.IsNullOrWhiteSpace(logPath))
+ message += $"\n\nLog: {logPath}";
+ await MessageAsync(_main is { IsVisible: true } main ? main : null, message);
services.GetRequiredService<UpdateService>().OpenDownloadPage();
}
diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.cs
index 1f4db326..c21e64b8 100644
--- a/tests/Filee.App.Tests/UpdateServiceTests.cs
+++ b/tests/Filee.App.Tests/UpdateServiceTests.cs
@@ -500,10 +500,13 @@ public class UpdateServiceTests
Assert.Contains("kill -0 \"$1\"", helperPsi.ArgumentList[1]);
Assert.Contains("\"$2\" --upgrade >> \"$4\" 2>&1", helperPsi.ArgumentList[1]);
Assert.Contains("exec \"$3\" --background --whats-new", helperPsi.ArgumentList[1]);
+ Assert.Contains("exec \"$3\" --background", helperPsi.ArgumentList[1]);
+ Assert.Contains("rm -rf \"$5\"", helperPsi.ArgumentList[1]);
Assert.Equal(Environment.ProcessId.ToString(), helperPsi.ArgumentList[3]);
Assert.EndsWith("install.sh", helperPsi.ArgumentList[4]);
Assert.Equal(Path.Combine(mockInstallDir, "Filee"), helperPsi.ArgumentList[5]);
Assert.EndsWith(".log", helperPsi.ArgumentList[6]);
+ Assert.EndsWith(".update-failed", helperPsi.ArgumentList[8]);
Assert.True(shutdownRequested, "Application shutdown must be requested before file swap");
}
@@ -645,41 +648,33 @@ public class UpdateServiceTests
[Fact]
public async Task Concurrent_secure_workspaces_are_isolated()
{
- var tasks = Enumerable.Range(0, 5).Select(_ => Task.Run(() => UpdateService.CreateSecureWorkspace())).ToArray();
- var workspaces = await Task.WhenAll(tasks);
-
+ var isolatedDir = TempFolder();
try
{
+ var tasks = Enumerable.Range(0, 5).Select(_ => Task.Run(() => UpdateService.CreateSecureWorkspace(isolatedDir))).ToArray();
+ var workspaces = await Task.WhenAll(tasks);
+
Assert.Equal(5, workspaces.Distinct().Count());
- Assert.All(workspaces, w => Assert.True(Directory.Exists(w)));
+ Assert.All(workspaces, w =>
+ {
+ Assert.True(Directory.Exists(w));
+ Assert.StartsWith(isolatedDir, w);
+ });
}
finally
{
- foreach (var w in workspaces)
- UpdateService.DeleteSecureWorkspace(w);
+ try
+ {
+ if (Directory.Exists(isolatedDir))
+ Directory.Delete(isolatedDir, recursive: true);
+ }
+ catch
+ {
+ // Best effort test cleanup
+ }
}
}
- [Fact]
- public void VerifyInstalledVersion_detects_mismatch()
- {
- var folder = TempFolder();
- var cli = Path.Combine(folder, "filee-cli");
- File.WriteAllText(cli, "#!/bin/sh\necho \"filee 1.0.0\"\n");
- if (OperatingSystem.IsLinux())
- File.SetUnixFileMode(cli, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
-
- Assert.True(UpdateService.VerifyInstalledVersion(folder, "1.0.0", out var actual));
- Assert.Equal("1.0.0", actual);
-
- Assert.False(UpdateService.VerifyInstalledVersion(folder, "1.0.2", out actual));
- Assert.Equal("1.0.0", actual);
-
- var emptyFolder = TempFolder();
- Assert.False(UpdateService.VerifyInstalledVersion(emptyFolder, "1.0.0", out actual));
- Assert.Null(actual);
- }
-
[Fact]
public void Tar_extraction_masks_mode_to_rwx_bits()
{
@@ -714,18 +709,189 @@ public class UpdateServiceTests
}
[Fact]
- public void FindLinuxRecoveryInfo_handles_trailing_directory_separator()
+ public void CheckPendingFailure_returns_false_when_marker_absent()
+ {
+ var dir = TempFolder();
+ var updates = new UpdateService(NullLogger<UpdateService>.Instance)
+ {
+ FailureMarkerPathOverride = Path.Combine(dir, ".update-failed"),
+ };
+
+ var result = updates.CheckPendingFailure(dir);
+ Assert.False(result);
+ Assert.Equal(UpdateStep.Idle, updates.Step);
+ Assert.Null(updates.LastFailureLogPath);
+ }
+
+ [Fact]
+ public void CheckPendingFailure_consumes_marker_and_records_failure()
{
- var baseDir = TempFolder();
- var installDir = Path.Combine(baseDir, "application");
- Directory.CreateDirectory(installDir);
+ var dir = TempFolder();
+ var marker = Path.Combine(dir, ".update-failed");
+ var logPath = Path.Combine(dir, "logs", "filee-test.log");
+ Directory.CreateDirectory(Path.GetDirectoryName(logPath)!);
+ File.WriteAllText(logPath, "some error log");
+ File.WriteAllText(marker, logPath + "\n");
+
+ var updates = new UpdateService(NullLogger<UpdateService>.Instance)
+ {
+ FailureMarkerPathOverride = marker,
+ };
+
+ var result = updates.CheckPendingFailure(dir);
+ Assert.True(result);
+ Assert.Equal(UpdateStep.Failed, updates.Step);
+ Assert.Equal(logPath, updates.LastFailureLogPath);
+ Assert.False(File.Exists(marker), "Marker file must be consumed (deleted)");
+ }
+
+ [Fact]
+ public void CheckPendingFailure_handles_malformed_marker_safely()
+ {
+ var dir = TempFolder();
+ var marker = Path.Combine(dir, ".update-failed");
+ File.WriteAllText(marker, "not-a-rooted-path\0evil");
+
+ var updates = new UpdateService(NullLogger<UpdateService>.Instance)
+ {
+ FailureMarkerPathOverride = marker,
+ };
+
+ var result = updates.CheckPendingFailure(dir);
+ Assert.True(result);
+ Assert.Equal(UpdateStep.Failed, updates.Step);
+ Assert.Null(updates.LastFailureLogPath);
+ Assert.False(File.Exists(marker), "Marker file must still be consumed");
+ }
+
+ [Fact]
+ public void DeleteStaleWorkspaces_preserves_active_pid_and_deletes_stale_dead_pid()
+ {
+ var root = TempFolder();
+ var activeDir = Path.Combine(root, $".update-{Environment.ProcessId}-active123");
+ var deadPid = 999999;
+ while (UpdateService.IsProcessAlive(deadPid))
+ deadPid++;
+
+ var deadStaleDir = Path.Combine(root, $".update-{deadPid}-stale456");
+ var deadFreshDir = Path.Combine(root, $".update-{deadPid}-fresh789");
+
+ Directory.CreateDirectory(activeDir);
+ Directory.CreateDirectory(deadStaleDir);
+ Directory.CreateDirectory(deadFreshDir);
+
+ Directory.SetLastWriteTimeUtc(deadStaleDir, DateTime.UtcNow.AddDays(-2));
+
+ UpdateService.DeleteStaleWorkspaces(root, TimeSpan.FromDays(1));
+
+ Assert.True(Directory.Exists(activeDir), "Active PID workspace must not be deleted even if stale");
+ Assert.False(Directory.Exists(deadStaleDir), "Stale dead PID workspace must be deleted");
+ Assert.True(Directory.Exists(deadFreshDir), "Fresh dead PID workspace must be kept");
+ }
+
+ [Fact]
+ public void Helper_script_restarts_filee_on_failure_and_writes_marker()
+ {
+ if (!OperatingSystem.IsLinux())
+ return;
+
+ var tempDir = TempFolder();
+ var workspace = Path.Combine(tempDir, "workspace");
+ Directory.CreateDirectory(workspace);
+
+ var installLog = Path.Combine(tempDir, "install.log");
+ var markerFile = Path.Combine(tempDir, ".update-failed");
+
+ var mockInstallSh = Path.Combine(tempDir, "install.sh");
+ File.WriteAllText(mockInstallSh, "#!/bin/sh\necho 'Rolling back...' >&2\nexit 2\n");
+ File.SetUnixFileMode(mockInstallSh, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+
+ var argsOut = Path.Combine(tempDir, "filee-args.txt");
+ var mockFilee = Path.Combine(tempDir, "Filee");
+ File.WriteAllText(mockFilee, $"#!/bin/sh\necho \"$@\" > '{argsOut}'\nexit 0\n");
+ File.SetUnixFileMode(mockFilee, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+
+ var deadPid = 999999;
+ while (UpdateService.IsProcessAlive(deadPid))
+ deadPid++;
+
+ var script =
+ "for _ in $(seq 1 600); do if ! kill -0 \"$1\" 2>/dev/null; then break; fi; sleep 0.1; done; " +
+ "if kill -0 \"$1\" 2>/dev/null; then echo \"Update aborted: Filee (PID $1) did not exit within timeout\" >> \"$4\"; rm -rf \"$5\" 2>/dev/null; exit 1; fi; " +
+ "\"$2\" --upgrade >> \"$4\" 2>&1; " +
+ "status=$?; " +
+ "rm -rf \"$5\" 2>/dev/null; " +
+ "if [ $status -eq 0 ]; then " +
+ "if [ -x \"$3\" ]; then exec \"$3\" --background --whats-new; else echo \"Update succeeded but '$3' is not executable\" >> \"$4\"; exit 1; fi; " +
+ "else " +
+ "echo \"Update failed with status $status\" >> \"$4\"; " +
+ "echo \"$4\" > \"$6.tmp\" 2>/dev/null && mv -f \"$6.tmp\" \"$6\" 2>/dev/null || true; " +
+ "if [ -x \"$3\" ]; then exec \"$3\" --background; else echo \"Cannot restart Filee: '$3' is not executable after rollback\" >> \"$4\"; exit $status; fi; " +
+ "fi";
+
+ using var proc = Process.Start(new ProcessStartInfo("/bin/sh")
+ {
+ ArgumentList = { "-c", script, "_", deadPid.ToString(), mockInstallSh, mockFilee, installLog, workspace, markerFile },
+ UseShellExecute = false,
+ });
+
+ Assert.NotNull(proc);
+ Assert.True(proc.WaitForExit(5000));
+ Assert.Equal(0, proc.ExitCode);
+
+ Assert.False(Directory.Exists(workspace), "Workspace directory must be cleaned up on failure");
+ Assert.True(File.Exists(markerFile), "Failure marker file must be created");
+ Assert.Equal(installLog, File.ReadAllText(markerFile).Trim());
+
+ Assert.True(File.Exists(argsOut), "Restored Filee executable must have been launched");
+ var args = File.ReadAllText(argsOut).Trim();
+ Assert.Equal("--background", args);
+ Assert.DoesNotContain("--whats-new", args);
+ }
+
+ [Fact]
+ public void Helper_script_cleans_up_workspace_on_timeout()
+ {
+ if (!OperatingSystem.IsLinux())
+ return;
+
+ var tempDir = TempFolder();
+ var workspace = Path.Combine(tempDir, "workspace");
+ Directory.CreateDirectory(workspace);
+
+ var installLog = Path.Combine(tempDir, "install.log");
+ var markerFile = Path.Combine(tempDir, ".update-failed");
+ var mockInstallSh = Path.Combine(tempDir, "install.sh");
+ File.WriteAllText(mockInstallSh, "#!/bin/sh\nexit 0\n");
+ var mockFilee = Path.Combine(tempDir, "Filee");
+ File.WriteAllText(mockFilee, "#!/bin/sh\nexit 0\n");
+
+ var timeoutScript =
+ "for _ in $(seq 1 2); do if ! kill -0 \"$1\" 2>/dev/null; then break; fi; sleep 0.01; done; " +
+ "if kill -0 \"$1\" 2>/dev/null; then echo \"Update aborted: Filee (PID $1) did not exit within timeout\" >> \"$4\"; rm -rf \"$5\" 2>/dev/null; exit 1; fi; " +
+ "\"$2\" --upgrade >> \"$4\" 2>&1; " +
+ "status=$?; " +
+ "rm -rf \"$5\" 2>/dev/null; " +
+ "if [ $status -eq 0 ]; then " +
+ "if [ -x \"$3\" ]; then exec \"$3\" --background --whats-new; else echo \"Update succeeded but '$3' is not executable\" >> \"$4\"; exit 1; fi; " +
+ "else " +
+ "echo \"Update failed with status $status\" >> \"$4\"; " +
+ "echo \"$4\" > \"$6.tmp\" 2>/dev/null && mv -f \"$6.tmp\" \"$6\" 2>/dev/null || true; " +
+ "if [ -x \"$3\" ]; then exec \"$3\" --background; else echo \"Cannot restart Filee: '$3' is not executable after rollback\" >> \"$4\"; exit $status; fi; " +
+ "fi";
+
+ using var proc = Process.Start(new ProcessStartInfo("/bin/sh")
+ {
+ ArgumentList = { "-c", timeoutScript, "_", Environment.ProcessId.ToString(), mockInstallSh, mockFilee, installLog, workspace, markerFile },
+ UseShellExecute = false,
+ });
- var backupDir = Path.Combine(baseDir, ".backup-123");
- Directory.CreateDirectory(backupDir);
+ Assert.NotNull(proc);
+ Assert.True(proc.WaitForExit(5000));
+ Assert.Equal(1, proc.ExitCode);
- var recovery = UpdateService.FindLinuxRecoveryInfo(installDir + Path.DirectorySeparatorChar);
- Assert.Contains(backupDir, recovery);
- Assert.Contains("To recover manually: mv", recovery);
+ Assert.False(Directory.Exists(workspace), "Workspace must be cleaned up on timeout");
+ Assert.Contains("Update aborted: Filee", File.ReadAllText(installLog));
}
private static byte[] CreateTarGz(Action<TarWriter> populate)