aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-10-09 18:02:11 -0500
committerJP Dillingham <jp@dillingham.me>2022-10-09 18:02:11 -0500
commit3345653b6b5293215b5eda2516e9c96bced83ab2 (patch)
tree1f10e872cabb18a0f9b050210831782d13a9b188 /src
parent1c81c5244a892da6b38600c2969debb323ff2c24 (diff)
downloadslskd-3345653b6b5293215b5eda2516e9c96bced83ab2.tar.gz
implement more explicit schema checks, add scans table
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Exceptions/ShareInitializationException.cs72
-rw-r--r--src/slskd/Shares/ShareRepository.cs61
-rw-r--r--src/slskd/Shares/ShareScanner.cs16
-rw-r--r--src/slskd/Shares/ShareService.cs59
4 files changed, 181 insertions, 27 deletions
diff --git a/src/slskd/Common/Exceptions/ShareInitializationException.cs b/src/slskd/Common/Exceptions/ShareInitializationException.cs
new file mode 100644
index 00000000..31e45b91
--- /dev/null
+++ b/src/slskd/Common/Exceptions/ShareInitializationException.cs
@@ -0,0 +1,72 @@
+// <copyright file="ShareInitializationException.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.Serialization;
+
+ /// <summary>
+ /// Represents an error that occurs when multiple share scans are attempted concurrently.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ [Serializable]
+ public class ShareInitializationException : SlskdException
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareInitializationException"/> class.
+ /// </summary>
+ public ShareInitializationException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareInitializationException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public ShareInitializationException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareInitializationException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public ShareInitializationException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareInitializationException"/> class with serialized data.
+ /// </summary>
+ /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
+ protected ShareInitializationException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs
index b8ecd2be..7b723ac6 100644
--- a/src/slskd/Shares/ShareRepository.cs
+++ b/src/slskd/Shares/ShareRepository.cs
@@ -23,7 +23,6 @@ namespace slskd.Shares
using System.Linq;
using Microsoft.Data.Sqlite;
using Serilog;
- using slskd.Transfers.Uploads;
using Soulseek;
/// <summary>
@@ -86,6 +85,13 @@ namespace slskd.Shares
void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp);
/// <summary>
+ /// Inserts a scan record at the specified <paramref name="timestamp"/>.
+ /// </summary>
+ /// <param name="timestamp">The timestamp associated with the scan.</param>
+ /// <param name="options">The options snapshot at the start of the scan.</param>
+ void InsertScan(long timestamp, Options.SharesOptions options);
+
+ /// <summary>
/// Lists all directories.
/// </summary>
/// <param name="parentDirectory">The optional directory prefix used for listing subdirectories.</param>
@@ -126,6 +132,13 @@ namespace slskd.Shares
/// <param name="query">The search query.</param>
/// <returns>The list of matching files.</returns>
IEnumerable<Soulseek.File> Search(SearchQuery query);
+
+ /// <summary>
+ /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>.
+ /// </summary>
+ /// <param name="timestamp">The timestamp associated with the scan.</param>
+ /// <param name="end">The timestamp at the conclusion of the scan.</param>
+ void UpdateScan(long timestamp, long end);
}
/// <summary>
@@ -160,10 +173,18 @@ namespace slskd.Shares
var log = Serilog.Log.ForContext<ShareRepository>();
+ // to update this schema map, run the following query against a valid, up-to-date database and paste the output below:
+ // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table'
var schema = new Dictionary<string, string>()
{
+ { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" },
{ "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" },
{ "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" },
+ { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" },
+ { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" },
+ { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" },
+ { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" },
+ { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" },
{ "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, timestamp INTEGER NOT NULL)" },
};
@@ -174,7 +195,7 @@ namespace slskd.Shares
using var conn = new SqliteConnection(connectionString);
conn.Open();
- using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table' AND name IN ('directories', 'filenames', 'files');", conn);
+ using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn);
var reader = cmd.ExecuteReader();
var rows = 0;
@@ -306,9 +327,11 @@ namespace slskd.Shares
if (discardExisting)
{
- conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;");
+ conn.ExecuteNonQuery("DROP TABLE IF EXISTS scans; DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;");
}
+ conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL);");
+
conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL);");
conn.ExecuteNonQuery("CREATE VIRTUAL TABLE IF NOT EXISTS filenames USING fts5(maskedFilename);");
@@ -392,6 +415,22 @@ namespace slskd.Shares
}
/// <summary>
+ /// Inserts a scan record at the specified <paramref name="timestamp"/>.
+ /// </summary>
+ /// <param name="timestamp">The timestamp associated with the scan.</param>
+ /// <param name="options">The options snapshot at the start of the scan.</param>
+ public void InsertScan(long timestamp, Options.SharesOptions options)
+ {
+ using var conn = GetConnection();
+
+ conn.ExecuteNonQuery("INSERT INTO scans (timestamp, options) VALUES(@timestamp, @options)", cmd =>
+ {
+ cmd.Parameters.AddWithValue("timestamp", timestamp);
+ cmd.Parameters.AddWithValue("options", options.ToJson());
+ });
+ }
+
+ /// <summary>
/// Lists all directories.
/// </summary>
/// <param name="parentDirectory">The optional directory prefix used for listing subdirectories.</param>
@@ -583,6 +622,22 @@ namespace slskd.Shares
}
}
+ /// <summary>
+ /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>.
+ /// </summary>
+ /// <param name="timestamp">The timestamp associated with the scan.</param>
+ /// <param name="end">The timestamp at the conclusion of the scan.</param>
+ public void UpdateScan(long timestamp, long end)
+ {
+ using var conn = GetConnection();
+
+ conn.ExecuteNonQuery("UPDATE scans SET end = @end WHERE timestamp = @timestamp;", cmd =>
+ {
+ cmd.Parameters.AddWithValue("end", end);
+ cmd.Parameters.AddWithValue("timestamp", timestamp);
+ });
+ }
+
private SqliteConnection GetConnection(string connectionString = null)
{
connectionString ??= ConnectionString;
diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs
index 369e4981..74f0d131 100644
--- a/src/slskd/Shares/ShareScanner.cs
+++ b/src/slskd/Shares/ShareScanner.cs
@@ -44,9 +44,9 @@ namespace slskd.Shares
/// Scans the configured shares and fills the cache.
/// </summary>
/// <param name="shares">The list of shares from which to fill the cache.</param>
- /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param>
+ /// <param name="options">The current options snapshot.</param>
/// <returns>The operation context.</returns>
- Task ScanAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters);
+ Task ScanAsync(IEnumerable<Share> shares, Options.SharesOptions options);
/// <summary>
/// Cancels the currently running fill operation, if one is running.
@@ -90,9 +90,9 @@ namespace slskd.Shares
/// Scans the configured shares and fills the cache.
/// </summary>
/// <param name="shares">The list of shares from which to fill the cache.</param>
- /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param>
+ /// <param name="options">The current options snapshot.</param>
/// <returns>The operation context.</returns>
- public async Task ScanAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters)
+ public async Task ScanAsync(IEnumerable<Share> shares, Options.SharesOptions options)
{
// obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running.
if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0))
@@ -130,10 +130,16 @@ namespace slskd.Shares
Log.Information("Shared file cache re-created and ready for scan.");
}
+ var filters = options.Filters
+ .Select(filter => new Regex(filter, RegexOptions.Compiled))
+ .ToList();
+
Log.Information("Starting shared file scan");
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+ Repository.InsertScan(timestamp, options);
+
var sw = new Stopwatch();
var swSnapshot = 0L;
sw.Start();
@@ -316,6 +322,8 @@ namespace slskd.Shares
State.SetValue(state => state with { Cancelled = true });
}
+ Repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
+
Log.Debug("Backing up shared file cache database...");
Repository.BackupTo(Program.ConnectionStrings.SharesBackup);
Log.Debug("Shared file cache database backup complete");
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index 09085b72..a9c8c629 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -94,7 +94,6 @@ namespace slskd.Shares
private List<Share> SharesList { get; set; } = new List<Share>();
private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
- private List<Regex> FilterRegexes { get; set; } = new List<Regex>();
private StorageMode CacheStorageMode { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<ShareService>();
@@ -218,7 +217,7 @@ namespace slskd.Shares
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
public Task ScanAsync()
{
- return Scanner.ScanAsync(Shares, FilterRegexes);
+ return Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares);
}
/// <summary>
@@ -251,6 +250,8 @@ namespace slskd.Shares
/// <returns>The operation context.</returns>
public async Task InitializeAsync(bool forceRescan = false)
{
+ Log.Information("Initializing shares");
+
try
{
if (forceRescan)
@@ -258,31 +259,54 @@ namespace slskd.Shares
Log.Warning("Performing a forced re-scan of shares");
await ScanAsync();
}
- else if (CacheStorageMode == StorageMode.Memory || (CacheStorageMode == StorageMode.Disk && !ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)))
+ else if (CacheStorageMode == StorageMode.Memory)
{
- Log.Debug($"Share cache {(CacheStorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup...");
+ Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup...");
- // the backup is missing; we can't do anything but recreate it from scratch
- if (!ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup))
+ if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup))
{
- Log.Warning("Share cache couldn't be loaded from backup");
- await InitializeAsync(forceRescan: true);
- }
- else
- {
- Log.Debug("Share cache backup located. Attempting to restore...");
+ Log.Information("Share cache backup validated. Attempting to restore...");
Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup);
Log.Information("Share cache successfully restored from backup");
}
+ else
+ {
+ Log.Warning("Share cache backup is missing, corrupt, or is out of date");
+ throw new ShareInitializationException("Share cache backup is missing, corrupt, or is out of date");
+ }
}
- else
+ else if (CacheStorageMode == StorageMode.Disk)
{
- // the cache mode is disk and the existing db is valid. nothing to do.
+ Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate...");
+
+ if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares))
+ {
+ // no-op
+ }
+ else
+ {
+ Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup...");
+
+ if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup))
+ {
+ Log.Information("Share cache backup validated. Attempting to restore...");
+
+ Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup);
+
+ Log.Information("Share cache successfully restored from backup");
+ }
+ else
+ {
+ Log.Warning("Share cache and backup are both missing, corrupt, or is out of date");
+ throw new ShareInitializationException("Share cache and backup are both missing, corrupt, or is out of date");
+ }
+ }
}
// one of several thigns happened above before we got here:
+ // this method was called with forceRescan = true
// 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
@@ -335,13 +359,8 @@ namespace slskd.Shares
.OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
.ToList();
- var regexes = options.Shares.Filters
- .Select(filter => new Regex(filter, RegexOptions.Compiled))
- .ToList();
-
SharesList = shares;
- FilterRegexes = regexes;
-
+
State.SetValue(state => state with { ScanPending = true });
LastOptionsHash = optionsHash;