MigrationRunner.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. };
  27. /// <summary>
  28. /// The list of known migrations, in order of applicability.
  29. /// </summary>
  30. private static readonly Type[] _migrationTypes =
  31. {
  32. typeof(Routines.DisableTranscodingThrottling),
  33. typeof(Routines.CreateUserLoggingConfigFile),
  34. typeof(Routines.MigrateActivityLogDb),
  35. typeof(Routines.RemoveDuplicateExtras),
  36. typeof(Routines.AddDefaultPluginRepository),
  37. typeof(Routines.MigrateUserDb),
  38. typeof(Routines.ReaddDefaultPluginRepository),
  39. typeof(Routines.MigrateDisplayPreferencesDb),
  40. typeof(Routines.RemoveDownloadImagesInAdvance),
  41. typeof(Routines.MigrateAuthenticationDb),
  42. typeof(Routines.FixPlaylistOwner),
  43. typeof(Routines.MigrateRatingLevels),
  44. typeof(Routines.AddDefaultCastReceivers),
  45. typeof(Routines.UpdateDefaultPluginRepository)
  46. };
  47. /// <summary>
  48. /// Run all needed migrations.
  49. /// </summary>
  50. /// <param name="host">CoreAppHost that hosts current version.</param>
  51. /// <param name="loggerFactory">Factory for making the logger.</param>
  52. public static void Run(CoreAppHost host, ILoggerFactory loggerFactory)
  53. {
  54. var logger = loggerFactory.CreateLogger<MigrationRunner>();
  55. var migrations = _migrationTypes
  56. .Select(m => ActivatorUtilities.CreateInstance(host.ServiceProvider, m))
  57. .OfType<IMigrationRoutine>()
  58. .ToArray();
  59. var migrationOptions = host.ConfigurationManager.GetConfiguration<MigrationOptions>(MigrationsListStore.StoreKey);
  60. HandleStartupWizardCondition(migrations, migrationOptions, host.ConfigurationManager.Configuration.IsStartupWizardCompleted, logger);
  61. PerformMigrations(migrations, migrationOptions, options => host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, options), logger);
  62. }
  63. /// <summary>
  64. /// Run all needed pre-startup migrations.
  65. /// </summary>
  66. /// <param name="appPaths">Application paths.</param>
  67. /// <param name="loggerFactory">Factory for making the logger.</param>
  68. public static void RunPreStartup(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory)
  69. {
  70. var logger = loggerFactory.CreateLogger<MigrationRunner>();
  71. var migrations = _preStartupMigrationTypes
  72. .Select(m => Activator.CreateInstance(m, appPaths, loggerFactory))
  73. .OfType<IMigrationRoutine>()
  74. .ToArray();
  75. var xmlSerializer = new MyXmlSerializer();
  76. var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, MigrationsListStore.StoreKey.ToLowerInvariant() + ".xml");
  77. var migrationOptions = File.Exists(migrationConfigPath)
  78. ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
  79. : new MigrationOptions();
  80. // We have to deserialize it manually since the configuration manager may overwrite it
  81. var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
  82. ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigurationFilePath)!
  83. : new ServerConfiguration();
  84. HandleStartupWizardCondition(migrations, migrationOptions, serverConfig.IsStartupWizardCompleted, logger);
  85. PerformMigrations(migrations, migrationOptions, options => xmlSerializer.SerializeToFile(options, migrationConfigPath), logger);
  86. }
  87. private static void HandleStartupWizardCondition(IEnumerable<IMigrationRoutine> migrations, MigrationOptions migrationOptions, bool isStartWizardCompleted, ILogger logger)
  88. {
  89. if (isStartWizardCompleted)
  90. {
  91. return;
  92. }
  93. // If startup wizard is not finished, this is a fresh install.
  94. var onlyOldInstalls = migrations.Where(m => !m.PerformOnNewInstall).ToArray();
  95. logger.LogInformation("Marking following migrations as applied because this is a fresh install: {@OnlyOldInstalls}", onlyOldInstalls.Select(m => m.Name));
  96. migrationOptions.Applied.AddRange(onlyOldInstalls.Select(m => (m.Id, m.Name)));
  97. }
  98. private static void PerformMigrations(IMigrationRoutine[] migrations, MigrationOptions migrationOptions, Action<MigrationOptions> saveConfiguration, ILogger logger)
  99. {
  100. // save already applied migrations, and skip them thereafter
  101. saveConfiguration(migrationOptions);
  102. var appliedMigrationIds = migrationOptions.Applied.Select(m => m.Id).ToHashSet();
  103. for (var i = 0; i < migrations.Length; i++)
  104. {
  105. var migrationRoutine = migrations[i];
  106. if (appliedMigrationIds.Contains(migrationRoutine.Id))
  107. {
  108. logger.LogDebug("Skipping migration '{Name}' since it is already applied", migrationRoutine.Name);
  109. continue;
  110. }
  111. logger.LogInformation("Applying migration '{Name}'", migrationRoutine.Name);
  112. try
  113. {
  114. migrationRoutine.Perform();
  115. }
  116. catch (Exception ex)
  117. {
  118. logger.LogError(ex, "Could not apply migration '{Name}'", migrationRoutine.Name);
  119. throw;
  120. }
  121. // Mark the migration as completed
  122. logger.LogInformation("Migration '{Name}' applied successfully", migrationRoutine.Name);
  123. migrationOptions.Applied.Add((migrationRoutine.Id, migrationRoutine.Name));
  124. saveConfiguration(migrationOptions);
  125. logger.LogDebug("Migration '{Name}' marked as applied in configuration.", migrationRoutine.Name);
  126. }
  127. }
  128. }
  129. }