InstallationManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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.FromMinutes(15)
  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="applicationVersion">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 applicationVersion, 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, applicationVersion, 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. var installationInfo = new InstallationInfo
  306. {
  307. Id = Guid.NewGuid(),
  308. Name = package.name,
  309. UpdateClass = package.classification,
  310. Version = package.versionStr
  311. };
  312. var innerCancellationTokenSource = new CancellationTokenSource();
  313. var tuple = new Tuple<InstallationInfo, CancellationTokenSource>(installationInfo, innerCancellationTokenSource);
  314. // Add it to the in-progress list
  315. lock (CurrentInstallations)
  316. {
  317. CurrentInstallations.Add(tuple);
  318. }
  319. var innerProgress = new ActionableProgress<double>();
  320. // Whenever the progress updates, update the outer progress object and InstallationInfo
  321. innerProgress.RegisterAction(percent =>
  322. {
  323. progress.Report(percent);
  324. installationInfo.PercentComplete = percent;
  325. });
  326. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token;
  327. var installationEventArgs = new InstallationEventArgs
  328. {
  329. InstallationInfo = installationInfo,
  330. PackageVersionInfo = package
  331. };
  332. EventHelper.QueueEventIfNotNull(PackageInstalling, this, installationEventArgs, _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, installationEventArgs, _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, installationEventArgs, _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 InstallationFailedEventArgs
  361. {
  362. InstallationInfo = installationInfo,
  363. Exception = ex
  364. }, _logger);
  365. throw;
  366. }
  367. finally
  368. {
  369. // Dispose the progress object and remove the installation from the in-progress list
  370. innerProgress.Dispose();
  371. tuple.Item2.Dispose();
  372. }
  373. }
  374. /// <summary>
  375. /// Installs the package internal.
  376. /// </summary>
  377. /// <param name="package">The package.</param>
  378. /// <param name="progress">The progress.</param>
  379. /// <param name="cancellationToken">The cancellation token.</param>
  380. /// <returns>Task.</returns>
  381. private async Task InstallPackageInternal(PackageVersionInfo package, IProgress<double> progress, CancellationToken cancellationToken)
  382. {
  383. // Do the install
  384. await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false);
  385. var extension = Path.GetExtension(package.targetFilename) ?? "";
  386. // Do plugin-specific processing
  387. if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase))
  388. {
  389. // Set last update time if we were installed before
  390. var plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.name, StringComparison.OrdinalIgnoreCase));
  391. if (plugin != null)
  392. {
  393. OnPluginUpdated(plugin, package);
  394. }
  395. else
  396. {
  397. OnPluginInstalled(package);
  398. }
  399. }
  400. }
  401. private async Task PerformPackageInstallation(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
  402. {
  403. // Target based on if it is an archive or single assembly
  404. // zip archives are assumed to contain directory structures relative to our ProgramDataPath
  405. var extension = Path.GetExtension(package.targetFilename);
  406. var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
  407. var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
  408. // Download to temporary file so that, if interrupted, it won't destroy the existing installation
  409. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  410. {
  411. Url = package.sourceUrl,
  412. CancellationToken = cancellationToken,
  413. Progress = progress
  414. }).ConfigureAwait(false);
  415. cancellationToken.ThrowIfCancellationRequested();
  416. // Validate with a checksum
  417. if (package.checksum != Guid.Empty) // support for legacy uploads for now
  418. {
  419. using (var crypto = new MD5CryptoServiceProvider())
  420. using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
  421. {
  422. var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
  423. if (check != package.checksum)
  424. {
  425. throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
  426. }
  427. }
  428. }
  429. cancellationToken.ThrowIfCancellationRequested();
  430. // Success - move it to the real target
  431. try
  432. {
  433. File.Copy(tempFile, target, true);
  434. //If it is an archive - write out a version file so we know what it is
  435. if (isArchive)
  436. {
  437. File.WriteAllText(target + ".ver", package.versionStr);
  438. }
  439. }
  440. catch (IOException e)
  441. {
  442. _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
  443. throw;
  444. }
  445. try
  446. {
  447. File.Delete(tempFile);
  448. }
  449. catch (IOException e)
  450. {
  451. // Don't fail because of this
  452. _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
  453. }
  454. }
  455. /// <summary>
  456. /// Uninstalls a plugin
  457. /// </summary>
  458. /// <param name="plugin">The plugin.</param>
  459. /// <exception cref="System.ArgumentException"></exception>
  460. public void UninstallPlugin(IPlugin plugin)
  461. {
  462. plugin.OnUninstalling();
  463. // Remove it the quick way for now
  464. _applicationHost.RemovePlugin(plugin);
  465. File.Delete(plugin.AssemblyFilePath);
  466. OnPluginUninstalled(plugin);
  467. _applicationHost.NotifyPendingRestart();
  468. }
  469. /// <summary>
  470. /// Releases unmanaged and - optionally - managed resources.
  471. /// </summary>
  472. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  473. protected virtual void Dispose(bool dispose)
  474. {
  475. if (dispose)
  476. {
  477. lock (CurrentInstallations)
  478. {
  479. foreach (var tuple in CurrentInstallations)
  480. {
  481. tuple.Item2.Dispose();
  482. }
  483. CurrentInstallations.Clear();
  484. }
  485. }
  486. }
  487. public void Dispose()
  488. {
  489. Dispose(true);
  490. }
  491. }
  492. }