BaseConfigurationManager.cs 14 KB

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