BaseConfigurationManager.cs 14 KB

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