BaseConfigurationManager.cs 14 KB

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