2
0

BaseConfigurationManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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));
  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 the configuration file has no entry (i.e. not set in UI)
  152. if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
  153. {
  154. // If the current live configuration has no entry (i.e. not set on CLI/envvars, during startup)
  155. if (string.IsNullOrWhiteSpace(((BaseApplicationPaths)CommonApplicationPaths).CachePath))
  156. {
  157. // Set cachePath to a default value under ProgramDataPath
  158. cachePath = Path.Combine(((BaseApplicationPaths)CommonApplicationPaths).ProgramDataPath, "cache");
  159. }
  160. else
  161. {
  162. // Set cachePath to the existing live value; will require restart if UI value is removed (but not replaced)
  163. // TODO: Figure out how to re-grab this from the CLI/envvars while running
  164. cachePath = ((BaseApplicationPaths)CommonApplicationPaths).CachePath;
  165. }
  166. }
  167. else
  168. {
  169. // Set cachePath to the new UI-set value
  170. cachePath = CommonConfiguration.CachePath;
  171. }
  172. Logger.LogInformation("Setting cache path to " + cachePath);
  173. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
  174. }
  175. /// <summary>
  176. /// Replaces the cache path.
  177. /// </summary>
  178. /// <param name="newConfig">The new configuration.</param>
  179. /// <exception cref="DirectoryNotFoundException"></exception>
  180. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  181. {
  182. var newPath = newConfig.CachePath;
  183. if (!string.IsNullOrWhiteSpace(newPath)
  184. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
  185. {
  186. // Validate
  187. if (!Directory.Exists(newPath))
  188. {
  189. throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
  190. }
  191. EnsureWriteAccess(newPath);
  192. }
  193. }
  194. protected void EnsureWriteAccess(string path)
  195. {
  196. var file = Path.Combine(path, Guid.NewGuid().ToString());
  197. File.WriteAllText(file, string.Empty);
  198. FileSystem.DeleteFile(file);
  199. }
  200. private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
  201. private string GetConfigurationFile(string key)
  202. {
  203. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLowerInvariant() + ".xml");
  204. }
  205. public object GetConfiguration(string key)
  206. {
  207. return _configurations.GetOrAdd(key, k =>
  208. {
  209. var file = GetConfigurationFile(key);
  210. var configurationInfo = _configurationStores
  211. .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  212. if (configurationInfo == null)
  213. {
  214. throw new ResourceNotFoundException("Configuration with key " + key + " not found.");
  215. }
  216. var configurationType = configurationInfo.ConfigurationType;
  217. lock (_configurationSyncLock)
  218. {
  219. return LoadConfiguration(file, configurationType);
  220. }
  221. });
  222. }
  223. private object LoadConfiguration(string path, Type configurationType)
  224. {
  225. if (!File.Exists(path))
  226. {
  227. return Activator.CreateInstance(configurationType);
  228. }
  229. try
  230. {
  231. return XmlSerializer.DeserializeFromFile(configurationType, path);
  232. }
  233. catch (IOException)
  234. {
  235. return Activator.CreateInstance(configurationType);
  236. }
  237. catch (Exception ex)
  238. {
  239. Logger.LogError(ex, "Error loading configuration file: {path}", path);
  240. return Activator.CreateInstance(configurationType);
  241. }
  242. }
  243. public void SaveConfiguration(string key, object configuration)
  244. {
  245. var configurationStore = GetConfigurationStore(key);
  246. var configurationType = configurationStore.ConfigurationType;
  247. if (configuration.GetType() != configurationType)
  248. {
  249. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  250. }
  251. var validatingStore = configurationStore as IValidatingConfiguration;
  252. if (validatingStore != null)
  253. {
  254. var currentConfiguration = GetConfiguration(key);
  255. validatingStore.Validate(currentConfiguration, configuration);
  256. }
  257. NamedConfigurationUpdating?.Invoke(this, new ConfigurationUpdateEventArgs
  258. {
  259. Key = key,
  260. NewConfiguration = configuration
  261. });
  262. _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
  263. var path = GetConfigurationFile(key);
  264. Directory.CreateDirectory(Path.GetDirectoryName(path));
  265. lock (_configurationSyncLock)
  266. {
  267. XmlSerializer.SerializeToFile(configuration, path);
  268. }
  269. OnNamedConfigurationUpdated(key, configuration);
  270. }
  271. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  272. {
  273. NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
  274. {
  275. Key = key,
  276. NewConfiguration = configuration
  277. });
  278. }
  279. public Type GetConfigurationType(string key)
  280. {
  281. return GetConfigurationStore(key)
  282. .ConfigurationType;
  283. }
  284. private ConfigurationStore GetConfigurationStore(string key)
  285. {
  286. return _configurationStores
  287. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  288. }
  289. }
  290. }