BackupService.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Text.Json;
  7. using System.Text.Json.Nodes;
  8. using System.Text.Json.Serialization;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Database.Implementations;
  12. using Jellyfin.Server.Implementations.StorageHelpers;
  13. using Jellyfin.Server.Implementations.SystemBackupService;
  14. using MediaBrowser.Controller;
  15. using MediaBrowser.Controller.SystemBackupService;
  16. using Microsoft.EntityFrameworkCore;
  17. using Microsoft.EntityFrameworkCore.Infrastructure;
  18. using Microsoft.EntityFrameworkCore.Migrations;
  19. using Microsoft.Extensions.Hosting;
  20. using Microsoft.Extensions.Logging;
  21. namespace Jellyfin.Server.Implementations.FullSystemBackup;
  22. /// <summary>
  23. /// Contains methods for creating and restoring backups.
  24. /// </summary>
  25. public class BackupService : IBackupService
  26. {
  27. private const string ManifestEntryName = "manifest.json";
  28. private readonly ILogger<BackupService> _logger;
  29. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  30. private readonly IServerApplicationHost _applicationHost;
  31. private readonly IServerApplicationPaths _applicationPaths;
  32. private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider;
  33. private readonly IHostApplicationLifetime _hostApplicationLifetime;
  34. private static readonly JsonSerializerOptions _serializerSettings = new JsonSerializerOptions(JsonSerializerDefaults.General)
  35. {
  36. AllowTrailingCommas = true,
  37. ReferenceHandler = ReferenceHandler.IgnoreCycles,
  38. };
  39. private readonly Version _backupEngineVersion = Version.Parse("0.2.0");
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="BackupService"/> class.
  42. /// </summary>
  43. /// <param name="logger">A logger.</param>
  44. /// <param name="dbProvider">A Database Factory.</param>
  45. /// <param name="applicationHost">The Application host.</param>
  46. /// <param name="applicationPaths">The application paths.</param>
  47. /// <param name="jellyfinDatabaseProvider">The Jellyfin database Provider in use.</param>
  48. /// <param name="applicationLifetime">The SystemManager.</param>
  49. public BackupService(
  50. ILogger<BackupService> logger,
  51. IDbContextFactory<JellyfinDbContext> dbProvider,
  52. IServerApplicationHost applicationHost,
  53. IServerApplicationPaths applicationPaths,
  54. IJellyfinDatabaseProvider jellyfinDatabaseProvider,
  55. IHostApplicationLifetime applicationLifetime)
  56. {
  57. _logger = logger;
  58. _dbProvider = dbProvider;
  59. _applicationHost = applicationHost;
  60. _applicationPaths = applicationPaths;
  61. _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
  62. _hostApplicationLifetime = applicationLifetime;
  63. }
  64. /// <inheritdoc/>
  65. public void ScheduleRestoreAndRestartServer(string archivePath)
  66. {
  67. _applicationHost.RestoreBackupPath = archivePath;
  68. _applicationHost.ShouldRestart = true;
  69. _applicationHost.NotifyPendingRestart();
  70. _ = Task.Run(async () =>
  71. {
  72. await Task.Delay(500).ConfigureAwait(false);
  73. _hostApplicationLifetime.StopApplication();
  74. });
  75. }
  76. /// <inheritdoc/>
  77. public async Task RestoreBackupAsync(string archivePath)
  78. {
  79. _logger.LogWarning("Begin restoring system to {BackupArchive}", archivePath); // Info isn't cutting it
  80. if (!File.Exists(archivePath))
  81. {
  82. throw new FileNotFoundException($"Requested backup file '{archivePath}' does not exist.");
  83. }
  84. StorageHelper.TestCommonPathsForStorageCapacity(_applicationPaths, _logger);
  85. var fileStream = File.OpenRead(archivePath);
  86. await using (fileStream.ConfigureAwait(false))
  87. {
  88. using var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read, false);
  89. var zipArchiveEntry = zipArchive.GetEntry(ManifestEntryName);
  90. if (zipArchiveEntry is null)
  91. {
  92. throw new NotSupportedException($"The loaded archive '{archivePath}' does not appear to be a Jellyfin backup as its missing the '{ManifestEntryName}'.");
  93. }
  94. BackupManifest? manifest;
  95. var manifestStream = zipArchiveEntry.Open();
  96. await using (manifestStream.ConfigureAwait(false))
  97. {
  98. manifest = await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).ConfigureAwait(false);
  99. }
  100. if (manifest!.ServerVersion > _applicationHost.ApplicationVersion) // newer versions of Jellyfin should be able to load older versions as we have migrations.
  101. {
  102. throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jellyfin ({manifest.ServerVersion}) and cannot be loaded in this version.");
  103. }
  104. if (!TestBackupVersionCompatibility(manifest.BackupEngineVersion))
  105. {
  106. throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jellyfin ({manifest.ServerVersion}) and cannot be loaded in this version.");
  107. }
  108. void CopyDirectory(string source, string target)
  109. {
  110. var fullSourcePath = NormalizePathSeparator(Path.GetFullPath(source) + Path.DirectorySeparatorChar);
  111. var fullTargetRoot = Path.GetFullPath(target) + Path.DirectorySeparatorChar;
  112. foreach (var item in zipArchive.Entries)
  113. {
  114. var sourcePath = NormalizePathSeparator(Path.GetFullPath(item.FullName));
  115. var targetPath = Path.GetFullPath(Path.Combine(target, Path.GetRelativePath(source, item.FullName)));
  116. if (!sourcePath.StartsWith(fullSourcePath, StringComparison.Ordinal)
  117. || !targetPath.StartsWith(fullTargetRoot, StringComparison.Ordinal))
  118. {
  119. continue;
  120. }
  121. _logger.LogInformation("Restore and override {File}", targetPath);
  122. Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!);
  123. item.ExtractToFile(targetPath, overwrite: true);
  124. }
  125. }
  126. CopyDirectory("Config", _applicationPaths.ConfigurationDirectoryPath);
  127. CopyDirectory("Data", _applicationPaths.DataPath);
  128. CopyDirectory("Root", _applicationPaths.RootFolderPath);
  129. if (manifest.Options.Database)
  130. {
  131. _logger.LogInformation("Begin restoring Database");
  132. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  133. await using (dbContext.ConfigureAwait(false))
  134. {
  135. // restore migration history manually
  136. var historyEntry = zipArchive.GetEntry(NormalizePathSeparator(Path.Combine("Database", $"{nameof(HistoryRow)}.json")));
  137. if (historyEntry is null)
  138. {
  139. _logger.LogInformation("No backup of the history table in archive. This is required for Jellyfin operation");
  140. throw new InvalidOperationException("Cannot restore backup that has no History data.");
  141. }
  142. HistoryRow[] historyEntries;
  143. var historyArchive = historyEntry.Open();
  144. await using (historyArchive.ConfigureAwait(false))
  145. {
  146. historyEntries = await JsonSerializer.DeserializeAsync<HistoryRow[]>(historyArchive).ConfigureAwait(false) ??
  147. throw new InvalidOperationException("Cannot restore backup that has no History data.");
  148. }
  149. var historyRepository = dbContext.GetService<IHistoryRepository>();
  150. await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
  151. foreach (var item in await historyRepository.GetAppliedMigrationsAsync(CancellationToken.None).ConfigureAwait(false))
  152. {
  153. var insertScript = historyRepository.GetDeleteScript(item.MigrationId);
  154. await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
  155. }
  156. foreach (var item in historyEntries)
  157. {
  158. var insertScript = historyRepository.GetInsertScript(item);
  159. await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
  160. }
  161. dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
  162. var entityTypes = typeof(JellyfinDbContext).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  163. .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
  164. .Select(e => (Type: e, Set: e.GetValue(dbContext) as IQueryable))
  165. .ToArray();
  166. var tableNames = entityTypes.Select(f => dbContext.Model.FindEntityType(f.Type.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!);
  167. _logger.LogInformation("Begin purging database");
  168. await _jellyfinDatabaseProvider.PurgeDatabase(dbContext, tableNames).ConfigureAwait(false);
  169. _logger.LogInformation("Database Purged");
  170. foreach (var entityType in entityTypes)
  171. {
  172. _logger.LogInformation("Read backup of {Table}", entityType.Type.Name);
  173. var zipEntry = zipArchive.GetEntry(NormalizePathSeparator(Path.Combine("Database", $"{entityType.Type.Name}.json")));
  174. if (zipEntry is null)
  175. {
  176. _logger.LogInformation("No backup of expected table {Table} is present in backup. Continue anyway.", entityType.Type.Name);
  177. continue;
  178. }
  179. var zipEntryStream = zipEntry.Open();
  180. await using (zipEntryStream.ConfigureAwait(false))
  181. {
  182. _logger.LogInformation("Restore backup of {Table}", entityType.Type.Name);
  183. var records = 0;
  184. await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<JsonObject>(zipEntryStream, _serializerSettings).ConfigureAwait(false))
  185. {
  186. var entity = item.Deserialize(entityType.Type.PropertyType.GetGenericArguments()[0]);
  187. if (entity is null)
  188. {
  189. throw new InvalidOperationException($"Cannot deserialize entity '{item}'");
  190. }
  191. try
  192. {
  193. records++;
  194. dbContext.Add(entity);
  195. }
  196. catch (Exception ex)
  197. {
  198. _logger.LogError(ex, "Could not store entity {Entity} continue anyway.", item);
  199. }
  200. }
  201. _logger.LogInformation("Prepared to restore {Number} entries for {Table}", records, entityType.Type.Name);
  202. }
  203. }
  204. _logger.LogInformation("Try restore Database");
  205. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  206. _logger.LogInformation("Restored database.");
  207. }
  208. }
  209. _logger.LogInformation("Restored Jellyfin system from {Date}.", manifest.DateCreated);
  210. }
  211. }
  212. private bool TestBackupVersionCompatibility(Version backupEngineVersion)
  213. {
  214. if (backupEngineVersion == _backupEngineVersion)
  215. {
  216. return true;
  217. }
  218. return false;
  219. }
  220. /// <inheritdoc/>
  221. public async Task<BackupManifestDto> CreateBackupAsync(BackupOptionsDto backupOptions)
  222. {
  223. var manifest = new BackupManifest()
  224. {
  225. DateCreated = DateTime.UtcNow,
  226. ServerVersion = _applicationHost.ApplicationVersion,
  227. DatabaseTables = null!,
  228. BackupEngineVersion = _backupEngineVersion,
  229. Options = Map(backupOptions)
  230. };
  231. await _jellyfinDatabaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false);
  232. var backupFolder = Path.Combine(_applicationPaths.BackupPath);
  233. if (!Directory.Exists(backupFolder))
  234. {
  235. Directory.CreateDirectory(backupFolder);
  236. }
  237. var backupStorageSpace = StorageHelper.GetFreeSpaceOf(_applicationPaths.BackupPath);
  238. const long FiveGigabyte = 5_368_709_115;
  239. if (backupStorageSpace.FreeSpace < FiveGigabyte)
  240. {
  241. throw new InvalidOperationException($"The backup directory '{backupStorageSpace.Path}' does not have at least '{StorageHelper.HumanizeStorageSize(FiveGigabyte)}' free space. Cannot create backup.");
  242. }
  243. var backupPath = Path.Combine(backupFolder, $"jellyfin-backup-{manifest.DateCreated.ToLocalTime():yyyyMMddHHmmss}.zip");
  244. _logger.LogInformation("Attempt to create a new backup at {BackupPath}", backupPath);
  245. var fileStream = File.OpenWrite(backupPath);
  246. await using (fileStream.ConfigureAwait(false))
  247. using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, false))
  248. {
  249. _logger.LogInformation("Start backup process.");
  250. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  251. await using (dbContext.ConfigureAwait(false))
  252. {
  253. dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
  254. static IAsyncEnumerable<object> GetValues(IQueryable dbSet)
  255. {
  256. var method = dbSet.GetType().GetMethod(nameof(DbSet<object>.AsAsyncEnumerable))!;
  257. var enumerable = method.Invoke(dbSet, null)!;
  258. return (IAsyncEnumerable<object>)enumerable;
  259. }
  260. // include the migration history as well
  261. var historyRepository = dbContext.GetService<IHistoryRepository>();
  262. var migrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
  263. ICollection<(Type Type, string SourceName, Func<IAsyncEnumerable<object>> ValueFactory)> entityTypes = [
  264. .. typeof(JellyfinDbContext)
  265. .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  266. .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
  267. .Select(e => (Type: e.PropertyType, dbContext.Model.FindEntityType(e.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!, ValueFactory: new Func<IAsyncEnumerable<object>>(() => GetValues((IQueryable)e.GetValue(dbContext)!)))),
  268. (Type: typeof(HistoryRow), SourceName: nameof(HistoryRow), ValueFactory: () => migrations.ToAsyncEnumerable())
  269. ];
  270. manifest.DatabaseTables = entityTypes.Select(e => e.Type.Name).ToArray();
  271. var transaction = await dbContext.Database.BeginTransactionAsync().ConfigureAwait(false);
  272. await using (transaction.ConfigureAwait(false))
  273. {
  274. _logger.LogInformation("Begin Database backup");
  275. foreach (var entityType in entityTypes)
  276. {
  277. _logger.LogInformation("Begin backup of entity {Table}", entityType.SourceName);
  278. var zipEntry = zipArchive.CreateEntry(NormalizePathSeparator(Path.Combine("Database", $"{entityType.SourceName}.json")));
  279. var entities = 0;
  280. var zipEntryStream = zipEntry.Open();
  281. await using (zipEntryStream.ConfigureAwait(false))
  282. {
  283. var jsonSerializer = new Utf8JsonWriter(zipEntryStream);
  284. await using (jsonSerializer.ConfigureAwait(false))
  285. {
  286. jsonSerializer.WriteStartArray();
  287. var set = entityType.ValueFactory().ConfigureAwait(false);
  288. await foreach (var item in set.ConfigureAwait(false))
  289. {
  290. entities++;
  291. try
  292. {
  293. JsonSerializer.SerializeToDocument(item, _serializerSettings).WriteTo(jsonSerializer);
  294. }
  295. catch (Exception ex)
  296. {
  297. _logger.LogError(ex, "Could not load entity {Entity}", item);
  298. throw;
  299. }
  300. }
  301. jsonSerializer.WriteEndArray();
  302. }
  303. }
  304. _logger.LogInformation("backup of entity {Table} with {Number} created", entityType.Type.Name, entities);
  305. }
  306. }
  307. }
  308. _logger.LogInformation("Backup of folder {Table}", _applicationPaths.ConfigurationDirectoryPath);
  309. foreach (var item in Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.xml", SearchOption.TopDirectoryOnly)
  310. .Union(Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.json", SearchOption.TopDirectoryOnly)))
  311. {
  312. zipArchive.CreateEntryFromFile(item, NormalizePathSeparator(Path.Combine("Config", Path.GetFileName(item))));
  313. }
  314. void CopyDirectory(string source, string target, string filter = "*")
  315. {
  316. if (!Directory.Exists(source))
  317. {
  318. return;
  319. }
  320. _logger.LogInformation("Backup of folder {Table}", source);
  321. foreach (var item in Directory.EnumerateFiles(source, filter, SearchOption.AllDirectories))
  322. {
  323. zipArchive.CreateEntryFromFile(item, NormalizePathSeparator(Path.Combine(target, Path.GetRelativePath(source, item))));
  324. }
  325. }
  326. CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "users"), Path.Combine("Config", "users"));
  327. CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"), Path.Combine("Config", "ScheduledTasks"));
  328. CopyDirectory(Path.Combine(_applicationPaths.RootFolderPath), "Root");
  329. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "collections"), Path.Combine("Data", "collections"));
  330. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "playlists"), Path.Combine("Data", "playlists"));
  331. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"), Path.Combine("Data", "ScheduledTasks"));
  332. if (backupOptions.Subtitles)
  333. {
  334. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "subtitles"), Path.Combine("Data", "subtitles"));
  335. }
  336. if (backupOptions.Trickplay)
  337. {
  338. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "trickplay"), Path.Combine("Data", "trickplay"));
  339. }
  340. if (backupOptions.Metadata)
  341. {
  342. CopyDirectory(Path.Combine(_applicationPaths.InternalMetadataPath), Path.Combine("Data", "metadata"));
  343. }
  344. var manifestStream = zipArchive.CreateEntry(ManifestEntryName).Open();
  345. await using (manifestStream.ConfigureAwait(false))
  346. {
  347. await JsonSerializer.SerializeAsync(manifestStream, manifest).ConfigureAwait(false);
  348. }
  349. }
  350. _logger.LogInformation("Backup created");
  351. return Map(manifest, backupPath);
  352. }
  353. /// <inheritdoc/>
  354. public async Task<BackupManifestDto?> GetBackupManifest(string archivePath)
  355. {
  356. if (!File.Exists(archivePath))
  357. {
  358. return null;
  359. }
  360. BackupManifest? manifest;
  361. try
  362. {
  363. manifest = await GetManifest(archivePath).ConfigureAwait(false);
  364. }
  365. catch (Exception ex)
  366. {
  367. _logger.LogError(ex, "Tried to load archive from {Path} but failed.", archivePath);
  368. return null;
  369. }
  370. if (manifest is null)
  371. {
  372. return null;
  373. }
  374. return Map(manifest, archivePath);
  375. }
  376. /// <inheritdoc/>
  377. public async Task<BackupManifestDto[]> EnumerateBackups()
  378. {
  379. if (!Directory.Exists(_applicationPaths.BackupPath))
  380. {
  381. return [];
  382. }
  383. var archives = Directory.EnumerateFiles(_applicationPaths.BackupPath, "*.zip");
  384. var manifests = new List<BackupManifestDto>();
  385. foreach (var item in archives)
  386. {
  387. try
  388. {
  389. var manifest = await GetManifest(item).ConfigureAwait(false);
  390. if (manifest is null)
  391. {
  392. continue;
  393. }
  394. manifests.Add(Map(manifest, item));
  395. }
  396. catch (Exception ex)
  397. {
  398. _logger.LogError(ex, "Could not load {BackupArchive} path.", item);
  399. }
  400. }
  401. return manifests.ToArray();
  402. }
  403. private static async ValueTask<BackupManifest?> GetManifest(string archivePath)
  404. {
  405. var archiveStream = File.OpenRead(archivePath);
  406. await using (archiveStream.ConfigureAwait(false))
  407. {
  408. using var zipStream = new ZipArchive(archiveStream, ZipArchiveMode.Read);
  409. var manifestEntry = zipStream.GetEntry(ManifestEntryName);
  410. if (manifestEntry is null)
  411. {
  412. return null;
  413. }
  414. var manifestStream = manifestEntry.Open();
  415. await using (manifestStream.ConfigureAwait(false))
  416. {
  417. return await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).ConfigureAwait(false);
  418. }
  419. }
  420. }
  421. private static BackupManifestDto Map(BackupManifest manifest, string path)
  422. {
  423. return new BackupManifestDto()
  424. {
  425. BackupEngineVersion = manifest.BackupEngineVersion,
  426. DateCreated = manifest.DateCreated,
  427. ServerVersion = manifest.ServerVersion,
  428. Path = path,
  429. Options = Map(manifest.Options)
  430. };
  431. }
  432. private static BackupOptionsDto Map(BackupOptions options)
  433. {
  434. return new BackupOptionsDto()
  435. {
  436. Metadata = options.Metadata,
  437. Subtitles = options.Subtitles,
  438. Trickplay = options.Trickplay,
  439. Database = options.Database
  440. };
  441. }
  442. private static BackupOptions Map(BackupOptionsDto options)
  443. {
  444. return new BackupOptions()
  445. {
  446. Metadata = options.Metadata,
  447. Subtitles = options.Subtitles,
  448. Trickplay = options.Trickplay,
  449. Database = options.Database
  450. };
  451. }
  452. /// <summary>
  453. /// Windows is able to handle '/' as a path seperator in zip files
  454. /// but linux isn't able to handle '\' as a path seperator in zip files,
  455. /// So normalize to '/'.
  456. /// </summary>
  457. /// <param name="path">The path to normalize.</param>
  458. /// <returns>The normalized path. </returns>
  459. private static string NormalizePathSeparator(string path)
  460. => path.Replace('\\', '/');
  461. }