MigrationRunner.cs 6.3 KB

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