1
0

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. namespace OSHttpServer
  34. {
  35. /// <summary>
  36. /// Timeout Manager. Checks for dead clients. Clients with open connections that are not doing anything. Closes sessions opened with keepalive.
  37. /// </summary>
  38. public static class ContextTimeoutManager
  39. {
  40. /// <summary>
  41. /// Use a Thread or a Timer to monitor the ugly
  42. /// </summary>
  43. private static Thread m_internalThread = null;
  44. private static readonly object m_threadLock = new();
  45. private static readonly ConcurrentQueue<HttpClientContext> m_contexts = new();
  46. private static readonly ConcurrentQueue<HttpClientContext> m_highPrio = new();
  47. private static readonly ConcurrentQueue<HttpClientContext> m_midPrio = new();
  48. private static readonly ConcurrentQueue<HttpClientContext> m_lowPrio = new();
  49. private static AutoResetEvent m_processWaitEven = new(false);
  50. private static bool m_shuttingDown;
  51. private static int m_ActiveSendingCount;
  52. private static double m_lastTimeOutCheckTime = 0;
  53. const int m_maxConcurrentSend = 32;
  54. static ContextTimeoutManager()
  55. {
  56. TimeStampClockPeriod = 1.0 / (double)Stopwatch.Frequency;
  57. TimeStampClockPeriodMS = 1e3 / (double)Stopwatch.Frequency;
  58. }
  59. public static void Start()
  60. {
  61. lock (m_threadLock)
  62. {
  63. if (m_internalThread != null)
  64. return;
  65. m_lastTimeOutCheckTime = GetTimeStamp();
  66. using(ExecutionContext.SuppressFlow())
  67. m_internalThread = new Thread(ThreadRunProcess);
  68. m_internalThread.Priority = ThreadPriority.Normal;
  69. m_internalThread.IsBackground = true;
  70. m_internalThread.CurrentCulture = new CultureInfo("en-US", false);
  71. m_internalThread.Name = "HttpServerMain";
  72. m_internalThread.Start();
  73. }
  74. }
  75. public static void Stop()
  76. {
  77. if (m_processWaitEven != null)
  78. {
  79. m_processWaitEven.Set();
  80. m_shuttingDown = true;
  81. }
  82. }
  83. private static void ThreadRunProcess()
  84. {
  85. while (!m_shuttingDown)
  86. {
  87. m_processWaitEven.WaitOne(500);
  88. if (m_shuttingDown)
  89. break;
  90. double now = GetTimeStamp();
  91. if(!m_contexts.IsEmpty)
  92. {
  93. ProcessSendQueues();
  94. if (m_shuttingDown)
  95. break;
  96. if (now - m_lastTimeOutCheckTime > 1.0)
  97. {
  98. ProcessContextTimeouts();
  99. m_lastTimeOutCheckTime = now;
  100. }
  101. }
  102. else
  103. m_lastTimeOutCheckTime = now;
  104. }
  105. ProcessShutDown();
  106. }
  107. public static void ProcessShutDown()
  108. {
  109. try
  110. {
  111. if(m_processWaitEven != null)
  112. {
  113. SocketError disconnectError = SocketError.HostDown;
  114. for (int i = 0; i < m_contexts.Count; i++)
  115. {
  116. if (m_contexts.TryDequeue(out HttpClientContext context))
  117. {
  118. try
  119. {
  120. context.Disconnect(disconnectError);
  121. }
  122. catch { }
  123. }
  124. }
  125. m_processWaitEven.Dispose();
  126. m_processWaitEven = null;
  127. }
  128. }
  129. catch
  130. {
  131. // We can't let this crash.
  132. }
  133. }
  134. public static void ProcessSendQueues()
  135. {
  136. int inqueues = m_highPrio.Count + m_midPrio.Count + m_lowPrio.Count;
  137. if(inqueues == 0)
  138. return;
  139. const int curbytesLimit = 128 * 1024;
  140. int curConcurrentLimit = m_maxConcurrentSend - m_ActiveSendingCount;
  141. if(curConcurrentLimit <= 0)
  142. return;
  143. if(curConcurrentLimit > inqueues)
  144. curConcurrentLimit = inqueues;
  145. HttpClientContext ctx;
  146. int sentFromQueue;
  147. bool done;
  148. while (curConcurrentLimit > 0)
  149. {
  150. sentFromQueue = 0;
  151. done = true;
  152. while (m_highPrio.TryDequeue(out ctx))
  153. {
  154. if (m_shuttingDown)
  155. return;
  156. done = false;
  157. if (ctx.TrySendResponse(curbytesLimit))
  158. {
  159. --curConcurrentLimit;
  160. if (++sentFromQueue == 3)
  161. break;
  162. }
  163. }
  164. sentFromQueue = 0;
  165. while(m_midPrio.TryDequeue(out ctx))
  166. {
  167. if (m_shuttingDown)
  168. return;
  169. done = false;
  170. if (ctx.TrySendResponse(curbytesLimit))
  171. {
  172. --curConcurrentLimit;
  173. if (++sentFromQueue >= 2)
  174. break;
  175. }
  176. }
  177. if (m_lowPrio.TryDequeue(out ctx))
  178. {
  179. if (m_shuttingDown)
  180. return;
  181. done = false;
  182. if (ctx.TrySendResponse(curbytesLimit))
  183. --curConcurrentLimit;
  184. }
  185. if (done)
  186. break;
  187. }
  188. }
  189. /// <summary>
  190. /// Causes the watcher to immediately check the connections.
  191. /// </summary>
  192. public static void ProcessContextTimeouts()
  193. {
  194. try
  195. {
  196. for (int i = 0; i < m_contexts.Count; i++)
  197. {
  198. if (m_shuttingDown)
  199. return;
  200. if (m_contexts.TryDequeue(out HttpClientContext context))
  201. {
  202. if (!ContextTimedOut(context, out SocketError disconnectError))
  203. m_contexts.Enqueue(context);
  204. else if(disconnectError != SocketError.InProgress)
  205. context.Disconnect(disconnectError);
  206. }
  207. }
  208. }
  209. catch
  210. {
  211. // We can't let this crash.
  212. }
  213. }
  214. private static bool ContextTimedOut(HttpClientContext context, out SocketError disconnectError)
  215. {
  216. disconnectError = SocketError.InProgress;
  217. // First our error conditions
  218. if (context.contextID < 0 || context.StopMonitoring || context.StreamPassedOff)
  219. return true;
  220. int nowMS = EnvironmentTickCount();
  221. // First we check first contact line
  222. if (!context.FirstRequestLineReceived)
  223. {
  224. if (EnvironmentTickCountAdd(context.TimeoutFirstLine, context.LastActivityTimeMS) < nowMS)
  225. {
  226. disconnectError = SocketError.TimedOut;
  227. return true;
  228. }
  229. return false;
  230. }
  231. // First we check first contact request
  232. if (!context.FullRequestReceived)
  233. {
  234. if (EnvironmentTickCountAdd(context.TimeoutRequestReceived, context.LastActivityTimeMS) < nowMS)
  235. {
  236. disconnectError = SocketError.TimedOut;
  237. return true;
  238. }
  239. return false;
  240. }
  241. if (context.TriggerKeepalive)
  242. {
  243. context.TriggerKeepalive = false;
  244. context.MonitorKeepaliveStartMS = nowMS + 500;
  245. return false;
  246. }
  247. if (context.MonitorKeepaliveStartMS != 0)
  248. {
  249. if (context.IsClosing)
  250. {
  251. disconnectError = SocketError.Success;
  252. return true;
  253. }
  254. if (EnvironmentTickCountAdd(context.TimeoutKeepAlive, context.MonitorKeepaliveStartMS) < nowMS)
  255. {
  256. disconnectError = SocketError.TimedOut;
  257. context.MonitorKeepaliveStartMS = 0;
  258. return true;
  259. }
  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)
  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. m_processWaitEven?.Set();
  291. }
  292. public static void PulseWaitSend()
  293. {
  294. m_processWaitEven?.Set();
  295. }
  296. public static void ContextEnterActiveSend()
  297. {
  298. Interlocked.Increment(ref m_ActiveSendingCount);
  299. }
  300. public static void ContextLeaveActiveSend()
  301. {
  302. Interlocked.Decrement(ref m_ActiveSendingCount);
  303. }
  304. /// <summary>
  305. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  306. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  307. /// for the callers.
  308. /// This trims it to a 12 day interval so don't let your frame time get too long.
  309. /// </summary>
  310. /// <returns></returns>
  311. public static int EnvironmentTickCount()
  312. {
  313. return Environment.TickCount & EnvironmentTickCountMask;
  314. }
  315. const int EnvironmentTickCountMask = 0x3fffffff;
  316. /// <summary>
  317. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  318. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  319. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  320. /// </summary>
  321. /// <param name="newValue"></param>
  322. /// <param name="prevValue"></param>
  323. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  324. public static int EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  325. {
  326. int diff = newValue - prevValue;
  327. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  328. }
  329. /// <summary>
  330. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  331. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  332. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  333. /// </summary>
  334. /// <param name="newValue"></param>
  335. /// <param name="prevValue"></param>
  336. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  337. public static int EnvironmentTickCountAdd(Int32 newValue, Int32 prevValue)
  338. {
  339. int ret = newValue + prevValue;
  340. return (ret >= 0) ? ret : (ret + EnvironmentTickCountMask + 1);
  341. }
  342. public static double TimeStampClockPeriodMS;
  343. public static double TimeStampClockPeriod;
  344. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  345. public static double GetTimeStamp()
  346. {
  347. return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
  348. }
  349. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  350. public static double GetTimeStampMS()
  351. {
  352. return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
  353. }
  354. // doing math in ticks is usefull to avoid loss of resolution
  355. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  356. public static long GetTimeStampTicks()
  357. {
  358. return Stopwatch.GetTimestamp();
  359. }
  360. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  361. public static double TimeStampTicksToMS(long ticks)
  362. {
  363. return ticks * TimeStampClockPeriodMS;
  364. }
  365. }
  366. }