BaseConfigurationManager.cs 13 KB

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