ServerManager.cs 14 KB

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