MigrationRunner.cs 8.9 KB

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