From b0420bd49b64995671b80deeef54cffece0a4d41 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 13:14:45 -0500 Subject: add StorageType --- src/slskd/Core/Types/StorageType.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/slskd/Core/Types/StorageType.cs (limited to 'src') diff --git a/src/slskd/Core/Types/StorageType.cs b/src/slskd/Core/Types/StorageType.cs new file mode 100644 index 00000000..63b19899 --- /dev/null +++ b/src/slskd/Core/Types/StorageType.cs @@ -0,0 +1,35 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Storage type. + /// + public enum StorageType + { + /// + /// Stored in memory. + /// + Memory = 0, + + /// + /// Stored on disk. + /// + Disk = 1, + } +} -- cgit v1.2.3 From 5e11cc0fc0703dc161140b28f7e2cd0f65facf9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 13:17:18 -0500 Subject: consolidate share options, add cache storage option --- config/slskd.example.yml | 12 ++++---- src/slskd/Core/Options.cs | 76 +++++++++++++++++++++++++++++++++++++---------- 2 files changed, 68 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7038c576..46033bff 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -12,8 +12,14 @@ # directories: # incomplete: ~ # downloads: ~ -# shared: +# shares: +# directories: # - ~ +# filters: +# - \.ini$ +# - Thumbs.db$ +# - \.DS_Store$ +# cache_storage: memory # rooms: # - ~ # global: @@ -48,10 +54,6 @@ # - alice # - bob # filters: -# share: -# - \.ini$ -# - Thumbs.db$ -# - \.DS_Store$ # search: # request: # - ^.{1,2}$ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d6d4b04c..327036aa 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -196,6 +196,13 @@ namespace slskd [RequiresRestart] public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); + /// + /// Gets share options. + /// + [Validate] + [RequiresRestart] + public SharesOptions Shares { get; init; } = new SharesOptions(); + /// /// Gets global options. /// @@ -324,7 +331,7 @@ namespace slskd /// /// Directory options. /// - public class DirectoriesOptions : IValidatableObject + public class DirectoriesOptions { /// /// Gets the path where incomplete downloads are saved. @@ -345,14 +352,36 @@ namespace slskd [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; + } + /// + /// Share options. + /// + public class SharesOptions : IValidatableObject + { /// /// Gets the list of paths to shared files. /// [Argument('s', "shared")] [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - public string[] Shared { get; init; } = Array.Empty(); + [Description("paths to shared files")] + public string[] Directories { get; init; } = Array.Empty(); + + /// + /// Gets the list of shared file filters. + /// + [Argument(default, "share-filter")] + [EnvironmentVariable("SHARE_FILTER")] + [Description("regular expressions to filter files from shares")] + public string[] Filters { get; init; } = Array.Empty(); + + /// + /// Gets the type of storage to use for the share cache. + /// + [Argument(default, "share-cache-storage")] + [EnvironmentVariable("SHARE_CACHE_STORAGE")] + [Description("the type of storage to use for the cache")] + public StorageType CacheStorage { get; init; } = StorageType.Memory; /// /// Extended validation. @@ -363,17 +392,27 @@ namespace slskd { var results = new List(); + results.AddRange(ValidateShares()); + results.AddRange(ValidateFilters()); + + return results; + } + + private IEnumerable ValidateShares() + { + var results = new List(); + bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); - Shared.Where(share => IsBlankPath(share)).ToList() + Directories.Where(share => IsBlankPath(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} doees not specify a path"))); bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); - Shared.Where(share => IsRootMount(share)).ToList() + Directories.Where(share => IsRootMount(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); // starts with '/', 'X:', or '\\' bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); - Shared.Where(share => !IsAbsolutePath(share)).ToList() + Directories.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); (string Raw, string Alias, string Path) Digest(string share) @@ -388,7 +427,7 @@ namespace slskd return (share, share.Split(new[] { '/', '\\' }).Last(), share); } - var digestedShared = Shared + var digestedShared = Directories .Select(share => Digest(share.TrimEnd('/', '\\'))) .ToHashSet(); @@ -415,6 +454,21 @@ namespace slskd return results; } + + private IEnumerable ValidateFilters() + { + var results = new List(); + + foreach (var filter in Filters) + { + if (!filter.IsValidRegex()) + { + results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); + } + } + + return results; + } } /// @@ -644,14 +698,6 @@ namespace slskd /// public class FiltersOptions : IValidatableObject { - /// - /// Gets the list of shared file filters. - /// - [Argument(default, "share-filter")] - [EnvironmentVariable("SHARE_FILTER")] - [Description("regular expressions to filter files from shares")] - public string[] Share { get; init; } = Array.Empty(); - /// /// Gets search filter options. /// -- cgit v1.2.3 From dab9af45aa0d06b882c661fc3cddb6af6f61545e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:37:33 -0500 Subject: add cache type --- config/slskd.example.yml | 3 ++- src/slskd/Core/Options.cs | 47 ++++++++++++++++++++--------------------------- 2 files changed, 22 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 46033bff..1f628077 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -19,7 +19,8 @@ # - \.ini$ # - Thumbs.db$ # - \.DS_Store$ -# cache_storage: memory +# cache: +# storage_mode: Memory # rooms: # - ~ # global: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 327036aa..2d561e29 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -200,7 +200,6 @@ namespace slskd /// Gets share options. /// [Validate] - [RequiresRestart] public SharesOptions Shares { get; init; } = new SharesOptions(); /// @@ -376,12 +375,26 @@ namespace slskd public string[] Filters { get; init; } = Array.Empty(); /// - /// Gets the type of storage to use for the share cache. + /// Share caching options. /// - [Argument(default, "share-cache-storage")] - [EnvironmentVariable("SHARE_CACHE_STORAGE")] - [Description("the type of storage to use for the cache")] - public StorageType CacheStorage { get; init; } = StorageType.Memory; + [Validate] + public ShareCacheOptions Cache { get; init; } = new ShareCacheOptions(); + + /// + /// Share caching options. + /// + public class ShareCacheOptions + { + /// + /// Gets the type of storage to use for the share cache. + /// + [Argument(default, "share-cache-storage-mode")] + [EnvironmentVariable("SHARE_CACHE_STORAGE_MODE")] + [Description("the type of storage to use for the cache")] + [Enum(typeof(StorageMode))] + [RequiresRestart] + public string StorageMode { get; init; } = slskd.StorageMode.Memory.ToString().ToLowerInvariant(); + } /// /// Extended validation. @@ -696,7 +709,7 @@ namespace slskd /// /// Filter options. /// - public class FiltersOptions : IValidatableObject + public class FiltersOptions { /// /// Gets search filter options. @@ -704,26 +717,6 @@ namespace slskd [Validate] public SearchOptions Search { get; init; } = new SearchOptions(); - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - foreach (var filter in Share) - { - if (!filter.IsValidRegex()) - { - results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); - } - } - - return results; - } - /// /// Search filter options. /// -- cgit v1.2.3 From 523ece5b03e4eb5ff298da7257239a728ea1aab4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:37:50 -0500 Subject: add ToEnum --- src/slskd/Common/CommonExtensions.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 6f39d17f..9b6a3c6c 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -359,6 +359,17 @@ namespace slskd obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); } + /// + /// Casts the string to . + /// + /// The Enum type to which to cast. + /// The string to cast. + /// The cast enum + public static T ToEnum(this string str) + { + return (T)Enum.Parse(typeof(T), str, ignoreCase: true); + } + /// /// Deserializes this string from json to an object of type . /// -- cgit v1.2.3 From 79649ecdc4e49a01de85d099f449662cb78f23df Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:38:12 -0500 Subject: StorageType -> StorageMode --- src/slskd/Core/Types/StorageMode.cs | 35 +++++++++++++++++++++++++++++++++++ src/slskd/Core/Types/StorageType.cs | 35 ----------------------------------- 2 files changed, 35 insertions(+), 35 deletions(-) create mode 100644 src/slskd/Core/Types/StorageMode.cs delete mode 100644 src/slskd/Core/Types/StorageType.cs (limited to 'src') diff --git a/src/slskd/Core/Types/StorageMode.cs b/src/slskd/Core/Types/StorageMode.cs new file mode 100644 index 00000000..aced3050 --- /dev/null +++ b/src/slskd/Core/Types/StorageMode.cs @@ -0,0 +1,35 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Storage mode. + /// + public enum StorageMode + { + /// + /// Stored in memory. + /// + Memory = 0, + + /// + /// Stored on disk. + /// + Disk = 1, + } +} diff --git a/src/slskd/Core/Types/StorageType.cs b/src/slskd/Core/Types/StorageType.cs deleted file mode 100644 index 63b19899..00000000 --- a/src/slskd/Core/Types/StorageType.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - /// - /// Storage type. - /// - public enum StorageType - { - /// - /// Stored in memory. - /// - Memory = 0, - - /// - /// Stored on disk. - /// - Disk = 1, - } -} -- cgit v1.2.3 From bc362491446e4bfa94b7891ac0694d4f9b35df16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:38:37 -0500 Subject: add share backup, remove Filenames --- src/slskd/Core/ConnectionStrings.cs | 1 + src/slskd/Core/Filenames.cs | 30 ------------------------------ 2 files changed, 1 insertion(+), 30 deletions(-) delete mode 100644 src/slskd/Core/Filenames.cs (limited to 'src') diff --git a/src/slskd/Core/ConnectionStrings.cs b/src/slskd/Core/ConnectionStrings.cs index e5bd4f05..6afab93f 100644 --- a/src/slskd/Core/ConnectionStrings.cs +++ b/src/slskd/Core/ConnectionStrings.cs @@ -24,6 +24,7 @@ namespace slskd { public string Transfers { get; init; } public string Shares { get; init; } + public string SharesBackup { get; init; } public string Search { get; init; } } } diff --git a/src/slskd/Core/Filenames.cs b/src/slskd/Core/Filenames.cs deleted file mode 100644 index 0fc55fc5..00000000 --- a/src/slskd/Core/Filenames.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - /// - /// Application files. - /// - public static class Filenames - { - public static readonly string TransfersDb = "transfers.db"; - public static readonly string SharesDb = "shares.db"; - public static readonly string SearchDb = "search.db"; - public static readonly string BrowseCache = "browse.cache"; - } -} -- cgit v1.2.3 From cad5239f816bc3f116a6ad8d3dea9e1e3f831a65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:38:57 -0500 Subject: simplify enum handling --- src/slskd/Integrations/FTP/FTPClientFactory.cs | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index 2e41ab03..70cfbc03 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -47,24 +47,10 @@ namespace slskd.Integrations.FTP public FtpClient CreateFtpClient() { var client = new FtpClient(FtpOptions.Address, FtpOptions.Port, FtpOptions.Username, FtpOptions.Password); - client.EncryptionMode = ParseFtpEncryptionMode(FtpOptions.EncryptionMode); + client.EncryptionMode = FtpOptions.EncryptionMode.ToEnum(); client.ValidateAnyCertificate = FtpOptions.IgnoreCertificateErrors; return client; } - - private FtpEncryptionMode ParseFtpEncryptionMode(string encryptionMode) - { - try - { - return (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), encryptionMode, ignoreCase: true); - } - catch (Exception ex) - { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this - // throws there's a bug somewhere. - throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); - } - } } } \ No newline at end of file -- cgit v1.2.3 From 7c4922e890bf0267ceb55ff568d03b0485edbd4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:39:44 -0500 Subject: backup and restore share cache from disk --- src/slskd/Shares/ShareService.cs | 8 +-- src/slskd/Shares/SharedFileCache.cs | 113 +++++++++++++++++++++++++----------- 2 files changed, 84 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 316e6b2f..dd808360 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -41,7 +41,7 @@ namespace slskd.Shares IOptionsMonitor optionsMonitor, ISharedFileCache sharedFileCache = null) { - Cache = sharedFileCache ?? new SharedFileCache(); + Cache = sharedFileCache ?? new SharedFileCache(storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum()); Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; @@ -180,21 +180,21 @@ namespace slskd.Shares try { - var optionsHash = Compute.Sha1Hash(string.Join(';', options.Directories.Shared)); + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); if (optionsHash == LastOptionsHash) { return; } - var shares = options.Directories.Shared + var shares = options.Shares.Directories .Select(share => share.TrimEnd('/', '\\')) .ToHashSet() // remove duplicates .Select(share => new Share(share)) // convert to Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); - var regexes = options.Filters.Share + var regexes = options.Shares.Filters .Select(filter => new Regex(filter, RegexOptions.Compiled)) .ToList(); diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index c7c1d30a..2c14024e 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -22,6 +22,7 @@ namespace slskd.Shares using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.Data; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; @@ -39,9 +40,11 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// + /// /// - public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(StorageMode storageMode, ISoulseekFileFactory soulseekFileFactory = null) { + StorageMode = storageMode; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -50,6 +53,7 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor => State; + private StorageMode StorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } @@ -144,19 +148,24 @@ namespace slskd.Shares try { + // drop and recreate the tables to clear them + // note: leave the backup in place. this will leave the app in a better position if the app stops during the scan. + CreateTables(); + State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0, + Directories = 0, + Files = 0, + ExcludedDirectories = 0, }); Log.Debug("Starting shared file scan"); await Task.Yield(); - ResetCache(); - var sw = new Stopwatch(); var swSnapshot = 0L; sw.Start(); @@ -301,6 +310,10 @@ namespace slskd.Shares Log.Debug("Inserted {Files} records in {Elapsed}ms", cached, sw.ElapsedMilliseconds - swSnapshot); + Log.Debug("Backing up shared file cache database..."); + Backup(); + Log.Debug("Shared file cache database backup complete"); + State.SetValue(state => state with { Filling = false, @@ -437,24 +450,48 @@ namespace slskd.Shares { try { - if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions")) + // see if we need to 'restore' the database from disk + if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !DatabaseExists(Program.ConnectionStrings.Shares))) { - // todo: check columns + Log.Debug($"Share cache {(StorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup..."); - State.SetValue(state => state with + // the backup is missing; we can't do anything but recreate it from scratch + if (!DatabaseExists(Program.ConnectionStrings.SharesBackup)) { - Filling = false, - Faulted = false, - Filled = true, - FillProgress = 1, - Directories = CountDirectories(), - Files = CountFiles(), - }); + Log.Debug("Share cache backup is missing; unable to restore"); + return false; + } - return true; + Log.Debug("Share cache backup located. Attempting to restore..."); + + using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup); + using var conn = GetConnection(); + backupConn.BackupDatabase(conn); + + Log.Debug("Share cache successfully restored from backup"); } - return false; + Log.Debug("Validating share cache database"); + + if (!TableExists("directories") || !TableExists("filenames") || !TableExists("files")) + { + Log.Warning("One or more tables are missing from the share cache database"); + return false; + } + + // todo: check columns + + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = CountDirectories(), + Files = CountFiles(), + }); + + return true; } catch (Exception ex) { @@ -463,6 +500,32 @@ namespace slskd.Shares } } + private bool DatabaseExists(string connectionString) + { + try + { + using var conn = GetConnection(connectionString); + + if (conn.State == ConnectionState.Open) + { + return true; + } + + return false; + } + catch + { + return false; + } + } + + private void Backup() + { + using var sourceConn = GetConnection(); + using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup); + sourceConn.BackupDatabase(backupConn); + } + private int CountDirectories() { using var conn = GetConnection(); @@ -494,9 +557,9 @@ namespace slskd.Shares "extension TEXT, attributeJson TEXT NOT NULL);"); } - private SqliteConnection GetConnection() + private SqliteConnection GetConnection(string connectionString = null) { - var conn = new SqliteConnection(Program.ConnectionStrings.Shares); + var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares); conn.Open(); return conn; } @@ -595,22 +658,6 @@ namespace slskd.Shares } } - private void ResetCache() - { - CreateTables(); - - try - { - System.IO.File.Delete(Path.Combine(Program.DataDirectory, Filenames.BrowseCache)); - } - catch (FileNotFoundException) - { - // noop - } - - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - private bool TableExists(string table) { using var conn = GetConnection(); -- cgit v1.2.3 From 8f12409567360bb08a9ce9a5d104786c27705a9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:40:03 -0500 Subject: simplify enum handling --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 54b9a6c3..2c7e3eac 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -402,7 +402,7 @@ namespace slskd.Transfers Priority = options.Groups.Default.Upload.Priority, Slots = Math.Min(options.Groups.Default.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup), - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true), + Strategy = options.Groups.Default.Upload.Strategy.ToEnum(), }, new UploadGroup() { @@ -410,7 +410,7 @@ namespace slskd.Transfers Priority = options.Groups.Leechers.Upload.Priority, Slots = Math.Min(options.Groups.Leechers.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.LeecherGroup), - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Leechers.Upload.Strategy, true), + Strategy = options.Groups.Leechers.Upload.Strategy.ToEnum(), }, }; @@ -421,7 +421,7 @@ namespace slskd.Transfers Priority = kvp.Value.Upload.Priority, Slots = Math.Min(kvp.Value.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(kvp.Key), - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), + Strategy = kvp.Value.Upload.Strategy.ToEnum(), })); Groups = groups.ToDictionary(g => g.Name); -- cgit v1.2.3 From e624d3bdc8a4eff1f3b97294ced81647b80983e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:40:30 -0500 Subject: hard code filenames, delete browse cache on scan start --- src/slskd/Application.cs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f3feec23..288ba07b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -428,7 +428,7 @@ namespace slskd BrowseResponse response = default; - var cacheFilename = Path.Combine(Program.DataDirectory, Filenames.BrowseCache); + var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache"); var cacheFileInfo = new FileInfo(cacheFilename); if (!cacheFileInfo.Exists) @@ -780,15 +780,15 @@ namespace slskd pendingReconnect |= requiresReconnect; } - if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() - || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) + if (PreviousOptions.Shares.Directories.Except(newOptions.Shares.Directories).Any() + || newOptions.Shares.Directories.Except(PreviousOptions.Shares.Directories).Any()) { State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect."); } - if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any() - || newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any()) + if (PreviousOptions.Shares.Filters.Except(newOptions.Shares.Filters).Any() + || newOptions.Shares.Filters.Except(PreviousOptions.Shares.Filters).Any()) { State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect."); @@ -989,7 +989,17 @@ namespace slskd SharesRefreshStarted = DateTime.UtcNow; State.SetValue(s => s with { Shares = current }); - Log.Information("Scanning shares"); + Log.Information("Share scan started"); + + try + { + System.IO.File.Delete(Path.Combine(Program.DataDirectory, "browse.cache")); + Log.Information("Cleared browse response cache"); + } + catch + { + // noop + } } else if (previous.Scanning && !current.Scanning) { @@ -1022,7 +1032,7 @@ namespace slskd { // the share transitioned into ready without completing a scan; it was loaded from disk State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); - Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files}", current.Directories, current.Files); + Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); _ = CacheBrowseResponse(); } else @@ -1045,7 +1055,7 @@ namespace slskd var response = new BrowseResponse(directories); Log.Information("Warming browse response cache..."); - System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, Filenames.BrowseCache), response.ToByteArray()); + System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, "browse.cache"), response.ToByteArray()); Log.Information("Browse response cached successfully"); } -- cgit v1.2.3 From 1cc28437711fdca0643f01191f84325e3b2359cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:41:06 -0500 Subject: hard code filenames, make SQLite init more prominent --- src/slskd/Program.cs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f4e59456..5a5d9ce9 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -252,17 +252,31 @@ namespace slskd return; } + InitSQLiteOrFailFast(); + // the application isn't being run in command mode. derive the application directory value // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; - DataDirectory = Path.Combine(AppDirectory, "data"); + // configure connection strings and configure SQLite + string shareDbDataSource = default; + + if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) + { + shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); + } + else + { + shareDbDataSource = "file:shares?mode=memory"; + } + ConnectionStrings = new() { - Search = $"Data Source={Path.Combine(DataDirectory, Filenames.SearchDb)};Cache=shared;Pooling=True;", - Transfers = $"Data Source={Path.Combine(DataDirectory, Filenames.TransfersDb)};Cache=shared;Pooling=True;", - Shares = $"Data Source={Path.Combine(DataDirectory, Filenames.SharesDb)};Cache=shared", + Search = $"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;", + Transfers = $"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;", + Shares = $"Data Source={shareDbDataSource};Cache=shared", + SharesBackup = $"Data Source={Path.Combine(DataDirectory, "shares.db.bak")};", }; DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); @@ -465,8 +479,6 @@ namespace slskd services.AddSingleton(); - ConfigureSQLite(); - services.AddDbContext(ConnectionStrings.Search); services.AddDbContext(ConnectionStrings.Transfers); @@ -492,7 +504,7 @@ namespace slskd return services; } - private static void ConfigureSQLite() + private static void InitSQLiteOrFailFast() { // initialize // avoids: System.Exception: You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init(). -- cgit v1.2.3 From 17a3f6c29799b2ee8fcb38a45a4b178e59ffa83a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Sep 2022 12:01:08 -0500 Subject: fully validate schemas --- src/slskd/Shares/SharedFileCache.cs | 81 +++++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 2c14024e..e865ff8d 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -450,13 +450,13 @@ namespace slskd.Shares { try { - // see if we need to 'restore' the database from disk - if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !DatabaseExists(Program.ConnectionStrings.Shares))) + // see if we need to 'restore' the database from disk, and do so + if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !ValidateTables(Program.ConnectionStrings.Shares))) { Log.Debug($"Share cache {(StorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup..."); // the backup is missing; we can't do anything but recreate it from scratch - if (!DatabaseExists(Program.ConnectionStrings.SharesBackup)) + if (!ValidateTables(Program.ConnectionStrings.SharesBackup)) { Log.Debug("Share cache backup is missing; unable to restore"); return false; @@ -471,16 +471,11 @@ namespace slskd.Shares Log.Debug("Share cache successfully restored from backup"); } - Log.Debug("Validating share cache database"); - - if (!TableExists("directories") || !TableExists("filenames") || !TableExists("files")) - { - Log.Warning("One or more tables are missing from the share cache database"); - return false; - } - - // todo: check columns - + // one of several thigns happened above before we got here: + // the storage mode is memory, and we loaded the in-memory db from a valid backup + // the storage mode is disk, and the file is there and valid + // the storage mode is disk but either missing or invalid, and we restored from a valid backup + // at this point there is a valid (existing, schema matching expected schema) database at the primary connection string State.SetValue(state => state with { Filling = false, @@ -500,21 +495,55 @@ namespace slskd.Shares } } - private bool DatabaseExists(string connectionString) + private bool ValidateTables(string connectionString) { + var schema = new Dictionary() + { + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY)" }, + { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL)" }, + }; + try { + Log.Debug("Validating shares database with connection string {String}", connectionString); + using var conn = GetConnection(connectionString); + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table' AND name IN ('directories', 'filenames', 'files');", conn); + + var reader = cmd.ExecuteReader(); + var rows = 0; + + while (reader.Read()) + { + var table = reader.GetString(0); + var expectedSql = reader.GetString(1); + + if (schema.TryGetValue(table, out var actualSql)) + { + if (actualSql != expectedSql) + { + throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}"); + } + else + { + Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); + } + } + + rows++; + } - if (conn.State == ConnectionState.Open) + if (rows != schema.Count) { - return true; + throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); } - return false; + return true; } - catch + catch (Exception ex) { + Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); return false; } } @@ -657,21 +686,5 @@ namespace slskd.Shares cmd?.Dispose(); } } - - private bool TableExists(string table) - { - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT name from sqlite_master WHERE type = 'table' AND name = @table;", conn); - cmd.Parameters.AddWithValue("table", table); - var reader = cmd.ExecuteReader(); - - if (reader.Read()) - { - var fetchedTable = reader.GetString(0); - return table == fetchedTable; - } - - return false; - } } } \ No newline at end of file -- cgit v1.2.3 From 2a0db7e44a0b25d2a505ae8472de214c6c68b5d2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Sep 2022 12:02:17 -0500 Subject: move connection string setup --- src/slskd/Program.cs | 49 +++++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5a5d9ce9..fe2bb626 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -252,33 +252,11 @@ namespace slskd return; } - InitSQLiteOrFailFast(); - // the application isn't being run in command mode. derive the application directory value // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; DataDirectory = Path.Combine(AppDirectory, "data"); - // configure connection strings and configure SQLite - string shareDbDataSource = default; - - if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) - { - shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); - } - else - { - shareDbDataSource = "file:shares?mode=memory"; - } - - ConnectionStrings = new() - { - Search = $"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;", - Transfers = $"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;", - Shares = $"Data Source={shareDbDataSource};Cache=shared", - SharesBackup = $"Data Source={Path.Combine(DataDirectory, "shares.db.bak")};", - }; - DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads"); DefaultIncompleteDirectory = Path.Combine(AppDirectory, "incomplete"); @@ -355,11 +333,38 @@ namespace slskd Log.Information("Process ID: {ProcessId}", ProcessId); Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); + // SQLite must have specific capabilities to function properly. this shouldn't be a concern for shrinkwrapped + // binaries or in Docker, but if someone builds from source weird things can happen. + InitSQLiteOrFailFast(); + Log.Information("Using application directory {AppDirectory}", AppDirectory); Log.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); + Log.Information("Storing application data in {DataDirectory}", DataDirectory); RecreateConfigurationFileIfMissing(ConfigurationFile); + // configure connection strings and configure SQLite + string shareDbDataSource = default; + + if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) + { + Log.Information("Using on-disk shared file database"); + shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); + } + else + { + Log.Information("Using in-memory shared file database"); + shareDbDataSource = "file:shares?mode=memory"; + } + + ConnectionStrings = new() + { + Search = $"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;", + Transfers = $"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;", + Shares = $"Data Source={shareDbDataSource};Cache=shared", + SharesBackup = $"Data Source={Path.Combine(DataDirectory, "shares.db.bak")};", + }; + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); -- cgit v1.2.3 From a596dfe252ef53e41b91ec6773aec93307c41f1e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Sep 2022 18:09:58 -0500 Subject: tweak logging for consistency --- src/slskd/Application.cs | 2 +- src/slskd/Program.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 288ba07b..cab2b649 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1032,7 +1032,7 @@ namespace slskd { // the share transitioned into ready without completing a scan; it was loaded from disk State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); - Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); + Log.Information("Share cache loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); _ = CacheBrowseResponse(); } else diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index fe2bb626..e828f242 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -348,12 +348,12 @@ namespace slskd if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) { - Log.Information("Using on-disk shared file database"); + Log.Information("Using on-disk shared file cache"); shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); } else { - Log.Information("Using in-memory shared file database"); + Log.Information("Using in-memory shared file cache"); shareDbDataSource = "file:shares?mode=memory"; } -- cgit v1.2.3