BaseConfigurationManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Events;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Serialization;
  13. using Microsoft.Extensions.Logging;
  14. namespace Emby.Server.Implementations.AppBase
  15. {
  16. /// <summary>
  17. /// Class BaseConfigurationManager.
  18. /// </summary>
  19. public abstract class BaseConfigurationManager : IConfigurationManager
  20. {
  21. private readonly IFileSystem _fileSystem;
  22. private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
  23. /// <summary>
  24. /// The _configuration sync lock.
  25. /// </summary>
  26. private readonly object _configurationSyncLock = new object();
  27. private ConfigurationStore[] _configurationStores = Array.Empty<ConfigurationStore>();
  28. private IConfigurationFactory[] _configurationFactories = Array.Empty<IConfigurationFactory>();
  29. /// <summary>
  30. /// The _configuration.
  31. /// </summary>
  32. private BaseApplicationConfiguration? _configuration;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
  35. /// </summary>
  36. /// <param name="applicationPaths">The application paths.</param>
  37. /// <param name="loggerFactory">The logger factory.</param>
  38. /// <param name="xmlSerializer">The XML serializer.</param>
  39. /// <param name="fileSystem">The file system.</param>
  40. protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  41. {
  42. CommonApplicationPaths = applicationPaths;
  43. XmlSerializer = xmlSerializer;
  44. _fileSystem = fileSystem;
  45. Logger = loggerFactory.CreateLogger<BaseConfigurationManager>();
  46. UpdateCachePath();
  47. }
  48. /// <summary>
  49. /// Occurs when [configuration updated].
  50. /// </summary>
  51. public event EventHandler<EventArgs>? ConfigurationUpdated;
  52. /// <summary>
  53. /// Occurs when [configuration updating].
  54. /// </summary>
  55. public event EventHandler<ConfigurationUpdateEventArgs>? NamedConfigurationUpdating;
  56. /// <summary>
  57. /// Occurs when [named configuration updated].
  58. /// </summary>
  59. public event EventHandler<ConfigurationUpdateEventArgs>? NamedConfigurationUpdated;
  60. /// <summary>
  61. /// Gets the type of the configuration.
  62. /// </summary>
  63. /// <value>The type of the configuration.</value>
  64. protected abstract Type ConfigurationType { get; }
  65. /// <summary>
  66. /// Gets the logger.
  67. /// </summary>
  68. /// <value>The logger.</value>
  69. protected ILogger<BaseConfigurationManager> Logger { get; private set; }
  70. /// <summary>
  71. /// Gets the XML serializer.
  72. /// </summary>
  73. /// <value>The XML serializer.</value>
  74. protected IXmlSerializer XmlSerializer { get; private set; }
  75. /// <summary>
  76. /// Gets the application paths.
  77. /// </summary>
  78. /// <value>The application paths.</value>
  79. public IApplicationPaths CommonApplicationPaths { get; private set; }
  80. /// <summary>
  81. /// Gets or sets the system configuration.
  82. /// </summary>
  83. /// <value>The configuration.</value>
  84. public BaseApplicationConfiguration CommonConfiguration
  85. {
  86. get
  87. {
  88. if (_configuration is not null)
  89. {
  90. return _configuration;
  91. }
  92. lock (_configurationSyncLock)
  93. {
  94. if (_configuration is not null)
  95. {
  96. return _configuration;
  97. }
  98. return _configuration = (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer);
  99. }
  100. }
  101. protected set
  102. {
  103. _configuration = value;
  104. }
  105. }
  106. /// <summary>
  107. /// Manually pre-loads a factory so that it is available pre system initialisation.
  108. /// </summary>
  109. /// <typeparam name="T">Class to register.</typeparam>
  110. public virtual void RegisterConfiguration<T>()
  111. where T : IConfigurationFactory
  112. {
  113. IConfigurationFactory factory = Activator.CreateInstance<T>();
  114. if (_configurationFactories is null)
  115. {
  116. _configurationFactories = new[] { factory };
  117. }
  118. else
  119. {
  120. var oldLen = _configurationFactories.Length;
  121. var arr = new IConfigurationFactory[oldLen + 1];
  122. _configurationFactories.CopyTo(arr, 0);
  123. arr[oldLen] = factory;
  124. _configurationFactories = arr;
  125. }
  126. _configurationStores = _configurationFactories
  127. .SelectMany(i => i.GetConfigurations())
  128. .ToArray();
  129. }
  130. /// <summary>
  131. /// Adds parts.
  132. /// </summary>
  133. /// <param name="factories">The configuration factories.</param>
  134. public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
  135. {
  136. _configurationFactories = factories.ToArray();
  137. _configurationStores = _configurationFactories
  138. .SelectMany(i => i.GetConfigurations())
  139. .ToArray();
  140. }
  141. /// <summary>
  142. /// Saves the configuration.
  143. /// </summary>
  144. public void SaveConfiguration()
  145. {
  146. Logger.LogInformation("Saving system configuration");
  147. var path = CommonApplicationPaths.SystemConfigurationFilePath;
  148. Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Path can't be a root directory."));
  149. lock (_configurationSyncLock)
  150. {
  151. XmlSerializer.SerializeToFile(CommonConfiguration, path);
  152. }
  153. OnConfigurationUpdated();
  154. }
  155. /// <summary>
  156. /// Called when [configuration updated].
  157. /// </summary>
  158. protected virtual void OnConfigurationUpdated()
  159. {
  160. UpdateCachePath();
  161. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  162. }
  163. /// <summary>
  164. /// Replaces the configuration.
  165. /// </summary>
  166. /// <param name="newConfiguration">The new configuration.</param>
  167. /// <exception cref="ArgumentNullException"><c>newConfiguration</c> is <c>null</c>.</exception>
  168. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
  169. {
  170. ArgumentNullException.ThrowIfNull(newConfiguration);
  171. ValidateCachePath(newConfiguration);
  172. CommonConfiguration = newConfiguration;
  173. SaveConfiguration();
  174. }
  175. /// <summary>
  176. /// Updates the items by name path.
  177. /// </summary>
  178. private void UpdateCachePath()
  179. {
  180. string cachePath;
  181. // If the configuration file has no entry (i.e. not set in UI)
  182. if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
  183. {
  184. // If the current live configuration has no entry (i.e. not set on CLI/envvars, during startup)
  185. if (string.IsNullOrWhiteSpace(((BaseApplicationPaths)CommonApplicationPaths).CachePath))
  186. {
  187. // Set cachePath to a default value under ProgramDataPath
  188. cachePath = Path.Combine(((BaseApplicationPaths)CommonApplicationPaths).ProgramDataPath, "cache");
  189. }
  190. else
  191. {
  192. // Set cachePath to the existing live value; will require restart if UI value is removed (but not replaced)
  193. // TODO: Figure out how to re-grab this from the CLI/envvars while running
  194. cachePath = ((BaseApplicationPaths)CommonApplicationPaths).CachePath;
  195. }
  196. }
  197. else
  198. {
  199. // Set cachePath to the new UI-set value
  200. cachePath = CommonConfiguration.CachePath;
  201. }
  202. Logger.LogInformation("Setting cache path: {Path}", cachePath);
  203. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
  204. }
  205. /// <summary>
  206. /// Replaces the cache path.
  207. /// </summary>
  208. /// <param name="newConfig">The new configuration.</param>
  209. /// <exception cref="DirectoryNotFoundException">The new cache path doesn't exist.</exception>
  210. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  211. {
  212. var newPath = newConfig.CachePath;
  213. if (!string.IsNullOrWhiteSpace(newPath)
  214. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath, StringComparison.Ordinal))
  215. {
  216. // Validate
  217. if (!Directory.Exists(newPath))
  218. {
  219. throw new DirectoryNotFoundException(
  220. string.Format(
  221. CultureInfo.InvariantCulture,
  222. "{0} does not exist.",
  223. newPath));
  224. }
  225. EnsureWriteAccess(newPath);
  226. }
  227. }
  228. /// <summary>
  229. /// Ensures that we have write access to the path.
  230. /// </summary>
  231. /// <param name="path">The path.</param>
  232. protected void EnsureWriteAccess(string path)
  233. {
  234. var file = Path.Combine(path, Guid.NewGuid().ToString());
  235. File.WriteAllText(file, string.Empty);
  236. _fileSystem.DeleteFile(file);
  237. }
  238. private string GetConfigurationFile(string key)
  239. {
  240. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLowerInvariant() + ".xml");
  241. }
  242. /// <inheritdoc />
  243. public object GetConfiguration(string key)
  244. {
  245. return _configurations.GetOrAdd(
  246. key,
  247. static (k, configurationManager) =>
  248. {
  249. var file = configurationManager.GetConfigurationFile(k);
  250. var configurationInfo = Array.Find(
  251. configurationManager._configurationStores,
  252. i => string.Equals(i.Key, k, StringComparison.OrdinalIgnoreCase));
  253. if (configurationInfo is null)
  254. {
  255. throw new ResourceNotFoundException("Configuration with key " + k + " not found.");
  256. }
  257. var configurationType = configurationInfo.ConfigurationType;
  258. lock (configurationManager._configurationSyncLock)
  259. {
  260. return configurationManager.LoadConfiguration(file, configurationType);
  261. }
  262. },
  263. this);
  264. }
  265. private object LoadConfiguration(string path, Type configurationType)
  266. {
  267. try
  268. {
  269. if (File.Exists(path))
  270. {
  271. return XmlSerializer.DeserializeFromFile(configurationType, path);
  272. }
  273. }
  274. catch (Exception ex) when (ex is not IOException)
  275. {
  276. Logger.LogError(ex, "Error loading configuration file: {Path}", path);
  277. }
  278. return Activator.CreateInstance(configurationType)
  279. ?? throw new InvalidOperationException("Configuration type can't be Nullable<T>.");
  280. }
  281. /// <inheritdoc />
  282. public void SaveConfiguration(string key, object configuration)
  283. {
  284. var configurationStore = GetConfigurationStore(key);
  285. var configurationType = configurationStore.ConfigurationType;
  286. if (configuration.GetType() != configurationType)
  287. {
  288. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  289. }
  290. if (configurationStore is IValidatingConfiguration validatingStore)
  291. {
  292. var currentConfiguration = GetConfiguration(key);
  293. validatingStore.Validate(currentConfiguration, configuration);
  294. }
  295. NamedConfigurationUpdating?.Invoke(this, new ConfigurationUpdateEventArgs(key, configuration));
  296. _configurations.AddOrUpdate(key, configuration, (_, _) => configuration);
  297. var path = GetConfigurationFile(key);
  298. Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Path can't be a root directory."));
  299. lock (_configurationSyncLock)
  300. {
  301. XmlSerializer.SerializeToFile(configuration, path);
  302. }
  303. OnNamedConfigurationUpdated(key, configuration);
  304. }
  305. /// <summary>
  306. /// Event handler for when a named configuration has been updated.
  307. /// </summary>
  308. /// <param name="key">The key of the configuration.</param>
  309. /// <param name="configuration">The old configuration.</param>
  310. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  311. {
  312. NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs(key, configuration));
  313. }
  314. /// <inheritdoc />
  315. public ConfigurationStore[] GetConfigurationStores()
  316. {
  317. return _configurationStores;
  318. }
  319. /// <inheritdoc />
  320. public Type GetConfigurationType(string key)
  321. {
  322. return GetConfigurationStore(key)
  323. .ConfigurationType;
  324. }
  325. private ConfigurationStore GetConfigurationStore(string key)
  326. {
  327. return _configurationStores
  328. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  329. }
  330. }
  331. }