BaseConfigurationManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Model.Configuration;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Common.Extensions;
  14. namespace MediaBrowser.Common.Implementations.Configuration
  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="logManager">The log manager.</param>
  91. /// <param name="xmlSerializer">The XML serializer.</param>
  92. protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  93. {
  94. CommonApplicationPaths = applicationPaths;
  95. XmlSerializer = xmlSerializer;
  96. FileSystem = fileSystem;
  97. Logger = logManager.GetLogger(GetType().Name);
  98. UpdateCachePath();
  99. }
  100. public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
  101. {
  102. _configurationFactories = factories.ToArray();
  103. _configurationStores = _configurationFactories
  104. .SelectMany(i => i.GetConfigurations())
  105. .ToArray();
  106. }
  107. /// <summary>
  108. /// Saves the configuration.
  109. /// </summary>
  110. public void SaveConfiguration()
  111. {
  112. Logger.Info("Saving system configuration");
  113. var path = CommonApplicationPaths.SystemConfigurationFilePath;
  114. FileSystem.CreateDirectory(Path.GetDirectoryName(path));
  115. lock (_configurationSyncLock)
  116. {
  117. XmlSerializer.SerializeToFile(CommonConfiguration, path);
  118. }
  119. OnConfigurationUpdated();
  120. }
  121. /// <summary>
  122. /// Called when [configuration updated].
  123. /// </summary>
  124. protected virtual void OnConfigurationUpdated()
  125. {
  126. UpdateCachePath();
  127. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  128. }
  129. /// <summary>
  130. /// Replaces the configuration.
  131. /// </summary>
  132. /// <param name="newConfiguration">The new configuration.</param>
  133. /// <exception cref="System.ArgumentNullException">newConfiguration</exception>
  134. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
  135. {
  136. if (newConfiguration == null)
  137. {
  138. throw new ArgumentNullException("newConfiguration");
  139. }
  140. ValidateCachePath(newConfiguration);
  141. CommonConfiguration = newConfiguration;
  142. SaveConfiguration();
  143. }
  144. /// <summary>
  145. /// Updates the items by name path.
  146. /// </summary>
  147. private void UpdateCachePath()
  148. {
  149. string cachePath;
  150. if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
  151. {
  152. cachePath = null;
  153. }
  154. else
  155. {
  156. cachePath = Path.Combine(CommonConfiguration.CachePath, "cache");
  157. }
  158. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
  159. }
  160. /// <summary>
  161. /// Replaces the cache path.
  162. /// </summary>
  163. /// <param name="newConfig">The new configuration.</param>
  164. /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
  165. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  166. {
  167. var newPath = newConfig.CachePath;
  168. if (!string.IsNullOrWhiteSpace(newPath)
  169. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
  170. {
  171. // Validate
  172. if (!FileSystem.DirectoryExists(newPath))
  173. {
  174. throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
  175. }
  176. EnsureWriteAccess(newPath);
  177. }
  178. }
  179. protected void EnsureWriteAccess(string path)
  180. {
  181. var file = Path.Combine(path, Guid.NewGuid().ToString());
  182. FileSystem.WriteAllText(file, string.Empty);
  183. FileSystem.DeleteFile(file);
  184. }
  185. private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
  186. private string GetConfigurationFile(string key)
  187. {
  188. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLower() + ".xml");
  189. }
  190. public object GetConfiguration(string key)
  191. {
  192. return _configurations.GetOrAdd(key, k =>
  193. {
  194. var file = GetConfigurationFile(key);
  195. var configurationInfo = _configurationStores
  196. .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  197. if (configurationInfo == null)
  198. {
  199. throw new ResourceNotFoundException("Configuration with key " + key + " not found.");
  200. }
  201. var configurationType = configurationInfo.ConfigurationType;
  202. lock (_configurationSyncLock)
  203. {
  204. return LoadConfiguration(file, configurationType);
  205. }
  206. });
  207. }
  208. private object LoadConfiguration(string path, Type configurationType)
  209. {
  210. try
  211. {
  212. return XmlSerializer.DeserializeFromFile(configurationType, path);
  213. }
  214. catch (FileNotFoundException)
  215. {
  216. return Activator.CreateInstance(configurationType);
  217. }
  218. catch (IOException)
  219. {
  220. return Activator.CreateInstance(configurationType);
  221. }
  222. catch (Exception ex)
  223. {
  224. Logger.ErrorException("Error loading configuration file: {0}", ex, path);
  225. return Activator.CreateInstance(configurationType);
  226. }
  227. }
  228. public void SaveConfiguration(string key, object configuration)
  229. {
  230. var configurationStore = GetConfigurationStore(key);
  231. var configurationType = configurationStore.ConfigurationType;
  232. if (configuration.GetType() != configurationType)
  233. {
  234. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  235. }
  236. var validatingStore = configurationStore as IValidatingConfiguration;
  237. if (validatingStore != null)
  238. {
  239. var currentConfiguration = GetConfiguration(key);
  240. validatingStore.Validate(currentConfiguration, configuration);
  241. }
  242. EventHelper.FireEventIfNotNull(NamedConfigurationUpdating, this, new ConfigurationUpdateEventArgs
  243. {
  244. Key = key,
  245. NewConfiguration = configuration
  246. }, Logger);
  247. _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
  248. var path = GetConfigurationFile(key);
  249. FileSystem.CreateDirectory(Path.GetDirectoryName(path));
  250. lock (_configurationSyncLock)
  251. {
  252. XmlSerializer.SerializeToFile(configuration, path);
  253. }
  254. OnNamedConfigurationUpdated(key, configuration);
  255. }
  256. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  257. {
  258. EventHelper.FireEventIfNotNull(NamedConfigurationUpdated, this, new ConfigurationUpdateEventArgs
  259. {
  260. Key = key,
  261. NewConfiguration = configuration
  262. }, Logger);
  263. }
  264. public Type GetConfigurationType(string key)
  265. {
  266. return GetConfigurationStore(key)
  267. .ConfigurationType;
  268. }
  269. private ConfigurationStore GetConfigurationStore(string key)
  270. {
  271. return _configurationStores
  272. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  273. }
  274. }
  275. }