From e22ee3167f93eac0b29160e726dbbd3c2d42f6c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Apr 2025 13:06:52 -0500 Subject: document force migrations flag --- docs/config.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs') diff --git a/docs/config.md b/docs/config.md index 92798196..a626cb4b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1226,6 +1226,7 @@ Several additional feature flags are provided to change the application's runtim | `--no-connect` | `SLSKD_NO_CONNECT` | Start the application, but don't connect to the server | | `--no-share-scan` | `SLSKD_NO_SHARE_SCAN` | Don't perform a scan of shared directories on startup | | `--force-share-scan` | `SLSKD_FORCE_SHARE_SCAN` | Force a scan of shared directories on startup | +| `--force-migrations` | `SLSKD_FORCE_MIGRATIONS` | Force database migrations to be applied on startup | | `--no-version-check` | `SLSKD_NO_VERSION_CHECK` | Don't perform a version check on startup | | `--log-sql` | `SLSKD_LOG_SQL` | Log SQL queries generated by Entity Framework | | `--volatile` | `SLSKD_VOLATILE` | Use volatile data storage (all data will be lost at shutdown) | @@ -1242,6 +1243,7 @@ flags: no_connect: false no_share_scan: false force_share_scan: false + force_migrations: false no_version_check: false log_sql: false experimental: false -- cgit v1.2.3 From e2f814f83cb5ce5861f9433a6727d6807c538bd4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 May 2025 14:48:17 -0500 Subject: add user docs --- docs/README.md | 6 +++++- docs/migrations.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 docs/migrations.md (limited to 'docs') diff --git a/docs/README.md b/docs/README.md index ce8316a7..eb08d969 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,4 +17,8 @@ ## Building slskd from Source -### [Build](https://github.com/slskd/slskd/blob/master/docs/build.md) \ No newline at end of file +### [Build](https://github.com/slskd/slskd/blob/master/docs/build.md) + +## Troubleshooting + +### [Migrations](https://github.com/slskd/slskd/blob/master/docs/migrations.md) \ No newline at end of file diff --git a/docs/migrations.md b/docs/migrations.md new file mode 100644 index 00000000..6f1ec5f5 --- /dev/null +++ b/docs/migrations.md @@ -0,0 +1,49 @@ +# Database Migrations + +Database migrations are used to update the structure of the application's databases to support new features or improve functionality. These migrations are applied automatically when the application starts. If a migration fails, the application will attempt to restore the database to its pre-migration state using backups created before the migration process began. + +## Migration Process + +When the application detects that a migration is required, it performs the following steps: + +1. Back up existing databases: Before applying any changes, the application creates a backup of each database. These backups are stored in the `migrations` directory within the application's data directory. The backup files are named using the format `.pre-migration-backup..db`. + +2. Apply migrations: The application applies the necessary changes to the database schema and data. + +3. Save migration history: After successfully applying migrations, the application updates the migration history file to record the applied changes. + +At the start of each migration a unique `migration id` is generated. If anything goes wrong, this ID can be used to locate the backup files created before the error occured (as subsequent migration attempts/retries will generate new backups, which may contain partially applied migrations). + +History is stored in the `migrations` directory so that the application can avoid running migrations that have already been applied. If this file is deleted, moved, or becomes corrupted, +all migrations will be applied the next time the application starts. Avoid deleting, moving or modifying this file. + +## What to Do If a Migration Fails + +If a migration fails, the application will attempt to restore the databases from the backups created before the migration. However, if the automatic restoration process fails, you can manually recover your data by following these steps: + +1. Locate the Backup Files: + - Find the _first_ failed migration attempt and note the associated ID (it will be in application logs). If it can't be located, it is safe to assume that the oldest ID is the correct one. + - Navigate to the `migrations` directory within the application's data directory. + - Look for files named `.pre-migration-backup..db`. + +2. Restore the Backup: + - Rename the backup file to replace the current database file. For example, rename `transfers.pre-migration-backup.040123_123456.db` to `transfers.db`. + - Ensure the restored file is placed in the root of the application's data directory (move it up, out of the `migrations` directory). + +3. Restart the Application: + - Start the application again. It will detect the restored database and attempt to reapply the migration. + +## If the Migration Continues to Fail + +If the application gets "stuck" in a reboot loop and can't complete migration(s) successfully, you will need to rename (or delete) the existing database files and allow the application to re-generate them. + +It should be possible to recover the old data, but the process will need to be manual. Create a GitHub issue and provide logs from the failing migration(s). + +## Preventing Migration Issues + +To minimize the risk of migration failures: + +- Ensure Sufficient Disk Space: Verify that there is enough disk space available for creating backups and applying migrations. +- Avoid Interruptions: Do not stop the application while a migration is in progress. +- Monitor Logs: Check the application logs for detailed information about the migration process and any errors encountered. + -- cgit v1.2.3 From 85ba3a74f27c753c08af970d4217ed9fc4a85b54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 May 2025 12:21:36 -0500 Subject: remove migration history file --- docs/migrations.md | 5 --- src/slskd/Core/Data/Migrations/README.md | 11 +++-- src/slskd/Core/Data/Migrator.cs | 69 ++++++-------------------------- 3 files changed, 17 insertions(+), 68 deletions(-) (limited to 'docs') diff --git a/docs/migrations.md b/docs/migrations.md index 6f1ec5f5..2b6450ca 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -10,13 +10,8 @@ When the application detects that a migration is required, it performs the follo 2. Apply migrations: The application applies the necessary changes to the database schema and data. -3. Save migration history: After successfully applying migrations, the application updates the migration history file to record the applied changes. - At the start of each migration a unique `migration id` is generated. If anything goes wrong, this ID can be used to locate the backup files created before the error occured (as subsequent migration attempts/retries will generate new backups, which may contain partially applied migrations). -History is stored in the `migrations` directory so that the application can avoid running migrations that have already been applied. If this file is deleted, moved, or becomes corrupted, -all migrations will be applied the next time the application starts. Avoid deleting, moving or modifying this file. - ## What to Do If a Migration Fails If a migration fails, the application will attempt to restore the databases from the backups created before the migration. However, if the automatic restoration process fails, you can manually recover your data by following these steps: diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index cae058b2..e8630265 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -1,11 +1,9 @@ # Database Migrations -In the hopefully unlikely event that a non-backwards-compatible schema change to a database migration is necessary, a migration must be written. +In the hopefully unlikely event that a schema change more complex than the simple addition of a column to a database migration is necessary, a migration must be written. Migrations are applied by the `Migrator` at startup. -The `history` file in the data directory is used to attempt to track whether migrations have already been applied. If a migration appears in the history file it won't be run again. Users can delete or modify the `history` file or use the `force` flag to apply them, meaning migrations **MUST** be idempotent. - The `Migrator` creates a backup of each database prior to running any migrations, and if an exception is thrown at any time during the process the `Migrator` will revert to these backups automatically. The backup files are left in place when the migration is complete so that users can manually revert if the migration left their application in a bad state or destroyed or lost data. ## Creating a Migration @@ -18,11 +16,12 @@ Z_Migration Migrations MUST: -* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable -and the name(s) of the table(s) that need to be migrated. +* Be idempotent. The migration must be able to be run any number of times without corrupting the database or losing data. * Inspect the target database(s) schema to determine whether the migration needs to be applied (if possible) * Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. -* Log progress, so users can see that the application is performing work while records are updated. +* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable +and the name(s) of the table(s) that need to be migrated. +* Log progress (with logs prefixed by >), so users can see that the application is performing work while records are updated. Review the `IMigration` interface to determine implementation details. diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 02b65c0c..4adc22fb 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -77,62 +77,31 @@ public class Migrator /// 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're going to disregard history and overwrite 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"); - } - } - - Log.Debug("Current history: {History}", history); + List migrationsToApply = []; + List migrationsToSkip = []; /* determine which migrations need to be applied - take the set difference between all registered migrations and the history file, then for each of the migrations - in that set, check to see if it needs to be applied. if it doesn't, add it to the history file with the current - timestamp. if it does, add it to the list of migrations to apply. - */ - List migrationsToApply = []; + for the time being, we'll rely on each of the migrations to determine whether they need to be applied + this will work until: + 1) there's a migration that isn't idempotent (can't tell whether it needs to be applied on its own), or.. + 2) there are > ~20 migrations, making repeated I/O of database files too slow/expensive on low spec hardware + when the time comes, migration history should be stored within the database files themselves. + */ try { - foreach (var migration in Migrations.Keys.Except(history.Keys)) + foreach (var migration in Migrations.Keys) { if (!Migrations[migration].NeedsToBeApplied()) // warning: performs I/O { Log.Debug("Migration {Name} does not need to be applied", migration); - history[migration] = DateTime.UtcNow; + migrationsToSkip.Add(migration); } else { + Log.Debug("Migration {Name} needs to be applied", migration); migrationsToApply.Add(migration); } } @@ -143,15 +112,10 @@ public class Migrator throw; } - Log.Debug("Updated history: {History}", history); - Log.Debug("Migrations to apply: {Migrations}", migrationsToApply); + Log.Debug("Migrations: {Migrations}", new { migrationsToApply, migrationsToSkip }); if (migrationsToApply.Count == 0) { - // write the history file to disk; if there are new migrations that didn't need to be applied, or the user - // used the 'force' flag, the history file on disk and in memory will have diverged. - UpdateHistoryFile(history); - Log.Information("Databases are up to date!"); return; } @@ -216,7 +180,6 @@ public class Migrator try { Migrations[migration].Apply(); - history[migration] = DateTime.UtcNow; Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); } @@ -260,17 +223,9 @@ public class Migrator throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); } - UpdateHistoryFile(history); Log.Information("Migration(s) complete!"); } - private void UpdateHistoryFile(Dictionary history) - { - var newHistory = history.ToJson(); - File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present - Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - } - private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataMigrationsDirectory, $"{database}.pre-migration-backup.{timestamp}.db"); } \ No newline at end of file -- cgit v1.2.3 From 930df71e94dedd5de5267418c3e7666a86eea416 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 May 2025 17:53:31 -0500 Subject: final tweaks --- docs/migrations.md | 6 ++--- src/slskd/Core/Data/IMigration.cs | 38 ++++++++++++++++++++++++++++++++ src/slskd/Core/Data/Migrations/README.md | 4 +--- src/slskd/Core/Data/Migrator.cs | 20 ----------------- 4 files changed, 42 insertions(+), 26 deletions(-) create mode 100644 src/slskd/Core/Data/IMigration.cs (limited to 'docs') diff --git a/docs/migrations.md b/docs/migrations.md index 2b6450ca..2fec53bd 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -6,7 +6,7 @@ Database migrations are used to update the structure of the application's databa When the application detects that a migration is required, it performs the following steps: -1. Back up existing databases: Before applying any changes, the application creates a backup of each database. These backups are stored in the `migrations` directory within the application's data directory. The backup files are named using the format `.pre-migration-backup..db`. +1. Back up existing databases: Before applying any changes, the application creates a backup of each database. These backups are stored in the `backups` directory within the application's data directory. The backup files are named using the format `.pre-migration-backup..db`. 2. Apply migrations: The application applies the necessary changes to the database schema and data. @@ -18,12 +18,12 @@ If a migration fails, the application will attempt to restore the databases from 1. Locate the Backup Files: - Find the _first_ failed migration attempt and note the associated ID (it will be in application logs). If it can't be located, it is safe to assume that the oldest ID is the correct one. - - Navigate to the `migrations` directory within the application's data directory. + - Navigate to the `backups` directory within the application's data directory. - Look for files named `.pre-migration-backup..db`. 2. Restore the Backup: - Rename the backup file to replace the current database file. For example, rename `transfers.pre-migration-backup.040123_123456.db` to `transfers.db`. - - Ensure the restored file is placed in the root of the application's data directory (move it up, out of the `migrations` directory). + - Ensure the restored file is placed in the root of the application's data directory (move it up, out of the `backups` directory). 3. Restart the Application: - Start the application again. It will detect the restored database and attempt to reapply the migration. diff --git a/src/slskd/Core/Data/IMigration.cs b/src/slskd/Core/Data/IMigration.cs new file mode 100644 index 00000000..18b198b2 --- /dev/null +++ b/src/slskd/Core/Data/IMigration.cs @@ -0,0 +1,38 @@ +// +// 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; + +/// +/// Applies database migrations. +/// +public interface IMigration +{ + /// + /// Determines whether the migration needs to be applied. + /// + /// + /// This method MUST be read-only and should contain no side effects. + /// + /// A value indicating whether the migration needs to be applied. + bool NeedsToBeApplied(); + + /// + /// Applies the migration. + /// + void Apply(); +} \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index e8630265..2b5fd6f4 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -27,6 +27,4 @@ Review the `IMigration` interface to determine implementation details. The new `IMigration` implementation must be added to the dictionary in the `Migrations` property of the `Migrator` in the desired order so that it can be run. -### Above all else, each and every migration **MUST** be idempotent. - -Users can delete the history file or use the `force` flag to cause migrations to be run again. We can inspect schemas to determine whether re-running is necessary, but there may be cases where that's not enough. \ No newline at end of file +### Above all else, each and every migration **MUST** be idempotent; they'll be evaluated and run each time the app starts. \ No newline at end of file diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 4cc56147..e359d334 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -25,26 +25,6 @@ using System.Linq; using Serilog; using slskd.Migrations; -/// -/// Applies database migrations. -/// -public interface IMigration -{ - /// - /// Determines whether the migration needs to be applied. - /// - /// - /// This method MUST be read-only and should contain no side effects. - /// - /// A value indicating whether the migration needs to be applied. - bool NeedsToBeApplied(); - - /// - /// Applies the migration. - /// - void Apply(); -} - /// /// Applies database migrations. /// -- cgit v1.2.3 From df331ce2f881aa89920c004eafcfd327c91b66f0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Jul 2025 18:52:50 -0500 Subject: docs --- docs/config.md | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) (limited to 'docs') diff --git a/docs/config.md b/docs/config.md index cf7fb9a3..ff3e8410 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1033,11 +1033,23 @@ integration: ### Scripts -User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` command that's used to execute the script. +User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` configuration that's used to execute the script. -The `run` command must be at least one word, with the first word identifying the executable to run and the rest of the string being the command and arguments that will be passed to the executable when the script is run. The executable needs to be on the system's PATH, otherwise it must be the fully qualified path to the file on disk. +The `run` configuration can take a few different forms (see examples below), but in all cases a new process is started using either the `executable` you specify or, if you don't specify one, the executable set in your system's `$SHELL` environment variable, or `cmd.exe` on Windows. -A reserved placeholder value `$DATA` is replaced with the stringified JSON data associated with the event that caused the script to run. It's the responsibility of the script to parse and handle this JSON. +Processes are started in the `/scripts` directory (meaning the working directory), and stdout and stderr are redirected to slskd for logging purposes. Depending on the `run` configuration your defined command will be passed as either a single argument or list of arguments, with the latter being easier to properly quote and escape. + +The data associated with the event that's invoking your script is stringified to JSON and set as the value of the `SLSKD_SCRIPT_DATA` environment variable. Whatever command or script you specify will need to read this value and handle the data. + +> [!DANGER] +> **Remote Code Execution Risk**: The event data in `$SLSKD_SCRIPT_DATA` originates from the Soulseek network and may contain malicious content. Passing this data as command-line arguments could allow attackers to inject shell commands through specially crafted filenames, usernames, or other fields. For example, a filename like `song"; rm -rf /; echo "` could delete your entire filesystem if passed unsafely to a shell command. +> +> **Safe practices:** +> - ✅ Read `$SLSKD_SCRIPT_DATA` as an environment variable +> - ✅ Parse the JSON and validate/sanitize individual fields before use +> - ✅ Use programming languages with proper JSON parsing (Python, Node.js, etc.) +> - ❌ Avoid using `$SLSKD_SCRIPT_DATA` in shell command substitution like `$(echo $SLSKD_SCRIPT_DATA)` +> - ❌ Avoid passing the raw data as arguments: `my_script.sh "$SLSKD_SCRIPT_DATA"` #### **YAML** ```yaml @@ -1047,11 +1059,22 @@ integration: on: - DownloadFileComplete - DownloadDirectoryComplete - run: /bin/sh data/my_script.sh --json-to-process "$DATA" # Linux/macOS + run: + command: "echo "new event!" >> event_log.txt # command is run with system $SHELL/cmd.exe on Windows my_logging_script: on: - - All - run: cmd.exe echo $DATA >> event_log.txt # Windows + - All + run: + executable: /bin/sh # explicitly setting executable; if omitted, $SHELL/cmd.exe is used + args: '-c "echo "new event!" >> event_log.txt"' + another_script: + on: + - All + run: + executable: /bin/sh # as above, can omit to use $SHELL/cmd.exe + arglist: # easier to properly quote + - /c + - 'echo "new event!" >> event_log.txt' ``` ## System-Defined -- cgit v1.2.3 From f68455f5560b983d0fe330be09de42aa29e3f5be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Jul 2025 19:04:16 -0500 Subject: tweak --- docs/config.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/config.md b/docs/config.md index ff3e8410..6f01c2af 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1041,10 +1041,10 @@ Processes are started in the `/scripts` directory (meaning the working directory The data associated with the event that's invoking your script is stringified to JSON and set as the value of the `SLSKD_SCRIPT_DATA` environment variable. Whatever command or script you specify will need to read this value and handle the data. -> [!DANGER] +> [!CAUTION] > **Remote Code Execution Risk**: The event data in `$SLSKD_SCRIPT_DATA` originates from the Soulseek network and may contain malicious content. Passing this data as command-line arguments could allow attackers to inject shell commands through specially crafted filenames, usernames, or other fields. For example, a filename like `song"; rm -rf /; echo "` could delete your entire filesystem if passed unsafely to a shell command. > -> **Safe practices:** +> **Best practices:** > - ✅ Read `$SLSKD_SCRIPT_DATA` as an environment variable > - ✅ Parse the JSON and validate/sanitize individual fields before use > - ✅ Use programming languages with proper JSON parsing (Python, Node.js, etc.) -- cgit v1.2.3