InstallationManager.cs 19 KB

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