BaseConfigurationManager.cs 13 KB

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