BackupService.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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.1.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. source = Path.GetFullPath(source);
  111. Directory.CreateDirectory(source);
  112. foreach (var item in zipArchive.Entries)
  113. {
  114. var sanitizedSourcePath = Path.GetFullPath(item.FullName.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
  115. if (!sanitizedSourcePath.StartsWith(target, StringComparison.Ordinal))
  116. {
  117. continue;
  118. }
  119. var targetPath = Path.Combine(source, sanitizedSourcePath[target.Length..].Trim('/'));
  120. _logger.LogInformation("Restore and override {File}", targetPath);
  121. item.ExtractToFile(targetPath);
  122. }
  123. }
  124. CopyDirectory(_applicationPaths.ConfigurationDirectoryPath, "Config/");
  125. CopyDirectory(_applicationPaths.DataPath, "Data/");
  126. CopyDirectory(_applicationPaths.RootFolderPath, "Root/");
  127. if (manifest.Options.Database)
  128. {
  129. _logger.LogInformation("Begin restoring Database");
  130. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  131. await using (dbContext.ConfigureAwait(false))
  132. {
  133. // restore migration history manually
  134. var historyEntry = zipArchive.GetEntry($"Database\\{nameof(HistoryRow)}.json");
  135. if (historyEntry is null)
  136. {
  137. _logger.LogInformation("No backup of the history table in archive. This is required for Jellyfin operation");
  138. throw new InvalidOperationException("Cannot restore backup that has no History data.");
  139. }
  140. HistoryRow[] historyEntries;
  141. var historyArchive = historyEntry.Open();
  142. await using (historyArchive.ConfigureAwait(false))
  143. {
  144. historyEntries = await JsonSerializer.DeserializeAsync<HistoryRow[]>(historyArchive).ConfigureAwait(false) ??
  145. throw new InvalidOperationException("Cannot restore backup that has no History data.");
  146. }
  147. var historyRepository = dbContext.GetService<IHistoryRepository>();
  148. await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
  149. foreach (var item in await historyRepository.GetAppliedMigrationsAsync(CancellationToken.None).ConfigureAwait(false))
  150. {
  151. var insertScript = historyRepository.GetDeleteScript(item.MigrationId);
  152. await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
  153. }
  154. foreach (var item in historyEntries)
  155. {
  156. var insertScript = historyRepository.GetInsertScript(item);
  157. await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
  158. }
  159. dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
  160. var entityTypes = typeof(JellyfinDbContext).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  161. .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
  162. .Select(e => (Type: e, Set: e.GetValue(dbContext) as IQueryable))
  163. .ToArray();
  164. var tableNames = entityTypes.Select(f => dbContext.Model.FindEntityType(f.Type.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!);
  165. _logger.LogInformation("Begin purging database");
  166. await _jellyfinDatabaseProvider.PurgeDatabase(dbContext, tableNames).ConfigureAwait(false);
  167. _logger.LogInformation("Database Purged");
  168. foreach (var entityType in entityTypes)
  169. {
  170. _logger.LogInformation("Read backup of {Table}", entityType.Type.Name);
  171. var zipEntry = zipArchive.GetEntry($"Database\\{entityType.Type.Name}.json");
  172. if (zipEntry is null)
  173. {
  174. _logger.LogInformation("No backup of expected table {Table} is present in backup. Continue anyway.", entityType.Type.Name);
  175. continue;
  176. }
  177. var zipEntryStream = zipEntry.Open();
  178. await using (zipEntryStream.ConfigureAwait(false))
  179. {
  180. _logger.LogInformation("Restore backup of {Table}", entityType.Type.Name);
  181. var records = 0;
  182. await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<JsonObject>(zipEntryStream, _serializerSettings).ConfigureAwait(false)!)
  183. {
  184. var entity = item.Deserialize(entityType.Type.PropertyType.GetGenericArguments()[0]);
  185. if (entity is null)
  186. {
  187. throw new InvalidOperationException($"Cannot deserialize entity '{item}'");
  188. }
  189. try
  190. {
  191. records++;
  192. dbContext.Add(entity);
  193. }
  194. catch (Exception ex)
  195. {
  196. _logger.LogError(ex, "Could not store entity {Entity} continue anyway.", item);
  197. }
  198. }
  199. _logger.LogInformation("Prepared to restore {Number} entries for {Table}", records, entityType.Type.Name);
  200. }
  201. }
  202. _logger.LogInformation("Try restore Database");
  203. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  204. _logger.LogInformation("Restored database.");
  205. }
  206. }
  207. _logger.LogInformation("Restored Jellyfin system from {Date}.", manifest.DateCreated);
  208. }
  209. }
  210. private bool TestBackupVersionCompatibility(Version backupEngineVersion)
  211. {
  212. if (backupEngineVersion == _backupEngineVersion)
  213. {
  214. return true;
  215. }
  216. return false;
  217. }
  218. /// <inheritdoc/>
  219. public async Task<BackupManifestDto> CreateBackupAsync(BackupOptionsDto backupOptions)
  220. {
  221. var manifest = new BackupManifest()
  222. {
  223. DateCreated = DateTime.UtcNow,
  224. ServerVersion = _applicationHost.ApplicationVersion,
  225. DatabaseTables = null!,
  226. BackupEngineVersion = _backupEngineVersion,
  227. Options = Map(backupOptions)
  228. };
  229. await _jellyfinDatabaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false);
  230. var backupFolder = Path.Combine(_applicationPaths.BackupPath);
  231. if (!Directory.Exists(backupFolder))
  232. {
  233. Directory.CreateDirectory(backupFolder);
  234. }
  235. var backupStorageSpace = StorageHelper.GetFreeSpaceOf(_applicationPaths.BackupPath);
  236. const long FiveGigabyte = 5_368_709_115;
  237. if (backupStorageSpace.FreeSpace < FiveGigabyte)
  238. {
  239. throw new InvalidOperationException($"The backup directory '{backupStorageSpace.Path}' does not have at least '{StorageHelper.HumanizeStorageSize(FiveGigabyte)}' free space. Cannot create backup.");
  240. }
  241. var backupPath = Path.Combine(backupFolder, $"jellyfin-backup-{manifest.DateCreated.ToLocalTime():yyyyMMddHHmmss}.zip");
  242. _logger.LogInformation("Attempt to create a new backup at {BackupPath}", backupPath);
  243. var fileStream = File.OpenWrite(backupPath);
  244. await using (fileStream.ConfigureAwait(false))
  245. using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, false))
  246. {
  247. _logger.LogInformation("Start backup process.");
  248. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  249. await using (dbContext.ConfigureAwait(false))
  250. {
  251. dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
  252. static IAsyncEnumerable<object> GetValues(IQueryable dbSet, Type type)
  253. {
  254. var method = dbSet.GetType().GetMethod(nameof(DbSet<object>.AsAsyncEnumerable))!;
  255. var enumerable = method.Invoke(dbSet, null)!;
  256. return (IAsyncEnumerable<object>)enumerable;
  257. }
  258. // include the migration history as well
  259. var historyRepository = dbContext.GetService<IHistoryRepository>();
  260. var migrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
  261. ICollection<(Type Type, string SourceName, Func<IAsyncEnumerable<object>> ValueFactory)> entityTypes = [
  262. .. typeof(JellyfinDbContext)
  263. .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  264. .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
  265. .Select(e => (Type: e.PropertyType, dbContext.Model.FindEntityType(e.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!, ValueFactory: new Func<IAsyncEnumerable<object>>(() => GetValues((IQueryable)e.GetValue(dbContext)!, e.PropertyType)))),
  266. (Type: typeof(HistoryRow), SourceName: nameof(HistoryRow), ValueFactory: new Func<IAsyncEnumerable<object>>(() => migrations.ToAsyncEnumerable()))
  267. ];
  268. manifest.DatabaseTables = entityTypes.Select(e => e.Type.Name).ToArray();
  269. var transaction = await dbContext.Database.BeginTransactionAsync().ConfigureAwait(false);
  270. await using (transaction.ConfigureAwait(false))
  271. {
  272. _logger.LogInformation("Begin Database backup");
  273. foreach (var entityType in entityTypes)
  274. {
  275. _logger.LogInformation("Begin backup of entity {Table}", entityType.SourceName);
  276. var zipEntry = zipArchive.CreateEntry($"Database\\{entityType.SourceName}.json");
  277. var entities = 0;
  278. var zipEntryStream = zipEntry.Open();
  279. await using (zipEntryStream.ConfigureAwait(false))
  280. {
  281. var jsonSerializer = new Utf8JsonWriter(zipEntryStream);
  282. await using (jsonSerializer.ConfigureAwait(false))
  283. {
  284. jsonSerializer.WriteStartArray();
  285. var set = entityType.ValueFactory().ConfigureAwait(false);
  286. await foreach (var item in set.ConfigureAwait(false))
  287. {
  288. entities++;
  289. try
  290. {
  291. JsonSerializer.SerializeToDocument(item, _serializerSettings).WriteTo(jsonSerializer);
  292. }
  293. catch (Exception ex)
  294. {
  295. _logger.LogError(ex, "Could not load entity {Entity}", item);
  296. throw;
  297. }
  298. }
  299. jsonSerializer.WriteEndArray();
  300. }
  301. }
  302. _logger.LogInformation("backup of entity {Table} with {Number} created", entityType.Type.Name, entities);
  303. }
  304. }
  305. }
  306. _logger.LogInformation("Backup of folder {Table}", _applicationPaths.ConfigurationDirectoryPath);
  307. foreach (var item in Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.xml", SearchOption.TopDirectoryOnly)
  308. .Union(Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.json", SearchOption.TopDirectoryOnly)))
  309. {
  310. zipArchive.CreateEntryFromFile(item, Path.Combine("Config", Path.GetFileName(item)));
  311. }
  312. void CopyDirectory(string source, string target, string filter = "*")
  313. {
  314. if (!Directory.Exists(source))
  315. {
  316. return;
  317. }
  318. _logger.LogInformation("Backup of folder {Table}", source);
  319. foreach (var item in Directory.EnumerateFiles(source, filter, SearchOption.AllDirectories))
  320. {
  321. zipArchive.CreateEntryFromFile(item, Path.Combine(target, item[..source.Length].Trim('\\')));
  322. }
  323. }
  324. CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "users"), Path.Combine("Config", "users"));
  325. CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"), Path.Combine("Config", "ScheduledTasks"));
  326. CopyDirectory(Path.Combine(_applicationPaths.RootFolderPath), "Root");
  327. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "collections"), Path.Combine("Data", "collections"));
  328. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "playlists"), Path.Combine("Data", "playlists"));
  329. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"), Path.Combine("Data", "ScheduledTasks"));
  330. if (backupOptions.Subtitles)
  331. {
  332. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "subtitles"), Path.Combine("Data", "subtitles"));
  333. }
  334. if (backupOptions.Trickplay)
  335. {
  336. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "trickplay"), Path.Combine("Data", "trickplay"));
  337. }
  338. if (backupOptions.Metadata)
  339. {
  340. CopyDirectory(Path.Combine(_applicationPaths.InternalMetadataPath), Path.Combine("Data", "metadata"));
  341. }
  342. var manifestStream = zipArchive.CreateEntry(ManifestEntryName).Open();
  343. await using (manifestStream.ConfigureAwait(false))
  344. {
  345. await JsonSerializer.SerializeAsync(manifestStream, manifest).ConfigureAwait(false);
  346. }
  347. }
  348. _logger.LogInformation("Backup created");
  349. return Map(manifest, backupPath);
  350. }
  351. /// <inheritdoc/>
  352. public async Task<BackupManifestDto?> GetBackupManifest(string archivePath)
  353. {
  354. if (!File.Exists(archivePath))
  355. {
  356. return null;
  357. }
  358. BackupManifest? manifest;
  359. try
  360. {
  361. manifest = await GetManifest(archivePath).ConfigureAwait(false);
  362. }
  363. catch (Exception ex)
  364. {
  365. _logger.LogError(ex, "Tried to load archive from {Path} but failed.", archivePath);
  366. return null;
  367. }
  368. if (manifest is null)
  369. {
  370. return null;
  371. }
  372. return Map(manifest, archivePath);
  373. }
  374. /// <inheritdoc/>
  375. public async Task<BackupManifestDto[]> EnumerateBackups()
  376. {
  377. if (!Directory.Exists(_applicationPaths.BackupPath))
  378. {
  379. return [];
  380. }
  381. var archives = Directory.EnumerateFiles(_applicationPaths.BackupPath, "*.zip");
  382. var manifests = new List<BackupManifestDto>();
  383. foreach (var item in archives)
  384. {
  385. try
  386. {
  387. var manifest = await GetManifest(item).ConfigureAwait(false);
  388. if (manifest is null)
  389. {
  390. continue;
  391. }
  392. manifests.Add(Map(manifest, item));
  393. }
  394. catch (Exception ex)
  395. {
  396. _logger.LogError(ex, "Could not load {BackupArchive} path.", item);
  397. }
  398. }
  399. return manifests.ToArray();
  400. }
  401. private static async ValueTask<BackupManifest?> GetManifest(string archivePath)
  402. {
  403. var archiveStream = File.OpenRead(archivePath);
  404. await using (archiveStream.ConfigureAwait(false))
  405. {
  406. using var zipStream = new ZipArchive(archiveStream, ZipArchiveMode.Read);
  407. var manifestEntry = zipStream.GetEntry(ManifestEntryName);
  408. if (manifestEntry is null)
  409. {
  410. return null;
  411. }
  412. var manifestStream = manifestEntry.Open();
  413. await using (manifestStream.ConfigureAwait(false))
  414. {
  415. return await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).ConfigureAwait(false);
  416. }
  417. }
  418. }
  419. private static BackupManifestDto Map(BackupManifest manifest, string path)
  420. {
  421. return new BackupManifestDto()
  422. {
  423. BackupEngineVersion = manifest.BackupEngineVersion,
  424. DateCreated = manifest.DateCreated,
  425. ServerVersion = manifest.ServerVersion,
  426. Path = path,
  427. Options = Map(manifest.Options)
  428. };
  429. }
  430. private static BackupOptionsDto Map(BackupOptions options)
  431. {
  432. return new BackupOptionsDto()
  433. {
  434. Metadata = options.Metadata,
  435. Subtitles = options.Subtitles,
  436. Trickplay = options.Trickplay,
  437. Database = options.Database
  438. };
  439. }
  440. private static BackupOptions Map(BackupOptionsDto options)
  441. {
  442. return new BackupOptions()
  443. {
  444. Metadata = options.Metadata,
  445. Subtitles = options.Subtitles,
  446. Trickplay = options.Trickplay,
  447. Database = options.Database
  448. };
  449. }
  450. }