MigrationRunner.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Emby.Server.Implementations;
  6. using Emby.Server.Implementations.Serialization;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Logging;
  11. namespace Jellyfin.Server.Migrations
  12. {
  13. /// <summary>
  14. /// The class that knows which migrations to apply and how to apply them.
  15. /// </summary>
  16. public sealed class MigrationRunner
  17. {
  18. /// <summary>
  19. /// The list of known pre-startup migrations, in order of applicability.
  20. /// </summary>
  21. private static readonly Type[] _preStartupMigrationTypes =
  22. {
  23. typeof(PreStartupRoutines.CreateNetworkConfiguration),
  24. typeof(PreStartupRoutines.MigrateMusicBrainzTimeout),
  25. typeof(PreStartupRoutines.MigrateNetworkConfiguration),
  26. typeof(PreStartupRoutines.MigrateEncodingOptions)
  27. };
  28. /// <summary>
  29. /// The list of known migrations, in order of applicability.
  30. /// </summary>
  31. private static readonly Type[] _migrationTypes =
  32. {
  33. typeof(Routines.DisableTranscodingThrottling),
  34. typeof(Routines.CreateUserLoggingConfigFile),
  35. typeof(Routines.MigrateActivityLogDb),
  36. typeof(Routines.RemoveDuplicateExtras),
  37. typeof(Routines.AddDefaultPluginRepository),
  38. typeof(Routines.MigrateUserDb),
  39. typeof(Routines.ReaddDefaultPluginRepository),
  40. typeof(Routines.MigrateDisplayPreferencesDb),
  41. typeof(Routines.RemoveDownloadImagesInAdvance),
  42. typeof(Routines.MigrateAuthenticationDb),
  43. typeof(Routines.FixPlaylistOwner),
  44. typeof(Routines.MigrateRatingLevels),
  45. typeof(Routines.AddDefaultCastReceivers),
  46. typeof(Routines.UpdateDefaultPluginRepository),
  47. typeof(Routines.FixAudioData),
  48. typeof(Routines.MoveTrickplayFiles),
  49. typeof(Routines.RemoveDuplicatePlaylistChildren)
  50. };
  51. private static readonly Guid _downgradeCheckMigration = Guid.Parse("36445464-849f-429f-9ad0-bb130efa0664");
  52. /// <summary>
  53. /// Run all needed migrations.
  54. /// </summary>
  55. /// <param name="host">CoreAppHost that hosts current version.</param>
  56. /// <param name="loggerFactory">Factory for making the logger.</param>
  57. public static void Run(CoreAppHost host, ILoggerFactory loggerFactory)
  58. {
  59. var logger = loggerFactory.CreateLogger<MigrationRunner>();
  60. var migrations = _migrationTypes
  61. .Select(m => ActivatorUtilities.CreateInstance(host.ServiceProvider, m))
  62. .OfType<IMigrationRoutine>()
  63. .ToArray();
  64. var migrationOptions = host.ConfigurationManager.GetConfiguration<MigrationOptions>(MigrationsListStore.StoreKey);
  65. HandleStartupWizardCondition(migrations, migrationOptions, host.ConfigurationManager.Configuration.IsStartupWizardCompleted, logger);
  66. PerformMigrations(migrations, migrationOptions, options => host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, options), logger);
  67. }
  68. /// <summary>
  69. /// Run all needed pre-startup migrations.
  70. /// </summary>
  71. /// <param name="appPaths">Application paths.</param>
  72. /// <param name="loggerFactory">Factory for making the logger.</param>
  73. public static void RunPreStartup(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory)
  74. {
  75. var logger = loggerFactory.CreateLogger<MigrationRunner>();
  76. var migrations = _preStartupMigrationTypes
  77. .Select(m => Activator.CreateInstance(m, appPaths, loggerFactory))
  78. .OfType<IMigrationRoutine>()
  79. .ToArray();
  80. var xmlSerializer = new MyXmlSerializer();
  81. var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, MigrationsListStore.StoreKey.ToLowerInvariant() + ".xml");
  82. var migrationOptions = File.Exists(migrationConfigPath)
  83. ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
  84. : new MigrationOptions();
  85. // 10.10 specific EFCore migration check.
  86. if (migrationOptions.Applied.Any(f => f.Id.Equals(_downgradeCheckMigration)))
  87. {
  88. throw new InvalidOperationException("You cannot downgrade your jellyfin install from the library.db migration.");
  89. }
  90. // We have to deserialize it manually since the configuration manager may overwrite it
  91. var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
  92. ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigurationFilePath)!
  93. : new ServerConfiguration();
  94. HandleStartupWizardCondition(migrations, migrationOptions, serverConfig.IsStartupWizardCompleted, logger);
  95. PerformMigrations(migrations, migrationOptions, options => xmlSerializer.SerializeToFile(options, migrationConfigPath), logger);
  96. }
  97. private static void HandleStartupWizardCondition(IEnumerable<IMigrationRoutine> migrations, MigrationOptions migrationOptions, bool isStartWizardCompleted, ILogger logger)
  98. {
  99. if (isStartWizardCompleted)
  100. {
  101. return;
  102. }
  103. // If startup wizard is not finished, this is a fresh install.
  104. var onlyOldInstalls = migrations.Where(m => !m.PerformOnNewInstall).ToArray();
  105. logger.LogInformation("Marking following migrations as applied because this is a fresh install: {@OnlyOldInstalls}", onlyOldInstalls.Select(m => m.Name));
  106. migrationOptions.Applied.AddRange(onlyOldInstalls.Select(m => (m.Id, m.Name)));
  107. }
  108. private static void PerformMigrations(IMigrationRoutine[] migrations, MigrationOptions migrationOptions, Action<MigrationOptions> saveConfiguration, ILogger logger)
  109. {
  110. // save already applied migrations, and skip them thereafter
  111. saveConfiguration(migrationOptions);
  112. var appliedMigrationIds = migrationOptions.Applied.Select(m => m.Id).ToHashSet();
  113. for (var i = 0; i < migrations.Length; i++)
  114. {
  115. var migrationRoutine = migrations[i];
  116. if (appliedMigrationIds.Contains(migrationRoutine.Id))
  117. {
  118. logger.LogDebug("Skipping migration '{Name}' since it is already applied", migrationRoutine.Name);
  119. continue;
  120. }
  121. logger.LogInformation("Applying migration '{Name}'", migrationRoutine.Name);
  122. try
  123. {
  124. migrationRoutine.Perform();
  125. }
  126. catch (Exception ex)
  127. {
  128. logger.LogError(ex, "Could not apply migration '{Name}'", migrationRoutine.Name);
  129. throw;
  130. }
  131. // Mark the migration as completed
  132. logger.LogInformation("Migration '{Name}' applied successfully", migrationRoutine.Name);
  133. migrationOptions.Applied.Add((migrationRoutine.Id, migrationRoutine.Name));
  134. saveConfiguration(migrationOptions);
  135. logger.LogDebug("Migration '{Name}' marked as applied in configuration.", migrationRoutine.Name);
  136. }
  137. }
  138. }
  139. }