PluginManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Text.Json;
  9. using MediaBrowser.Common;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Common.Json;
  12. using MediaBrowser.Common.Plugins;
  13. using MediaBrowser.Model.Configuration;
  14. using MediaBrowser.Model.Plugins;
  15. using Microsoft.Extensions.DependencyInjection;
  16. using Microsoft.Extensions.Logging;
  17. namespace Emby.Server.Implementations.Plugins
  18. {
  19. /// <summary>
  20. /// Defines the <see cref="PluginManager" />.
  21. /// </summary>
  22. public class PluginManager : IPluginManager
  23. {
  24. private readonly string _pluginsPath;
  25. private readonly Version _appVersion;
  26. private readonly JsonSerializerOptions _jsonOptions;
  27. private readonly ILogger<PluginManager> _logger;
  28. private readonly IApplicationHost _appHost;
  29. private readonly ServerConfiguration _config;
  30. private readonly IList<LocalPlugin> _plugins;
  31. private readonly Version _minimumVersion;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="PluginManager"/> class.
  34. /// </summary>
  35. /// <param name="logger">The <see cref="ILogger"/>.</param>
  36. /// <param name="appHost">The <see cref="IApplicationHost"/>.</param>
  37. /// <param name="config">The <see cref="ServerConfiguration"/>.</param>
  38. /// <param name="pluginsPath">The plugin path.</param>
  39. /// <param name="appVersion">The application version.</param>
  40. public PluginManager(
  41. ILogger<PluginManager> logger,
  42. IApplicationHost appHost,
  43. ServerConfiguration config,
  44. string pluginsPath,
  45. Version appVersion)
  46. {
  47. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  48. _pluginsPath = pluginsPath;
  49. _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion));
  50. _jsonOptions = JsonDefaults.GetOptions();
  51. _jsonOptions.WriteIndented = true;
  52. _config = config;
  53. _appHost = appHost;
  54. _minimumVersion = new Version(0, 0, 0, 1);
  55. _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>();
  56. }
  57. /// <summary>
  58. /// Gets the Plugins.
  59. /// </summary>
  60. public IList<LocalPlugin> Plugins => _plugins;
  61. /// <summary>
  62. /// Returns all the assemblies.
  63. /// </summary>
  64. /// <returns>An IEnumerable{Assembly}.</returns>
  65. public IEnumerable<Assembly> LoadAssemblies()
  66. {
  67. // Attempt to remove any deleted plugins and change any successors to be active.
  68. for (int a = _plugins.Count - 1; a >= 0; a--)
  69. {
  70. var plugin = _plugins[a];
  71. if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin))
  72. {
  73. UpdateSuccessors(plugin);
  74. }
  75. }
  76. // Now load the assemblies..
  77. foreach (var plugin in _plugins)
  78. {
  79. UpdatePluginSuperceedStatus(plugin);
  80. if (plugin.IsEnabledAndSupported == false)
  81. {
  82. _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name);
  83. continue;
  84. }
  85. foreach (var file in plugin.DllFiles)
  86. {
  87. Assembly assembly;
  88. try
  89. {
  90. assembly = Assembly.LoadFrom(file);
  91. }
  92. catch (FileLoadException ex)
  93. {
  94. _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin.", file);
  95. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  96. continue;
  97. }
  98. _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file);
  99. yield return assembly;
  100. }
  101. }
  102. }
  103. /// <summary>
  104. /// Creates all the plugin instances.
  105. /// </summary>
  106. public void CreatePlugins()
  107. {
  108. _ = _appHost.GetExports<IPlugin>(CreatePluginInstance)
  109. .Where(i => i != null)
  110. .ToArray();
  111. }
  112. /// <summary>
  113. /// Registers the plugin's services with the DI.
  114. /// Note: DI is not yet instantiated yet.
  115. /// </summary>
  116. /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param>
  117. public void RegisterServices(IServiceCollection serviceCollection)
  118. {
  119. foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>())
  120. {
  121. var plugin = GetPluginByType(pluginServiceRegistrator.Assembly.GetType());
  122. if (plugin == null)
  123. {
  124. _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.FullName);
  125. continue;
  126. }
  127. UpdatePluginSuperceedStatus(plugin);
  128. if (!plugin.IsEnabledAndSupported)
  129. {
  130. continue;
  131. }
  132. try
  133. {
  134. var instance = (IPluginServiceRegistrator?)Activator.CreateInstance(pluginServiceRegistrator);
  135. instance?.RegisterServices(serviceCollection);
  136. }
  137. #pragma warning disable CA1031 // Do not catch general exception types
  138. catch (Exception ex)
  139. #pragma warning restore CA1031 // Do not catch general exception types
  140. {
  141. _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly.FullName);
  142. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  143. {
  144. _logger.LogInformation("Disabling plugin {Path}", plugin.Path);
  145. }
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// Imports a plugin manifest from <paramref name="folder"/>.
  151. /// </summary>
  152. /// <param name="folder">Folder of the plugin.</param>
  153. public void ImportPluginFrom(string folder)
  154. {
  155. if (string.IsNullOrEmpty(folder))
  156. {
  157. throw new ArgumentNullException(nameof(folder));
  158. }
  159. // Load the plugin.
  160. var plugin = LoadManifest(folder);
  161. // Make sure we haven't already loaded this.
  162. if (_plugins.Any(p => p.Manifest.Equals(plugin.Manifest)))
  163. {
  164. return;
  165. }
  166. _plugins.Add(plugin);
  167. EnablePlugin(plugin);
  168. }
  169. /// <summary>
  170. /// Removes the plugin reference '<paramref name="plugin"/>.
  171. /// </summary>
  172. /// <param name="plugin">The plugin.</param>
  173. /// <returns>Outcome of the operation.</returns>
  174. public bool RemovePlugin(LocalPlugin plugin)
  175. {
  176. if (plugin == null)
  177. {
  178. throw new ArgumentNullException(nameof(plugin));
  179. }
  180. if (DeletePlugin(plugin))
  181. {
  182. return true;
  183. }
  184. _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path);
  185. // Unable to delete, so disable.
  186. return ChangePluginState(plugin, PluginStatus.Deleted);
  187. }
  188. /// <summary>
  189. /// Attempts to find the plugin with and id of <paramref name="id"/>.
  190. /// </summary>
  191. /// <param name="id">The <see cref="Guid"/> of plugin.</param>
  192. /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param>
  193. /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
  194. public LocalPlugin? GetPlugin(Guid id, Version? version = null)
  195. {
  196. LocalPlugin? plugin;
  197. if (version == null)
  198. {
  199. // If no version is given, return the current instance.
  200. var plugins = _plugins.Where(p => p.Id.Equals(id));
  201. plugin = plugins.FirstOrDefault(p => p.Instance != null);
  202. if (plugin == null)
  203. {
  204. plugin = plugins.OrderByDescending(p => p.Version).FirstOrDefault();
  205. }
  206. }
  207. else
  208. {
  209. // Match id and version number.
  210. plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version));
  211. }
  212. return plugin;
  213. }
  214. /// <summary>
  215. /// Enables the plugin, disabling all other versions.
  216. /// </summary>
  217. /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
  218. public void EnablePlugin(LocalPlugin plugin)
  219. {
  220. if (plugin == null)
  221. {
  222. throw new ArgumentNullException(nameof(plugin));
  223. }
  224. if (ChangePluginState(plugin, PluginStatus.Active))
  225. {
  226. UpdateSuccessors(plugin);
  227. }
  228. }
  229. /// <summary>
  230. /// Disable the plugin.
  231. /// </summary>
  232. /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
  233. public void DisablePlugin(LocalPlugin plugin)
  234. {
  235. if (plugin == null)
  236. {
  237. throw new ArgumentNullException(nameof(plugin));
  238. }
  239. // Update the manifest on disk
  240. if (ChangePluginState(plugin, PluginStatus.Disabled))
  241. {
  242. UpdateSuccessors(plugin);
  243. }
  244. }
  245. /// <summary>
  246. /// Disable the plugin.
  247. /// </summary>
  248. /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
  249. public void FailPlugin(Assembly assembly)
  250. {
  251. // Only save if disabled.
  252. if (assembly == null)
  253. {
  254. throw new ArgumentNullException(nameof(assembly));
  255. }
  256. var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location));
  257. if (plugin == null)
  258. {
  259. // A plugin's assembly didn't cause this issue, so ignore it.
  260. return;
  261. }
  262. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  263. }
  264. /// <summary>
  265. /// Saves the manifest back to disk.
  266. /// </summary>
  267. /// <param name="manifest">The <see cref="PluginManifest"/> to save.</param>
  268. /// <param name="path">The path where to save the manifest.</param>
  269. /// <returns>True if successful.</returns>
  270. public bool SaveManifest(PluginManifest manifest, string path)
  271. {
  272. if (manifest == null)
  273. {
  274. return false;
  275. }
  276. try
  277. {
  278. var data = JsonSerializer.Serialize(manifest, _jsonOptions);
  279. File.WriteAllText(Path.Combine(path, "meta.json"), data, Encoding.UTF8);
  280. return true;
  281. }
  282. #pragma warning disable CA1031 // Do not catch general exception types
  283. catch (Exception e)
  284. #pragma warning restore CA1031 // Do not catch general exception types
  285. {
  286. _logger.LogWarning(e, "Unable to save plugin manifest. {Path}", path);
  287. return false;
  288. }
  289. }
  290. /// <summary>
  291. /// Changes a plugin's load status.
  292. /// </summary>
  293. /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
  294. /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
  295. /// <returns>Success of the task.</returns>
  296. private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
  297. {
  298. if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
  299. {
  300. // No need to save as the state hasn't changed.
  301. return true;
  302. }
  303. plugin.Manifest.Status = state;
  304. return SaveManifest(plugin.Manifest, plugin.Path);
  305. }
  306. /// <summary>
  307. /// Finds the plugin record using the type.
  308. /// </summary>
  309. /// <param name="type">The <see cref="Type"/> being sought.</param>
  310. /// <returns>The matching record, or null if not found.</returns>
  311. private LocalPlugin? GetPluginByType(Type type)
  312. {
  313. // Find which plugin it is by the path.
  314. return _plugins.FirstOrDefault(p => string.Equals(p.Path, Path.GetDirectoryName(type.Assembly.Location), StringComparison.Ordinal));
  315. }
  316. /// <summary>
  317. /// Creates the instance safe.
  318. /// </summary>
  319. /// <param name="type">The type.</param>
  320. /// <returns>System.Object.</returns>
  321. private IPlugin? CreatePluginInstance(Type type)
  322. {
  323. // Find the record for this plugin.
  324. var plugin = GetPluginByType(type);
  325. if (plugin?.Manifest.Status < PluginStatus.Active)
  326. {
  327. return null;
  328. }
  329. try
  330. {
  331. _logger.LogDebug("Creating instance of {Type}", type);
  332. var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider, type);
  333. if (plugin == null)
  334. {
  335. // Create a dummy record for the providers.
  336. // TODO: remove this code, if all provided have been released as separate plugins.
  337. plugin = new LocalPlugin(
  338. instance.AssemblyFilePath,
  339. true,
  340. new PluginManifest
  341. {
  342. Id = instance.Id,
  343. Status = PluginStatus.Active,
  344. Name = instance.Name,
  345. Version = instance.Version.ToString()
  346. })
  347. {
  348. Instance = instance
  349. };
  350. _plugins.Add(plugin);
  351. plugin.Manifest.Status = PluginStatus.Active;
  352. }
  353. else
  354. {
  355. plugin.Instance = instance;
  356. var manifest = plugin.Manifest;
  357. var pluginStr = plugin.Instance.Version.ToString();
  358. bool changed = false;
  359. if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal))
  360. {
  361. // If a plugin without a manifest failed to load due to an external issue (eg config),
  362. // this updates the manifest to the actual plugin values.
  363. manifest.Version = pluginStr;
  364. manifest.Name = plugin.Instance.Name;
  365. manifest.Description = plugin.Instance.Description;
  366. changed = true;
  367. }
  368. changed = changed || manifest.Status != PluginStatus.Active;
  369. manifest.Status = PluginStatus.Active;
  370. if (changed)
  371. {
  372. SaveManifest(manifest, plugin.Path);
  373. }
  374. }
  375. _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  376. return instance;
  377. }
  378. #pragma warning disable CA1031 // Do not catch general exception types
  379. catch (Exception ex)
  380. #pragma warning restore CA1031 // Do not catch general exception types
  381. {
  382. _logger.LogError(ex, "Error creating {Type}", type.FullName);
  383. if (plugin != null)
  384. {
  385. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  386. {
  387. _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
  388. return null;
  389. }
  390. }
  391. _logger.LogDebug("Unable to auto-disable.");
  392. return null;
  393. }
  394. }
  395. private void UpdatePluginSuperceedStatus(LocalPlugin plugin)
  396. {
  397. if (plugin.Manifest.Status != PluginStatus.Superceded)
  398. {
  399. return;
  400. }
  401. var predecessor = _plugins.OrderByDescending(p => p.Version)
  402. .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
  403. if (predecessor != null)
  404. {
  405. return;
  406. }
  407. plugin.Manifest.Status = PluginStatus.Active;
  408. }
  409. /// <summary>
  410. /// Attempts to delete a plugin.
  411. /// </summary>
  412. /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
  413. /// <returns>True if successful.</returns>
  414. private bool DeletePlugin(LocalPlugin plugin)
  415. {
  416. // Attempt a cleanup of old folders.
  417. try
  418. {
  419. Directory.Delete(plugin.Path, true);
  420. _logger.LogDebug("Deleted {Path}", plugin.Path);
  421. }
  422. #pragma warning disable CA1031 // Do not catch general exception types
  423. catch
  424. #pragma warning restore CA1031 // Do not catch general exception types
  425. {
  426. return false;
  427. }
  428. return _plugins.Remove(plugin);
  429. }
  430. private LocalPlugin LoadManifest(string dir)
  431. {
  432. Version? version;
  433. PluginManifest? manifest = null;
  434. var metafile = Path.Combine(dir, "meta.json");
  435. if (File.Exists(metafile))
  436. {
  437. try
  438. {
  439. var data = File.ReadAllText(metafile, Encoding.UTF8);
  440. manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
  441. }
  442. #pragma warning disable CA1031 // Do not catch general exception types
  443. catch (Exception ex)
  444. #pragma warning restore CA1031 // Do not catch general exception types
  445. {
  446. _logger.LogError(ex, "Error deserializing {Path}.", dir);
  447. }
  448. }
  449. if (manifest != null)
  450. {
  451. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  452. {
  453. targetAbi = _minimumVersion;
  454. }
  455. if (!Version.TryParse(manifest.Version, out version))
  456. {
  457. manifest.Version = _minimumVersion.ToString();
  458. }
  459. return new LocalPlugin(dir, _appVersion >= targetAbi, manifest);
  460. }
  461. // No metafile, so lets see if the folder is versioned.
  462. // TODO: Phase this support out in future versions.
  463. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  464. int versionIndex = dir.LastIndexOf('_');
  465. if (versionIndex != -1)
  466. {
  467. // Get the version number from the filename if possible.
  468. metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex];
  469. version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
  470. }
  471. else
  472. {
  473. // Un-versioned folder - Add it under the path name and version it suitable for this instance.
  474. version = _appVersion;
  475. }
  476. // Auto-create a plugin manifest, so we can disable it, if it fails to load.
  477. manifest = new PluginManifest
  478. {
  479. Status = PluginStatus.Restart,
  480. Name = metafile,
  481. AutoUpdate = false,
  482. Id = metafile.GetMD5(),
  483. TargetAbi = _appVersion.ToString(),
  484. Version = version.ToString()
  485. };
  486. return new LocalPlugin(dir, true, manifest);
  487. }
  488. /// <summary>
  489. /// Gets the list of local plugins.
  490. /// </summary>
  491. /// <returns>Enumerable of local plugins.</returns>
  492. private IEnumerable<LocalPlugin> DiscoverPlugins()
  493. {
  494. var versions = new List<LocalPlugin>();
  495. if (!Directory.Exists(_pluginsPath))
  496. {
  497. // Plugin path doesn't exist, don't try to enumerate sub-folders.
  498. return Enumerable.Empty<LocalPlugin>();
  499. }
  500. var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
  501. foreach (var dir in directories)
  502. {
  503. versions.Add(LoadManifest(dir));
  504. }
  505. string lastName = string.Empty;
  506. versions.Sort(LocalPlugin.Compare);
  507. // Traverse backwards through the list.
  508. // The first item will be the latest version.
  509. for (int x = versions.Count - 1; x >= 0; x--)
  510. {
  511. var entry = versions[x];
  512. if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
  513. {
  514. entry.DllFiles.AddRange(Directory.EnumerateFiles(entry.Path, "*.dll", SearchOption.AllDirectories));
  515. if (entry.IsEnabledAndSupported)
  516. {
  517. lastName = entry.Name;
  518. continue;
  519. }
  520. }
  521. if (string.IsNullOrEmpty(lastName))
  522. {
  523. continue;
  524. }
  525. var manifest = entry.Manifest;
  526. var cleaned = false;
  527. var path = entry.Path;
  528. if (_config.RemoveOldPlugins)
  529. {
  530. // Attempt a cleanup of old folders.
  531. try
  532. {
  533. _logger.LogDebug("Deleting {Path}", path);
  534. Directory.Delete(path, true);
  535. cleaned = true;
  536. }
  537. #pragma warning disable CA1031 // Do not catch general exception types
  538. catch (Exception e)
  539. #pragma warning restore CA1031 // Do not catch general exception types
  540. {
  541. _logger.LogWarning(e, "Unable to delete {Path}", path);
  542. }
  543. if (cleaned)
  544. {
  545. versions.RemoveAt(x);
  546. }
  547. else
  548. {
  549. if (manifest == null)
  550. {
  551. _logger.LogWarning("Unable to disable plugin {Path}", entry.Path);
  552. continue;
  553. }
  554. ChangePluginState(entry, PluginStatus.Deleted);
  555. }
  556. }
  557. }
  558. // Only want plugin folders which have files.
  559. return versions.Where(p => p.DllFiles.Count != 0);
  560. }
  561. /// <summary>
  562. /// Changes the status of the other versions of the plugin to "Superceded".
  563. /// </summary>
  564. /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param>
  565. private void UpdateSuccessors(LocalPlugin plugin)
  566. {
  567. // This value is memory only - so that the web will show restart required.
  568. plugin.Manifest.Status = PluginStatus.Restart;
  569. // Detect whether there is another version of this plugin that needs disabling.
  570. var predecessor = _plugins.OrderByDescending(p => p.Version)
  571. .FirstOrDefault(
  572. p => p.Id.Equals(plugin.Id)
  573. && p.IsEnabledAndSupported
  574. && p.Version != plugin.Version);
  575. if (predecessor == null)
  576. {
  577. return;
  578. }
  579. if (predecessor.Manifest.Status == PluginStatus.Active && !ChangePluginState(predecessor, PluginStatus.Superceded))
  580. {
  581. _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name);
  582. }
  583. }
  584. }
  585. }