MigrationRunner.cs 9.0 KB

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