InstallationManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. if (packageType.HasValue)
  155. {
  156. packages = packages.Where(p => p.type == packageType.Value).ToList();
  157. }
  158. // If an app version was supplied, filter the versions for each package to only include supported versions
  159. if (applicationVersion != null)
  160. {
  161. foreach (var package in packages)
  162. {
  163. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  164. }
  165. }
  166. // Remove packages with no versions
  167. packages = packages.Where(p => p.versions.Any()).ToList();
  168. return packages;
  169. }
  170. /// <summary>
  171. /// Determines whether [is package version up to date] [the specified package version info].
  172. /// </summary>
  173. /// <param name="packageVersionInfo">The package version info.</param>
  174. /// <param name="applicationVersion">The application version.</param>
  175. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  176. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version applicationVersion)
  177. {
  178. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  179. {
  180. return true;
  181. }
  182. Version requiredVersion;
  183. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && applicationVersion >= requiredVersion;
  184. }
  185. /// <summary>
  186. /// Gets the package.
  187. /// </summary>
  188. /// <param name="name">The name.</param>
  189. /// <param name="classification">The classification.</param>
  190. /// <param name="version">The version.</param>
  191. /// <returns>Task{PackageVersionInfo}.</returns>
  192. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  193. {
  194. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  195. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  196. if (package == null)
  197. {
  198. return null;
  199. }
  200. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  201. }
  202. /// <summary>
  203. /// Gets the latest compatible version.
  204. /// </summary>
  205. /// <param name="name">The name.</param>
  206. /// <param name="classification">The classification.</param>
  207. /// <returns>Task{PackageVersionInfo}.</returns>
  208. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, PackageVersionClass classification = PackageVersionClass.Release)
  209. {
  210. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  211. return GetLatestCompatibleVersion(packages, name, classification);
  212. }
  213. /// <summary>
  214. /// Gets the latest compatible version.
  215. /// </summary>
  216. /// <param name="availablePackages">The available packages.</param>
  217. /// <param name="name">The name.</param>
  218. /// <param name="classification">The classification.</param>
  219. /// <returns>PackageVersionInfo.</returns>
  220. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, PackageVersionClass classification = PackageVersionClass.Release)
  221. {
  222. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  223. if (package == null)
  224. {
  225. return null;
  226. }
  227. return package.versions
  228. .OrderByDescending(v => v.version)
  229. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, ApplicationHost.ApplicationVersion));
  230. }
  231. /// <summary>
  232. /// Gets the available plugin updates.
  233. /// </summary>
  234. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  235. /// <param name="cancellationToken">The cancellation token.</param>
  236. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  237. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  238. {
  239. var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false);
  240. var plugins = ApplicationHost.Plugins;
  241. if (withAutoUpdateEnabled)
  242. {
  243. plugins = plugins.Where(p => p.Configuration.EnableAutoUpdate);
  244. }
  245. // Figure out what needs to be installed
  246. return plugins.Select(p =>
  247. {
  248. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Configuration.UpdateClass);
  249. return latestPluginInfo != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  250. }).Where(p => !CompletedInstallations.Any(i => string.Equals(i.Name, p.name, StringComparison.OrdinalIgnoreCase)))
  251. .Where(p => p != null && !string.IsNullOrWhiteSpace(p.sourceUrl));
  252. }
  253. /// <summary>
  254. /// Installs the package.
  255. /// </summary>
  256. /// <param name="package">The package.</param>
  257. /// <param name="progress">The progress.</param>
  258. /// <param name="cancellationToken">The cancellation token.</param>
  259. /// <returns>Task.</returns>
  260. /// <exception cref="System.ArgumentNullException">package</exception>
  261. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  262. {
  263. if (package == null)
  264. {
  265. throw new ArgumentNullException("package");
  266. }
  267. if (progress == null)
  268. {
  269. throw new ArgumentNullException("progress");
  270. }
  271. if (cancellationToken == null)
  272. {
  273. throw new ArgumentNullException("cancellationToken");
  274. }
  275. var installationInfo = new InstallationInfo
  276. {
  277. Id = Guid.NewGuid(),
  278. Name = package.name,
  279. UpdateClass = package.classification,
  280. Version = package.versionStr
  281. };
  282. var innerCancellationTokenSource = new CancellationTokenSource();
  283. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  284. // Add it to the in-progress list
  285. lock (CurrentInstallations)
  286. {
  287. CurrentInstallations.Add(tuple);
  288. }
  289. var innerProgress = new ActionableProgress<double>();
  290. // Whenever the progress updates, update the outer progress object and InstallationInfo
  291. innerProgress.RegisterAction(percent =>
  292. {
  293. progress.Report(percent);
  294. installationInfo.PercentComplete = percent;
  295. });
  296. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  297. EventHelper.QueueEventIfNotNull(PackageInstalling, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  298. try
  299. {
  300. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  301. lock (CurrentInstallations)
  302. {
  303. CurrentInstallations.Remove(tuple);
  304. }
  305. CompletedInstallations.Add(installationInfo);
  306. EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  307. }
  308. catch (OperationCanceledException)
  309. {
  310. lock (CurrentInstallations)
  311. {
  312. CurrentInstallations.Remove(tuple);
  313. }
  314. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  315. EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  316. throw;
  317. }
  318. catch (Exception ex)
  319. {
  320. _logger.ErrorException("Package installation failed", ex);
  321. lock (CurrentInstallations)
  322. {
  323. CurrentInstallations.Remove(tuple);
  324. }
  325. EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new GenericEventArgs<InstallationInfo> { Argument = installationInfo }, _logger);
  326. throw;
  327. }
  328. finally
  329. {
  330. // Dispose the progress object and remove the installation from the in-progress list
  331. innerProgress.Dispose();
  332. tuple.Item2.Dispose();
  333. }
  334. }
  335. /// <summary>
  336. /// Installs the package internal.
  337. /// </summary>
  338. /// <param name="package">The package.</param>
  339. /// <param name="progress">The progress.</param>
  340. /// <param name="cancellationToken">The cancellation token.</param>
  341. /// <returns>Task.</returns>
  342. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  343. {
  344. // Do the install
  345. await _packageManager.InstallPackage(progress, package, cancellationToken).ConfigureAwait(false);
  346. // Do plugin-specific processing
  347. if (!(Path.GetExtension(package.targetFilename) ?? "").Equals(".zip", StringComparison.OrdinalIgnoreCase))
  348. {
  349. // Set last update time if we were installed before
  350. var plugin = ApplicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  351. if (plugin != null)
  352. {
  353. OnPluginUpdated(plugin, package);
  354. }
  355. else
  356. {
  357. OnPluginInstalled(package);
  358. }
  359. }
  360. }
  361. /// <summary>
  362. /// Uninstalls a plugin
  363. /// </summary>
  364. /// <param name="plugin">The plugin.</param>
  365. /// <exception cref="System.ArgumentException"></exception>
  366. public void UninstallPlugin(IPlugin plugin)
  367. {
  368. plugin.OnUninstalling();
  369. // Remove it the quick way for now
  370. ApplicationHost.RemovePlugin(plugin);
  371. File.Delete(plugin.AssemblyFilePath);
  372. OnPluginUninstalled(plugin);
  373. ApplicationHost.NotifyPendingRestart();
  374. }
  375. /// <summary>
  376. /// Releases unmanaged and - optionally - managed resources.
  377. /// </summary>
  378. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  379. protected virtual void Dispose(bool dispose)
  380. {
  381. if (dispose)
  382. {
  383. lock (CurrentInstallations)
  384. {
  385. foreach (var tuple in CurrentInstallations)
  386. {
  387. tuple.Item2.Dispose();
  388. }
  389. CurrentInstallations.Clear();
  390. }
  391. }
  392. }
  393. public void Dispose()
  394. {
  395. Dispose(true);
  396. }
  397. }
  398. }