ContextTimeoutManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. if (m_contexts.TryDequeue(out HttpClientContext context))
  112. {
  113. try
  114. {
  115. context.Disconnect(disconnectError);
  116. }
  117. catch { }
  118. }
  119. }
  120. m_processWaitEven.Dispose();
  121. m_processWaitEven = null;
  122. }
  123. catch
  124. {
  125. // We can't let this crash.
  126. }
  127. }
  128. public static void ProcessSendQueues(double now)
  129. {
  130. int inqueues = m_highPrio.Count + m_midPrio.Count + m_lowPrio.Count;
  131. if(inqueues == 0)
  132. return;
  133. double dt = now - m_lastSendCheckTime;
  134. m_lastSendCheckTime = now;
  135. int totalSending = m_ActiveSendingCount;
  136. int curConcurrentLimit = m_maxConcurrenSend - totalSending;
  137. if(curConcurrentLimit <= 0)
  138. return;
  139. if(curConcurrentLimit > inqueues)
  140. curConcurrentLimit = inqueues;
  141. if (dt > 0.5)
  142. dt = 0.5;
  143. dt /= curConcurrentLimit;
  144. int curbytesLimit = (int)(m_maxBandWidth * dt);
  145. if(curbytesLimit < 8192)
  146. curbytesLimit = 8192;
  147. HttpClientContext ctx;
  148. int sent;
  149. while (curConcurrentLimit > 0)
  150. {
  151. sent = 0;
  152. while (m_highPrio.TryDequeue(out ctx))
  153. {
  154. if(TrySend(ctx, curbytesLimit))
  155. m_highPrio.Enqueue(ctx);
  156. if (m_shuttingDown)
  157. return;
  158. --curConcurrentLimit;
  159. if (++sent == 4)
  160. break;
  161. }
  162. sent = 0;
  163. while(m_midPrio.TryDequeue(out ctx))
  164. {
  165. if(TrySend(ctx, curbytesLimit))
  166. m_midPrio.Enqueue(ctx);
  167. if (m_shuttingDown)
  168. return;
  169. --curConcurrentLimit;
  170. if (++sent >= 2)
  171. break;
  172. }
  173. if (m_lowPrio.TryDequeue(out ctx))
  174. {
  175. --curConcurrentLimit;
  176. if(TrySend(ctx, curbytesLimit))
  177. m_lowPrio.Enqueue(ctx);
  178. }
  179. if (m_shuttingDown)
  180. return;
  181. }
  182. }
  183. private static bool TrySend(HttpClientContext ctx, int bytesLimit)
  184. {
  185. if(!ctx.CanSend())
  186. return false;
  187. return ctx.TrySendResponse(bytesLimit);
  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, 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. }