1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
|
// <copyright file="Migrator.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ 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, version 3.
// │
// │ 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/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
namespace slskd;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Serilog;
using slskd.Migrations;
/// <summary>
/// Applies database migrations.
/// </summary>
public class Migrator
{
/// <summary>
/// Initializes a new instance of the <see cref="Migrator"/> class.
/// </summary>
/// <param name="databases">A list of known databases.</param>
public Migrator(ConnectionStringDictionary databases)
{
Databases = databases;
Migrations = new()
{
{ nameof(Z2025_04_01_TransferStateMigration), new Z2025_04_01_TransferStateMigration(connectionStrings: Databases) },
{ nameof(Z2025_07_06_TransferIndexesMigration), new Z2025_07_06_TransferIndexesMigration(connectionStrings: Databases) },
{ nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) },
{ nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) },
{ nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) },
{ nameof(Z2026_04_30_DropTransferStartOffsetMigration), new Z2026_04_30_DropTransferStartOffsetMigration(connectionStrings: Databases) },
{ nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) },
};
}
private ConnectionStringDictionary Databases { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<Migrator>();
/// <summary>
/// A map of all migrations, to be applied in the order they are specified (descending).
/// </summary>
/// <remarks>
/// This could be done with reflection (e.g. find all instances of IMigration) but it's useful during development
/// to selectively add/comment out lines. Slight risk that something is missed, so this should be append only.
/// </remarks>
private Dictionary<string, IMigration> Migrations { get; }
/// <summary>
/// Applies database migrations.
/// </summary>
/// <param name="force">Apply all migrations, regardless of whether there's evidence they have been applied already.</param>
public void Migrate(bool force = false)
{
List<string> migrationsToApply = [];
List<string> migrationsToSkip = [];
/*
determine which migrations need to be applied
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)
{
// warning: performs I/O
if (!Migrations[migration].NeedsToBeApplied())
{
Log.Debug("Migration {Name} does not need to be applied", migration);
migrationsToSkip.Add(migration);
}
else
{
Log.Debug("Migration {Name} needs to be applied", migration);
migrationsToApply.Add(migration);
}
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Failed to disposition migrations: {Message}", ex.Message);
throw;
}
Log.Debug("Migrations: {@Migrations}", new { migrationsToApply, migrationsToSkip });
if (migrationsToApply.Count == 0)
{
Log.Information("Databases are up to date!");
return;
}
/*
MIGRATION TIME!
---------------------------------------------------------------------------------------------------------------------------------------------------
*/
Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsToApply.Count());
var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss");
Log.Warning("--> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups, should manual cleanup be needed. <--", migrationId);
// 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 Database.List)
{
var src = MakeSourceDatabasePath(database.Name);
var dest = MakeBackupDatabasePath(database.Name, migrationId);
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 = migrationsToApply.Count();
var currentSw = new Stopwatch();
foreach (var migration in migrationsToApply)
{
current++;
currentSw.Restart();
Log.Warning("Applying migration {Name} ({Current} of {Total})", migration, current, total);
try
{
Migrations[migration].Apply();
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)", 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 Database.List)
{
var name = Path.Combine(Program.DataDirectory, database.Name);
var src = MakeBackupDatabasePath(database.Name, migrationId);
var dest = MakeSourceDatabasePath(database.Name);
// note: leave the backup in place just in case; automatic cleanup will delete them later
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 '<database>.pre-migration.{migrationId}.db' to '<database>.db' prior to starting the application again.");
}
throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex);
}
Log.Information("Migration(s) complete!");
}
private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db");
private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataBackupDirectory, $"{database}.pre-migration-backup.{timestamp}.db");
}
|