jellyfin/MediaBrowser.Common/Kernel/BaseKernel.cs

328 lines
11 KiB
C#
Raw Normal View History

2012-09-07 16:17:39 +00:00
using MediaBrowser.Common.Logging;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Net.Handlers;
2012-09-07 16:17:39 +00:00
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Serialization;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Progress;
using System;
2012-07-26 13:51:26 +00:00
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Kernel
{
/// <summary>
2012-09-11 19:37:14 +00:00
/// Represents a shared base kernel for both the Ui and server apps
/// </summary>
public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
where TConfigurationType : BaseApplicationConfiguration, new()
where TApplicationPathsType : BaseApplicationPaths, new()
{
/// <summary>
/// Gets the current configuration
/// </summary>
public TConfigurationType Configuration { get; private set; }
public TApplicationPathsType ApplicationPaths { get; private set; }
/// <summary>
/// Gets the list of currently loaded plugins
/// </summary>
[ImportMany(typeof(BasePlugin))]
public IEnumerable<BasePlugin> Plugins { get; private set; }
2012-07-26 13:51:26 +00:00
/// <summary>
/// Gets the list of currently registered http handlers
/// </summary>
[ImportMany(typeof(BaseHandler))]
private IEnumerable<BaseHandler> HttpHandlers { get; set; }
/// <summary>
2012-09-11 19:37:14 +00:00
/// Both the Ui and server will have a built-in HttpServer.
/// People will inevitably want remote control apps so it's needed in the Ui too.
/// </summary>
public HttpServer HttpServer { get; private set; }
/// <summary>
/// This subscribes to HttpListener requests and finds the appropate BaseHandler to process it
/// </summary>
private IDisposable HttpListener { get; set; }
2012-09-02 17:34:12 +00:00
protected virtual string HttpServerUrlPrefix
{
get
{
return "http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/";
}
}
/// <summary>
/// Gets the kernel context. Subclasses will have to override.
/// </summary>
public abstract KernelContext KernelContext { get; }
/// <summary>
/// Initializes the Kernel
/// </summary>
public async Task Init(IProgress<TaskProgress> progress)
{
// Performs initializations that only occur once
InitializeInternal(progress);
// Performs initializations that can be reloaded at anytime
await Reload(progress).ConfigureAwait(false);
2012-09-17 18:47:51 +00:00
progress.Report(new TaskProgress { Description = "Loading Complete" });
}
/// <summary>
/// Performs initializations that only occur once
/// </summary>
protected virtual void InitializeInternal(IProgress<TaskProgress> progress)
{
ApplicationPaths = new TApplicationPathsType();
2012-09-03 19:12:02 +00:00
ReloadLogger();
2012-09-17 18:47:51 +00:00
progress.Report(new TaskProgress { Description = "Loading configuration" });
2012-09-03 19:12:02 +00:00
ReloadConfiguration();
2012-09-17 18:47:51 +00:00
progress.Report(new TaskProgress { Description = "Starting Http server" });
2012-09-03 19:12:02 +00:00
ReloadHttpServer();
}
/// <summary>
/// Performs initializations that can be reloaded at anytime
/// </summary>
public virtual async Task Reload(IProgress<TaskProgress> progress)
{
await Task.Run(() =>
{
2012-09-17 18:47:51 +00:00
progress.Report(new TaskProgress { Description = "Loading Plugins" });
ReloadComposableParts();
}).ConfigureAwait(false);
}
/// <summary>
/// Disposes the current logger and creates a new one
/// </summary>
private void ReloadLogger()
{
DisposeLogger();
DateTime now = DateTime.Now;
string logFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
Trace.Listeners.Add(new TextWriterTraceListener(logFilePath));
Trace.AutoFlush = true;
Logger.LoggerInstance = new TraceLogger();
}
2012-07-26 13:51:26 +00:00
/// <summary>
/// Uses MEF to locate plugins
/// Subclasses can use this to locate types within plugins
/// </summary>
private void ReloadComposableParts()
{
DisposeComposableParts();
var container = GetCompositionContainer(includeCurrentAssembly: true);
2012-09-03 19:12:02 +00:00
container.ComposeParts(this);
2012-09-03 19:12:02 +00:00
OnComposablePartsLoaded();
2012-09-03 19:12:02 +00:00
container.Catalog.Dispose();
container.Dispose();
2012-09-03 19:12:02 +00:00
}
/// <summary>
/// Constructs an MEF CompositionContainer based on the current running assembly and all plugin assemblies
/// </summary>
2012-09-03 19:12:02 +00:00
public CompositionContainer GetCompositionContainer(bool includeCurrentAssembly = false)
{
// Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
// This will prevent the .dll file from getting locked, and allow us to replace it when needed
IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly).Select(f => Assembly.Load(File.ReadAllBytes((f))));
var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
// Include composable parts in the Common assembly
// Uncomment this if it's ever needed
//catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
2012-09-03 19:12:02 +00:00
if (includeCurrentAssembly)
{
// Include composable parts in the subclass assembly
catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
}
2012-07-26 13:51:26 +00:00
2012-09-03 19:12:02 +00:00
return new CompositionContainer(catalog);
}
2012-07-26 13:51:26 +00:00
/// <summary>
/// Fires after MEF finishes finding composable parts within plugin assemblies
/// </summary>
protected virtual void OnComposablePartsLoaded()
{
// Start-up each plugin
2012-07-26 13:51:26 +00:00
foreach (BasePlugin plugin in Plugins)
{
plugin.Initialize(this);
2012-07-26 13:51:26 +00:00
}
}
2012-07-26 13:51:26 +00:00
/// <summary>
/// Reloads application configuration from the config file
/// </summary>
private void ReloadConfiguration()
{
2012-08-02 03:13:44 +00:00
//Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
// Deserialize config
if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
{
Configuration = new TConfigurationType();
2012-09-03 21:56:30 +00:00
XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
}
else
{
Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
}
Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
}
2012-07-26 13:51:26 +00:00
/// <summary>
/// Restarts the Http Server, or starts it if not currently running
/// </summary>
private void ReloadHttpServer()
2012-07-30 04:06:05 +00:00
{
DisposeHttpServer();
2012-09-02 17:34:12 +00:00
HttpServer = new HttpServer(HttpServerUrlPrefix);
2012-09-11 18:20:12 +00:00
HttpListener = HttpServer.Subscribe(ctx =>
{
BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));
// Find the appropiate http handler
if (handler != null)
{
// Need to create a new instance because handlers are currently stateful
handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;
// No need to await this, despite the compiler warning
handler.ProcessRequest(ctx);
}
});
2012-07-30 04:06:05 +00:00
}
/// <summary>
/// Disposes all resources currently in use.
/// </summary>
public virtual void Dispose()
2012-07-30 04:06:05 +00:00
{
Logger.LogInfo("Beginning Kernel.Dispose");
DisposeComposableParts();
2012-07-30 04:06:05 +00:00
DisposeHttpServer();
DisposeLogger();
}
/// <summary>
/// Disposes all objects gathered through MEF composable parts
/// </summary>
protected virtual void DisposeComposableParts()
{
DisposePlugins();
}
/// <summary>
/// Disposes all plugins
/// </summary>
private void DisposePlugins()
{
if (Plugins != null)
{
Logger.LogInfo("Disposing Plugins");
foreach (BasePlugin plugin in Plugins)
{
plugin.Dispose();
}
}
}
/// <summary>
/// Disposes the current HttpServer
/// </summary>
private void DisposeHttpServer()
{
if (HttpServer != null)
{
Logger.LogInfo("Disposing Http Server");
HttpServer.Dispose();
}
if (HttpListener != null)
{
HttpListener.Dispose();
}
}
/// <summary>
/// Disposes the current Logger instance
/// </summary>
private void DisposeLogger()
{
Trace.Listeners.Clear();
if (Logger.LoggerInstance != null)
{
Logger.LogInfo("Disposing Logger");
Logger.LoggerInstance.Dispose();
}
2012-07-30 04:06:05 +00:00
}
2012-08-19 21:29:15 +00:00
/// <summary>
/// Gets the current application version
/// </summary>
public Version ApplicationVersion
{
get
{
return GetType().Assembly.GetName().Version;
}
}
BaseApplicationPaths IKernel.ApplicationPaths
{
get { return ApplicationPaths; }
}
}
public interface IKernel
{
BaseApplicationPaths ApplicationPaths { get; }
KernelContext KernelContext { get; }
Task Init(IProgress<TaskProgress> progress);
Task Reload(IProgress<TaskProgress> progress);
void Dispose();
}
}