BaseConfigurationManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  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 Microsoft.Extensions.Logging;
  13. using MediaBrowser.Model.Serialization;
  14. namespace Emby.Server.Implementations.AppBase
  15. {
  16. /// <summary>
  17. /// Class BaseConfigurationManager
  18. /// </summary>
  19. public abstract class BaseConfigurationManager : IConfigurationManager
  20. {
  21. /// <summary>
  22. /// Gets the type of the configuration.
  23. /// </summary>
  24. /// <value>The type of the configuration.</value>
  25. protected abstract Type ConfigurationType { get; }
  26. /// <summary>
  27. /// Occurs when [configuration updated].
  28. /// </summary>
  29. public event EventHandler<EventArgs> ConfigurationUpdated;
  30. /// <summary>
  31. /// Occurs when [configuration updating].
  32. /// </summary>
  33. public event EventHandler<ConfigurationUpdateEventArgs> NamedConfigurationUpdating;
  34. /// <summary>
  35. /// Occurs when [named configuration updated].
  36. /// </summary>
  37. public event EventHandler<ConfigurationUpdateEventArgs> NamedConfigurationUpdated;
  38. /// <summary>
  39. /// Gets the logger.
  40. /// </summary>
  41. /// <value>The logger.</value>
  42. protected ILogger Logger { get; private set; }
  43. /// <summary>
  44. /// Gets the XML serializer.
  45. /// </summary>
  46. /// <value>The XML serializer.</value>
  47. protected IXmlSerializer XmlSerializer { get; private set; }
  48. /// <summary>
  49. /// Gets or sets the application paths.
  50. /// </summary>
  51. /// <value>The application paths.</value>
  52. public IApplicationPaths CommonApplicationPaths { get; private set; }
  53. public readonly IFileSystem FileSystem;
  54. /// <summary>
  55. /// The _configuration loaded
  56. /// </summary>
  57. private bool _configurationLoaded;
  58. /// <summary>
  59. /// The _configuration sync lock
  60. /// </summary>
  61. private object _configurationSyncLock = new object();
  62. /// <summary>
  63. /// The _configuration
  64. /// </summary>
  65. private BaseApplicationConfiguration _configuration;
  66. /// <summary>
  67. /// Gets the system configuration
  68. /// </summary>
  69. /// <value>The configuration.</value>
  70. public BaseApplicationConfiguration CommonConfiguration
  71. {
  72. get
  73. {
  74. // Lazy load
  75. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer, FileSystem));
  76. return _configuration;
  77. }
  78. protected set
  79. {
  80. _configuration = value;
  81. _configurationLoaded = value != null;
  82. }
  83. }
  84. private ConfigurationStore[] _configurationStores = { };
  85. private IConfigurationFactory[] _configurationFactories = { };
  86. /// <summary>
  87. /// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
  88. /// </summary>
  89. /// <param name="applicationPaths">The application paths.</param>
  90. /// <param name="loggerFactory">The logger factory.</param>
  91. /// <param name="xmlSerializer">The XML serializer.</param>
  92. /// <param name="fileSystem">The file system</param>
  93. protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  94. {
  95. CommonApplicationPaths = applicationPaths;
  96. XmlSerializer = xmlSerializer;
  97. FileSystem = fileSystem;
  98. Logger = loggerFactory.CreateLogger(GetType().Name);
  99. UpdateCachePath();
  100. }
  101. public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
  102. {
  103. _configurationFactories = factories.ToArray();
  104. _configurationStores = _configurationFactories
  105. .SelectMany(i => i.GetConfigurations())
  106. .ToArray();
  107. }
  108. /// <summary>
  109. /// Saves the configuration.
  110. /// </summary>
  111. public void SaveConfiguration()
  112. {
  113. Logger.LogInformation("Saving system configuration");
  114. var path = CommonApplicationPaths.SystemConfigurationFilePath;
  115. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path));
  116. lock (_configurationSyncLock)
  117. {
  118. XmlSerializer.SerializeToFile(CommonConfiguration, path);
  119. }
  120. OnConfigurationUpdated();
  121. }
  122. /// <summary>
  123. /// Called when [configuration updated].
  124. /// </summary>
  125. protected virtual void OnConfigurationUpdated()
  126. {
  127. UpdateCachePath();
  128. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  129. }
  130. /// <summary>
  131. /// Replaces the configuration.
  132. /// </summary>
  133. /// <param name="newConfiguration">The new configuration.</param>
  134. /// <exception cref="System.ArgumentNullException">newConfiguration</exception>
  135. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
  136. {
  137. if (newConfiguration == null)
  138. {
  139. throw new ArgumentNullException(nameof(newConfiguration));
  140. }
  141. ValidateCachePath(newConfiguration);
  142. CommonConfiguration = newConfiguration;
  143. SaveConfiguration();
  144. }
  145. /// <summary>
  146. /// Updates the items by name path.
  147. /// </summary>
  148. private void UpdateCachePath()
  149. {
  150. string cachePath;
  151. if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
  152. {
  153. cachePath = null;
  154. }
  155. else
  156. {
  157. cachePath = Path.Combine(CommonConfiguration.CachePath, "cache");
  158. }
  159. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
  160. }
  161. /// <summary>
  162. /// Replaces the cache path.
  163. /// </summary>
  164. /// <param name="newConfig">The new configuration.</param>
  165. /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
  166. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  167. {
  168. var newPath = newConfig.CachePath;
  169. if (!string.IsNullOrWhiteSpace(newPath)
  170. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
  171. {
  172. // Validate
  173. if (!FileSystem.DirectoryExists(newPath))
  174. {
  175. throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
  176. }
  177. EnsureWriteAccess(newPath);
  178. }
  179. }
  180. protected void EnsureWriteAccess(string path)
  181. {
  182. var file = Path.Combine(path, Guid.NewGuid().ToString());
  183. FileSystem.WriteAllText(file, string.Empty);
  184. FileSystem.DeleteFile(file);
  185. }
  186. private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
  187. private string GetConfigurationFile(string key)
  188. {
  189. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLower() + ".xml");
  190. }
  191. public object GetConfiguration(string key)
  192. {
  193. return _configurations.GetOrAdd(key, k =>
  194. {
  195. var file = GetConfigurationFile(key);
  196. var configurationInfo = _configurationStores
  197. .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  198. if (configurationInfo == null)
  199. {
  200. throw new ResourceNotFoundException("Configuration with key " + key + " not found.");
  201. }
  202. var configurationType = configurationInfo.ConfigurationType;
  203. lock (_configurationSyncLock)
  204. {
  205. return LoadConfiguration(file, configurationType);
  206. }
  207. });
  208. }
  209. private object LoadConfiguration(string path, Type configurationType)
  210. {
  211. try
  212. {
  213. return XmlSerializer.DeserializeFromFile(configurationType, path);
  214. }
  215. catch (FileNotFoundException)
  216. {
  217. return Activator.CreateInstance(configurationType);
  218. }
  219. catch (IOException)
  220. {
  221. return Activator.CreateInstance(configurationType);
  222. }
  223. catch (Exception ex)
  224. {
  225. Logger.LogError(ex, "Error loading configuration file: {path}", path);
  226. return Activator.CreateInstance(configurationType);
  227. }
  228. }
  229. public void SaveConfiguration(string key, object configuration)
  230. {
  231. var configurationStore = GetConfigurationStore(key);
  232. var configurationType = configurationStore.ConfigurationType;
  233. if (configuration.GetType() != configurationType)
  234. {
  235. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  236. }
  237. var validatingStore = configurationStore as IValidatingConfiguration;
  238. if (validatingStore != null)
  239. {
  240. var currentConfiguration = GetConfiguration(key);
  241. validatingStore.Validate(currentConfiguration, configuration);
  242. }
  243. NamedConfigurationUpdating?.Invoke( this, new ConfigurationUpdateEventArgs
  244. {
  245. Key = key,
  246. NewConfiguration = configuration
  247. });
  248. _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
  249. var path = GetConfigurationFile(key);
  250. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path));
  251. lock (_configurationSyncLock)
  252. {
  253. XmlSerializer.SerializeToFile(configuration, path);
  254. }
  255. OnNamedConfigurationUpdated(key, configuration);
  256. }
  257. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  258. {
  259. NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
  260. {
  261. Key = key,
  262. NewConfiguration = configuration
  263. });
  264. }
  265. public Type GetConfigurationType(string key)
  266. {
  267. return GetConfigurationStore(key)
  268. .ConfigurationType;
  269. }
  270. private ConfigurationStore GetConfigurationStore(string key)
  271. {
  272. return _configurationStores
  273. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  274. }
  275. }
  276. }