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(100);
  88. if(m_shuttingDown)
  89. return;
  90. double now = GetTimeStampMS();
  91. if(m_contexts.Count > 0)
  92. {
  93. ProcessSendQueues(now);
  94. if (now - m_lastTimeOutCheckTime > 1000)
  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.1)
  143. dt = 0.1;
  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. // Now we start checking for actual timeouts
  222. // First we check that we got at least one line within context.TimeoutFirstLine milliseconds
  223. if (!context.FirstRequestLineReceived)
  224. {
  225. if (EnvironmentTickCountAdd(context.TimeoutFirstLine, context.MonitorStartMS) <= EnvironmentTickCount())
  226. {
  227. disconnectError = SocketError.TimedOut;
  228. context.MonitorStartMS = 0;
  229. return true;
  230. }
  231. }
  232. if (!context.FullRequestReceived)
  233. {
  234. if (EnvironmentTickCountAdd(context.TimeoutRequestReceived, context.MonitorStartMS) <= EnvironmentTickCount())
  235. {
  236. disconnectError = SocketError.TimedOut;
  237. context.MonitorStartMS = 0;
  238. return true;
  239. }
  240. }
  241. //
  242. if (!context.FullRequestProcessed)
  243. {
  244. if (EnvironmentTickCountAdd(context.TimeoutFullRequestProcessed, context.MonitorStartMS) <= EnvironmentTickCount())
  245. {
  246. disconnectError = SocketError.TimedOut;
  247. context.MonitorStartMS = 0;
  248. return true;
  249. }
  250. }
  251. if (context.TriggerKeepalive)
  252. {
  253. context.TriggerKeepalive = false;
  254. context.MonitorKeepaliveMS = EnvironmentTickCount();
  255. }
  256. if (context.FullRequestProcessed && context.MonitorKeepaliveMS == 0)
  257. return true;
  258. if (context.MonitorKeepaliveMS != 0 &&
  259. EnvironmentTickCountAdd(context.TimeoutKeepAlive, context.MonitorKeepaliveMS) <= EnvironmentTickCount())
  260. {
  261. disconnectError = SocketError.TimedOut;
  262. context.MonitorStartMS = 0;
  263. context.MonitorKeepaliveMS = 0;
  264. return true;
  265. }
  266. return false;
  267. }
  268. public static void StartMonitoringContext(HttpClientContext context)
  269. {
  270. context.MonitorStartMS = EnvironmentTickCount();
  271. m_contexts.Enqueue(context);
  272. }
  273. public static void EnqueueSend(HttpClientContext context, int priority)
  274. {
  275. switch(priority)
  276. {
  277. case 0:
  278. m_highPrio.Enqueue(context);
  279. break;
  280. case 1:
  281. m_midPrio.Enqueue(context);
  282. break;
  283. case 2:
  284. m_lowPrio.Enqueue(context);
  285. break;
  286. default:
  287. return;
  288. }
  289. m_processWaitEven.Set();
  290. }
  291. public static void ContextEnterActiveSend()
  292. {
  293. Interlocked.Increment(ref m_ActiveSendingCount);
  294. }
  295. public static void ContextLeaveActiveSend()
  296. {
  297. Interlocked.Decrement(ref m_ActiveSendingCount);
  298. }
  299. /// <summary>
  300. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  301. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  302. /// for the callers.
  303. /// This trims it to a 12 day interval so don't let your frame time get too long.
  304. /// </summary>
  305. /// <returns></returns>
  306. public static int EnvironmentTickCount()
  307. {
  308. return Environment.TickCount & EnvironmentTickCountMask;
  309. }
  310. const int EnvironmentTickCountMask = 0x3fffffff;
  311. /// <summary>
  312. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  313. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  314. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  315. /// </summary>
  316. /// <param name="newValue"></param>
  317. /// <param name="prevValue"></param>
  318. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  319. public static int EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  320. {
  321. int diff = newValue - prevValue;
  322. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  323. }
  324. /// <summary>
  325. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  326. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  327. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  328. /// </summary>
  329. /// <param name="newValue"></param>
  330. /// <param name="prevValue"></param>
  331. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  332. public static int EnvironmentTickCountAdd(Int32 newValue, Int32 prevValue)
  333. {
  334. int ret = newValue + prevValue;
  335. return (ret >= 0) ? ret : (ret + EnvironmentTickCountMask + 1);
  336. }
  337. public static double TimeStampClockPeriodMS;
  338. public static double TimeStampClockPeriod;
  339. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  340. public static double GetTimeStamp()
  341. {
  342. return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
  343. }
  344. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  345. public static double GetTimeStampMS()
  346. {
  347. return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
  348. }
  349. // doing math in ticks is usefull to avoid loss of resolution
  350. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  351. public static long GetTimeStampTicks()
  352. {
  353. return Stopwatch.GetTimestamp();
  354. }
  355. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  356. public static double TimeStampTicksToMS(long ticks)
  357. {
  358. return ticks * TimeStampClockPeriodMS;
  359. }
  360. }
  361. }