BaseConfigurationManager.cs 14 KB

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