| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.IO; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Reflection; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using Emby.Server.Implementations.Serialization; |
| | | 10 | | using Jellyfin.Database.Implementations; |
| | | 11 | | using Jellyfin.Server.Implementations.SystemBackupService; |
| | | 12 | | using Jellyfin.Server.Migrations.Stages; |
| | | 13 | | using Jellyfin.Server.ServerSetupApp; |
| | | 14 | | using MediaBrowser.Common.Configuration; |
| | | 15 | | using MediaBrowser.Controller.SystemBackupService; |
| | | 16 | | using MediaBrowser.Model.Configuration; |
| | | 17 | | using Microsoft.EntityFrameworkCore; |
| | | 18 | | using Microsoft.EntityFrameworkCore.Infrastructure; |
| | | 19 | | using Microsoft.EntityFrameworkCore.Migrations; |
| | | 20 | | using Microsoft.EntityFrameworkCore.Storage; |
| | | 21 | | using Microsoft.Extensions.Logging; |
| | | 22 | | |
| | | 23 | | namespace Jellyfin.Server.Migrations; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Handles Migration of the Jellyfin data structure. |
| | | 27 | | /// </summary> |
| | | 28 | | internal class JellyfinMigrationService |
| | | 29 | | { |
| | | 30 | | private const string DbFilename = "library.db"; |
| | | 31 | | private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory; |
| | | 32 | | private readonly ILoggerFactory _loggerFactory; |
| | | 33 | | private readonly IStartupLogger _startupLogger; |
| | | 34 | | private readonly IBackupService? _backupService; |
| | | 35 | | private readonly IJellyfinDatabaseProvider? _jellyfinDatabaseProvider; |
| | | 36 | | private readonly IApplicationPaths _applicationPaths; |
| | | 37 | | private (string? LibraryDb, string? JellyfinDb, BackupManifestDto? FullBackup) _backupKey; |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Initializes a new instance of the <see cref="JellyfinMigrationService"/> class. |
| | | 41 | | /// </summary> |
| | | 42 | | /// <param name="dbContextFactory">Provides access to the jellyfin database.</param> |
| | | 43 | | /// <param name="loggerFactory">The logger factory.</param> |
| | | 44 | | /// <param name="startupLogger">The startup logger for Startup UI intigration.</param> |
| | | 45 | | /// <param name="applicationPaths">Application paths for library.db backup.</param> |
| | | 46 | | /// <param name="backupService">The jellyfin backup service.</param> |
| | | 47 | | /// <param name="jellyfinDatabaseProvider">The jellyfin database provider.</param> |
| | | 48 | | public JellyfinMigrationService( |
| | | 49 | | IDbContextFactory<JellyfinDbContext> dbContextFactory, |
| | | 50 | | ILoggerFactory loggerFactory, |
| | | 51 | | IStartupLogger<JellyfinMigrationService> startupLogger, |
| | | 52 | | IApplicationPaths applicationPaths, |
| | | 53 | | IBackupService? backupService = null, |
| | | 54 | | IJellyfinDatabaseProvider? jellyfinDatabaseProvider = null) |
| | | 55 | | { |
| | 90 | 56 | | _dbContextFactory = dbContextFactory; |
| | 90 | 57 | | _loggerFactory = loggerFactory; |
| | 90 | 58 | | _startupLogger = startupLogger; |
| | 90 | 59 | | _backupService = backupService; |
| | 90 | 60 | | _jellyfinDatabaseProvider = jellyfinDatabaseProvider; |
| | 90 | 61 | | _applicationPaths = applicationPaths; |
| | 90 | 62 | | Migrations = [.. typeof(IAsyncMigrationRoutine).Assembly.GetTypes().Where(e => typeof(IAsyncMigrationRoutine).Is |
| | 90 | 63 | | .Select(e => (Type: e, Metadata: e.GetCustomAttribute<JellyfinMigrationAttribute>(), Backup: e.GetCustomAttr |
| | 90 | 64 | | .Where(e => e.Metadata is not null) |
| | 90 | 65 | | .GroupBy(e => e.Metadata!.Stage) |
| | 90 | 66 | | .Select(f => |
| | 90 | 67 | | { |
| | 90 | 68 | | var stage = new MigrationStage(f.Key); |
| | 90 | 69 | | foreach (var item in f) |
| | 90 | 70 | | { |
| | 90 | 71 | | JellyfinMigrationBackupAttribute? backupMetadata = null; |
| | 90 | 72 | | if (item.Backup?.Any() == true) |
| | 90 | 73 | | { |
| | 90 | 74 | | backupMetadata = item.Backup.Aggregate(MergeBackupAttributes); |
| | 90 | 75 | | } |
| | 90 | 76 | | |
| | 90 | 77 | | stage.Add(new(item.Type, item.Metadata!, backupMetadata)); |
| | 90 | 78 | | } |
| | 90 | 79 | | |
| | 90 | 80 | | return stage; |
| | 90 | 81 | | })]; |
| | 90 | 82 | | } |
| | | 83 | | |
| | | 84 | | private interface IInternalMigration |
| | | 85 | | { |
| | | 86 | | Task PerformAsync(IStartupLogger logger); |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | private HashSet<MigrationStage> Migrations { get; set; } |
| | | 90 | | |
| | | 91 | | public async Task CheckFirstTimeRunOrMigration(IApplicationPaths appPaths, StartupOptions startupOptions) |
| | | 92 | | { |
| | 36 | 93 | | var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migration |
| | 36 | 94 | | logger.LogInformation("Initialise Migration service."); |
| | 36 | 95 | | var xmlSerializer = new MyXmlSerializer(); |
| | 36 | 96 | | var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath) |
| | 36 | 97 | | ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigu |
| | 36 | 98 | | : new ServerConfiguration(); |
| | 36 | 99 | | if (!serverConfig.IsStartupWizardCompleted || startupOptions.StartupMode is Configuration.StartupMode.SeedSystem |
| | | 100 | | { |
| | 29 | 101 | | logger.LogInformation("System initialization detected. Seed data. Startup mode is: {StartupMode}", startupOp |
| | 29 | 102 | | var flatApplyMigrations = Migrations.SelectMany(e => e.Where(f => !f.Metadata.RunMigrationOnSetup)).ToArray( |
| | | 103 | | |
| | 29 | 104 | | var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); |
| | 29 | 105 | | await using (dbContext.ConfigureAwait(false)) |
| | | 106 | | { |
| | 29 | 107 | | var databaseCreator = dbContext.Database.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator |
| | 29 | 108 | | ?? throw new InvalidOperationException("Jellyfin does only support relational databases."); |
| | 29 | 109 | | if (!await databaseCreator.ExistsAsync().ConfigureAwait(false)) |
| | | 110 | | { |
| | 29 | 111 | | await databaseCreator.CreateAsync().ConfigureAwait(false); |
| | | 112 | | } |
| | | 113 | | |
| | 29 | 114 | | var historyRepository = dbContext.GetService<IHistoryRepository>(); |
| | | 115 | | |
| | 29 | 116 | | await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false); |
| | 29 | 117 | | var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false); |
| | 29 | 118 | | var startupScripts = flatApplyMigrations |
| | 29 | 119 | | .Where(e => !appliedMigrations.Any(f => f != e.BuildCodeMigrationId())) |
| | 29 | 120 | | .Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.Buil |
| | 29 | 121 | | .ToArray(); |
| | 2610 | 122 | | foreach (var item in startupScripts) |
| | | 123 | | { |
| | 1276 | 124 | | logger.LogInformation("Seed migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name); |
| | 1276 | 125 | | await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false); |
| | | 126 | | } |
| | 29 | 127 | | } |
| | | 128 | | |
| | 29 | 129 | | logger.LogInformation("Migration system initialisation completed."); |
| | 29 | 130 | | } |
| | | 131 | | else |
| | | 132 | | { |
| | | 133 | | // Only a media server start is refused. A MigrateSystem run is left to the migrations, which another databa |
| | | 134 | | // provider may rely on to initialise its database, and a restore replaces the database later, in StartServe |
| | 7 | 135 | | var startupMode = startupOptions.StartupMode ?? Configuration.StartupMode.MediaServer; |
| | 7 | 136 | | if (startupMode == Configuration.StartupMode.MediaServer && string.IsNullOrWhiteSpace(startupOptions.Restore |
| | | 137 | | { |
| | 5 | 138 | | await EnsureExistingDatabaseAsync(appPaths, logger).ConfigureAwait(false); |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | // migrate any existing migration.xml files |
| | 3 | 142 | | var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, "migrations.xml"); |
| | 3 | 143 | | var migrationOptions = File.Exists(migrationConfigPath) |
| | 3 | 144 | | ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)! |
| | 3 | 145 | | : null; |
| | 3 | 146 | | if (migrationOptions is not null && migrationOptions.Applied.Count > 0) |
| | | 147 | | { |
| | 0 | 148 | | logger.LogInformation("Old migration style migration.xml detected. Migrate now."); |
| | | 149 | | try |
| | | 150 | | { |
| | 0 | 151 | | var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); |
| | 0 | 152 | | await using (dbContext.ConfigureAwait(false)) |
| | | 153 | | { |
| | 0 | 154 | | var historyRepository = dbContext.GetService<IHistoryRepository>(); |
| | 0 | 155 | | var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(fals |
| | 0 | 156 | | var lastOldAppliedMigration = Migrations |
| | 0 | 157 | | .SelectMany(e => e.Where(e => e.Metadata.Key is not null)) // only consider migrations that |
| | 0 | 158 | | .Where(e => migrationOptions.Applied.Any(f => f.Id.Equals(e.Metadata.Key!.Value))) |
| | 0 | 159 | | .Where(e => !appliedMigrations.Contains(e.BuildCodeMigrationId())) |
| | 0 | 160 | | .OrderBy(e => e.BuildCodeMigrationId()) |
| | 0 | 161 | | .Last(); // this is the latest migration applied in the old migration.xml |
| | | 162 | | |
| | 0 | 163 | | IReadOnlyList<CodeMigration> oldMigrations = [ |
| | 0 | 164 | | .. Migrations |
| | 0 | 165 | | .SelectMany(e => e) |
| | 0 | 166 | | .OrderBy(e => e.BuildCodeMigrationId()) |
| | 0 | 167 | | .TakeWhile(e => e.BuildCodeMigrationId() != lastOldAppliedMigration.BuildCodeMigrationId()), |
| | 0 | 168 | | lastOldAppliedMigration |
| | 0 | 169 | | ]; |
| | | 170 | | // those are all migrations that had to run in the old migration system, even if not noted in th |
| | | 171 | | |
| | 0 | 172 | | var startupScripts = oldMigrations.Select(e => (Migration: e.Metadata, Script: historyRepository |
| | 0 | 173 | | foreach (var item in startupScripts) |
| | | 174 | | { |
| | 0 | 175 | | logger.LogInformation("Migrate migration {Key}-{Name}.", item.Migration.Key, item.Migration. |
| | 0 | 176 | | await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false); |
| | | 177 | | } |
| | | 178 | | |
| | 0 | 179 | | logger.LogInformation("Rename old migration.xml to migration.xml.backup"); |
| | 0 | 180 | | File.Move(migrationConfigPath, Path.ChangeExtension(migrationConfigPath, ".xml.backup"), true); |
| | 0 | 181 | | } |
| | 0 | 182 | | } |
| | 0 | 183 | | catch (Exception ex) |
| | | 184 | | { |
| | 0 | 185 | | logger.LogCritical(ex, "Failed to apply migrations"); |
| | 0 | 186 | | throw; |
| | | 187 | | } |
| | | 188 | | } |
| | 3 | 189 | | } |
| | 32 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Stops the startup of a server that has been set up before but whose database is missing or empty. Running the mi |
| | | 194 | | /// against such a database fails part way through, and seeding it would leave a server nobody can log in to. |
| | | 195 | | /// </summary> |
| | | 196 | | private async Task EnsureExistingDatabaseAsync(IApplicationPaths appPaths, ILogger logger) |
| | | 197 | | { |
| | 5 | 198 | | string? problem = null; |
| | 5 | 199 | | var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); |
| | 5 | 200 | | await using (dbContext.ConfigureAwait(false)) |
| | | 201 | | { |
| | 5 | 202 | | var databaseCreator = dbContext.Database.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator |
| | 5 | 203 | | ?? throw new InvalidOperationException("Jellyfin does only support relational databases."); |
| | | 204 | | |
| | | 205 | | // Check existence first: opening a connection to a missing SQLite database creates an empty file. |
| | 5 | 206 | | if (!await databaseCreator.ExistsAsync().ConfigureAwait(false)) |
| | | 207 | | { |
| | 2 | 208 | | problem = "the database does not exist"; |
| | | 209 | | } |
| | | 210 | | else |
| | | 211 | | { |
| | 3 | 212 | | var historyRepository = dbContext.GetService<IHistoryRepository>(); |
| | 3 | 213 | | if (!await historyRepository.ExistsAsync().ConfigureAwait(false)) |
| | | 214 | | { |
| | 1 | 215 | | problem = "the database has no migration history"; |
| | | 216 | | } |
| | 2 | 217 | | else if ((await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false)).Count == 0) |
| | | 218 | | { |
| | 1 | 219 | | problem = "the migration history of the database is empty"; |
| | | 220 | | } |
| | 3 | 221 | | } |
| | | 222 | | } |
| | | 223 | | |
| | 5 | 224 | | if (problem is null) |
| | | 225 | | { |
| | 1 | 226 | | return; |
| | | 227 | | } |
| | | 228 | | |
| | 4 | 229 | | var message = string.Format( |
| | 4 | 230 | | CultureInfo.InvariantCulture, |
| | 4 | 231 | | "This server has been set up before (IsStartupWizardCompleted is true in {0}), but {1}. Jellyfin will not st |
| | 4 | 232 | | + "To continue, either restore the previous database; or start over and keep this server's settings by setti |
| | 4 | 233 | | + "(users, watch history and everything else stored in the database will not come back); or set up a new ser |
| | 4 | 234 | | appPaths.SystemConfigurationFilePath, |
| | 4 | 235 | | problem); |
| | 4 | 236 | | logger.LogCritical("{Message}", message); |
| | 4 | 237 | | throw new InvalidOperationException(message); |
| | 1 | 238 | | } |
| | | 239 | | |
| | | 240 | | /// <summary> |
| | | 241 | | /// Runs all pending migrations of the requested stage. |
| | | 242 | | /// </summary> |
| | | 243 | | /// <param name="stage">The stage to migrate.</param> |
| | | 244 | | /// <param name="serviceProvider">The service provider handed to the migrations.</param> |
| | | 245 | | /// <returns>A value indicating whether at least one migration has been applied.</returns> |
| | | 246 | | public async Task<bool> MigrateStepAsync(JellyfinMigrationStageTypes stage, IServiceProvider serviceProvider) |
| | | 247 | | { |
| | 81 | 248 | | var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migrate s |
| | 81 | 249 | | ICollection<CodeMigration> migrationStage = (Migrations.FirstOrDefault(e => e.Stage == stage) as ICollection<Cod |
| | | 250 | | |
| | 81 | 251 | | var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); |
| | 81 | 252 | | await using (dbContext.ConfigureAwait(false)) |
| | | 253 | | { |
| | 81 | 254 | | var historyRepository = dbContext.GetService<IHistoryRepository>(); |
| | 81 | 255 | | var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>(); |
| | 81 | 256 | | var completedMigrations = 0; |
| | 81 | 257 | | string? lastMigrationKey = null; |
| | | 258 | | |
| | 1647 | 259 | | while (true) |
| | | 260 | | { |
| | | 261 | | // A single migration can change which migrations still apply: IMigrator.MigrateAsync treats its argumen |
| | | 262 | | // state to end up in, so it reverts everything applied after it, and a reverted migration can take code |
| | | 263 | | // with it (AddNormalizedUsername.Down drops the UpdateNormalizedUsername history row). Anything compute |
| | | 264 | | // that point is stale, so only ever run the next migration and then work out the pending set again. |
| | 1728 | 265 | | var appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false); |
| | 1728 | 266 | | var pendingCodeMigrations = migrationStage |
| | 1728 | 267 | | .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId())) |
| | 1728 | 268 | | .Select(e => (Key: e.BuildCodeMigrationId(), Migration: new InternalCodeMigration(e, serviceProvider |
| | 1728 | 269 | | .ToArray(); |
| | | 270 | | |
| | 1728 | 271 | | (string Key, InternalDatabaseMigration Migration)[] pendingDatabaseMigrations = []; |
| | 1728 | 272 | | if (stage is JellyfinMigrationStageTypes.CoreInitialisation) |
| | | 273 | | { |
| | 1539 | 274 | | pendingDatabaseMigrations = migrationsAssembly.Migrations.Where(f => appliedMigrations.All(e => e.Mi |
| | 1539 | 275 | | .Select(e => (Key: e.Key, Migration: new InternalDatabaseMigration(e, dbContext))) |
| | 1539 | 276 | | .ToArray(); |
| | | 277 | | } |
| | | 278 | | |
| | 1728 | 279 | | (string Key, IInternalMigration Migration)[] pendingMigrations = [.. pendingCodeMigrations, .. pendingDa |
| | 1728 | 280 | | if (pendingMigrations.Length == 0) |
| | | 281 | | { |
| | | 282 | | break; |
| | | 283 | | } |
| | | 284 | | |
| | 1647 | 285 | | if (completedMigrations == 0) |
| | | 286 | | { |
| | 54 | 287 | | logger.LogInformation("There are {Pending} migrations for stage {Stage}.", pendingMigrations.Length, |
| | | 288 | | } |
| | | 289 | | |
| | 1647 | 290 | | var item = pendingMigrations.OrderBy(e => e.Key, StringComparer.Ordinal).First(); |
| | 1647 | 291 | | if (string.Equals(item.Key, lastMigrationKey, StringComparison.Ordinal)) |
| | | 292 | | { |
| | 0 | 293 | | throw new InvalidOperationException($"Migration {item.Key} ran but did not record itself as applied |
| | | 294 | | } |
| | | 295 | | |
| | 1647 | 296 | | lastMigrationKey = item.Key; |
| | | 297 | | |
| | | 298 | | // Surface generic "Running migration X of Y" progress in the always-visible startup UI header. |
| | 1647 | 299 | | SetupServer.ReportActivity(StartupActivity.Migration(completedMigrations + 1, completedMigrations + pend |
| | 1647 | 300 | | var migrationLogger = logger.With(_loggerFactory.CreateLogger(item.Migration.GetType().Name)).BeginGroup |
| | | 301 | | try |
| | | 302 | | { |
| | 1647 | 303 | | migrationLogger.LogInformation("Perform migration {Name}", item.Key); |
| | 1647 | 304 | | await item.Migration.PerformAsync(migrationLogger).ConfigureAwait(false); |
| | 1647 | 305 | | migrationLogger.LogInformation("Migration {Name} was successfully applied", item.Key); |
| | 1647 | 306 | | } |
| | 0 | 307 | | catch (Exception ex) |
| | | 308 | | { |
| | 0 | 309 | | migrationLogger.LogCritical("Error: {Error}", ex.Message); |
| | 0 | 310 | | migrationLogger.LogError(ex, "Migration {Name} failed", item.Key); |
| | | 311 | | |
| | 0 | 312 | | if (_backupKey != default && _backupService is not null && _jellyfinDatabaseProvider is not null) |
| | | 313 | | { |
| | 0 | 314 | | if (_backupKey.LibraryDb is not null) |
| | | 315 | | { |
| | 0 | 316 | | migrationLogger.LogInformation("Attempt to rollback librarydb."); |
| | | 317 | | try |
| | | 318 | | { |
| | 0 | 319 | | var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename); |
| | 0 | 320 | | File.Move(_backupKey.LibraryDb, libraryDbPath, true); |
| | 0 | 321 | | } |
| | 0 | 322 | | catch (Exception inner) |
| | | 323 | | { |
| | 0 | 324 | | migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual interventio |
| | 0 | 325 | | } |
| | | 326 | | } |
| | | 327 | | |
| | 0 | 328 | | if (_backupKey.JellyfinDb is not null) |
| | | 329 | | { |
| | 0 | 330 | | migrationLogger.LogInformation("Attempt to rollback JellyfinDb."); |
| | | 331 | | try |
| | | 332 | | { |
| | 0 | 333 | | await _jellyfinDatabaseProvider.RestoreBackupFast(_backupKey.JellyfinDb, CancellationTok |
| | 0 | 334 | | } |
| | 0 | 335 | | catch (Exception inner) |
| | | 336 | | { |
| | 0 | 337 | | migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual interventio |
| | 0 | 338 | | } |
| | | 339 | | } |
| | | 340 | | |
| | 0 | 341 | | if (_backupKey.FullBackup is not null) |
| | | 342 | | { |
| | 0 | 343 | | migrationLogger.LogInformation("Attempt to rollback from backup."); |
| | | 344 | | try |
| | | 345 | | { |
| | 0 | 346 | | await _backupService.RestoreBackupAsync(_backupKey.FullBackup.Path).ConfigureAwait(false |
| | 0 | 347 | | } |
| | 0 | 348 | | catch (Exception inner) |
| | | 349 | | { |
| | 0 | 350 | | migrationLogger.LogCritical(inner, "Could not rollback from backup {Backup}. Manual inte |
| | 0 | 351 | | } |
| | | 352 | | } |
| | | 353 | | } |
| | | 354 | | |
| | 0 | 355 | | throw; |
| | | 356 | | } |
| | | 357 | | |
| | 1647 | 358 | | completedMigrations++; |
| | 1647 | 359 | | } |
| | | 360 | | |
| | 81 | 361 | | return completedMigrations > 0; |
| | | 362 | | } |
| | 81 | 363 | | } |
| | | 364 | | |
| | | 365 | | private static string GetJellyfinVersion() |
| | | 366 | | { |
| | 1411 | 367 | | return Assembly.GetEntryAssembly()!.GetName().Version!.ToString(); |
| | | 368 | | } |
| | | 369 | | |
| | | 370 | | public async Task CleanupSystemAfterMigration(ILogger logger) |
| | | 371 | | { |
| | 0 | 372 | | if (_backupKey != default) |
| | | 373 | | { |
| | 0 | 374 | | if (_backupKey.LibraryDb is not null) |
| | | 375 | | { |
| | 0 | 376 | | logger.LogInformation("Attempt to cleanup librarydb backup."); |
| | | 377 | | try |
| | | 378 | | { |
| | 0 | 379 | | File.Delete(_backupKey.LibraryDb); |
| | 0 | 380 | | } |
| | 0 | 381 | | catch (Exception inner) |
| | | 382 | | { |
| | 0 | 383 | | logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.LibraryDb); |
| | 0 | 384 | | } |
| | | 385 | | } |
| | | 386 | | |
| | 0 | 387 | | if (_backupKey.JellyfinDb is not null && _jellyfinDatabaseProvider is not null) |
| | | 388 | | { |
| | 0 | 389 | | logger.LogInformation("Attempt to cleanup JellyfinDb backup."); |
| | | 390 | | try |
| | | 391 | | { |
| | 0 | 392 | | await _jellyfinDatabaseProvider.DeleteBackup(_backupKey.JellyfinDb).ConfigureAwait(false); |
| | 0 | 393 | | } |
| | 0 | 394 | | catch (Exception inner) |
| | | 395 | | { |
| | 0 | 396 | | logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.JellyfinDb); |
| | 0 | 397 | | } |
| | | 398 | | } |
| | | 399 | | |
| | 0 | 400 | | if (_backupKey.FullBackup is not null) |
| | | 401 | | { |
| | 0 | 402 | | logger.LogInformation("Attempt to cleanup from migration backup."); |
| | | 403 | | try |
| | | 404 | | { |
| | 0 | 405 | | File.Delete(_backupKey.FullBackup.Path); |
| | 0 | 406 | | } |
| | 0 | 407 | | catch (Exception inner) |
| | | 408 | | { |
| | 0 | 409 | | logger.LogCritical(inner, "Could not cleanup backup {Backup}.", _backupKey.FullBackup.Path); |
| | 0 | 410 | | } |
| | | 411 | | } |
| | | 412 | | } |
| | 0 | 413 | | } |
| | | 414 | | |
| | | 415 | | public async Task PrepareSystemForMigration(ILogger logger) |
| | | 416 | | { |
| | 0 | 417 | | logger.LogInformation("Prepare system for possible migrations"); |
| | | 418 | | JellyfinMigrationBackupAttribute backupInstruction; |
| | | 419 | | IReadOnlyList<HistoryRow> appliedMigrations; |
| | 0 | 420 | | var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); |
| | 0 | 421 | | await using (dbContext.ConfigureAwait(false)) |
| | | 422 | | { |
| | 0 | 423 | | var historyRepository = dbContext.GetService<IHistoryRepository>(); |
| | 0 | 424 | | var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>(); |
| | 0 | 425 | | appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false); |
| | 0 | 426 | | backupInstruction = new JellyfinMigrationBackupAttribute() |
| | 0 | 427 | | { |
| | 0 | 428 | | JellyfinDb = migrationsAssembly.Migrations.Any(f => appliedMigrations.All(e => e.MigrationId != f.Key)) |
| | 0 | 429 | | }; |
| | 0 | 430 | | } |
| | | 431 | | |
| | 0 | 432 | | backupInstruction = Migrations.SelectMany(e => e) |
| | 0 | 433 | | .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId())) |
| | 0 | 434 | | .Select(e => e.BackupRequirements) |
| | 0 | 435 | | .Where(e => e is not null) |
| | 0 | 436 | | .Aggregate(backupInstruction, MergeBackupAttributes!); |
| | | 437 | | |
| | 0 | 438 | | if (backupInstruction.LegacyLibraryDb) |
| | | 439 | | { |
| | 0 | 440 | | logger.LogInformation("A migration will attempt to modify the library.db, will attempt to backup the file no |
| | | 441 | | // for legacy migrations that still operates on the library.db |
| | 0 | 442 | | var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename); |
| | 0 | 443 | | if (File.Exists(libraryDbPath)) |
| | | 444 | | { |
| | 0 | 445 | | for (int i = 1; ; i++) |
| | | 446 | | { |
| | 0 | 447 | | var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", libraryDbPath, i); |
| | 0 | 448 | | if (!File.Exists(bakPath)) |
| | | 449 | | { |
| | | 450 | | try |
| | | 451 | | { |
| | 0 | 452 | | logger.LogInformation("Backing up {Library} to {BackupPath}", DbFilename, bakPath); |
| | 0 | 453 | | File.Copy(libraryDbPath, bakPath); |
| | 0 | 454 | | _backupKey = (bakPath, _backupKey.JellyfinDb, _backupKey.FullBackup); |
| | 0 | 455 | | logger.LogInformation("{Library} backed up to {BackupPath}", DbFilename, bakPath); |
| | 0 | 456 | | break; |
| | | 457 | | } |
| | 0 | 458 | | catch (Exception ex) |
| | | 459 | | { |
| | 0 | 460 | | logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, ba |
| | 0 | 461 | | throw; |
| | | 462 | | } |
| | | 463 | | } |
| | | 464 | | } |
| | | 465 | | |
| | 0 | 466 | | logger.LogInformation("{Library} has been backed up as {BackupPath}", DbFilename, _backupKey.LibraryDb); |
| | | 467 | | } |
| | | 468 | | else |
| | | 469 | | { |
| | 0 | 470 | | logger.LogError("Cannot make a backup of {Library} at path {BackupPath} because file could not be found |
| | | 471 | | } |
| | | 472 | | } |
| | | 473 | | |
| | 0 | 474 | | if (backupInstruction.JellyfinDb && _jellyfinDatabaseProvider is not null) |
| | | 475 | | { |
| | 0 | 476 | | logger.LogInformation("A migration will attempt to modify the jellyfin.db, will attempt to backup the file n |
| | 0 | 477 | | _backupKey = (_backupKey.LibraryDb, await _jellyfinDatabaseProvider.MigrationBackupFast(CancellationToken.No |
| | 0 | 478 | | logger.LogInformation("Jellyfin database has been backed up as {BackupPath}", _backupKey.JellyfinDb); |
| | | 479 | | } |
| | | 480 | | |
| | 0 | 481 | | if (_backupService is not null && (backupInstruction.Metadata || backupInstruction.Subtitles || backupInstructio |
| | | 482 | | { |
| | 0 | 483 | | logger.LogInformation("A migration will attempt to modify system resources. Will attempt to create backup no |
| | 0 | 484 | | _backupKey = (_backupKey.LibraryDb, _backupKey.JellyfinDb, await _backupService.CreateBackupAsync(new Backup |
| | 0 | 485 | | { |
| | 0 | 486 | | Metadata = backupInstruction.Metadata, |
| | 0 | 487 | | Subtitles = backupInstruction.Subtitles, |
| | 0 | 488 | | Trickplay = backupInstruction.Trickplay, |
| | 0 | 489 | | Database = false // database backups are explicitly handled by the provider itself as the backup service |
| | 0 | 490 | | }).ConfigureAwait(false)); |
| | 0 | 491 | | logger.LogInformation("Pre-Migration backup successfully created as {BackupKey}", _backupKey.FullBackup.Path |
| | | 492 | | } |
| | 0 | 493 | | } |
| | | 494 | | |
| | | 495 | | private static JellyfinMigrationBackupAttribute MergeBackupAttributes(JellyfinMigrationBackupAttribute left, Jellyfi |
| | | 496 | | { |
| | 0 | 497 | | return new JellyfinMigrationBackupAttribute() |
| | 0 | 498 | | { |
| | 0 | 499 | | JellyfinDb = left!.JellyfinDb || right!.JellyfinDb, |
| | 0 | 500 | | LegacyLibraryDb = left.LegacyLibraryDb || right!.LegacyLibraryDb, |
| | 0 | 501 | | Metadata = left.Metadata || right!.Metadata, |
| | 0 | 502 | | Subtitles = left.Subtitles || right!.Subtitles, |
| | 0 | 503 | | Trickplay = left.Trickplay || right!.Trickplay |
| | 0 | 504 | | }; |
| | | 505 | | } |
| | | 506 | | |
| | | 507 | | private class InternalCodeMigration : IInternalMigration |
| | | 508 | | { |
| | | 509 | | private readonly CodeMigration _codeMigration; |
| | | 510 | | private readonly IServiceProvider _serviceProvider; |
| | | 511 | | private JellyfinDbContext _dbContext; |
| | | 512 | | |
| | | 513 | | public InternalCodeMigration(CodeMigration codeMigration, IServiceProvider serviceProvider, JellyfinDbContext db |
| | | 514 | | { |
| | 405 | 515 | | _codeMigration = codeMigration; |
| | 405 | 516 | | _serviceProvider = serviceProvider; |
| | 405 | 517 | | _dbContext = dbContext; |
| | 405 | 518 | | } |
| | | 519 | | |
| | | 520 | | public async Task PerformAsync(IStartupLogger logger) |
| | | 521 | | { |
| | 135 | 522 | | await _codeMigration.Perform(_serviceProvider, logger, CancellationToken.None).ConfigureAwait(false); |
| | | 523 | | |
| | 135 | 524 | | var historyRepository = _dbContext.GetService<IHistoryRepository>(); |
| | 135 | 525 | | var createScript = historyRepository.GetInsertScript(new HistoryRow(_codeMigration.BuildCodeMigrationId(), G |
| | 135 | 526 | | await _dbContext.Database.ExecuteSqlRawAsync(createScript).ConfigureAwait(false); |
| | 135 | 527 | | } |
| | | 528 | | } |
| | | 529 | | |
| | | 530 | | private class InternalDatabaseMigration : IInternalMigration |
| | | 531 | | { |
| | | 532 | | private readonly JellyfinDbContext _jellyfinDbContext; |
| | | 533 | | private KeyValuePair<string, TypeInfo> _databaseMigrationInfo; |
| | | 534 | | |
| | | 535 | | public InternalDatabaseMigration(KeyValuePair<string, TypeInfo> databaseMigrationInfo, JellyfinDbContext jellyfi |
| | | 536 | | { |
| | 43092 | 537 | | _databaseMigrationInfo = databaseMigrationInfo; |
| | 43092 | 538 | | _jellyfinDbContext = jellyfinDbContext; |
| | 43092 | 539 | | } |
| | | 540 | | |
| | | 541 | | public async Task PerformAsync(IStartupLogger logger) |
| | | 542 | | { |
| | 1512 | 543 | | var migrator = _jellyfinDbContext.GetService<IMigrator>(); |
| | 1512 | 544 | | await migrator.MigrateAsync(_databaseMigrationInfo.Key).ConfigureAwait(false); |
| | 1512 | 545 | | } |
| | | 546 | | } |
| | | 547 | | } |