InstallationManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. /// <returns>Task{List{PackageInfo}}.</returns>
  142. public async Task<IEnumerable<PackageInfo>> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken)
  143. {
  144. if (_lastPackageListResult != null)
  145. {
  146. // Let dev users get results more often for testing purposes
  147. var cacheLength = _config.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Dev
  148. ? TimeSpan.FromHours(1)
  149. : TimeSpan.FromHours(12);
  150. if ((DateTime.UtcNow - _lastPackageListResult.Item2) < cacheLength)
  151. {
  152. return _lastPackageListResult.Item1;
  153. }
  154. }
  155. using (var json = await _httpClient.Get(Constants.Constants.MbAdminUrl + "service/MB3Packages.json", cancellationToken).ConfigureAwait(false))
  156. {
  157. cancellationToken.ThrowIfCancellationRequested();
  158. var packages = _jsonSerializer.DeserializeFromStream<List<PackageInfo>>(json).ToList();
  159. packages = FilterPackages(packages).ToList();
  160. _lastPackageListResult = new Tuple<List<PackageInfo>, DateTime>(packages, DateTime.UtcNow);
  161. return _lastPackageListResult.Item1;
  162. }
  163. }
  164. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages)
  165. {
  166. foreach (var package in packages)
  167. {
  168. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  169. .OrderByDescending(v => v.version).ToList();
  170. }
  171. // Remove packages with no versions
  172. packages = packages.Where(p => p.versions.Any()).ToList();
  173. return packages;
  174. }
  175. protected IEnumerable<PackageInfo> FilterPackages(List<PackageInfo> packages, PackageType? packageType, Version applicationVersion)
  176. {
  177. foreach (var package in packages)
  178. {
  179. package.versions = package.versions.Where(v => !string.IsNullOrWhiteSpace(v.sourceUrl))
  180. .OrderByDescending(v => v.version).ToList();
  181. }
  182. if (packageType.HasValue)
  183. {
  184. packages = packages.Where(p => p.type == packageType.Value).ToList();
  185. }
  186. // If an app version was supplied, filter the versions for each package to only include supported versions
  187. if (applicationVersion != null)
  188. {
  189. foreach (var package in packages)
  190. {
  191. package.versions = package.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToList();
  192. }
  193. }
  194. // Remove packages with no versions
  195. packages = packages.Where(p => p.versions.Any()).ToList();
  196. return packages;
  197. }
  198. /// <summary>
  199. /// Determines whether [is package version up to date] [the specified package version info].
  200. /// </summary>
  201. /// <param name="packageVersionInfo">The package version info.</param>
  202. /// <param name="currentServerVersion">The current server version.</param>
  203. /// <returns><c>true</c> if [is package version up to date] [the specified package version info]; otherwise, <c>false</c>.</returns>
  204. private bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion)
  205. {
  206. if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr))
  207. {
  208. return true;
  209. }
  210. Version requiredVersion;
  211. return Version.TryParse(packageVersionInfo.requiredVersionStr, out requiredVersion) && currentServerVersion >= requiredVersion;
  212. }
  213. /// <summary>
  214. /// Gets the package.
  215. /// </summary>
  216. /// <param name="name">The name.</param>
  217. /// <param name="classification">The classification.</param>
  218. /// <param name="version">The version.</param>
  219. /// <returns>Task{PackageVersionInfo}.</returns>
  220. public async Task<PackageVersionInfo> GetPackage(string name, PackageVersionClass classification, Version version)
  221. {
  222. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  223. var package = packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  224. if (package == null)
  225. {
  226. return null;
  227. }
  228. return package.versions.FirstOrDefault(v => v.version.Equals(version) && v.classification == classification);
  229. }
  230. /// <summary>
  231. /// Gets the latest compatible version.
  232. /// </summary>
  233. /// <param name="name">The name.</param>
  234. /// <param name="currentServerVersion">The current server version.</param>
  235. /// <param name="classification">The classification.</param>
  236. /// <returns>Task{PackageVersionInfo}.</returns>
  237. public async Task<PackageVersionInfo> GetLatestCompatibleVersion(string name, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  238. {
  239. var packages = await GetAvailablePackages(CancellationToken.None).ConfigureAwait(false);
  240. return GetLatestCompatibleVersion(packages, name, currentServerVersion, classification);
  241. }
  242. /// <summary>
  243. /// Gets the latest compatible version.
  244. /// </summary>
  245. /// <param name="availablePackages">The available packages.</param>
  246. /// <param name="name">The name.</param>
  247. /// <param name="currentServerVersion">The current server version.</param>
  248. /// <param name="classification">The classification.</param>
  249. /// <returns>PackageVersionInfo.</returns>
  250. public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable<PackageInfo> availablePackages, string name, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release)
  251. {
  252. var package = availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase));
  253. if (package == null)
  254. {
  255. return null;
  256. }
  257. return package.versions
  258. .OrderByDescending(v => v.version)
  259. .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion));
  260. }
  261. /// <summary>
  262. /// Gets the available plugin updates.
  263. /// </summary>
  264. /// <param name="currentServerVersion">The current server version.</param>
  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>> GetAvailablePluginUpdates(Version currentServerVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken)
  269. {
  270. var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  271. var plugins = _applicationHost.Plugins.ToList();
  272. if (withAutoUpdateEnabled)
  273. {
  274. plugins = plugins
  275. .Where(p => p.Configuration.EnableAutoUpdate)
  276. .ToList();
  277. }
  278. // Figure out what needs to be installed
  279. var packages = plugins.Select(p =>
  280. {
  281. var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, currentServerVersion, p.Configuration.UpdateClass);
  282. return latestPluginInfo != null && latestPluginInfo.version != null && latestPluginInfo.version > p.Version ? latestPluginInfo : null;
  283. }).Where(i => i != null).ToList();
  284. return packages
  285. .Where(p => !string.IsNullOrWhiteSpace(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.Name, p.name, StringComparison.OrdinalIgnoreCase)));
  286. }
  287. /// <summary>
  288. /// Installs the package.
  289. /// </summary>
  290. /// <param name="package">The package.</param>
  291. /// <param name="progress">The progress.</param>
  292. /// <param name="cancellationToken">The cancellation token.</param>
  293. /// <returns>Task.</returns>
  294. /// <exception cref="System.ArgumentNullException">package</exception>
  295. public async Task InstallPackage(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  296. {
  297. if (package == null)
  298. {
  299. throw new ArgumentNullException("package");
  300. }
  301. if (progress == null)
  302. {
  303. throw new ArgumentNullException("progress");
  304. }
  305. if (cancellationToken == null)
  306. {
  307. throw new ArgumentNullException("cancellationToken");
  308. }
  309. var installationInfo = new InstallationInfo
  310. {
  311. Id = Guid.NewGuid(),
  312. Name = package.name,
  313. UpdateClass = package.classification,
  314. Version = package.versionStr
  315. };
  316. var innerCancellationTokenSource = new CancellationTokenSource();
  317. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  318. // Add it to the in-progress list
  319. lock (CurrentInstallations)
  320. {
  321. CurrentInstallations.Add(tuple);
  322. }
  323. var innerProgress = new ActionableProgress<double>();
  324. // Whenever the progress updates, update the outer progress object and InstallationInfo
  325. innerProgress.RegisterAction(percent =>
  326. {
  327. progress.Report(percent);
  328. installationInfo.PercentComplete = percent;
  329. });
  330. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  331. var installationEventArgs = new InstallationEventArgs
  332. {
  333. InstallationInfo = installationInfo,
  334. PackageVersionInfo = package
  335. };
  336. EventHelper.QueueEventIfNotNull(PackageInstalling, this, installationEventArgs, _logger);
  337. try
  338. {
  339. await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false);
  340. lock (CurrentInstallations)
  341. {
  342. CurrentInstallations.Remove(tuple);
  343. }
  344. CompletedInstallations.Add(installationInfo);
  345. EventHelper.QueueEventIfNotNull(PackageInstallationCompleted, this, installationEventArgs, _logger);
  346. }
  347. catch (OperationCanceledException)
  348. {
  349. lock (CurrentInstallations)
  350. {
  351. CurrentInstallations.Remove(tuple);
  352. }
  353. _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr);
  354. EventHelper.QueueEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger);
  355. throw;
  356. }
  357. catch (Exception ex)
  358. {
  359. _logger.ErrorException("Package installation failed", ex);
  360. lock (CurrentInstallations)
  361. {
  362. CurrentInstallations.Remove(tuple);
  363. }
  364. EventHelper.QueueEventIfNotNull(PackageInstallationFailed, this, new InstallationFailedEventArgs
  365. {
  366. InstallationInfo = installationInfo,
  367. Exception = ex
  368. }, _logger);
  369. throw;
  370. }
  371. finally
  372. {
  373. // Dispose the progress object and remove the installation from the in-progress list
  374. innerProgress.Dispose();
  375. tuple.Item2.Dispose();
  376. }
  377. }
  378. /// <summary>
  379. /// Installs the package internal.
  380. /// </summary>
  381. /// <param name="package">The package.</param>
  382. /// <param name="progress">The progress.</param>
  383. /// <param name="cancellationToken">The cancellation token.</param>
  384. /// <returns>Task.</returns>
  385. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  386. {
  387. // Do the install
  388. await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  389. var extension = Path.GetExtension(package.targetFilename) ?? "";
  390. // Do plugin-specific processing
  391. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase))
  392. {
  393. // Set last update time if we were installed before
  394. var plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  395. if (plugin != null)
  396. {
  397. OnPluginUpdated(plugin, package);
  398. }
  399. else
  400. {
  401. OnPluginInstalled(package);
  402. }
  403. }
  404. }
  405. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  406. {
  407. // Target based on if it is an archive or single assembly
  408. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  409. var extension = Path.GetExtension(package.targetFilename);
  410. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  411. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  412. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  413. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  414. {
  415. Url = package.sourceUrl,
  416. CancellationToken = cancellationToken,
  417. Progress = progress
  418. }).ConfigureAwait(false);
  419. cancellationToken.ThrowIfCancellationRequested();
  420. // Validate with a checksum
  421. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  422. {
  423. using (var crypto = new MD5CryptoServiceProvider())
  424. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  425. {
  426. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  427. if (check != package.checksum)
  428. {
  429. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  430. }
  431. }
  432. }
  433. cancellationToken.ThrowIfCancellationRequested();
  434. // Success - move it to the real target
  435. try
  436. {
  437. File.Copy(tempFile, target, true);
  438. //If it is an archive - write out a version file so we know what it is
  439. if (isArchive)
  440. {
  441. File.WriteAllText(target + ".ver", package.versionStr);
  442. }
  443. }
  444. catch (IOException e)
  445. {
  446. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  447. throw;
  448. }
  449. try
  450. {
  451. File.Delete(tempFile);
  452. }
  453. catch (IOException e)
  454. {
  455. // Don't fail because of this
  456. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  457. }
  458. }
  459. /// <summary>
  460. /// Uninstalls a plugin
  461. /// </summary>
  462. /// <param name="plugin">The plugin.</param>
  463. /// <exception cref="System.ArgumentException"></exception>
  464. public void UninstallPlugin(IPlugin plugin)
  465. {
  466. plugin.OnUninstalling();
  467. // Remove it the quick way for now
  468. _applicationHost.RemovePlugin(plugin);
  469. File.Delete(plugin.AssemblyFilePath);
  470. OnPluginUninstalled(plugin);
  471. _applicationHost.NotifyPendingRestart();
  472. }
  473. /// <summary>
  474. /// Releases unmanaged and - optionally - managed resources.
  475. /// </summary>
  476. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  477. protected virtual void Dispose(bool dispose)
  478. {
  479. if (dispose)
  480. {
  481. lock (CurrentInstallations)
  482. {
  483. foreach (var tuple in CurrentInstallations)
  484. {
  485. tuple.Item2.Dispose();
  486. }
  487. CurrentInstallations.Clear();
  488. }
  489. }
  490. }
  491. public void Dispose()
  492. {
  493. Dispose(true);
  494. }
  495. }
  496. }