BaseConfigurationManager.cs 14 KB

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