ServerManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Net;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.ServerManager
  15. {
  16. /// <summary>
  17. /// Manages the Http Server, Udp Server and WebSocket connections
  18. /// </summary>
  19. public class ServerManager : IServerManager
  20. {
  21. /// <summary>
  22. /// Both the Ui and server will have a built-in HttpServer.
  23. /// People will inevitably want remote control apps so it's needed in the Ui too.
  24. /// </summary>
  25. /// <value>The HTTP server.</value>
  26. private IHttpServer HttpServer { get; set; }
  27. /// <summary>
  28. /// Gets or sets the json serializer.
  29. /// </summary>
  30. /// <value>The json serializer.</value>
  31. private readonly IJsonSerializer _jsonSerializer;
  32. /// <summary>
  33. /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
  34. /// </summary>
  35. /// <value>The HTTP listener.</value>
  36. private IDisposable HttpListener { get; set; }
  37. /// <summary>
  38. /// The web socket connections
  39. /// </summary>
  40. private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
  41. /// <summary>
  42. /// Gets or sets the external web socket server.
  43. /// </summary>
  44. /// <value>The external web socket server.</value>
  45. private IWebSocketServer ExternalWebSocketServer { get; set; }
  46. /// <summary>
  47. /// The _logger
  48. /// </summary>
  49. private readonly ILogger _logger;
  50. /// <summary>
  51. /// The _application host
  52. /// </summary>
  53. private readonly IApplicationHost _applicationHost;
  54. /// <summary>
  55. /// Gets or sets the configuration manager.
  56. /// </summary>
  57. /// <value>The configuration manager.</value>
  58. private IServerConfigurationManager ConfigurationManager { get; set; }
  59. /// <summary>
  60. /// Gets a value indicating whether [supports web socket].
  61. /// </summary>
  62. /// <value><c>true</c> if [supports web socket]; otherwise, <c>false</c>.</value>
  63. public bool SupportsNativeWebSocket
  64. {
  65. get { return HttpServer != null && HttpServer.SupportsWebSockets; }
  66. }
  67. /// <summary>
  68. /// Gets the web socket port number.
  69. /// </summary>
  70. /// <value>The web socket port number.</value>
  71. public int WebSocketPortNumber
  72. {
  73. get { return SupportsNativeWebSocket ? ConfigurationManager.Configuration.HttpServerPortNumber : ConfigurationManager.Configuration.LegacyWebSocketPortNumber; }
  74. }
  75. /// <summary>
  76. /// Gets the web socket listeners.
  77. /// </summary>
  78. /// <value>The web socket listeners.</value>
  79. private readonly List<IWebSocketListener> _webSocketListeners = new List<IWebSocketListener>();
  80. private readonly Kernel _kernel;
  81. /// <summary>
  82. /// Initializes a new instance of the <see cref="ServerManager" /> class.
  83. /// </summary>
  84. /// <param name="applicationHost">The application host.</param>
  85. /// <param name="jsonSerializer">The json serializer.</param>
  86. /// <param name="logger">The logger.</param>
  87. /// <param name="configurationManager">The configuration manager.</param>
  88. /// <param name="kernel">The kernel.</param>
  89. /// <exception cref="System.ArgumentNullException">applicationHost</exception>
  90. public ServerManager(IApplicationHost applicationHost, IJsonSerializer jsonSerializer, ILogger logger, IServerConfigurationManager configurationManager, Kernel kernel)
  91. {
  92. if (applicationHost == null)
  93. {
  94. throw new ArgumentNullException("applicationHost");
  95. }
  96. if (jsonSerializer == null)
  97. {
  98. throw new ArgumentNullException("jsonSerializer");
  99. }
  100. if (logger == null)
  101. {
  102. throw new ArgumentNullException("logger");
  103. }
  104. _logger = logger;
  105. _jsonSerializer = jsonSerializer;
  106. _applicationHost = applicationHost;
  107. ConfigurationManager = configurationManager;
  108. _kernel = kernel;
  109. }
  110. /// <summary>
  111. /// Starts this instance.
  112. /// </summary>
  113. public void Start()
  114. {
  115. ReloadHttpServer();
  116. if (!SupportsNativeWebSocket)
  117. {
  118. ReloadExternalWebSocketServer();
  119. }
  120. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  121. }
  122. /// <summary>
  123. /// Starts the external web socket server.
  124. /// </summary>
  125. private void ReloadExternalWebSocketServer()
  126. {
  127. DisposeExternalWebSocketServer();
  128. ExternalWebSocketServer = _applicationHost.Resolve<IWebSocketServer>();
  129. ExternalWebSocketServer.Start(ConfigurationManager.Configuration.LegacyWebSocketPortNumber);
  130. ExternalWebSocketServer.WebSocketConnected += HttpServer_WebSocketConnected;
  131. }
  132. /// <summary>
  133. /// Restarts the Http Server, or starts it if not currently running
  134. /// </summary>
  135. private void ReloadHttpServer()
  136. {
  137. // Only reload if the port has changed, so that we don't disconnect any active users
  138. if (HttpServer != null && HttpServer.UrlPrefix.Equals(_kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  139. {
  140. return;
  141. }
  142. DisposeHttpServer();
  143. _logger.Info("Loading Http Server");
  144. try
  145. {
  146. HttpServer = _applicationHost.Resolve<IHttpServer>();
  147. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  148. HttpServer.Start(_kernel.HttpServerUrlPrefix);
  149. }
  150. catch (HttpListenerException ex)
  151. {
  152. _logger.ErrorException("Error starting Http Server", ex);
  153. throw;
  154. }
  155. HttpServer.WebSocketConnected += HttpServer_WebSocketConnected;
  156. }
  157. /// <summary>
  158. /// Handles the WebSocketConnected event of the HttpServer control.
  159. /// </summary>
  160. /// <param name="sender">The source of the event.</param>
  161. /// <param name="e">The <see cref="WebSocketConnectEventArgs" /> instance containing the event data.</param>
  162. void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e)
  163. {
  164. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger) { OnReceive = ProcessWebSocketMessageReceived };
  165. _webSocketConnections.Add(connection);
  166. }
  167. /// <summary>
  168. /// Processes the web socket message received.
  169. /// </summary>
  170. /// <param name="result">The result.</param>
  171. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  172. {
  173. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  174. {
  175. try
  176. {
  177. await i.ProcessMessage(result).ConfigureAwait(false);
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType);
  182. }
  183. }));
  184. await Task.WhenAll(tasks).ConfigureAwait(false);
  185. }
  186. /// <summary>
  187. /// Sends a message to all clients currently connected via a web socket
  188. /// </summary>
  189. /// <typeparam name="T"></typeparam>
  190. /// <param name="messageType">Type of the message.</param>
  191. /// <param name="data">The data.</param>
  192. /// <returns>Task.</returns>
  193. public void SendWebSocketMessage<T>(string messageType, T data)
  194. {
  195. SendWebSocketMessage(messageType, () => data);
  196. }
  197. /// <summary>
  198. /// Sends a message to all clients currently connected via a web socket
  199. /// </summary>
  200. /// <typeparam name="T"></typeparam>
  201. /// <param name="messageType">Type of the message.</param>
  202. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  203. public void SendWebSocketMessage<T>(string messageType, Func<T> dataFunction)
  204. {
  205. Task.Run(async () => await SendWebSocketMessageAsync(messageType, dataFunction, CancellationToken.None).ConfigureAwait(false));
  206. }
  207. /// <summary>
  208. /// Sends a message to all clients currently connected via a web socket
  209. /// </summary>
  210. /// <typeparam name="T"></typeparam>
  211. /// <param name="messageType">Type of the message.</param>
  212. /// <param name="dataFunction">The function that generates the data to send, if there are any connected clients</param>
  213. /// <param name="cancellationToken">The cancellation token.</param>
  214. /// <returns>Task.</returns>
  215. /// <exception cref="System.ArgumentNullException">messageType</exception>
  216. public async Task SendWebSocketMessageAsync<T>(string messageType, Func<T> dataFunction, CancellationToken cancellationToken)
  217. {
  218. if (string.IsNullOrEmpty(messageType))
  219. {
  220. throw new ArgumentNullException("messageType");
  221. }
  222. if (dataFunction == null)
  223. {
  224. throw new ArgumentNullException("dataFunction");
  225. }
  226. if (cancellationToken == null)
  227. {
  228. throw new ArgumentNullException("cancellationToken");
  229. }
  230. cancellationToken.ThrowIfCancellationRequested();
  231. var connections = _webSocketConnections.Where(s => s.State == WebSocketState.Open).ToList();
  232. if (connections.Count > 0)
  233. {
  234. _logger.Info("Sending web socket message {0}", messageType);
  235. var message = new WebSocketMessage<T> { MessageType = messageType, Data = dataFunction() };
  236. var bytes = _jsonSerializer.SerializeToBytes(message);
  237. var tasks = connections.Select(s => Task.Run(() =>
  238. {
  239. try
  240. {
  241. s.SendAsync(bytes, cancellationToken);
  242. }
  243. catch (OperationCanceledException)
  244. {
  245. throw;
  246. }
  247. catch (Exception ex)
  248. {
  249. _logger.ErrorException("Error sending web socket message {0} to {1}", ex, messageType, s.RemoteEndPoint);
  250. }
  251. }));
  252. await Task.WhenAll(tasks).ConfigureAwait(false);
  253. }
  254. }
  255. /// <summary>
  256. /// Disposes the current HttpServer
  257. /// </summary>
  258. private void DisposeHttpServer()
  259. {
  260. foreach (var socket in _webSocketConnections)
  261. {
  262. // Dispose the connection
  263. socket.Dispose();
  264. }
  265. _webSocketConnections.Clear();
  266. if (HttpServer != null)
  267. {
  268. HttpServer.WebSocketConnected -= HttpServer_WebSocketConnected;
  269. HttpServer.Dispose();
  270. }
  271. if (HttpListener != null)
  272. {
  273. HttpListener.Dispose();
  274. }
  275. DisposeExternalWebSocketServer();
  276. }
  277. /// <summary>
  278. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  279. /// </summary>
  280. public void Dispose()
  281. {
  282. Dispose(true);
  283. GC.SuppressFinalize(this);
  284. }
  285. /// <summary>
  286. /// Releases unmanaged and - optionally - managed resources.
  287. /// </summary>
  288. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  289. protected virtual void Dispose(bool dispose)
  290. {
  291. if (dispose)
  292. {
  293. DisposeHttpServer();
  294. }
  295. }
  296. /// <summary>
  297. /// Disposes the external web socket server.
  298. /// </summary>
  299. private void DisposeExternalWebSocketServer()
  300. {
  301. if (ExternalWebSocketServer != null)
  302. {
  303. _logger.Info("Disposing {0}", ExternalWebSocketServer.GetType().Name);
  304. ExternalWebSocketServer.Dispose();
  305. }
  306. }
  307. /// <summary>
  308. /// Handles the ConfigurationUpdated event of the _kernel control.
  309. /// </summary>
  310. /// <param name="sender">The source of the event.</param>
  311. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  312. /// <exception cref="System.NotImplementedException"></exception>
  313. void ConfigurationUpdated(object sender, EventArgs e)
  314. {
  315. HttpServer.EnableHttpRequestLogging = ConfigurationManager.Configuration.EnableHttpLevelLogging;
  316. if (!string.Equals(HttpServer.UrlPrefix, _kernel.HttpServerUrlPrefix, StringComparison.OrdinalIgnoreCase))
  317. {
  318. ReloadHttpServer();
  319. }
  320. if (!SupportsNativeWebSocket && ExternalWebSocketServer != null && ExternalWebSocketServer.Port != ConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  321. {
  322. ReloadExternalWebSocketServer();
  323. }
  324. }
  325. /// <summary>
  326. /// Adds the web socket listeners.
  327. /// </summary>
  328. /// <param name="listeners">The listeners.</param>
  329. public void AddWebSocketListeners(IEnumerable<IWebSocketListener> listeners)
  330. {
  331. _webSocketListeners.AddRange(listeners);
  332. }
  333. }
  334. }