ContextTimeoutManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Concurrent;
  29. using System.Diagnostics;
  30. using System.Globalization;
  31. using System.Net.Sockets;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. namespace OSHttpServer
  35. {
  36. /// <summary>
  37. /// Timeout Manager. Checks for dead clients. Clients with open connections that are not doing anything. Closes sessions opened with keepalive.
  38. /// </summary>
  39. public static class ContextTimeoutManager
  40. {
  41. /// <summary>
  42. /// Use a Thread or a Timer to monitor the ugly
  43. /// </summary>
  44. private static Thread m_internalThread = null;
  45. private static object m_threadLock = new object();
  46. private static ConcurrentQueue<HttpClientContext> m_contexts = new ConcurrentQueue<HttpClientContext>();
  47. private static ConcurrentQueue<HttpClientContext> m_highPrio = new ConcurrentQueue<HttpClientContext>();
  48. private static ConcurrentQueue<HttpClientContext> m_midPrio = new ConcurrentQueue<HttpClientContext>();
  49. private static ConcurrentQueue<HttpClientContext> m_lowPrio = new ConcurrentQueue<HttpClientContext>();
  50. private static AutoResetEvent m_processWaitEven = new AutoResetEvent(false);
  51. private static bool m_shuttingDown;
  52. private static int m_ActiveSendingCount;
  53. private static double m_lastTimeOutCheckTime = 0;
  54. private static double m_lastSendCheckTime = 0;
  55. const int m_maxBandWidth = 10485760; //80Mbps
  56. const int m_maxConcurrenSend = 32;
  57. static ContextTimeoutManager()
  58. {
  59. TimeStampClockPeriod = 1.0 / (double)Stopwatch.Frequency;
  60. TimeStampClockPeriodMS = 1e3 / (double)Stopwatch.Frequency;
  61. }
  62. public static void Start()
  63. {
  64. lock (m_threadLock)
  65. {
  66. if (m_internalThread != null)
  67. return;
  68. m_lastTimeOutCheckTime = GetTimeStampMS();
  69. m_internalThread = new Thread(ThreadRunProcess);
  70. m_internalThread.Priority = ThreadPriority.Normal;
  71. m_internalThread.IsBackground = true;
  72. m_internalThread.CurrentCulture = new CultureInfo("en-US", false);
  73. m_internalThread.Name = "HttpServerMain";
  74. m_internalThread.Start();
  75. }
  76. }
  77. public static void Stop()
  78. {
  79. m_shuttingDown = true;
  80. m_internalThread.Join();
  81. ProcessShutDown();
  82. }
  83. private static void ThreadRunProcess()
  84. {
  85. while (!m_shuttingDown)
  86. {
  87. m_processWaitEven.WaitOne(500);
  88. if(m_shuttingDown)
  89. return;
  90. double now = GetTimeStamp();
  91. if(m_contexts.Count > 0)
  92. {
  93. ProcessSendQueues(now);
  94. if (now - m_lastTimeOutCheckTime > 1.0)
  95. {
  96. ProcessContextTimeouts();
  97. m_lastTimeOutCheckTime = now;
  98. }
  99. }
  100. else
  101. m_lastTimeOutCheckTime = now;
  102. }
  103. }
  104. public static void ProcessShutDown()
  105. {
  106. try
  107. {
  108. SocketError disconnectError = SocketError.HostDown;
  109. for (int i = 0; i < m_contexts.Count; i++)
  110. {
  111. HttpClientContext context = null;
  112. if (m_contexts.TryDequeue(out context))
  113. {
  114. try
  115. {
  116. context.Disconnect(disconnectError);
  117. }
  118. catch { }
  119. }
  120. }
  121. m_processWaitEven.Dispose();
  122. m_processWaitEven = null;
  123. }
  124. catch
  125. {
  126. // We can't let this crash.
  127. }
  128. }
  129. public static void ProcessSendQueues(double now)
  130. {
  131. int inqueues = m_highPrio.Count + m_midPrio.Count + m_lowPrio.Count;
  132. if(inqueues == 0)
  133. return;
  134. double dt = now - m_lastSendCheckTime;
  135. m_lastSendCheckTime = now;
  136. int totalSending = m_ActiveSendingCount;
  137. int curConcurrentLimit = m_maxConcurrenSend - totalSending;
  138. if(curConcurrentLimit <= 0)
  139. return;
  140. if(curConcurrentLimit > inqueues)
  141. curConcurrentLimit = inqueues;
  142. if (dt > 0.5)
  143. dt = 0.5;
  144. dt /= curConcurrentLimit;
  145. int curbytesLimit = (int)(m_maxBandWidth * dt);
  146. if(curbytesLimit < 8192)
  147. curbytesLimit = 8192;
  148. HttpClientContext ctx;
  149. int sent;
  150. while (curConcurrentLimit > 0)
  151. {
  152. sent = 0;
  153. while (m_highPrio.TryDequeue(out ctx))
  154. {
  155. if(TrySend(ctx, curbytesLimit))
  156. m_highPrio.Enqueue(ctx);
  157. if (m_shuttingDown)
  158. return;
  159. --curConcurrentLimit;
  160. if (++sent == 4)
  161. break;
  162. }
  163. sent = 0;
  164. while(m_midPrio.TryDequeue(out ctx))
  165. {
  166. if(TrySend(ctx, curbytesLimit))
  167. m_midPrio.Enqueue(ctx);
  168. if (m_shuttingDown)
  169. return;
  170. --curConcurrentLimit;
  171. if (++sent >= 2)
  172. break;
  173. }
  174. if (m_lowPrio.TryDequeue(out ctx))
  175. {
  176. --curConcurrentLimit;
  177. if(TrySend(ctx, curbytesLimit))
  178. m_lowPrio.Enqueue(ctx);
  179. }
  180. if (m_shuttingDown)
  181. return;
  182. }
  183. }
  184. private static bool TrySend(HttpClientContext ctx, int bytesLimit)
  185. {
  186. if(!ctx.CanSend())
  187. return false;
  188. return ctx.TrySendResponse(bytesLimit);
  189. }
  190. /// <summary>
  191. /// Causes the watcher to immediately check the connections.
  192. /// </summary>
  193. public static void ProcessContextTimeouts()
  194. {
  195. try
  196. {
  197. for (int i = 0; i < m_contexts.Count; i++)
  198. {
  199. if (m_shuttingDown)
  200. return;
  201. if (m_contexts.TryDequeue(out HttpClientContext context))
  202. {
  203. if (!ContextTimedOut(context, out SocketError disconnectError))
  204. m_contexts.Enqueue(context);
  205. else if(disconnectError != SocketError.InProgress)
  206. context.Disconnect(disconnectError);
  207. }
  208. }
  209. }
  210. catch
  211. {
  212. // We can't let this crash.
  213. }
  214. }
  215. private static bool ContextTimedOut(HttpClientContext context, out SocketError disconnectError)
  216. {
  217. disconnectError = SocketError.InProgress;
  218. // First our error conditions
  219. if (context.contextID < 0 || context.StopMonitoring || context.StreamPassedOff)
  220. return true;
  221. int nowMS = EnvironmentTickCount();
  222. // First we check first contact line
  223. if (!context.FirstRequestLineReceived)
  224. {
  225. if (EnvironmentTickCountAdd(context.TimeoutFirstLine, context.LastActivityTimeMS) < nowMS)
  226. {
  227. disconnectError = SocketError.TimedOut;
  228. return true;
  229. }
  230. return false;
  231. }
  232. // First we check first contact request
  233. if (!context.FullRequestReceived)
  234. {
  235. if (EnvironmentTickCountAdd(context.TimeoutRequestReceived, context.LastActivityTimeMS) < nowMS)
  236. {
  237. disconnectError = SocketError.TimedOut;
  238. return true;
  239. }
  240. return false;
  241. }
  242. if (context.TriggerKeepalive)
  243. {
  244. context.TriggerKeepalive = false;
  245. context.MonitorKeepaliveStartMS = nowMS + 1;
  246. return false;
  247. }
  248. if (context.MonitorKeepaliveStartMS != 0)
  249. {
  250. if (EnvironmentTickCountAdd(context.TimeoutKeepAlive, context.MonitorKeepaliveStartMS) < nowMS)
  251. {
  252. if(context.IsClosing)
  253. disconnectError = SocketError.Success;
  254. else
  255. disconnectError = SocketError.TimedOut;
  256. context.MonitorKeepaliveStartMS = 0;
  257. return true;
  258. }
  259. return false;
  260. }
  261. if (EnvironmentTickCountAdd(context.TimeoutMaxIdle, context.LastActivityTimeMS) < nowMS)
  262. {
  263. disconnectError = SocketError.TimedOut;
  264. context.MonitorKeepaliveStartMS = 0;
  265. return true;
  266. }
  267. return false;
  268. }
  269. public static void StartMonitoringContext(HttpClientContext context)
  270. {
  271. context.LastActivityTimeMS = EnvironmentTickCount();
  272. m_contexts.Enqueue(context);
  273. }
  274. public static void EnqueueSend(HttpClientContext context, int priority, bool notThrottled = true)
  275. {
  276. switch(priority)
  277. {
  278. case 0:
  279. m_highPrio.Enqueue(context);
  280. break;
  281. case 1:
  282. m_midPrio.Enqueue(context);
  283. break;
  284. case 2:
  285. m_lowPrio.Enqueue(context);
  286. break;
  287. default:
  288. return;
  289. }
  290. if(notThrottled)
  291. m_processWaitEven.Set();
  292. }
  293. public static void ContextEnterActiveSend()
  294. {
  295. Interlocked.Increment(ref m_ActiveSendingCount);
  296. }
  297. public static void ContextLeaveActiveSend()
  298. {
  299. Interlocked.Decrement(ref m_ActiveSendingCount);
  300. }
  301. /// <summary>
  302. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  303. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  304. /// for the callers.
  305. /// This trims it to a 12 day interval so don't let your frame time get too long.
  306. /// </summary>
  307. /// <returns></returns>
  308. public static int EnvironmentTickCount()
  309. {
  310. return Environment.TickCount & EnvironmentTickCountMask;
  311. }
  312. const int EnvironmentTickCountMask = 0x3fffffff;
  313. /// <summary>
  314. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  315. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  316. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  317. /// </summary>
  318. /// <param name="newValue"></param>
  319. /// <param name="prevValue"></param>
  320. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  321. public static int EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  322. {
  323. int diff = newValue - prevValue;
  324. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  325. }
  326. /// <summary>
  327. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  328. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  329. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  330. /// </summary>
  331. /// <param name="newValue"></param>
  332. /// <param name="prevValue"></param>
  333. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  334. public static int EnvironmentTickCountAdd(Int32 newValue, Int32 prevValue)
  335. {
  336. int ret = newValue + prevValue;
  337. return (ret >= 0) ? ret : (ret + EnvironmentTickCountMask + 1);
  338. }
  339. public static double TimeStampClockPeriodMS;
  340. public static double TimeStampClockPeriod;
  341. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  342. public static double GetTimeStamp()
  343. {
  344. return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
  345. }
  346. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  347. public static double GetTimeStampMS()
  348. {
  349. return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
  350. }
  351. // doing math in ticks is usefull to avoid loss of resolution
  352. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  353. public static long GetTimeStampTicks()
  354. {
  355. return Stopwatch.GetTimestamp();
  356. }
  357. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  358. public static double TimeStampTicksToMS(long ticks)
  359. {
  360. return ticks * TimeStampClockPeriodMS;
  361. }
  362. }
  363. }