PluginManager.cs 24 KB

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