jellyfin-server/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs

388 lines
14 KiB
C#
Raw Normal View History

2013-03-07 05:34:00 +00:00
using MediaBrowser.Common;
using MediaBrowser.Common.Net;
2013-03-07 05:34:00 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
2013-02-21 21:39:53 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
2013-02-25 02:41:51 +00:00
using MediaBrowser.Model.Serialization;
2013-02-21 01:33:05 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
2013-03-07 05:34:00 +00:00
namespace MediaBrowser.Server.Implementations.ServerManager
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Manages the Http Server, Udp Server and WebSocket connections
/// </summary>
2013-03-27 22:13:46 +00:00
public class ServerManager : IServerManager
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// 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>
/// <value>The HTTP server.</value>
private IHttpServer HttpServer { get; set; }
2013-02-21 01:33:05 +00:00
2013-02-24 21:53:54 +00:00
/// <summary>
/// Gets or sets the json serializer.
/// </summary>
/// <value>The json serializer.</value>
2013-02-25 00:13:45 +00:00
private readonly IJsonSerializer _jsonSerializer;
2013-02-21 01:33:05 +00:00
/// <summary>
/// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
/// </summary>
/// <value>The HTTP listener.</value>
private IDisposable HttpListener { get; set; }
/// <summary>
/// The web socket connections
/// </summary>
private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets or sets the external web socket server.
/// </summary>
/// <value>The external web socket server.</value>
private IWebSocketServer ExternalWebSocketServer { get; set; }
2013-02-21 01:33:05 +00:00
2013-02-21 21:39:53 +00:00
/// <summary>
/// The _logger
/// </summary>
private readonly ILogger _logger;
2013-02-22 04:23:06 +00:00
/// <summary>
/// The _application host
/// </summary>
private readonly IApplicationHost _applicationHost;
2013-02-21 01:33:05 +00:00
2013-03-04 05:43:06 +00:00
/// <summary>
/// Gets or sets the configuration manager.
/// </summary>
/// <value>The configuration manager.</value>
2013-03-07 05:34:00 +00:00
private IServerConfigurationManager ConfigurationManager { get; set; }
2013-03-04 05:43:06 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets a value indicating whether [supports web socket].
/// </summary>
/// <value><c>true</c> if [supports web socket]; otherwise, <c>false</c>.</value>
public bool SupportsNativeWebSocket
2013-02-21 01:33:05 +00:00
{
get { return HttpServer != null && HttpServer.SupportsWebSockets; }
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Gets the web socket port number.
/// </summary>
/// <value>The web socket port number.</value>
public int WebSocketPortNumber
{
2013-03-07 05:34:00 +00:00
get { return SupportsNativeWebSocket ? ConfigurationManager.Configuration.HttpServerPortNumber : ConfigurationManager.Configuration.LegacyWebSocketPortNumber; }
2013-02-21 01:33:05 +00:00
}
2013-02-27 16:46:48 +00:00
/// <summary>
/// Gets the web socket listeners.
/// </summary>
/// <value>The web socket listeners.</value>
2013-03-04 05:43:06 +00:00
private readonly List<IWebSocketListener> _webSocketListeners = new List<IWebSocketListener>();
2013-02-27 16:46:48 +00:00
private readonly Kernel _kernel;
2013-03-27 22:13:46 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="ServerManager" /> class.
2013-02-21 01:33:05 +00:00
/// </summary>
2013-02-22 04:23:06 +00:00
/// <param name="applicationHost">The application host.</param>
2013-02-24 21:53:54 +00:00
/// <param name="jsonSerializer">The json serializer.</param>
2013-02-21 21:39:53 +00:00
/// <param name="logger">The logger.</param>
2013-03-04 05:43:06 +00:00
/// <param name="configurationManager">The configuration manager.</param>
2013-03-27 22:13:46 +00:00
/// <param name="kernel">The kernel.</param>
2013-02-24 21:53:54 +00:00
/// <exception cref="System.ArgumentNullException">applicationHost</exception>
2013-03-27 22:13:46 +00:00
public ServerManager(IApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager, Kernel kernel)
2013-02-21 01:33:05 +00:00
{
if (applicationHost == null)
{
throw new ArgumentNullException("applicationHost");
}
2013-02-24 21:53:54 +00:00
if (jsonSerializer == null)
{
throw new ArgumentNullException("jsonSerializer");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
2013-02-21 21:39:53 +00:00
_logger = logger;
2013-02-24 21:53:54 +00:00
_jsonSerializer = jsonSerializer;
2013-02-22 04:23:06 +00:00
_applicationHost = applicationHost;
2013-03-04 05:43:06 +00:00
ConfigurationManager = configurationManager;
2013-03-07 05:34:00 +00:00
_kernel = kernel;
}
2013-02-21 21:39:53 +00:00
/// <summary>
/// Starts this instance.
/// </summary>
public void Start()
{
2013-02-21 01:33:05 +00:00
ReloadHttpServer();
if (!SupportsNativeWebSocket)
{
ReloadExternalWebSocketServer();
}
2013-03-27 22:13:46 +00:00
ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Starts the external web socket server.
/// </summary>
private void ReloadExternalWebSocketServer()
{
DisposeExternalWebSocketServer();
ExternalWebSocketServer = _applicationHost.Resolve<IWebSocketServer>();
2013-02-21 01:33:05 +00:00
2013-03-07 05:34:00 +00:00
ExternalWebSocketServer.Start(ConfigurationManager.Configuration.LegacyWebSocketPortNumber);
ExternalWebSocketServer.WebSocketConnected += HttpServer_WebSocketConnected;
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Restarts the Http Server, or starts it if not currently running
/// </summary>
2013-03-27 22:13:46 +00:00
private void ReloadHttpServer()
2013-02-21 01:33:05 +00:00
{
// Only reload if the port has changed, so that we don't disconnect any active users
if (HttpServer != null && HttpServer.UrlPrefix.Equals(_kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
2013-02-21 01:33:05 +00:00
{
return;
}
DisposeHttpServer();
2013-02-21 21:39:53 +00:00
_logger.Info("Loading Http Server");
2013-02-21 01:33:05 +00:00
try
{
HttpServer = _applicationHost.Resolve<IHttpServer>();
2013-03-07 05:34:00 +00:00
HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
HttpServer.Start(_kernel.HttpServerUrlPrefix);
2013-02-21 01:33:05 +00:00
}
catch (HttpListenerException ex)
{
2013-02-21 21:39:53 +00:00
_logger.ErrorException("Error starting Http Server", ex);
2013-02-21 01:33:05 +00:00
throw;
}
HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
}
/// <summary>
/// Handles the WebSocketConnected event of the HttpServer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
{
var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger) { OnReceive = ProcessWebSocketMessageReceived };
2013-02-21 01:33:05 +00:00
_webSocketConnections.Add(connection);
}
/// <summary>
/// Processes the web socket message received.
/// </summary>
/// <param name="result">The result.</param>
private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
{
2013-03-04 05:43:06 +00:00
var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
2013-02-21 01:33:05 +00:00
{
try
{
await i.ProcessMessage(result).ConfigureAwait(false);
}
catch (Exception ex)
{
2013-02-21 21:39:53 +00:00
_logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
2013-02-21 01:33:05 +00:00
}
}));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>
/// Sends a message to all clients currently connected via a web socket
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="data">The data.</param>
/// <returns>Task.</returns>
public void SendWebSocketMessage<T>(string messageType, T data)
{
SendWebSocketMessage(messageType, () => data);
}
/// <summary>
/// Sends a message to all clients currently connected via a web socket
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
{
Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
}
/// <summary>
/// Sends a message to all clients currently connected via a web socket
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="messageType">Type of the message.</param>
/// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">messageType</exception>
public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(messageType))
{
throw new ArgumentNullException("messageType");
}
if (dataFunction == null)
{
throw new ArgumentNullException("dataFunction");
}
if (cancellationToken == null)
{
throw new ArgumentNullException("cancellationToken");
}
cancellationToken.ThrowIfCancellationRequested();
var connections = _webSocketConnections.Where(s => s.State == WebSocketState.Open).ToList();
if (connections.Count > 0)
{
2013-02-21 21:39:53 +00:00
_logger.Info("Sending web socket message {0}", messageType);
2013-02-21 01:33:05 +00:00
var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
2013-02-24 21:53:54 +00:00
var bytes = _jsonSerializer.SerializeToBytes(message);
2013-02-21 01:33:05 +00:00
var tasks = connections.Select(s => Task.Run(() =>
{
try
{
s.SendAsync(bytes, cancellationToken);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
2013-02-21 21:39:53 +00:00
_logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
2013-02-21 01:33:05 +00:00
}
}));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
/// <summary>
/// Disposes the current HttpServer
/// </summary>
private void DisposeHttpServer()
{
foreach (var socket in _webSocketConnections)
{
// Dispose the connection
socket.Dispose();
}
_webSocketConnections.Clear();
if (HttpServer != null)
{
HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
HttpServer.Dispose();
}
if (HttpListener != null)
{
HttpListener.Dispose();
}
DisposeExternalWebSocketServer();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
2013-02-21 01:33:05 +00:00
{
if (dispose)
{
DisposeHttpServer();
}
}
/// <summary>
/// Disposes the external web socket server.
/// </summary>
private void DisposeExternalWebSocketServer()
{
if (ExternalWebSocketServer != null)
{
_logger.Info("Disposing {0}", ExternalWebSocketServer.GetType().Name);
2013-02-21 01:33:05 +00:00
ExternalWebSocketServer.Dispose();
}
}
/// <summary>
/// Handles the ConfigurationUpdated event of the _kernel control.
2013-02-21 01:33:05 +00:00
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
/// <exception cref="System.NotImplementedException"></exception>
2013-03-27 22:13:46 +00:00
void ConfigurationUpdated(object sender, EventArgs e)
2013-02-21 01:33:05 +00:00
{
2013-03-07 05:34:00 +00:00
HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
if (!string.Equals(HttpServer.UrlPrefix, _kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
2013-02-21 01:33:05 +00:00
{
ReloadHttpServer();
}
2013-03-07 05:34:00 +00:00
if (!SupportsNativeWebSocket && ExternalWebSocketServer != null && ExternalWebSocketServer.Port != ConfigurationManager.Configuration.LegacyWebSocketPortNumber)
2013-02-21 01:33:05 +00:00
{
ReloadExternalWebSocketServer();
}
}
2013-02-27 16:46:48 +00:00
/// <summary>
/// Adds the web socket listeners.
/// </summary>
/// <param name="listeners">The listeners.</param>
public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
{
2013-03-04 05:43:06 +00:00
_webSocketListeners.AddRange(listeners);
2013-02-27 16:46:48 +00:00
}
2013-02-21 01:33:05 +00:00
}
}