aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-10-15 14:27:13 -0500
committerGitHub <noreply@github.com>2023-10-15 14:27:13 -0500
commit5986bcadc179e3e9a34152687b80210dcc65e366 (patch)
tree69c89224d513f513793ac415664b4b584c383a82
parent12e89983470a55e03f30f35002135b921183c72b (diff)
parent4670f2a708b48d3bb73021a3954b8ca76bf56aa5 (diff)
downloadslskd-5986bcadc179e3e9a34152687b80210dcc65e366.tar.gz
Merge pull request #978 from slskd/file-retention
Add automated removal of downloaded and incomplete files, and application logs
-rw-r--r--config/slskd.example.yml4
-rw-r--r--docs/config.md12
-rw-r--r--src/slskd/Application.cs63
-rw-r--r--src/slskd/Core/Clock.cs41
-rw-r--r--src/slskd/Core/Options.cs30
-rw-r--r--src/slskd/Program.cs3
6 files changed, 145 insertions, 8 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml
index 2c22d020..daabc838 100644
--- a/config/slskd.example.yml
+++ b/config/slskd.example.yml
@@ -116,6 +116,10 @@
# succeeded: 1440 # 1 day
# errored: 20160 # 2 weeks
# cancelled: 5
+# files:
+# complete: 20160 # 2 weeks
+# incomplete: 43200 # 30 days
+# logs: 259200 # 180 days
# logger:
# loki: ~
# metrics:
diff --git a/docs/config.md b/docs/config.md
index b08cd797..2038d98a 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -721,7 +721,13 @@ filters:
# Data Retention
-Retention of transfer records on the UI (and in API endpoints) is, by default, indefinite; completed transfers will remain visible until they are manually removed. Users can optionally configure time-based retention rules for both uploads and downloads, and can specify different settings for different dispositions (succeeded, errored, and cancelled). Transfers are checked for expiration on a 5 minute interval, and the minimum retention time is 5 minutes.
+By default, most things created by the application are retained indefinitely; they have to be removed manually by the user. Users can optionally configure certain things to be removed or deleted automatically after a period of time.
+
+Transfers can be configured to be removed from the UI after they are complete by specifying retention periods for uploads and downloads separately, and by transfer state; succeeded, errored, and cancelled.
+
+Files (on disk) can be configured to be deleted after the age of their last access time exceeds the configured time. Completed and incomplete files can be configured separately.
+
+Application logs are removed after 180 days by default, but this can be configured as well.
All retention periods are specified in minutes.
@@ -736,6 +742,10 @@ retention:
succeeded: 1440 # 1 day
errored: 20160 # 2 weeks
cancelled: 5
+ files:
+ complete: 20160 # 2 weeks
+ incomplete: 43200 # 30 days
+ logs: 259200 # 180 days
```
# Integrations
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 7002da24..6d6ccd37 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -285,6 +285,10 @@ namespace slskd
{
Log.Information("Application started");
+ Log.Debug("Starting clock");
+ await Clock.StartAsync();
+ Log.Debug("Clock started");
+
// if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these
// records to be updated if the application has started to shut down so that we can do this cleanup and properly
// disposition them as having failed due to an application shutdown, instead of some random exception thrown while
@@ -442,6 +446,9 @@ namespace slskd
{
ShuttingDown = true;
Log.Warning("Application is shutting down");
+
+ Clock.Stop();
+
Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down"));
Client.Dispose();
Log.Information("Client stopped");
@@ -727,17 +734,71 @@ namespace slskd
private void Clock_EveryFiveMinutes(object sender, EventArgs e)
{
- PruneTransfers();
+ _ = Task.Run(() => PruneTransfers());
}
private void Clock_EveryThirtyMinutes(object sender, EventArgs e)
{
+ _ = Task.Run(() => PruneFiles());
}
private void Clock_EveryHour(object sender, EventArgs e)
{
}
+ private void PruneFiles()
+ {
+ void PruneDirectory(int? age, string directory)
+ {
+ try
+ {
+ if (!age.HasValue)
+ {
+ return;
+ }
+
+ Log.Debug("Pruning files older than {Age} minutes from {Directory}", age, directory);
+
+ var options = new EnumerationOptions
+ {
+ IgnoreInaccessible = true,
+ AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
+ RecurseSubdirectories = true,
+ };
+
+ var files = System.IO.Directory.GetFiles(directory, "*", options)
+ .Select(filename => new FileInfo(filename))
+ .Where(file => file.LastAccessTimeUtc <= DateTime.UtcNow.AddMinutes(-age.Value));
+
+ Log.Debug("Found {Count} files of need of pruning", files.Count());
+
+ int errors = 0;
+
+ foreach (var file in files)
+ {
+ try
+ {
+ file.Delete();
+ }
+ catch (Exception ex)
+ {
+ errors++;
+ Log.Warning(ex, "Failed to prune file {File}: {Message}", file, ex.Message);
+ }
+ }
+
+ Log.Debug("Pruning complete. Deleted: {Deleted}, Errors: {Errors}", files.Count() - errors, errors);
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Failed to prune files in directory {Directory}: {Message}", directory, ex.Message);
+ }
+ }
+
+ PruneDirectory(age: Options.Retention.Files.Incomplete, directory: Options.Directories.Incomplete);
+ PruneDirectory(age: Options.Retention.Files.Complete, directory: Options.Directories.Downloads);
+ }
+
private void PruneTransfers()
{
var options = OptionsMonitor.CurrentValue.Retention;
diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs
index 332308d7..31519fc8 100644
--- a/src/slskd/Core/Clock.cs
+++ b/src/slskd/Core/Clock.cs
@@ -18,6 +18,7 @@
namespace slskd
{
using System;
+ using System.Threading.Tasks;
using System.Timers;
/// <summary>
@@ -27,10 +28,10 @@ namespace slskd
{
static Clock()
{
- EveryMinuteTimer.Elapsed += (_, _) => EveryMinute?.Invoke(null, EventArgs.Empty);
- EveryFiveMinutesTimer.Elapsed += (_, _) => EveryFiveMinutes?.Invoke(null, EventArgs.Empty);
- EveryThirtyMinutesTimer.Elapsed += (_, _) => EveryThirtyMinutes?.Invoke(null, EventArgs.Empty);
- EveryHourTimer.Elapsed += (_, _) => EveryHour?.Invoke(null, EventArgs.Empty);
+ EveryMinuteTimer.Elapsed += (_, _) => Fire(EveryMinute);
+ EveryFiveMinutesTimer.Elapsed += (_, _) => Fire(EveryFiveMinutes);
+ EveryThirtyMinutesTimer.Elapsed += (_, _) => Fire(EveryThirtyMinutes);
+ EveryHourTimer.Elapsed += (_, _) => Fire(EveryHour);
}
/// <summary>
@@ -53,11 +54,41 @@ namespace slskd
/// </summary>
public static event EventHandler EveryHour;
+ /// <summary>
+ /// Starts the clock.
+ /// </summary>
+ /// <returns>A Task that completes when all startup events have finished processing.</returns>
+ public static Task StartAsync()
+ {
+ EveryMinuteTimer.Enabled = true;
+ EveryFiveMinutesTimer.Enabled = true;
+ EveryThirtyMinutesTimer.Enabled = true;
+ EveryHourTimer.Enabled = true;
+
+ return Task.WhenAll(
+ Task.Run(() => Fire(EveryMinute)),
+ Task.Run(() => Fire(EveryFiveMinutes)),
+ Task.Run(() => Fire(EveryThirtyMinutes)),
+ Task.Run(() => Fire(EveryHour)));
+ }
+
+ /// <summary>
+ /// Stops the clock.
+ /// </summary>
+ public static void Stop()
+ {
+ EveryMinuteTimer.Stop();
+ EveryFiveMinutesTimer.Stop();
+ EveryThirtyMinutesTimer.Stop();
+ EveryHourTimer.Stop();
+ }
+
private static Timer EveryMinuteTimer { get; } = CreateTimer(interval: 1000 * 60);
private static Timer EveryFiveMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 5);
private static Timer EveryThirtyMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 30);
private static Timer EveryHourTimer { get; } = CreateTimer(interval: 1000 * 60 * 60);
- private static Timer CreateTimer(double interval) => new() { AutoReset = true, Interval = interval, Enabled = true };
+ private static Timer CreateTimer(double interval) => new() { AutoReset = true, Interval = interval, Enabled = false };
+ private static void Fire(EventHandler e) => e?.Invoke(null, EventArgs.Empty);
}
} \ No newline at end of file
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 30297cac..9d92bb95 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -1060,6 +1060,12 @@ namespace slskd
public class RetentionOptions
{
/// <summary>
+ /// Gets file retention options.
+ /// </summary>
+ [Validate]
+ public FileRetentionOptions Files { get; init; } = new FileRetentionOptions();
+
+ /// <summary>
/// Gets upload retention options.
/// </summary>
[Validate]
@@ -1072,6 +1078,30 @@ namespace slskd
public TransferRetentionOptions Download { get; init; } = new TransferRetentionOptions();
/// <summary>
+ /// Gets the time to retain logs, in days.
+ /// </summary>
+ [Range(1, maximum: int.MaxValue)]
+ public int Logs { get; init; } = 180;
+
+ /// <summary>
+ /// File retention options.
+ /// </summary>
+ public class FileRetentionOptions
+ {
+ /// <summary>
+ /// Gets the time to retain completed files, in minutes.
+ /// </summary>
+ [Range(30, maximum: int.MaxValue)]
+ public int? Complete { get; init; } = null;
+
+ /// <summary>
+ /// Gets the time to retain incomplete files, in minutes.
+ /// </summary>
+ [Range(30, maximum: int.MaxValue)]
+ public int? Incomplete { get; init; } = null;
+ }
+
+ /// <summary>
/// Transfer retention options.
/// </summary>
public class TransferRetentionOptions
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 418a29c2..7a832ddb 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -952,7 +952,8 @@ namespace slskd
config.File(
Path.Combine(AppDirectory, "logs", $"{AppName}-.log"),
outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
- rollingInterval: RollingInterval.Day))
+ rollingInterval: RollingInterval.Day,
+ retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))
.WriteTo.Conditional(
e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
config => config.GrafanaLoki(