BaseConfigurationManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 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. /// <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. Directory.CreateDirectory(Path.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="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="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 (!Directory.Exists(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. string text = string.Empty;
  184. File.WriteAllText(file, text);
  185. FileSystem.DeleteFile(file);
  186. }
  187. private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
  188. private string GetConfigurationFile(string key)
  189. {
  190. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLower() + ".xml");
  191. }
  192. public object GetConfiguration(string key)
  193. {
  194. return _configurations.GetOrAdd(key, k =>
  195. {
  196. var file = GetConfigurationFile(key);
  197. var configurationInfo = _configurationStores
  198. .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  199. if (configurationInfo == null)
  200. {
  201. throw new ResourceNotFoundException("Configuration with key " + key + " not found.");
  202. }
  203. var configurationType = configurationInfo.ConfigurationType;
  204. lock (_configurationSyncLock)
  205. {
  206. return LoadConfiguration(file, configurationType);
  207. }
  208. });
  209. }
  210. private object LoadConfiguration(string path, Type configurationType)
  211. {
  212. if (!File.Exists(path))
  213. {
  214. return Activator.CreateInstance(configurationType);
  215. }
  216. try
  217. {
  218. return XmlSerializer.DeserializeFromFile(configurationType, path);
  219. }
  220. catch (IOException)
  221. {
  222. return Activator.CreateInstance(configurationType);
  223. }
  224. catch (Exception ex)
  225. {
  226. Logger.LogError(ex, "Error loading configuration file: {path}", path);
  227. return Activator.CreateInstance(configurationType);
  228. }
  229. }
  230. public void SaveConfiguration(string key, object configuration)
  231. {
  232. var configurationStore = GetConfigurationStore(key);
  233. var configurationType = configurationStore.ConfigurationType;
  234. if (configuration.GetType() != configurationType)
  235. {
  236. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  237. }
  238. var validatingStore = configurationStore as IValidatingConfiguration;
  239. if (validatingStore != null)
  240. {
  241. var currentConfiguration = GetConfiguration(key);
  242. validatingStore.Validate(currentConfiguration, configuration);
  243. }
  244. NamedConfigurationUpdating?.Invoke(this, new ConfigurationUpdateEventArgs
  245. {
  246. Key = key,
  247. NewConfiguration = configuration
  248. });
  249. _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
  250. var path = GetConfigurationFile(key);
  251. Directory.CreateDirectory(Path.GetDirectoryName(path));
  252. lock (_configurationSyncLock)
  253. {
  254. XmlSerializer.SerializeToFile(configuration, path);
  255. }
  256. OnNamedConfigurationUpdated(key, configuration);
  257. }
  258. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  259. {
  260. NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
  261. {
  262. Key = key,
  263. NewConfiguration = configuration
  264. });
  265. }
  266. public Type GetConfigurationType(string key)
  267. {
  268. return GetConfigurationStore(key)
  269. .ConfigurationType;
  270. }
  271. private ConfigurationStore GetConfigurationStore(string key)
  272. {
  273. return _configurationStores
  274. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  275. }
  276. }
  277. }