InstallationManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Plugins;
  5. using MediaBrowser.Common.Progress;
  6. using MediaBrowser.Common.Updates;
  7. using MediaBrowser.Controller.Updates;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Serialization;
  10. using MediaBrowser.Model.Updates;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Updates
  19. {
  20. /// <summary>
  21. /// Manages all install, uninstall and update operations (both plugins and system)
  22. /// </summary>
  23. public class InstallationManager : IInstallationManager
  24. {
  25. public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstalling;
  26. public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationCompleted;
  27. public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationFailed;
  28. public event EventHandler<GenericEventArgs<InstallationInfo>> PackageInstallationCancelled;
  29. /// <summary>
  30. /// The current installations
  31. /// </summary>
  32. public List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
  33. /// <summary>
  34. /// The completed installations
  35. /// </summary>
  36. public ConcurrentBag<InstallationInfo> CompletedInstallations { get; set; }
  37. #region PluginUninstalled Event
  38. /// <summary>
  39. /// Occurs when [plugin uninstalled].
  40. /// </summary>
  41. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  42. /// <summary>
  43. /// Called when [plugin uninstalled].
  44. /// </summary>
  45. /// <param name="plugin">The plugin.</param>
  46. private void OnPluginUninstalled(IPlugin plugin)
  47. {
  48. EventHelper.QueueEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  49. }
  50. #endregion
  51. #region PluginUpdated Event
  52. /// <summary>
  53. /// Occurs when [plugin updated].
  54. /// </summary>
  55. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  56. /// <summary>
  57. /// Called when [plugin updated].
  58. /// </summary>
  59. /// <param name="plugin">The plugin.</param>
  60. /// <param name="newVersion">The new version.</param>
  61. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  62. {
  63. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);
  64. EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  65. ApplicationHost.NotifyPendingRestart();
  66. }
  67. #endregion
  68. #region PluginInstalled Event
  69. /// <summary>
  70. /// Occurs when [plugin updated].
  71. /// </summary>
  72. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  73. /// <summary>
  74. /// Called when [plugin installed].
  75. /// </summary>
  76. /// <param name="package">The package.</param>
  77. private void OnPluginInstalled(PackageVersionInfo package)
  78. {
  79. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);
  80. EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  81. ApplicationHost.NotifyPendingRestart();
  82. }
  83. #endregion
  84. /// <summary>
  85. /// The _logger
  86. /// </summary>
  87. private readonly ILogger _logger;
  88. /// <summary>
  89. /// The package manager
  90. /// </summary>
  91. private readonly IPackageManager _packageManager;
  92. /// <summary>
  93. /// Gets the json serializer.
  94. /// </summary>
  95. /// <value>The json serializer.</value>
  96. protected IJsonSerializer JsonSerializer { get; private set; }
  97. /// <summary>
  98. /// Gets the HTTP client.
  99. /// </summary>
  100. /// <value>The HTTP client.</value>
  101. protected IHttpClient HttpClient { get; private set; }
  102. /// <summary>
  103. /// Gets the application host.
  104. /// </summary>
  105. /// <value>The application host.</value>
  106. protected IApplicationHost ApplicationHost { get; private set; }
  107. /// <summary>
  108. /// Initializes a new instance of the <see cref="InstallationManager" /> class.
  109. /// </summary>
  110. /// <param name="httpClient">The HTTP client.</param>
  111. /// <param name="packageManager">The package manager.</param>
  112. /// <param name="jsonSerializer">The json serializer.</param>
  113. /// <param name="logger">The logger.</param>
  114. /// <param name="appHost">The app host.</param>
  115. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  116. public InstallationManager(IHttpClient httpClient, IPackageManager packageManager, IJsonSerializer jsonSerializer, ILogger logger, IApplicationHost appHost)
  117. {
  118. if (packageManager == null)
  119. {
  120. throw new ArgumentNullException("packageManager");
  121. }
  122. if (logger == null)
  123. {
  124. throw new ArgumentNullException("logger");
  125. }
  126. if (jsonSerializer == null)
  127. {
  128. throw new ArgumentNullException("jsonSerializer");
  129. }
  130. if (httpClient == null)
  131. {
  132. throw new ArgumentNullException("httpClient");
  133. }
  134. CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  135. CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  136. JsonSerializer = jsonSerializer;
  137. HttpClient = httpClient;
  138. ApplicationHost = appHost;
  139. _packageManager = packageManager;
  140. _logger = logger;
  141. }
  142. /// <summary>
  143. /// Gets all available packages.
  144. /// </summary>
  145. /// <param name="cancellationToken">The cancellation token.</param>
  146. /// <param name="packageType">Type of the package.</param>
  147. /// <param name="applicationVersion">The application version.</param>
  148. /// <returns>Task{List{PackageInfo}}.</returns>
  149. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  150. PackageType? packageType = null,
  151. Version applicationVersion = null)
  152. {
  153. var packages = (await _packageManager.GetAvailablePackages(cancellationToken).ConfigureAwait(false)).ToList();
  154. return FilterPackages(packages, packageType, applicationVersion);
  155. }
  156. /// <summary>
  157. /// Gets all available packages.
  158. /// </summary>
  159. /// <param name="cancellationToken">The cancellation token.</param>
  160. /// <param name="packageType">Type of the package.</param>
  161. /// <param name="applicationVersion">The application version.</param>
  162. /// <returns>Task{List{PackageInfo}}.</returns>
  163. protected async Task<IEnumerable<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken,
  164. PackageType? packageType = null,
  165. Version applicationVersion = null)
  166. {
  167. var packages = (await _packageManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false)).ToList();
  168. return FilterPackages(packages, packageType, applicationVersion);
  169. }
  170. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, PackageType? packageType, Version applicationVersion)
  171. {
  172. if (packageType.HasValue)
  173. {
  174. packages = packages.Where(p => p.type == packageType.Value).ToList();
  175. }
  176. // If an app version was supplied, filter the versions for each package to only include supported versions
  177. if (applicationVersion != null)
  178. {
  179. foreach (var package in packages)
  180. {
  181. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  182. }
  183. }
  184. // Remove packages with no versions
  185. packages = packages.Where(p => p.versions.Any()).ToList();
  186. return packages;
  187. }
  188. /// <summary>
  189. /// Determines whether [is package version up to date] [the specified package version info].
  190. /// </summary>
  191. /// <param name="packageVersionInfo">The package version info.</param>
  192. /// <param name="applicationVersion">The application version.</param>
  193. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  194. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version applicationVersion)
  195. {
  196. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  197. {
  198. return true;
  199. }
  200. Version requiredVersion;
  201. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && applicationVersion >= requiredVersion;
  202. }
  203. /// <summary>
  204. /// Gets the package.
  205. /// </summary>
  206. /// <param name="name">The name.</param>
  207. /// <param name="classification">The classification.</param>
  208. /// <param name="version">The version.</param>
  209. /// <returns>Task{PackageVersionInfo}.</returns>
  210. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  211. {
  212. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  213. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  214. if (package == null)
  215. {
  216. return null;
  217. }
  218. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  219. }
  220. /// <summary>
  221. /// Gets the latest compatible version.
  222. /// </summary>
  223. /// <param name="name">The name.</param>
  224. /// <param name="classification">The classification.</param>
  225. /// <returns>Task{PackageVersionInfo}.</returns>
  226. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, PackageVersionClass classification = PackageVersionClass.Release)
  227. {
  228. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  229. return GetLatestCompatibleVersion(packages, name, classification);
  230. }
  231. /// <summary>
  232. /// Gets the latest compatible version.
  233. /// </summary>
  234. /// <param name="availablePackages">The available packages.</param>
  235. /// <param name="name">The name.</param>
  236. /// <param name="classification">The classification.</param>
  237. /// <returns>PackageVersionInfo.</returns>
  238. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, PackageVersionClass classification = PackageVersionClass.Release)
  239. {
  240. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  241. if (package == null)
  242. {
  243. return null;
  244. }
  245. return package.versions
  246. .OrderByDescending(v => v.version)
  247. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, ApplicationHost.ApplicationVersion));
  248. }
  249. /// <summary>
  250. /// Gets the available plugin updates including registration information for each one.
  251. /// Used with API and catalog.
  252. /// </summary>
  253. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  254. /// <param name="cancellationToken">The cancellation token.</param>
  255. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  256. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  257. {
  258. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  259. return FilterCatalog(catalog, withAutoUpdateEnabled);
  260. }
  261. /// <summary>
  262. /// Gets the available plugin updates from a static resource - no registration information.
  263. /// Used for update checks.
  264. /// </summary>
  265. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  266. /// <param name="cancellationToken">The cancellation token.</param>
  267. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  268. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdatesWithoutRegistrationInfo(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  269. {
  270. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  271. return FilterCatalog(catalog, withAutoUpdateEnabled);
  272. }
  273. protected IEnumerable<PackageVersionInfo> FilterCatalog(IEnumerable<PackageInfo> catalog, bool withAutoUpdateEnabled)
  274. {
  275. var plugins = ApplicationHost.Plugins;
  276. if (withAutoUpdateEnabled)
  277. {
  278. plugins = plugins.Where(p => p.Configuration.EnableAutoUpdate);
  279. }
  280. // Figure out what needs to be installed
  281. return plugins.Select(p =>
  282. {
  283. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Configuration.UpdateClass);
  284. return latestPluginInfo != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  285. }).Where(p => !CompletedInstallations.Any(i => string.Equals(i.Name, p.name, StringComparison.OrdinalIgnoreCase)))
  286. .Where(p => p != null && !string.IsNullOrWhiteSpace(p.sourceUrl));
  287. }
  288. /// <summary>
  289. /// Installs the package.
  290. /// </summary>
  291. /// <param name="package">The package.</param>
  292. /// <param name="progress">The progress.</param>
  293. /// <param name="cancellationToken">The cancellation token.</param>
  294. /// <returns>Task.</returns>
  295. /// <exception cref="System.ArgumentNullException">package</exception>
  296. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  297. {
  298. if (package == null)
  299. {
  300. throw new ArgumentNullException("package");
  301. }
  302. if (progress == null)
  303. {
  304. throw new ArgumentNullException("progress");
  305. }
  306. if (cancellationToken == null)
  307. {
  308. throw new ArgumentNullException("cancellationToken");
  309. }
  310. var installationInfo = new InstallationInfo
  311. {
  312. Id = Guid.NewGuid(),
  313. Name = package.name,
  314. UpdateClass = package.classification,
  315. Version = package.versionStr
  316. };
  317. var innerCancellationTokenSource = new CancellationTokenSource();
  318. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  319. // Add it to the in-progress list
  320. lock (CurrentInstallations)
  321. {
  322. CurrentInstallations.Add(tuple);
  323. }
  324. var innerProgress = new ActionableProgress<double>();
  325. // Whenever the progress updates, update the outer progress object and InstallationInfo
  326. innerProgress.RegisterAction(percent =>
  327. {
  328. progress.Report(percent);
  329. installationInfo.PercentComplete = percent;
  330. });
  331. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  332. EventHelper.QueueEventIfNotNull(PackageInstalling, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  333. try
  334. {
  335. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  336. lock (CurrentInstallations)
  337. {
  338. CurrentInstallations.Remove(tuple);
  339. }
  340. CompletedInstallations.Add(installationInfo);
  341. EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  342. }
  343. catch (OperationCanceledException)
  344. {
  345. lock (CurrentInstallations)
  346. {
  347. CurrentInstallations.Remove(tuple);
  348. }
  349. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  350. EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  351. throw;
  352. }
  353. catch (Exception ex)
  354. {
  355. _logger.ErrorException("Package installation failed", ex);
  356. lock (CurrentInstallations)
  357. {
  358. CurrentInstallations.Remove(tuple);
  359. }
  360. EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  361. throw;
  362. }
  363. finally
  364. {
  365. // Dispose the progress object and remove the installation from the in-progress list
  366. innerProgress.Dispose();
  367. tuple.Item2.Dispose();
  368. }
  369. }
  370. /// <summary>
  371. /// Installs the package internal.
  372. /// </summary>
  373. /// <param name="package">The package.</param>
  374. /// <param name="progress">The progress.</param>
  375. /// <param name="cancellationToken">The cancellation token.</param>
  376. /// <returns>Task.</returns>
  377. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  378. {
  379. // Do the install
  380. await _packageManager.InstallPackage(progress, package, cancellationToken).ConfigureAwait(false);
  381. // Do plugin-specific processing
  382. if (!(Path.GetExtension(package.targetFilename) ?? "").Equals(".zip", StringComparison.OrdinalIgnoreCase))
  383. {
  384. // Set last update time if we were installed before
  385. var plugin = ApplicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  386. if (plugin != null)
  387. {
  388. OnPluginUpdated(plugin, package);
  389. }
  390. else
  391. {
  392. OnPluginInstalled(package);
  393. }
  394. }
  395. }
  396. /// <summary>
  397. /// Uninstalls a plugin
  398. /// </summary>
  399. /// <param name="plugin">The plugin.</param>
  400. /// <exception cref="System.ArgumentException"></exception>
  401. public void UninstallPlugin(IPlugin plugin)
  402. {
  403. plugin.OnUninstalling();
  404. // Remove it the quick way for now
  405. ApplicationHost.RemovePlugin(plugin);
  406. File.Delete(plugin.AssemblyFilePath);
  407. OnPluginUninstalled(plugin);
  408. ApplicationHost.NotifyPendingRestart();
  409. }
  410. /// <summary>
  411. /// Releases unmanaged and - optionally - managed resources.
  412. /// </summary>
  413. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  414. protected virtual void Dispose(bool dispose)
  415. {
  416. if (dispose)
  417. {
  418. lock (CurrentInstallations)
  419. {
  420. foreach (var tuple in CurrentInstallations)
  421. {
  422. tuple.Item2.Dispose();
  423. }
  424. CurrentInstallations.Clear();
  425. }
  426. }
  427. }
  428. public void Dispose()
  429. {
  430. Dispose(true);
  431. }
  432. }
  433. }