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/SharedFileCache.cs | 113 +++++++++++++++++++++++++----------- 1 file changed, 80 insertions(+), 33 deletions(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') 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 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/slskd/Shares/SharedFileCache.cs') 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