BaseConfigurationManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 System.Threading;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Events;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Serialization;
  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 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(GetType().Name);
  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 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 or sets the application paths.
  82. /// </summary>
  83. /// <value>The application paths.</value>
  84. public IApplicationPaths CommonApplicationPaths { get; private set; }
  85. /// <summary>
  86. /// Gets the system configuration
  87. /// </summary>
  88. /// <value>The configuration.</value>
  89. public BaseApplicationConfiguration CommonConfiguration
  90. {
  91. get
  92. {
  93. // Lazy load
  94. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer));
  95. return _configuration;
  96. }
  97. protected set
  98. {
  99. _configuration = value;
  100. _configurationLoaded = value != null;
  101. }
  102. }
  103. public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
  104. {
  105. _configurationFactories = factories.ToArray();
  106. _configurationStores = _configurationFactories
  107. .SelectMany(i => i.GetConfigurations())
  108. .ToArray();
  109. }
  110. /// <summary>
  111. /// Saves the configuration.
  112. /// </summary>
  113. public void SaveConfiguration()
  114. {
  115. Logger.LogInformation("Saving system configuration");
  116. var path = CommonApplicationPaths.SystemConfigurationFilePath;
  117. Directory.CreateDirectory(Path.GetDirectoryName(path));
  118. lock (_configurationSyncLock)
  119. {
  120. XmlSerializer.SerializeToFile(CommonConfiguration, path);
  121. }
  122. OnConfigurationUpdated();
  123. }
  124. /// <summary>
  125. /// Called when [configuration updated].
  126. /// </summary>
  127. protected virtual void OnConfigurationUpdated()
  128. {
  129. UpdateCachePath();
  130. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  131. }
  132. /// <summary>
  133. /// Replaces the configuration.
  134. /// </summary>
  135. /// <param name="newConfiguration">The new configuration.</param>
  136. /// <exception cref="ArgumentNullException">newConfiguration</exception>
  137. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
  138. {
  139. if (newConfiguration == null)
  140. {
  141. throw new ArgumentNullException(nameof(newConfiguration));
  142. }
  143. ValidateCachePath(newConfiguration);
  144. CommonConfiguration = newConfiguration;
  145. SaveConfiguration();
  146. }
  147. /// <summary>
  148. /// Updates the items by name path.
  149. /// </summary>
  150. private void UpdateCachePath()
  151. {
  152. string cachePath;
  153. // If the configuration file has no entry (i.e. not set in UI)
  154. if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
  155. {
  156. // If the current live configuration has no entry (i.e. not set on CLI/envvars, during startup)
  157. if (string.IsNullOrWhiteSpace(((BaseApplicationPaths)CommonApplicationPaths).CachePath))
  158. {
  159. // Set cachePath to a default value under ProgramDataPath
  160. cachePath = Path.Combine(((BaseApplicationPaths)CommonApplicationPaths).ProgramDataPath, "cache");
  161. }
  162. else
  163. {
  164. // Set cachePath to the existing live value; will require restart if UI value is removed (but not replaced)
  165. // TODO: Figure out how to re-grab this from the CLI/envvars while running
  166. cachePath = ((BaseApplicationPaths)CommonApplicationPaths).CachePath;
  167. }
  168. }
  169. else
  170. {
  171. // Set cachePath to the new UI-set value
  172. cachePath = CommonConfiguration.CachePath;
  173. }
  174. Logger.LogInformation("Setting cache path to " + cachePath);
  175. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
  176. }
  177. /// <summary>
  178. /// Replaces the cache path.
  179. /// </summary>
  180. /// <param name="newConfig">The new configuration.</param>
  181. /// <exception cref="DirectoryNotFoundException"></exception>
  182. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  183. {
  184. var newPath = newConfig.CachePath;
  185. if (!string.IsNullOrWhiteSpace(newPath)
  186. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath, StringComparison.Ordinal))
  187. {
  188. // Validate
  189. if (!Directory.Exists(newPath))
  190. {
  191. throw new FileNotFoundException(
  192. string.Format(
  193. CultureInfo.InvariantCulture,
  194. "{0} does not exist.",
  195. newPath));
  196. }
  197. EnsureWriteAccess(newPath);
  198. }
  199. }
  200. protected void EnsureWriteAccess(string path)
  201. {
  202. var file = Path.Combine(path, Guid.NewGuid().ToString());
  203. File.WriteAllText(file, string.Empty);
  204. _fileSystem.DeleteFile(file);
  205. }
  206. private string GetConfigurationFile(string key)
  207. {
  208. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLowerInvariant() + ".xml");
  209. }
  210. public object GetConfiguration(string key)
  211. {
  212. return _configurations.GetOrAdd(key, k =>
  213. {
  214. var file = GetConfigurationFile(key);
  215. var configurationInfo = _configurationStores
  216. .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  217. if (configurationInfo == null)
  218. {
  219. throw new ResourceNotFoundException("Configuration with key " + key + " not found.");
  220. }
  221. var configurationType = configurationInfo.ConfigurationType;
  222. lock (_configurationSyncLock)
  223. {
  224. return LoadConfiguration(file, configurationType);
  225. }
  226. });
  227. }
  228. private object LoadConfiguration(string path, Type configurationType)
  229. {
  230. if (!File.Exists(path))
  231. {
  232. return Activator.CreateInstance(configurationType);
  233. }
  234. try
  235. {
  236. return XmlSerializer.DeserializeFromFile(configurationType, path);
  237. }
  238. catch (IOException)
  239. {
  240. return Activator.CreateInstance(configurationType);
  241. }
  242. catch (Exception ex)
  243. {
  244. Logger.LogError(ex, "Error loading configuration file: {path}", path);
  245. return Activator.CreateInstance(configurationType);
  246. }
  247. }
  248. public void SaveConfiguration(string key, object configuration)
  249. {
  250. var configurationStore = GetConfigurationStore(key);
  251. var configurationType = configurationStore.ConfigurationType;
  252. if (configuration.GetType() != configurationType)
  253. {
  254. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  255. }
  256. var validatingStore = configurationStore as IValidatingConfiguration;
  257. if (validatingStore != null)
  258. {
  259. var currentConfiguration = GetConfiguration(key);
  260. validatingStore.Validate(currentConfiguration, configuration);
  261. }
  262. NamedConfigurationUpdating?.Invoke(this, new ConfigurationUpdateEventArgs
  263. {
  264. Key = key,
  265. NewConfiguration = configuration
  266. });
  267. _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
  268. var path = GetConfigurationFile(key);
  269. Directory.CreateDirectory(Path.GetDirectoryName(path));
  270. lock (_configurationSyncLock)
  271. {
  272. XmlSerializer.SerializeToFile(configuration, path);
  273. }
  274. OnNamedConfigurationUpdated(key, configuration);
  275. }
  276. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  277. {
  278. NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
  279. {
  280. Key = key,
  281. NewConfiguration = configuration
  282. });
  283. }
  284. public Type GetConfigurationType(string key)
  285. {
  286. return GetConfigurationStore(key)
  287. .ConfigurationType;
  288. }
  289. private ConfigurationStore GetConfigurationStore(string key)
  290. {
  291. return _configurationStores
  292. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  293. }
  294. }
  295. }