diff options
| author | JP Dillingham <jp@dillingham.me> | 2023-10-15 14:27:13 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-10-15 14:27:13 -0500 |
| commit | 5986bcadc179e3e9a34152687b80210dcc65e366 (patch) | |
| tree | 69c89224d513f513793ac415664b4b584c383a82 /src | |
| parent | 12e89983470a55e03f30f35002135b921183c72b (diff) | |
| parent | 4670f2a708b48d3bb73021a3954b8ca76bf56aa5 (diff) | |
| download | slskd-5986bcadc179e3e9a34152687b80210dcc65e366.tar.gz | |
Merge pull request #978 from slskd/file-retention
Add automated removal of downloaded and incomplete files, and application logs
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 63 | ||||
| -rw-r--r-- | src/slskd/Core/Clock.cs | 41 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 3 |
4 files changed, 130 insertions, 7 deletions
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( |
