MigrationRunner.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Emby.Server.Implementations;
  8. using Emby.Server.Implementations.Serialization;
  9. using Jellyfin.Database.Implementations;
  10. using Jellyfin.Server.Implementations;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Model.Configuration;
  13. using Microsoft.EntityFrameworkCore.Storage;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using Microsoft.Extensions.Logging;
  16. namespace Jellyfin.Server.Migrations
  17. {
  18. /// <summary>
  19. /// The class that knows which migrations to apply and how to apply them.
  20. /// </summary>
  21. public sealed class MigrationRunner
  22. {
  23. /// <summary>
  24. /// The list of known pre-startup migrations, in order of applicability.
  25. /// </summary>
  26. private static readonly Type[] _preStartupMigrationTypes =
  27. {
  28. typeof(PreStartupRoutines.CreateNetworkConfiguration),
  29. typeof(PreStartupRoutines.MigrateMusicBrainzTimeout),
  30. typeof(PreStartupRoutines.MigrateNetworkConfiguration),
  31. typeof(PreStartupRoutines.MigrateEncodingOptions)
  32. };
  33. /// <summary>
  34. /// The list of known migrations, in order of applicability.
  35. /// </summary>
  36. private static readonly Type[] _migrationTypes =
  37. {
  38. typeof(Routines.DisableTranscodingThrottling),
  39. typeof(Routines.CreateUserLoggingConfigFile),
  40. typeof(Routines.MigrateActivityLogDb),
  41. typeof(Routines.RemoveDuplicateExtras),
  42. typeof(Routines.AddDefaultPluginRepository),
  43. typeof(Routines.MigrateUserDb),
  44. typeof(Routines.ReaddDefaultPluginRepository),
  45. typeof(Routines.MigrateDisplayPreferencesDb),
  46. typeof(Routines.RemoveDownloadImagesInAdvance),
  47. typeof(Routines.MigrateAuthenticationDb),
  48. typeof(Routines.FixPlaylistOwner),
  49. typeof(Routines.MigrateRatingLevels),
  50. typeof(Routines.AddDefaultCastReceivers),
  51. typeof(Routines.UpdateDefaultPluginRepository),
  52. typeof(Routines.FixAudioData),
  53. typeof(Routines.MoveTrickplayFiles),
  54. typeof(Routines.RemoveDuplicatePlaylistChildren),
  55. typeof(Routines.MigrateLibraryDb),
  56. };
  57. /// <summary>
  58. /// Run all needed migrations.
  59. /// </summary>
  60. /// <param name="host">CoreAppHost that hosts current version.</param>
  61. /// <param name="loggerFactory">Factory for making the logger.</param>
  62. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  63. public static async Task Run(CoreAppHost host, ILoggerFactory loggerFactory)
  64. {
  65. var logger = loggerFactory.CreateLogger<MigrationRunner>();
  66. var migrations = _migrationTypes
  67. .Select(m => ActivatorUtilities.CreateInstance(host.ServiceProvider, m))
  68. .OfType<IMigrationRoutine>()
  69. .ToArray();
  70. var migrationOptions = host.ConfigurationManager.GetConfiguration<MigrationOptions>(MigrationsListStore.StoreKey);
  71. HandleStartupWizardCondition(migrations, migrationOptions, host.ConfigurationManager.Configuration.IsStartupWizardCompleted, logger);
  72. await PerformMigrations(migrations, migrationOptions, options => host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, options), logger, host.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>())
  73. .ConfigureAwait(false);
  74. }
  75. /// <summary>
  76. /// Run all needed pre-startup migrations.
  77. /// </summary>
  78. /// <param name="appPaths">Application paths.</param>
  79. /// <param name="loggerFactory">Factory for making the logger.</param>
  80. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  81. public static async Task RunPreStartup(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory)
  82. {
  83. var logger = loggerFactory.CreateLogger<MigrationRunner>();
  84. var migrations = _preStartupMigrationTypes
  85. .Select(m => Activator.CreateInstance(m, appPaths, loggerFactory))
  86. .OfType<IMigrationRoutine>()
  87. .ToArray();
  88. var xmlSerializer = new MyXmlSerializer();
  89. var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, MigrationsListStore.StoreKey.ToLowerInvariant() + ".xml");
  90. var migrationOptions = File.Exists(migrationConfigPath)
  91. ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
  92. : new MigrationOptions();
  93. // We have to deserialize it manually since the configuration manager may overwrite it
  94. var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
  95. ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigurationFilePath)!
  96. : new ServerConfiguration();
  97. HandleStartupWizardCondition(migrations, migrationOptions, serverConfig.IsStartupWizardCompleted, logger);
  98. await PerformMigrations(migrations, migrationOptions, options => xmlSerializer.SerializeToFile(options, migrationConfigPath), logger, null).ConfigureAwait(false);
  99. }
  100. private static void HandleStartupWizardCondition(IEnumerable<IMigrationRoutine> migrations, MigrationOptions migrationOptions, bool isStartWizardCompleted, ILogger logger)
  101. {
  102. if (isStartWizardCompleted)
  103. {
  104. return;
  105. }
  106. // If startup wizard is not finished, this is a fresh install.
  107. var onlyOldInstalls = migrations.Where(m => !m.PerformOnNewInstall).ToArray();
  108. logger.LogInformation("Marking following migrations as applied because this is a fresh install: {@OnlyOldInstalls}", onlyOldInstalls.Select(m => m.Name));
  109. migrationOptions.Applied.AddRange(onlyOldInstalls.Select(m => (m.Id, m.Name)));
  110. }
  111. private static async Task PerformMigrations(
  112. IMigrationRoutine[] migrations,
  113. MigrationOptions migrationOptions,
  114. Action<MigrationOptions> saveConfiguration,
  115. ILogger logger,
  116. IJellyfinDatabaseProvider? jellyfinDatabaseProvider)
  117. {
  118. // save already applied migrations, and skip them thereafter
  119. saveConfiguration(migrationOptions);
  120. var appliedMigrationIds = migrationOptions.Applied.Select(m => m.Id).ToHashSet();
  121. var migrationsToBeApplied = migrations.Where(e => !appliedMigrationIds.Contains(e.Id)).ToArray();
  122. string? migrationKey = null;
  123. if (jellyfinDatabaseProvider is not null && migrationsToBeApplied.Any(f => f is IDatabaseMigrationRoutine))
  124. {
  125. logger.LogInformation("Performing database backup");
  126. try
  127. {
  128. migrationKey = await jellyfinDatabaseProvider.MigrationBackupFast(CancellationToken.None).ConfigureAwait(false);
  129. logger.LogInformation("Database backup with key '{BackupKey}' has been successfully created.", migrationKey);
  130. }
  131. catch (NotImplementedException)
  132. {
  133. logger.LogWarning("Could not perform backup of database before migration because provider does not support it");
  134. }
  135. }
  136. try
  137. {
  138. foreach (var migrationRoutine in migrationsToBeApplied)
  139. {
  140. logger.LogInformation("Applying migration '{Name}'", migrationRoutine.Name);
  141. try
  142. {
  143. migrationRoutine.Perform();
  144. }
  145. catch (Exception ex)
  146. {
  147. logger.LogError(ex, "Could not apply migration '{Name}'", migrationRoutine.Name);
  148. throw;
  149. }
  150. // Mark the migration as completed
  151. logger.LogInformation("Migration '{Name}' applied successfully", migrationRoutine.Name);
  152. migrationOptions.Applied.Add((migrationRoutine.Id, migrationRoutine.Name));
  153. saveConfiguration(migrationOptions);
  154. logger.LogDebug("Migration '{Name}' marked as applied in configuration.", migrationRoutine.Name);
  155. }
  156. }
  157. catch (System.Exception) when (migrationKey is not null && jellyfinDatabaseProvider is not null)
  158. {
  159. logger.LogInformation("Rollback on database as migration reported failure.");
  160. await jellyfinDatabaseProvider.RestoreBackupFast(migrationKey, CancellationToken.None).ConfigureAwait(false);
  161. throw;
  162. }
  163. }
  164. }
  165. }