BaseConfigurationManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 = [factory];
  113. }
  114. else
  115. {
  116. _configurationFactories = [.._configurationFactories, factory];
  117. }
  118. _configurationStores = _configurationFactories
  119. .SelectMany(i => i.GetConfigurations())
  120. .ToArray();
  121. }
  122. /// <summary>
  123. /// Adds parts.
  124. /// </summary>
  125. /// <param name="factories">The configuration factories.</param>
  126. public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
  127. {
  128. _configurationFactories = factories.ToArray();
  129. _configurationStores = _configurationFactories
  130. .SelectMany(i => i.GetConfigurations())
  131. .ToArray();
  132. }
  133. /// <summary>
  134. /// Saves the configuration.
  135. /// </summary>
  136. public void SaveConfiguration()
  137. {
  138. Logger.LogInformation("Saving system configuration");
  139. var path = CommonApplicationPaths.SystemConfigurationFilePath;
  140. Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Path can't be a root directory."));
  141. lock (_configurationSyncLock)
  142. {
  143. XmlSerializer.SerializeToFile(CommonConfiguration, path);
  144. }
  145. OnConfigurationUpdated();
  146. }
  147. /// <summary>
  148. /// Called when [configuration updated].
  149. /// </summary>
  150. protected virtual void OnConfigurationUpdated()
  151. {
  152. UpdateCachePath();
  153. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  154. }
  155. /// <summary>
  156. /// Replaces the configuration.
  157. /// </summary>
  158. /// <param name="newConfiguration">The new configuration.</param>
  159. /// <exception cref="ArgumentNullException"><c>newConfiguration</c> is <c>null</c>.</exception>
  160. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
  161. {
  162. ArgumentNullException.ThrowIfNull(newConfiguration);
  163. ValidateCachePath(newConfiguration);
  164. CommonConfiguration = newConfiguration;
  165. SaveConfiguration();
  166. }
  167. /// <summary>
  168. /// Updates the items by name path.
  169. /// </summary>
  170. private void UpdateCachePath()
  171. {
  172. string cachePath;
  173. // If the configuration file has no entry (i.e. not set in UI)
  174. if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
  175. {
  176. // If the current live configuration has no entry (i.e. not set on CLI/envvars, during startup)
  177. if (string.IsNullOrWhiteSpace(((BaseApplicationPaths)CommonApplicationPaths).CachePath))
  178. {
  179. // Set cachePath to a default value under ProgramDataPath
  180. cachePath = Path.Combine(((BaseApplicationPaths)CommonApplicationPaths).ProgramDataPath, "cache");
  181. }
  182. else
  183. {
  184. // Set cachePath to the existing live value; will require restart if UI value is removed (but not replaced)
  185. // TODO: Figure out how to re-grab this from the CLI/envvars while running
  186. cachePath = ((BaseApplicationPaths)CommonApplicationPaths).CachePath;
  187. }
  188. }
  189. else
  190. {
  191. // Set cachePath to the new UI-set value
  192. cachePath = CommonConfiguration.CachePath;
  193. }
  194. Logger.LogInformation("Setting cache path: {Path}", cachePath);
  195. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
  196. }
  197. /// <summary>
  198. /// Replaces the cache path.
  199. /// </summary>
  200. /// <param name="newConfig">The new configuration.</param>
  201. /// <exception cref="DirectoryNotFoundException">The new cache path doesn't exist.</exception>
  202. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  203. {
  204. var newPath = newConfig.CachePath;
  205. if (!string.IsNullOrWhiteSpace(newPath)
  206. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath, StringComparison.Ordinal))
  207. {
  208. // Validate
  209. if (!Directory.Exists(newPath))
  210. {
  211. throw new DirectoryNotFoundException(
  212. string.Format(
  213. CultureInfo.InvariantCulture,
  214. "{0} does not exist.",
  215. newPath));
  216. }
  217. EnsureWriteAccess(newPath);
  218. }
  219. }
  220. /// <summary>
  221. /// Ensures that we have write access to the path.
  222. /// </summary>
  223. /// <param name="path">The path.</param>
  224. protected void EnsureWriteAccess(string path)
  225. {
  226. var file = Path.Combine(path, Guid.NewGuid().ToString());
  227. File.WriteAllText(file, string.Empty);
  228. File.Delete(file);
  229. }
  230. private string GetConfigurationFile(string key)
  231. {
  232. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLowerInvariant() + ".xml");
  233. }
  234. /// <inheritdoc />
  235. public object GetConfiguration(string key)
  236. {
  237. return _configurations.GetOrAdd(
  238. key,
  239. static (k, configurationManager) =>
  240. {
  241. var file = configurationManager.GetConfigurationFile(k);
  242. var configurationInfo = Array.Find(
  243. configurationManager._configurationStores,
  244. i => string.Equals(i.Key, k, StringComparison.OrdinalIgnoreCase));
  245. if (configurationInfo is null)
  246. {
  247. throw new ResourceNotFoundException("Configuration with key " + k + " not found.");
  248. }
  249. var configurationType = configurationInfo.ConfigurationType;
  250. lock (configurationManager._configurationSyncLock)
  251. {
  252. return configurationManager.LoadConfiguration(file, configurationType);
  253. }
  254. },
  255. this);
  256. }
  257. private object LoadConfiguration(string path, Type configurationType)
  258. {
  259. try
  260. {
  261. if (File.Exists(path))
  262. {
  263. return XmlSerializer.DeserializeFromFile(configurationType, path);
  264. }
  265. }
  266. catch (Exception ex) when (ex is not IOException)
  267. {
  268. Logger.LogError(ex, "Error loading configuration file: {Path}", path);
  269. }
  270. return Activator.CreateInstance(configurationType)
  271. ?? throw new InvalidOperationException("Configuration type can't be Nullable<T>.");
  272. }
  273. /// <inheritdoc />
  274. public void SaveConfiguration(string key, object configuration)
  275. {
  276. var configurationStore = GetConfigurationStore(key);
  277. var configurationType = configurationStore.ConfigurationType;
  278. if (configuration.GetType() != configurationType)
  279. {
  280. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  281. }
  282. if (configurationStore is IValidatingConfiguration validatingStore)
  283. {
  284. var currentConfiguration = GetConfiguration(key);
  285. validatingStore.Validate(currentConfiguration, configuration);
  286. }
  287. NamedConfigurationUpdating?.Invoke(this, new ConfigurationUpdateEventArgs(key, configuration));
  288. _configurations.AddOrUpdate(key, configuration, (_, _) => configuration);
  289. var path = GetConfigurationFile(key);
  290. Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Path can't be a root directory."));
  291. lock (_configurationSyncLock)
  292. {
  293. XmlSerializer.SerializeToFile(configuration, path);
  294. }
  295. OnNamedConfigurationUpdated(key, configuration);
  296. }
  297. /// <summary>
  298. /// Event handler for when a named configuration has been updated.
  299. /// </summary>
  300. /// <param name="key">The key of the configuration.</param>
  301. /// <param name="configuration">The old configuration.</param>
  302. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  303. {
  304. NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs(key, configuration));
  305. }
  306. /// <inheritdoc />
  307. public ConfigurationStore[] GetConfigurationStores()
  308. {
  309. return _configurationStores;
  310. }
  311. /// <inheritdoc />
  312. public Type GetConfigurationType(string key)
  313. {
  314. return GetConfigurationStore(key)
  315. .ConfigurationType;
  316. }
  317. private ConfigurationStore GetConfigurationStore(string key)
  318. {
  319. return _configurationStores
  320. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  321. }
  322. }
  323. }