PluginManager.cs 24 KB

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