BaseConfigurationManager.cs 14 KB

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