BackupService.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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, string SourceName, 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, dbContext.Model.FindEntityType(e.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!, ValueFactory: new Func<IAsyncEnumerable<object>>(() => GetValues((IQueryable)e.GetValue(dbContext)!, e.PropertyType)))),
  261. (Type: typeof(HistoryRow), SourceName: nameof(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. _logger.LogInformation("Begin backup of entity {Table}", entityType.SourceName);
  271. var zipEntry = zipArchive.CreateEntry($"Database\\{entityType.SourceName}.json");
  272. var entities = 0;
  273. var zipEntryStream = zipEntry.Open();
  274. await using (zipEntryStream.ConfigureAwait(false))
  275. {
  276. var jsonSerializer = new Utf8JsonWriter(zipEntryStream);
  277. await using (jsonSerializer.ConfigureAwait(false))
  278. {
  279. jsonSerializer.WriteStartArray();
  280. var set = entityType.ValueFactory().ConfigureAwait(false);
  281. await foreach (var item in set.ConfigureAwait(false))
  282. {
  283. entities++;
  284. try
  285. {
  286. JsonSerializer.SerializeToDocument(item, _serializerSettings).WriteTo(jsonSerializer);
  287. }
  288. catch (Exception ex)
  289. {
  290. _logger.LogError(ex, "Could not load entity {Entity}", item);
  291. throw;
  292. }
  293. }
  294. jsonSerializer.WriteEndArray();
  295. }
  296. }
  297. _logger.LogInformation("backup of entity {Table} with {Number} created", entityType.Type.Name, entities);
  298. }
  299. }
  300. }
  301. _logger.LogInformation("Backup of folder {Table}", _applicationPaths.ConfigurationDirectoryPath);
  302. foreach (var item in Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.xml", SearchOption.TopDirectoryOnly)
  303. .Union(Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.json", SearchOption.TopDirectoryOnly)))
  304. {
  305. zipArchive.CreateEntryFromFile(item, Path.Combine("Config", Path.GetFileName(item)));
  306. }
  307. void CopyDirectory(string source, string target, string filter = "*")
  308. {
  309. if (!Directory.Exists(source))
  310. {
  311. return;
  312. }
  313. _logger.LogInformation("Backup of folder {Table}", source);
  314. foreach (var item in Directory.EnumerateFiles(source, filter, SearchOption.AllDirectories))
  315. {
  316. zipArchive.CreateEntryFromFile(item, Path.Combine(target, item[..source.Length].Trim('\\')));
  317. }
  318. }
  319. CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "users"), Path.Combine("Config", "users"));
  320. CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"), Path.Combine("Config", "ScheduledTasks"));
  321. CopyDirectory(Path.Combine(_applicationPaths.RootFolderPath), "Root");
  322. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "collections"), Path.Combine("Data", "collections"));
  323. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "playlists"), Path.Combine("Data", "playlists"));
  324. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"), Path.Combine("Data", "ScheduledTasks"));
  325. if (backupOptions.Subtitles)
  326. {
  327. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "subtitles"), Path.Combine("Data", "subtitles"));
  328. }
  329. if (backupOptions.Trickplay)
  330. {
  331. CopyDirectory(Path.Combine(_applicationPaths.DataPath, "trickplay"), Path.Combine("Data", "trickplay"));
  332. }
  333. if (backupOptions.Metadata)
  334. {
  335. CopyDirectory(Path.Combine(_applicationPaths.InternalMetadataPath), Path.Combine("Data", "metadata"));
  336. }
  337. var manifestStream = zipArchive.CreateEntry(ManifestEntryName).Open();
  338. await using (manifestStream.ConfigureAwait(false))
  339. {
  340. await JsonSerializer.SerializeAsync(manifestStream, manifest).ConfigureAwait(false);
  341. }
  342. }
  343. _logger.LogInformation("Backup created");
  344. return Map(manifest, backupPath);
  345. }
  346. /// <inheritdoc/>
  347. public async Task<BackupManifestDto?> GetBackupManifest(string archivePath)
  348. {
  349. if (!File.Exists(archivePath))
  350. {
  351. return null;
  352. }
  353. BackupManifest? manifest;
  354. try
  355. {
  356. manifest = await GetManifest(archivePath).ConfigureAwait(false);
  357. }
  358. catch (Exception ex)
  359. {
  360. _logger.LogError(ex, "Tried to load archive from {Path} but failed.", archivePath);
  361. return null;
  362. }
  363. if (manifest is null)
  364. {
  365. return null;
  366. }
  367. return Map(manifest, archivePath);
  368. }
  369. /// <inheritdoc/>
  370. public async Task<BackupManifestDto[]> EnumerateBackups()
  371. {
  372. if (!Directory.Exists(_applicationPaths.BackupPath))
  373. {
  374. return [];
  375. }
  376. var archives = Directory.EnumerateFiles(_applicationPaths.BackupPath, "*.zip");
  377. var manifests = new List<BackupManifestDto>();
  378. foreach (var item in archives)
  379. {
  380. try
  381. {
  382. var manifest = await GetManifest(item).ConfigureAwait(false);
  383. if (manifest is null)
  384. {
  385. continue;
  386. }
  387. manifests.Add(Map(manifest, item));
  388. }
  389. catch (Exception ex)
  390. {
  391. _logger.LogError(ex, "Could not load {BackupArchive} path.", item);
  392. }
  393. }
  394. return manifests.ToArray();
  395. }
  396. private static async ValueTask<BackupManifest?> GetManifest(string archivePath)
  397. {
  398. var archiveStream = File.OpenRead(archivePath);
  399. await using (archiveStream.ConfigureAwait(false))
  400. {
  401. using var zipStream = new ZipArchive(archiveStream, ZipArchiveMode.Read);
  402. var manifestEntry = zipStream.GetEntry(ManifestEntryName);
  403. if (manifestEntry is null)
  404. {
  405. return null;
  406. }
  407. var manifestStream = manifestEntry.Open();
  408. await using (manifestStream.ConfigureAwait(false))
  409. {
  410. return await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).ConfigureAwait(false);
  411. }
  412. }
  413. }
  414. private static BackupManifestDto Map(BackupManifest manifest, string path)
  415. {
  416. return new BackupManifestDto()
  417. {
  418. BackupEngineVersion = manifest.BackupEngineVersion,
  419. DateCreated = manifest.DateCreated,
  420. ServerVersion = manifest.ServerVersion,
  421. Path = path,
  422. Options = Map(manifest.Options)
  423. };
  424. }
  425. private static BackupOptionsDto Map(BackupOptions options)
  426. {
  427. return new BackupOptionsDto()
  428. {
  429. Metadata = options.Metadata,
  430. Subtitles = options.Subtitles,
  431. Trickplay = options.Trickplay,
  432. Database = options.Database
  433. };
  434. }
  435. private static BackupOptions Map(BackupOptionsDto options)
  436. {
  437. return new BackupOptions()
  438. {
  439. Metadata = options.Metadata,
  440. Subtitles = options.Subtitles,
  441. Trickplay = options.Trickplay,
  442. Database = options.Database
  443. };
  444. }
  445. }