From 534d8824c4a3f1aae0448a17f734b57ea395c59f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Apr 2025 19:01:17 -0500 Subject: wip --- src/slskd/Common/Waiter.cs | 2 +- src/slskd/Core/Data/Migrations/Migration.cs | 82 ++++++++ .../Migrations/TransferStateMigration_04012025.cs | 155 ++++++++++++++ src/slskd/Core/Data/Migrator.cs | 204 +++++++++++++++++++ .../Migrations/TransferStateMigration_04012025.cs | 151 -------------- src/slskd/Core/Migrator.cs | 222 --------------------- src/slskd/Program.cs | 2 + 7 files changed, 444 insertions(+), 374 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Migration.cs create mode 100644 src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs create mode 100644 src/slskd/Core/Data/Migrator.cs delete mode 100644 src/slskd/Core/Migrations/TransferStateMigration_04012025.cs delete mode 100644 src/slskd/Core/Migrator.cs (limited to 'src') diff --git a/src/slskd/Common/Waiter.cs b/src/slskd/Common/Waiter.cs index f8b3d305..d32f23b4 100644 --- a/src/slskd/Common/Waiter.cs +++ b/src/slskd/Common/Waiter.cs @@ -450,7 +450,7 @@ namespace slskd if (disposing) { CancellationTokenRegistration.Dispose(); - TimeoutTokenSource.Dispose(); + TimeoutTokenSource?.Dispose(); TimeoutTokenRegistration.Dispose(); } diff --git a/src/slskd/Core/Data/Migrations/Migration.cs b/src/slskd/Core/Data/Migrations/Migration.cs new file mode 100644 index 00000000..02f87a9c --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Migration.cs @@ -0,0 +1,82 @@ +// +// 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.Migrations; + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Data.Sqlite; + +public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); + +public abstract class Migration +{ + public Migration(string databaseName) + { + DatabaseName = databaseName; + } + + public string DatabaseName { get; } + public string DatabaseFileName => Path.Combine(Program.DataDirectory, DatabaseName); + public string ConnectionString => $"Data Source={DatabaseFileName}.db"; + + public abstract void Apply(); + + protected Dictionary> GetDatabaseSchema() + { + try + { + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + var dict = new Dictionary>(); + + using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); + using var tableReader = tableCommand.ExecuteReader(); + + while (tableReader.Read()) + { + var table = tableReader.GetString(0); + + var columns = new List(); + + using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); + using var cr = columnCommand.ExecuteReader(); + + while (cr.Read()) + { + columns.Add(new ColumnInfo( + Cid: cr.GetInt64(cr.GetOrdinal("cid")), + Name: cr.GetString(cr.GetOrdinal("name")), + Type: cr.GetString(cr.GetOrdinal("type")), + NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, + DefaultValue: cr["dflt_value"], + PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); + } + + dict[table] = columns; + } + + return dict; + } + catch (Exception ex) + { + throw new SlskdException($"Failed to retrieve schema information for database '{DatabaseName}'. The database might be corrupt or in use by another application; if the problem persists the file ({DatabaseFileName}) may need to be deleted", ex); + } + } +} \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs new file mode 100644 index 00000000..37171a77 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -0,0 +1,155 @@ +// +// 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.Migrations; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to: +/// +/// * Add a new StatusDescription (TEXT) column +/// * Copy the current (string) contents of the Status column to StatusDescription +/// * Change the type of the Status column to INTEGER +/// * Set the contents of the Status column to the numeric representation of the existing Status +/// +/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored +/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class TransferStateMigration_04012025 : Migration +{ + public TransferStateMigration_04012025(string databasName) + : base(databasName) + { + } + + private string DbName => "transfers"; + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public override void Apply() + { + // first, check the existing database to see if the StatusDescription column exists + // if it does, the migration has already been applied + var schema = GetDatabaseSchema(); + var txfers = schema["Transfers"]; + + if (txfers.Any(c => c.Name == "StatusDescription")) + { + Log.Information("Migration {Name} has already been applied", nameof(TransferStateMigration_04012025)); + return; + } + + AddStateDescriptionColumn(Path.Combine(Program.DataDirectory, "transfers.db")); + } + + static void AddStateDescriptionColumn(string dbPath) + { + if (!File.Exists(dbPath)) + { + Console.WriteLine("Database file not found."); + return; + } + + string connectionString = $"Data Source={dbPath};"; + + using (var connection = new SqliteConnection(connectionString)) + { + connection.Open(); + + using (var transaction = connection.BeginTransaction()) + { + try + { + // Rename old table + using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) + { + renameCommand.ExecuteNonQuery(); + } + + // Create new table with StateDescription after State + string createNewTableSQL = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- New column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + );"; + + using (var createCommand = new SqliteCommand(createNewTableSQL, connection)) + { + createCommand.ExecuteNonQuery(); + } + + // Copy data into the new table + string copyDataSQL = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using (var copyCommand = new SqliteCommand(copyDataSQL, connection)) + { + copyCommand.ExecuteNonQuery(); + } + + // Drop the old table + using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) + { + dropCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + Console.WriteLine("Column 'StateDescription' added successfully."); + } + catch (Exception ex) + { + transaction.Rollback(); + Console.WriteLine($"Error: {ex.Message}"); + } + } + + connection.Close(); + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs new file mode 100644 index 00000000..f3543ca9 --- /dev/null +++ b/src/slskd/Core/Data/Migrator.cs @@ -0,0 +1,204 @@ +// +// 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; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Serilog; +using slskd.Migrations; + +/// +/// Applies database migrations. +/// +public class Migrator +{ + /// + /// Initializes a new instance of the class. + /// + /// A list of known databases. + public Migrator(params string[] databases) + { + Databases = databases; + } + + private string HistoryFileName { get; } = Path.Combine(Program.DataDirectory, "migration.history"); + private IEnumerable Databases { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// A map of all migrations, to be applied in the order they are specified (descending). + /// + private Dictionary Migrations { get; } = new() + { + { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025("transfers") }, + }; + + /// + /// Applies database migrations. + /// + /// Apply all migrations, regardless of whether there's evidence they have been applied already. + public void Migrate(bool force = false) + { + Dictionary history = []; + + Log.Information("Checking for outstanding database migrations..."); + + // load migration history from the history file in the root of the data directory. this file contains a key/value + // pair for each migration that's been applied, along with the migration date. + // if force=true, we don't care about the history and there's no reason to look at it. + if (!force) + { + try + { + if (File.Exists(HistoryFileName)) + { + var txt = File.ReadAllText(HistoryFileName); + history = txt.FromJson>(); + + Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); + } + else + { + Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); + } + } + catch (Exception ex) + { + // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, + // it just takes unnecessary time. + Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); + Log.Warning("Migration history will be overwritten and all migrations will be applied"); + } + } + + // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents + var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + + if (!migrationsNotYetApplied.Any()) + { + Log.Information("Databases are up to date"); + return; + } + + Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); + + // take some simple backups before we do anything. this gives users a way to get back to a working configuration + // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files + // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied + try + { + Log.Information("Backing up existing databases..."); + + foreach (var database in Databases) + { + var name = Path.Combine(Program.DataDirectory, database); + var src = $"{name}.db"; + var dest = $"{name}.db.pre-migration"; + + File.Copy(src, dest, overwrite: true); + + Log.Information("Backed database {Original} up to {Backup}", src, dest); + } + + Log.Information("Databases backed up successfully"); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to back up one or more database(s) prior to migration, operation cannot continue: {Message}", ex.Message); + Log.Fatal("Try again, revert the application to the previous version, or delete existing databases (warning: history will be lost!) to continue"); + throw; + } + + // we know which migrations to apply, and we've backed all of the databases up. let's go! + try + { + Log.Warning("Beginning migration(s)"); + Log.Warning("This may take some time. Avoid stopping the application before the process is complete. If the process is interrupted it may be necessary to manually revert to backups."); + + var overallSw = new Stopwatch(); + overallSw.Start(); + + var current = 0; + var total = migrationsNotYetApplied.Count(); + + var currentSw = new Stopwatch(); + + foreach (var migration in migrationsNotYetApplied) + { + current++; + currentSw.Restart(); + + Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total); + + try + { + Migrations[migration].Apply(); + history[migration] = DateTime.UtcNow; + + Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration, ex.Message); + throw; + } + } + + Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms elapsed)", total, overallSw.ElapsedMilliseconds); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply one or more migration(s): {Message}", ex.Message); + + try + { + Log.Information("Attempting to restore databases from backups..."); + + foreach (var database in Databases) + { + var name = Path.Combine(Program.DataDirectory, database); + var src = $"{name}.db.pre-migration"; + var dest = $"{name}.db"; + + // note: leave the backup in place to give users peace of mind + File.Copy(src, dest, overwrite: true); + + Log.Information("Restored {Original} from {Backup}", dest, src); + } + + Log.Information("Databases restored successfully"); + } + catch (Exception restoreEx) + { + Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); + Log.Fatal("Restore manually by renaming '.db.pre-migration' to '.db' prior to starting the application again."); + } + + throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); + } + + var newHistory = history.ToJson(); + File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present + Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); + + Log.Information("Migration(s) complete"); + } +} \ No newline at end of file diff --git a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs deleted file mode 100644 index ea295851..00000000 --- a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs +++ /dev/null @@ -1,151 +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.Migrations; - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.Data.Sqlite; - -public class TransferStateMigration_04012025 : IMigration -{ - private string DbName => "transfers"; - - public void Apply(IEnumerable databases) - { - if (!databases.Contains(DbName)) - { - throw new SlskdException($"Attempting to migrate database {DbName} but {DbName} is not in the list of known databases ({string.Join(",", databases)}). This is a precautionary check to ensure databases are properly backed up prior to migration, and the check has failed. Only an application update can fix this; please create an urgent issue: {Program.IssuesUrl}"); - } - } - - static void AddStateDescriptionColumn(string dbPath) - { - if (!File.Exists(dbPath)) - { - Console.WriteLine("Database file not found."); - return; - } - - string connectionString = $"Data Source={dbPath};Version=3;"; - - using (var connection = new SqliteConnection(connectionString)) - { - connection.Open(); - - // Check if the column exists - bool columnExists = false; - using (var command = new SqliteCommand("PRAGMA table_info(Transfers);", connection)) - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - string columnName = reader["name"].ToString(); - if (columnName.Equals("StateDescription", StringComparison.OrdinalIgnoreCase)) - { - columnExists = true; - break; - } - } - } - - if (columnExists) - { - Console.WriteLine("Column 'StateDescription' already exists."); - return; - } - - Console.WriteLine("Adding 'StateDescription' column..."); - - using (var transaction = connection.BeginTransaction()) - { - try - { - // Rename old table - using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) - { - renameCommand.ExecuteNonQuery(); - } - - // Create new table with StateDescription after State - string createNewTableSQL = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State TEXT NOT NULL, - StateDescription TEXT, -- New column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - );"; - - using (var createCommand = new SqliteCommand(createNewTableSQL, connection)) - { - createCommand.ExecuteNonQuery(); - } - - // Copy data into the new table - string copyDataSQL = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using (var copyCommand = new SqliteCommand(copyDataSQL, connection)) - { - copyCommand.ExecuteNonQuery(); - } - - // Drop the old table - using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) - { - dropCommand.ExecuteNonQuery(); - } - - transaction.Commit(); - Console.WriteLine("Column 'StateDescription' added successfully."); - } - catch (Exception ex) - { - transaction.Rollback(); - Console.WriteLine($"Error: {ex.Message}"); - } - } - - connection.Close(); - } - } -} diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs deleted file mode 100644 index 86056751..00000000 --- a/src/slskd/Core/Migrator.cs +++ /dev/null @@ -1,222 +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; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Serilog; -using slskd.Migrations; - -/// -/// A database migration. -/// -public interface IMigration -{ - /// - /// Apply the database migration. - /// - /// - /// The database list is included to help ensure that we're backing up databases before we start. Migrations - /// must check the supplied list to ensure the database(s) they are attempting to migrate are included; if - /// they are missing they haven't been backed up. - /// - /// A list of known databases. - public void Apply(IEnumerable databases); -} - -/// -/// Applies database migrations. -/// -public class Migrator -{ - /// - /// Initializes a new instance of the class. - /// - /// A list of known databases. - public Migrator(params string[] databases) - { - Databases = databases; - } - - private string HistoryFileName { get; } = Path.Combine(Program.DataDirectory, "migration.history"); - private IEnumerable Databases { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// A map of all migrations, to be applied in the order they are specified (descending). - /// - private Dictionary Migrations { get; } = new() - { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, - }; - - /// - /// Applies database migrations. - /// - /// Apply all migrations, regardless of whether there's evidence they have been applied already. - public void Migrate(bool force = false) - { - Dictionary history = []; - - Log.Information("Checking for outstanding database migrations..."); - - // load migration history from the history file in the root of the data directory. this file contains a key/value - // pair for each migration that's been applied, along with the migration date. - // if force=true, we don't care about the history and there's no reason to look at it. - if (!force) - { - try - { - if (File.Exists(HistoryFileName)) - { - var txt = File.ReadAllText(HistoryFileName); - history = txt.FromJson>(); - - Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); - } - else - { - Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); - } - } - catch (Exception ex) - { - // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, - // it just takes unnecessary time. - Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); - Log.Warning("Migration history will be overwritten and all migrations will be applied"); - } - } - - // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents - var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); - - if (!migrationsNotYetApplied.Any()) - { - Log.Information("Databases are up to date"); - return; - } - - Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); - - // take some simple backups before we do anything. this gives users a way to get back to a working configuration - // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files - // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied - try - { - Log.Information("Backing up existing databases..."); - - foreach (var database in Databases) - { - var name = Path.Combine(Program.DataDirectory, database); - var src = $"{name}.db"; - var dest = $"{name}.db.pre-migration"; - - File.Copy(src, dest, overwrite: true); - - Log.Information("Backed database {Original} up to {Backup}", src, dest); - } - - Log.Information("Databases backed up successfully"); - } - catch (Exception ex) - { - Log.Fatal(ex, "Failed to back up one or more database(s) prior to migration, operation cannot continue: {Message}", ex.Message); - Log.Fatal("Try again, revert the application to the previous version, or delete existing databases (warning: history will be lost!) to continue"); - throw; - } - - // we know which migrations to apply, and we've backed all of the databases up. let's go! - try - { - Log.Warning("Beginning migration(s)"); - Log.Warning("This may take some time. Avoid stopping the application before the process is complete. If the process is interrupted it may be necessary to manually revert to backups."); - - var overallSw = new Stopwatch(); - overallSw.Start(); - - var current = 0; - var total = migrationsNotYetApplied.Count(); - - var currentSw = new Stopwatch(); - - foreach (var migration in migrationsNotYetApplied) - { - current++; - currentSw.Restart(); - - Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total); - - try - { - Migrations[migration].Apply(Databases); - history[migration] = DateTime.UtcNow; - - Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); - } - catch (Exception ex) - { - Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration, ex.Message); - throw; - } - } - - Log.Information("{Count} migration(s) applied successfully (elapsed: {Duration}ms elapsed)", total, overallSw.ElapsedMilliseconds); - } - catch (Exception ex) - { - Log.Fatal(ex, "Failed to apply one or more migration(s): {Message}", ex.Message); - - try - { - Log.Information("Attempting to restore databases from backups..."); - - foreach (var database in Databases) - { - var name = Path.Combine(Program.DataDirectory, database); - var src = $"{name}.db.pre-migration"; - var dest = $"{name}.db"; - - // note: leave the backup in place to give users peace of mind - File.Copy(src, dest, overwrite: true); - - Log.Information("Restored {Original} from {Backup}", dest, src); - } - - Log.Information("Databases restored successfully"); - } - catch (Exception restoreEx) - { - Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); - Log.Fatal("Restore manually by renaming '.db.pre-migration' to '.db' prior to starting the application again."); - throw; - } - - throw; - } - - var newHistory = history.ToJson(); - File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present - Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - - Log.Information("Migration(s) complete"); - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 690960a7..763b345a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -500,6 +500,8 @@ namespace slskd app.Services.GetService().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } + Environment.Exit(1); + // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService(); -- cgit v1.2.3