BackupService.cs 23 KB

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