BaseConfigurationManager.cs 13 KB

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