BaseKernel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Security;
  3. using MediaBrowser.Model.Configuration;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using MediaBrowser.Model.System;
  7. using System;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading;
  11. namespace MediaBrowser.Common.Kernel
  12. {
  13. /// <summary>
  14. /// Represents a shared base kernel for both the Ui and server apps
  15. /// </summary>
  16. /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam>
  17. /// <typeparam name="TApplicationPathsType">The type of the T application paths type.</typeparam>
  18. public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
  19. where TConfigurationType : BaseApplicationConfiguration, new()
  20. where TApplicationPathsType : IApplicationPaths
  21. {
  22. /// <summary>
  23. /// Occurs when [has pending restart changed].
  24. /// </summary>
  25. public event EventHandler HasPendingRestartChanged;
  26. #region ConfigurationUpdated Event
  27. /// <summary>
  28. /// Occurs when [configuration updated].
  29. /// </summary>
  30. public event EventHandler<EventArgs> ConfigurationUpdated;
  31. /// <summary>
  32. /// Called when [configuration updated].
  33. /// </summary>
  34. internal void OnConfigurationUpdated()
  35. {
  36. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  37. }
  38. #endregion
  39. #region ApplicationUpdated Event
  40. /// <summary>
  41. /// Occurs when [application updated].
  42. /// </summary>
  43. public event EventHandler<GenericEventArgs<Version>> ApplicationUpdated;
  44. /// <summary>
  45. /// Called when [application updated].
  46. /// </summary>
  47. /// <param name="newVersion">The new version.</param>
  48. public void OnApplicationUpdated(Version newVersion)
  49. {
  50. EventHelper.QueueEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<Version> { Argument = newVersion }, Logger);
  51. NotifyPendingRestart();
  52. }
  53. #endregion
  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 TConfigurationType _configuration;
  66. /// <summary>
  67. /// Gets the system configuration
  68. /// </summary>
  69. /// <value>The configuration.</value>
  70. public TConfigurationType Configuration
  71. {
  72. get
  73. {
  74. // Lazy load
  75. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => GetXmlConfiguration<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath));
  76. return _configuration;
  77. }
  78. protected set
  79. {
  80. _configuration = value;
  81. if (value == null)
  82. {
  83. _configurationLoaded = false;
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
  89. /// </summary>
  90. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  91. public bool HasPendingRestart { get; private set; }
  92. /// <summary>
  93. /// Gets the application paths.
  94. /// </summary>
  95. /// <value>The application paths.</value>
  96. public TApplicationPathsType ApplicationPaths { get; private set; }
  97. /// <summary>
  98. /// Gets or sets the TCP manager.
  99. /// </summary>
  100. /// <value>The TCP manager.</value>
  101. private IServerManager ServerManager { get; set; }
  102. /// <summary>
  103. /// Gets the plug-in security manager.
  104. /// </summary>
  105. /// <value>The plug-in security manager.</value>
  106. public ISecurityManager SecurityManager { get; set; }
  107. /// <summary>
  108. /// Gets the UDP server port number.
  109. /// This can't be configurable because then the user would have to configure their client to discover the server.
  110. /// </summary>
  111. /// <value>The UDP server port number.</value>
  112. public abstract int UdpServerPortNumber { get; }
  113. /// <summary>
  114. /// Gets the name of the web application that can be used for url building.
  115. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  116. /// </summary>
  117. /// <value>The name of the web application.</value>
  118. public string WebApplicationName
  119. {
  120. get { return "mediabrowser"; }
  121. }
  122. /// <summary>
  123. /// Gets the HTTP server URL prefix.
  124. /// </summary>
  125. /// <value>The HTTP server URL prefix.</value>
  126. public virtual string HttpServerUrlPrefix
  127. {
  128. get
  129. {
  130. return "http://+:" + Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/";
  131. }
  132. }
  133. /// <summary>
  134. /// Gets the kernel context. Subclasses will have to override.
  135. /// </summary>
  136. /// <value>The kernel context.</value>
  137. public abstract KernelContext KernelContext { get; }
  138. /// <summary>
  139. /// Gets the logger.
  140. /// </summary>
  141. /// <value>The logger.</value>
  142. protected ILogger Logger { get; private set; }
  143. /// <summary>
  144. /// Gets or sets the application host.
  145. /// </summary>
  146. /// <value>The application host.</value>
  147. protected IApplicationHost ApplicationHost { get; private set; }
  148. /// <summary>
  149. /// The _XML serializer
  150. /// </summary>
  151. private readonly IXmlSerializer _xmlSerializer;
  152. /// <summary>
  153. /// Initializes a new instance of the <see cref="BaseKernel{TApplicationPathsType}" /> class.
  154. /// </summary>
  155. /// <param name="appHost">The app host.</param>
  156. /// <param name="appPaths">The app paths.</param>
  157. /// <param name="xmlSerializer">The XML serializer.</param>
  158. /// <param name="logger">The logger.</param>
  159. /// <exception cref="System.ArgumentNullException">isoManager</exception>
  160. protected BaseKernel(IApplicationHost appHost, TApplicationPathsType appPaths, IXmlSerializer xmlSerializer, ILogger logger)
  161. {
  162. ApplicationPaths = appPaths;
  163. ApplicationHost = appHost;
  164. _xmlSerializer = xmlSerializer;
  165. Logger = logger;
  166. }
  167. /// <summary>
  168. /// Initializes the Kernel
  169. /// </summary>
  170. /// <returns>Task.</returns>
  171. public void Init()
  172. {
  173. ReloadInternal();
  174. Logger.Info("Kernel.Init Complete");
  175. }
  176. /// <summary>
  177. /// Performs initializations that can be reloaded at anytime
  178. /// </summary>
  179. /// <returns>Task.</returns>
  180. protected virtual void ReloadInternal()
  181. {
  182. ServerManager = ApplicationHost.Resolve<IServerManager>();
  183. }
  184. /// <summary>
  185. /// Notifies that the kernel that a change has been made that requires a restart
  186. /// </summary>
  187. public void NotifyPendingRestart()
  188. {
  189. HasPendingRestart = true;
  190. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  191. }
  192. /// <summary>
  193. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  194. /// </summary>
  195. public void Dispose()
  196. {
  197. Dispose(true);
  198. GC.SuppressFinalize(this);
  199. }
  200. /// <summary>
  201. /// Releases unmanaged and - optionally - managed resources.
  202. /// </summary>
  203. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  204. protected virtual void Dispose(bool dispose)
  205. {
  206. }
  207. /// <summary>
  208. /// Performs the pending restart.
  209. /// </summary>
  210. /// <returns>Task.</returns>
  211. public void PerformPendingRestart()
  212. {
  213. if (HasPendingRestart)
  214. {
  215. Logger.Info("Restarting the application");
  216. ApplicationHost.Restart();
  217. }
  218. else
  219. {
  220. Logger.Info("PerformPendingRestart - not needed");
  221. }
  222. }
  223. /// <summary>
  224. /// Gets the system status.
  225. /// </summary>
  226. /// <returns>SystemInfo.</returns>
  227. public virtual SystemInfo GetSystemInfo()
  228. {
  229. return new SystemInfo
  230. {
  231. HasPendingRestart = HasPendingRestart,
  232. Version = ApplicationHost.ApplicationVersion.ToString(),
  233. IsNetworkDeployed = ApplicationHost.CanSelfUpdate,
  234. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  235. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  236. FailedPluginAssemblies = ApplicationHost.FailedAssemblies.ToArray()
  237. };
  238. }
  239. /// <summary>
  240. /// The _save lock
  241. /// </summary>
  242. private readonly object _configurationSaveLock = new object();
  243. /// <summary>
  244. /// Saves the current configuration
  245. /// </summary>
  246. public void SaveConfiguration()
  247. {
  248. lock (_configurationSaveLock)
  249. {
  250. _xmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
  251. }
  252. OnConfigurationUpdated();
  253. }
  254. /// <summary>
  255. /// Gets the application paths.
  256. /// </summary>
  257. /// <value>The application paths.</value>
  258. IApplicationPaths IKernel.ApplicationPaths
  259. {
  260. get { return ApplicationPaths; }
  261. }
  262. /// <summary>
  263. /// Gets the configuration.
  264. /// </summary>
  265. /// <value>The configuration.</value>
  266. BaseApplicationConfiguration IKernel.Configuration
  267. {
  268. get { return Configuration; }
  269. }
  270. /// <summary>
  271. /// Reads an xml configuration file from the file system
  272. /// It will immediately re-serialize and save if new serialization data is available due to property changes
  273. /// </summary>
  274. /// <param name="type">The type.</param>
  275. /// <param name="path">The path.</param>
  276. /// <returns>System.Object.</returns>
  277. public object GetXmlConfiguration(Type type, string path)
  278. {
  279. Logger.Info("Loading {0} at {1}", type.Name, path);
  280. object configuration;
  281. byte[] buffer = null;
  282. // Use try/catch to avoid the extra file system lookup using File.Exists
  283. try
  284. {
  285. buffer = File.ReadAllBytes(path);
  286. configuration = _xmlSerializer.DeserializeFromBytes(type, buffer);
  287. }
  288. catch (FileNotFoundException)
  289. {
  290. configuration = Activator.CreateInstance(type);
  291. }
  292. // Take the object we just got and serialize it back to bytes
  293. var newBytes = _xmlSerializer.SerializeToBytes(configuration);
  294. // If the file didn't exist before, or if something has changed, re-save
  295. if (buffer == null || !buffer.SequenceEqual(newBytes))
  296. {
  297. Logger.Info("Saving {0} to {1}", type.Name, path);
  298. // Save it after load in case we got new items
  299. File.WriteAllBytes(path, newBytes);
  300. }
  301. return configuration;
  302. }
  303. /// <summary>
  304. /// Reads an xml configuration file from the file system
  305. /// It will immediately save the configuration after loading it, just
  306. /// in case there are new serializable properties
  307. /// </summary>
  308. /// <typeparam name="T"></typeparam>
  309. /// <param name="path">The path.</param>
  310. /// <returns>``0.</returns>
  311. private T GetXmlConfiguration<T>(string path)
  312. where T : class
  313. {
  314. return GetXmlConfiguration(typeof(T), path) as T;
  315. }
  316. /// <summary>
  317. /// Limits simultaneous access to various resources
  318. /// </summary>
  319. /// <value>The resource pools.</value>
  320. public ResourcePool ResourcePools { get; set; }
  321. }
  322. }