InstallationManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Plugins;
  5. using MediaBrowser.Common.Progress;
  6. using MediaBrowser.Common.Security;
  7. using MediaBrowser.Common.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.Security.Cryptography;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Implementations.Updates
  20. {
  21. /// <summary>
  22. /// Manages all install, uninstall and update operations (both plugins and system)
  23. /// </summary>
  24. public class InstallationManager : IInstallationManager
  25. {
  26. public event EventHandler<InstallationEventArgs> PackageInstalling;
  27. public event EventHandler<InstallationEventArgs> PackageInstallationCompleted;
  28. public event EventHandler<InstallationFailedEventArgs> PackageInstallationFailed;
  29. public event EventHandler<InstallationEventArgs> PackageInstallationCancelled;
  30. /// <summary>
  31. /// The current installations
  32. /// </summary>
  33. public List<Tuple<InstallationInfo, CancellationTokenSource>> CurrentInstallations { get; set; }
  34. /// <summary>
  35. /// The completed installations
  36. /// </summary>
  37. public ConcurrentBag<InstallationInfo> CompletedInstallations { get; set; }
  38. #region PluginUninstalled Event
  39. /// <summary>
  40. /// Occurs when [plugin uninstalled].
  41. /// </summary>
  42. public event EventHandler<GenericEventArgs<IPlugin>> PluginUninstalled;
  43. /// <summary>
  44. /// Called when [plugin uninstalled].
  45. /// </summary>
  46. /// <param name="plugin">The plugin.</param>
  47. private void OnPluginUninstalled(IPlugin plugin)
  48. {
  49. EventHelper.QueueEventIfNotNull(PluginUninstalled, this, new GenericEventArgs<IPlugin> { Argument = plugin }, _logger);
  50. }
  51. #endregion
  52. #region PluginUpdated Event
  53. /// <summary>
  54. /// Occurs when [plugin updated].
  55. /// </summary>
  56. public event EventHandler<GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>>> PluginUpdated;
  57. /// <summary>
  58. /// Called when [plugin updated].
  59. /// </summary>
  60. /// <param name="plugin">The plugin.</param>
  61. /// <param name="newVersion">The new version.</param>
  62. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion)
  63. {
  64. _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.version, newVersion.classification);
  65. EventHelper.QueueEventIfNotNull(PluginUpdated, this, new GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> { Argument = new Tuple<IPlugin, PackageVersionInfo>(plugin, newVersion) }, _logger);
  66. _applicationHost.NotifyPendingRestart();
  67. }
  68. #endregion
  69. #region PluginInstalled Event
  70. /// <summary>
  71. /// Occurs when [plugin updated].
  72. /// </summary>
  73. public event EventHandler<GenericEventArgs<PackageVersionInfo>> PluginInstalled;
  74. /// <summary>
  75. /// Called when [plugin installed].
  76. /// </summary>
  77. /// <param name="package">The package.</param>
  78. private void OnPluginInstalled(PackageVersionInfo package)
  79. {
  80. _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.version, package.classification);
  81. EventHelper.QueueEventIfNotNull(PluginInstalled, this, new GenericEventArgs<PackageVersionInfo> { Argument = package }, _logger);
  82. _applicationHost.NotifyPendingRestart();
  83. }
  84. #endregion
  85. /// <summary>
  86. /// The _logger
  87. /// </summary>
  88. private readonly ILogger _logger;
  89. private readonly IApplicationPaths _appPaths;
  90. private readonly IHttpClient _httpClient;
  91. private readonly IJsonSerializer _jsonSerializer;
  92. private readonly ISecurityManager _securityManager;
  93. private readonly INetworkManager _networkManager;
  94. private readonly IConfigurationManager _config;
  95. /// <summary>
  96. /// Gets the application host.
  97. /// </summary>
  98. /// <value>The application host.</value>
  99. private readonly IApplicationHost _applicationHost;
  100. public InstallationManager(ILogger logger, IApplicationHost appHost, IApplicationPaths appPaths, IHttpClient httpClient, IJsonSerializer jsonSerializer, ISecurityManager securityManager, INetworkManager networkManager, IConfigurationManager config)
  101. {
  102. if (logger == null)
  103. {
  104. throw new ArgumentNullException("logger");
  105. }
  106. CurrentInstallations = new List<Tuple<InstallationInfo, CancellationTokenSource>>();
  107. CompletedInstallations = new ConcurrentBag<InstallationInfo>();
  108. _applicationHost = appHost;
  109. _appPaths = appPaths;
  110. _httpClient = httpClient;
  111. _jsonSerializer = jsonSerializer;
  112. _securityManager = securityManager;
  113. _networkManager = networkManager;
  114. _config = config;
  115. _logger = logger;
  116. }
  117. /// <summary>
  118. /// Gets all available packages.
  119. /// </summary>
  120. /// <param name="cancellationToken">The cancellation token.</param>
  121. /// <param name="packageType">Type of the package.</param>
  122. /// <param name="applicationVersion">The application version.</param>
  123. /// <returns>Task{List{PackageInfo}}.</returns>
  124. public async Task<IEnumerable<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken,
  125. PackageType? packageType = null,
  126. Version applicationVersion = null)
  127. {
  128. var data = new Dictionary<string, string> { { "key", _securityManager.SupporterKey }, { "mac", _networkManager.GetMacAddress() } };
  129. using (var json = await _httpClient.Post(Constants.Constants.MbAdminUrl + "service/package/retrieveall", data, cancellationToken).ConfigureAwait(false))
  130. {
  131. cancellationToken.ThrowIfCancellationRequested();
  132. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  133. return FilterPackages(packages, packageType, applicationVersion);
  134. }
  135. }
  136. private Tuple<List<PackageInfo>, DateTime> _lastPackageListResult;
  137. /// <summary>
  138. /// Gets all available packages.
  139. /// </summary>
  140. /// <param name="cancellationToken">The cancellation token.</param>
  141. /// <param name="packageType">Type of the package.</param>
  142. /// <param name="applicationVersion">The application version.</param>
  143. /// <returns>Task{List{PackageInfo}}.</returns>
  144. public async Task<IEnumerable<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken,
  145. PackageType? packageType = null,
  146. Version applicationVersion = null)
  147. {
  148. if (_lastPackageListResult != null)
  149. {
  150. // Let dev users get results more often for testing purposes
  151. var cacheLength = _config.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Dev
  152. ? TimeSpan.FromHours(1)
  153. : TimeSpan.FromHours(12);
  154. if ((DateTime.UtcNow - _lastPackageListResult.Item2) < cacheLength)
  155. {
  156. return _lastPackageListResult.Item1;
  157. }
  158. }
  159. using (var json = await _httpClient.Get(Constants.Constants.MbAdminUrl + "service/MB3Packages.json", cancellationToken).ConfigureAwait(false))
  160. {
  161. cancellationToken.ThrowIfCancellationRequested();
  162. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  163. _lastPackageListResult = new Tuple<List<PackageInfo>, DateTime>(packages, DateTime.UtcNow);
  164. return FilterPackages(packages, packageType, applicationVersion);
  165. }
  166. }
  167. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, PackageType? packageType, Version applicationVersion)
  168. {
  169. foreach (var package in packages)
  170. {
  171. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  172. .OrderByDescending(v => v.version).ToList();
  173. }
  174. if (packageType.HasValue)
  175. {
  176. packages = packages.Where(p => p.type == packageType.Value).ToList();
  177. }
  178. // If an app version was supplied, filter the versions for each package to only include supported versions
  179. if (applicationVersion != null)
  180. {
  181. foreach (var package in packages)
  182. {
  183. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  184. }
  185. }
  186. // Remove packages with no versions
  187. packages = packages.Where(p => p.versions.Any()).ToList();
  188. return packages;
  189. }
  190. /// <summary>
  191. /// Determines whether [is package version up to date] [the specified package version info].
  192. /// </summary>
  193. /// <param name="packageVersionInfo">The package version info.</param>
  194. /// <param name="currentServerVersion">The current server version.</param>
  195. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  196. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  197. {
  198. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  199. {
  200. return true;
  201. }
  202. Version requiredVersion;
  203. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && currentServerVersion >= requiredVersion;
  204. }
  205. /// <summary>
  206. /// Gets the package.
  207. /// </summary>
  208. /// <param name="name">The name.</param>
  209. /// <param name="classification">The classification.</param>
  210. /// <param name="version">The version.</param>
  211. /// <returns>Task{PackageVersionInfo}.</returns>
  212. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  213. {
  214. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  215. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  216. if (package == null)
  217. {
  218. return null;
  219. }
  220. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  221. }
  222. /// <summary>
  223. /// Gets the latest compatible version.
  224. /// </summary>
  225. /// <param name="name">The name.</param>
  226. /// <param name="currentServerVersion">The current server version.</param>
  227. /// <param name="classification">The classification.</param>
  228. /// <returns>Task{PackageVersionInfo}.</returns>
  229. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  230. {
  231. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  232. return GetLatestCompatibleVersion(packages, name, currentServerVersion, classification);
  233. }
  234. /// <summary>
  235. /// Gets the latest compatible version.
  236. /// </summary>
  237. /// <param name="availablePackages">The available packages.</param>
  238. /// <param name="name">The name.</param>
  239. /// <param name="currentServerVersion">The current server version.</param>
  240. /// <param name="classification">The classification.</param>
  241. /// <returns>PackageVersionInfo.</returns>
  242. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  243. {
  244. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  245. if (package == null)
  246. {
  247. return null;
  248. }
  249. return package.versions
  250. .OrderByDescending(v => v.version)
  251. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  252. }
  253. /// <summary>
  254. /// Gets the available plugin updates.
  255. /// </summary>
  256. /// <param name="currentServerVersion">The current server version.</param>
  257. /// <param name="withAutoUpdateEnabled">if set to <c>true</c> [with auto update enabled].</param>
  258. /// <param name="cancellationToken">The cancellation token.</param>
  259. /// <returns>Task{IEnumerable{PackageVersionInfo}}.</returns>
  260. public async Task<IEnumerable<PackageVersionInfo>> GetAvailablePluginUpdates(Version currentServerVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  261. {
  262. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  263. var plugins = _applicationHost.Plugins.ToList();
  264. if (withAutoUpdateEnabled)
  265. {
  266. plugins = plugins
  267. .Where(p => p.Configuration.EnableAutoUpdate)
  268. .ToList();
  269. }
  270. // Figure out what needs to be installed
  271. var packages = plugins.Select(p =>
  272. {
  273. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, currentServerVersion, p.Configuration.UpdateClass);
  274. return latestPluginInfo != null && latestPluginInfo.version != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  275. }).Where(i => i != null).ToList();
  276. return packages
  277. .Where(p => !string.IsNullOrWhiteSpace(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.Name, p.name, StringComparison.OrdinalIgnoreCase)));
  278. }
  279. /// <summary>
  280. /// Installs the package.
  281. /// </summary>
  282. /// <param name="package">The package.</param>
  283. /// <param name="progress">The progress.</param>
  284. /// <param name="cancellationToken">The cancellation token.</param>
  285. /// <returns>Task.</returns>
  286. /// <exception cref="System.ArgumentNullException">package</exception>
  287. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  288. {
  289. if (package == null)
  290. {
  291. throw new ArgumentNullException("package");
  292. }
  293. if (progress == null)
  294. {
  295. throw new ArgumentNullException("progress");
  296. }
  297. if (cancellationToken == null)
  298. {
  299. throw new ArgumentNullException("cancellationToken");
  300. }
  301. var installationInfo = new InstallationInfo
  302. {
  303. Id = Guid.NewGuid(),
  304. Name = package.name,
  305. UpdateClass = package.classification,
  306. Version = package.versionStr
  307. };
  308. var innerCancellationTokenSource = new CancellationTokenSource();
  309. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  310. // Add it to the in-progress list
  311. lock (CurrentInstallations)
  312. {
  313. CurrentInstallations.Add(tuple);
  314. }
  315. var innerProgress = new ActionableProgress<double>();
  316. // Whenever the progress updates, update the outer progress object and InstallationInfo
  317. innerProgress.RegisterAction(percent =>
  318. {
  319. progress.Report(percent);
  320. installationInfo.PercentComplete = percent;
  321. });
  322. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  323. var installationEventArgs = new InstallationEventArgs
  324. {
  325. InstallationInfo = installationInfo,
  326. PackageVersionInfo = package
  327. };
  328. EventHelper.QueueEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
  329. try
  330. {
  331. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  332. lock (CurrentInstallations)
  333. {
  334. CurrentInstallations.Remove(tuple);
  335. }
  336. CompletedInstallations.Add(installationInfo);
  337. EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  338. }
  339. catch (OperationCanceledException)
  340. {
  341. lock (CurrentInstallations)
  342. {
  343. CurrentInstallations.Remove(tuple);
  344. }
  345. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  346. EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  347. throw;
  348. }
  349. catch (Exception ex)
  350. {
  351. _logger.ErrorException("Package installation failed", ex);
  352. lock (CurrentInstallations)
  353. {
  354. CurrentInstallations.Remove(tuple);
  355. }
  356. EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  357. {
  358. InstallationInfo = installationInfo,
  359. Exception = ex
  360. }, _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 PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  381. var extension = Path.GetExtension(package.targetFilename) ?? "";
  382. // Do plugin-specific processing
  383. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase))
  384. {
  385. // Set last update time if we were installed before
  386. var plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  387. if (plugin != null)
  388. {
  389. OnPluginUpdated(plugin, package);
  390. }
  391. else
  392. {
  393. OnPluginInstalled(package);
  394. }
  395. }
  396. }
  397. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  398. {
  399. // Target based on if it is an archive or single assembly
  400. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  401. var extension = Path.GetExtension(package.targetFilename);
  402. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  403. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  404. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  405. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  406. {
  407. Url = package.sourceUrl,
  408. CancellationToken = cancellationToken,
  409. Progress = progress
  410. }).ConfigureAwait(false);
  411. cancellationToken.ThrowIfCancellationRequested();
  412. // Validate with a checksum
  413. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  414. {
  415. using (var crypto = new MD5CryptoServiceProvider())
  416. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  417. {
  418. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  419. if (check != package.checksum)
  420. {
  421. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  422. }
  423. }
  424. }
  425. cancellationToken.ThrowIfCancellationRequested();
  426. // Success - move it to the real target
  427. try
  428. {
  429. File.Copy(tempFile, target, true);
  430. //If it is an archive - write out a version file so we know what it is
  431. if (isArchive)
  432. {
  433. File.WriteAllText(target + ".ver", package.versionStr);
  434. }
  435. }
  436. catch (IOException e)
  437. {
  438. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  439. throw;
  440. }
  441. try
  442. {
  443. File.Delete(tempFile);
  444. }
  445. catch (IOException e)
  446. {
  447. // Don't fail because of this
  448. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  449. }
  450. }
  451. /// <summary>
  452. /// Uninstalls a plugin
  453. /// </summary>
  454. /// <param name="plugin">The plugin.</param>
  455. /// <exception cref="System.ArgumentException"></exception>
  456. public void UninstallPlugin(IPlugin plugin)
  457. {
  458. plugin.OnUninstalling();
  459. // Remove it the quick way for now
  460. _applicationHost.RemovePlugin(plugin);
  461. File.Delete(plugin.AssemblyFilePath);
  462. OnPluginUninstalled(plugin);
  463. _applicationHost.NotifyPendingRestart();
  464. }
  465. /// <summary>
  466. /// Releases unmanaged and - optionally - managed resources.
  467. /// </summary>
  468. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  469. protected virtual void Dispose(bool dispose)
  470. {
  471. if (dispose)
  472. {
  473. lock (CurrentInstallations)
  474. {
  475. foreach (var tuple in CurrentInstallations)
  476. {
  477. tuple.Item2.Dispose();
  478. }
  479. CurrentInstallations.Clear();
  480. }
  481. }
  482. }
  483. public void Dispose()
  484. {
  485. Dispose(true);
  486. }
  487. }
  488. }