ContextTimeoutManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. using(ExecutionContext.SuppressFlow())
  70. m_internalThread = new Thread(ThreadRunProcess);
  71. m_internalThread.Priority = ThreadPriority.Normal;
  72. m_internalThread.IsBackground = true;
  73. m_internalThread.CurrentCulture = new CultureInfo("en-US", false);
  74. m_internalThread.Name = "HttpServerMain";
  75. m_internalThread.Start();
  76. }
  77. }
  78. public static void Stop()
  79. {
  80. m_shuttingDown = true;
  81. m_processWaitEven.Set();
  82. //m_internalThread.Join();
  83. //ProcessShutDown();
  84. }
  85. private static void ThreadRunProcess()
  86. {
  87. while (!m_shuttingDown)
  88. {
  89. m_processWaitEven.WaitOne(500);
  90. if(m_shuttingDown)
  91. return;
  92. double now = GetTimeStamp();
  93. if(m_contexts.Count > 0)
  94. {
  95. ProcessSendQueues(now);
  96. if (now - m_lastTimeOutCheckTime > 1.0)
  97. {
  98. ProcessContextTimeouts();
  99. m_lastTimeOutCheckTime = now;
  100. }
  101. }
  102. else
  103. m_lastTimeOutCheckTime = now;
  104. }
  105. }
  106. public static void ProcessShutDown()
  107. {
  108. try
  109. {
  110. SocketError disconnectError = SocketError.HostDown;
  111. for (int i = 0; i < m_contexts.Count; i++)
  112. {
  113. if (m_contexts.TryDequeue(out HttpClientContext context))
  114. {
  115. try
  116. {
  117. context.Disconnect(disconnectError);
  118. }
  119. catch { }
  120. }
  121. }
  122. m_processWaitEven.Dispose();
  123. m_processWaitEven = null;
  124. }
  125. catch
  126. {
  127. // We can't let this crash.
  128. }
  129. }
  130. public static void ProcessSendQueues(double now)
  131. {
  132. int inqueues = m_highPrio.Count + m_midPrio.Count + m_lowPrio.Count;
  133. if(inqueues == 0)
  134. return;
  135. double dt = now - m_lastSendCheckTime;
  136. m_lastSendCheckTime = now;
  137. int totalSending = m_ActiveSendingCount;
  138. int curConcurrentLimit = m_maxConcurrenSend - totalSending;
  139. if(curConcurrentLimit <= 0)
  140. return;
  141. if(curConcurrentLimit > inqueues)
  142. curConcurrentLimit = inqueues;
  143. if (dt > 0.5)
  144. dt = 0.5;
  145. dt /= curConcurrentLimit;
  146. int curbytesLimit = (int)(m_maxBandWidth * dt);
  147. if(curbytesLimit < 1024)
  148. curbytesLimit = 1024;
  149. HttpClientContext ctx;
  150. int sent;
  151. while (curConcurrentLimit > 0)
  152. {
  153. sent = 0;
  154. while (m_highPrio.TryDequeue(out ctx))
  155. {
  156. if(TrySend(ctx, curbytesLimit))
  157. m_highPrio.Enqueue(ctx);
  158. if (m_shuttingDown)
  159. return;
  160. --curConcurrentLimit;
  161. if (++sent == 4)
  162. break;
  163. }
  164. sent = 0;
  165. while(m_midPrio.TryDequeue(out ctx))
  166. {
  167. if(TrySend(ctx, curbytesLimit))
  168. m_midPrio.Enqueue(ctx);
  169. if (m_shuttingDown)
  170. return;
  171. --curConcurrentLimit;
  172. if (++sent >= 2)
  173. break;
  174. }
  175. if (m_lowPrio.TryDequeue(out ctx))
  176. {
  177. --curConcurrentLimit;
  178. if(TrySend(ctx, curbytesLimit))
  179. m_lowPrio.Enqueue(ctx);
  180. }
  181. if (m_shuttingDown)
  182. return;
  183. }
  184. }
  185. private static bool TrySend(HttpClientContext ctx, int bytesLimit)
  186. {
  187. if(!ctx.CanSend())
  188. return false;
  189. return ctx.TrySendResponse(bytesLimit);
  190. }
  191. /// <summary>
  192. /// Causes the watcher to immediately check the connections.
  193. /// </summary>
  194. public static void ProcessContextTimeouts()
  195. {
  196. try
  197. {
  198. for (int i = 0; i < m_contexts.Count; i++)
  199. {
  200. if (m_shuttingDown)
  201. return;
  202. if (m_contexts.TryDequeue(out HttpClientContext context))
  203. {
  204. if (!ContextTimedOut(context, out SocketError disconnectError))
  205. m_contexts.Enqueue(context);
  206. else if(disconnectError != SocketError.InProgress)
  207. context.Disconnect(disconnectError);
  208. }
  209. }
  210. }
  211. catch
  212. {
  213. // We can't let this crash.
  214. }
  215. }
  216. private static bool ContextTimedOut(HttpClientContext context, out SocketError disconnectError)
  217. {
  218. disconnectError = SocketError.InProgress;
  219. // First our error conditions
  220. if (context.contextID < 0 || context.StopMonitoring || context.StreamPassedOff)
  221. return true;
  222. int nowMS = EnvironmentTickCount();
  223. // First we check first contact line
  224. if (!context.FirstRequestLineReceived)
  225. {
  226. if (EnvironmentTickCountAdd(context.TimeoutFirstLine, context.LastActivityTimeMS) < nowMS)
  227. {
  228. disconnectError = SocketError.TimedOut;
  229. return true;
  230. }
  231. return false;
  232. }
  233. // First we check first contact request
  234. if (!context.FullRequestReceived)
  235. {
  236. if (EnvironmentTickCountAdd(context.TimeoutRequestReceived, context.LastActivityTimeMS) < nowMS)
  237. {
  238. disconnectError = SocketError.TimedOut;
  239. return true;
  240. }
  241. return false;
  242. }
  243. if (context.TriggerKeepalive)
  244. {
  245. context.TriggerKeepalive = false;
  246. context.MonitorKeepaliveStartMS = nowMS + 500;
  247. return false;
  248. }
  249. if (context.MonitorKeepaliveStartMS != 0)
  250. {
  251. if (context.IsClosing)
  252. {
  253. disconnectError = SocketError.Success;
  254. return true;
  255. }
  256. if (EnvironmentTickCountAdd(context.TimeoutKeepAlive, context.MonitorKeepaliveStartMS) < nowMS)
  257. {
  258. disconnectError = SocketError.TimedOut;
  259. context.MonitorKeepaliveStartMS = 0;
  260. return true;
  261. }
  262. }
  263. if (EnvironmentTickCountAdd(context.TimeoutMaxIdle, context.LastActivityTimeMS) < nowMS)
  264. {
  265. disconnectError = SocketError.TimedOut;
  266. context.MonitorKeepaliveStartMS = 0;
  267. return true;
  268. }
  269. return false;
  270. }
  271. public static void StartMonitoringContext(HttpClientContext context)
  272. {
  273. context.LastActivityTimeMS = EnvironmentTickCount();
  274. m_contexts.Enqueue(context);
  275. }
  276. public static void EnqueueSend(HttpClientContext context, int priority, bool notThrottled = true)
  277. {
  278. switch(priority)
  279. {
  280. case 0:
  281. m_highPrio.Enqueue(context);
  282. break;
  283. case 1:
  284. m_midPrio.Enqueue(context);
  285. break;
  286. case 2:
  287. m_lowPrio.Enqueue(context);
  288. break;
  289. default:
  290. return;
  291. }
  292. if(notThrottled)
  293. m_processWaitEven.Set();
  294. }
  295. public static void ContextEnterActiveSend()
  296. {
  297. Interlocked.Increment(ref m_ActiveSendingCount);
  298. }
  299. public static void ContextLeaveActiveSend()
  300. {
  301. Interlocked.Decrement(ref m_ActiveSendingCount);
  302. }
  303. /// <summary>
  304. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  305. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  306. /// for the callers.
  307. /// This trims it to a 12 day interval so don't let your frame time get too long.
  308. /// </summary>
  309. /// <returns></returns>
  310. public static int EnvironmentTickCount()
  311. {
  312. return Environment.TickCount & EnvironmentTickCountMask;
  313. }
  314. const int EnvironmentTickCountMask = 0x3fffffff;
  315. /// <summary>
  316. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  317. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  318. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  319. /// </summary>
  320. /// <param name="newValue"></param>
  321. /// <param name="prevValue"></param>
  322. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  323. public static int EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  324. {
  325. int diff = newValue - prevValue;
  326. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  327. }
  328. /// <summary>
  329. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  330. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  331. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  332. /// </summary>
  333. /// <param name="newValue"></param>
  334. /// <param name="prevValue"></param>
  335. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  336. public static int EnvironmentTickCountAdd(Int32 newValue, Int32 prevValue)
  337. {
  338. int ret = newValue + prevValue;
  339. return (ret >= 0) ? ret : (ret + EnvironmentTickCountMask + 1);
  340. }
  341. public static double TimeStampClockPeriodMS;
  342. public static double TimeStampClockPeriod;
  343. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  344. public static double GetTimeStamp()
  345. {
  346. return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
  347. }
  348. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  349. public static double GetTimeStampMS()
  350. {
  351. return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
  352. }
  353. // doing math in ticks is usefull to avoid loss of resolution
  354. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  355. public static long GetTimeStampTicks()
  356. {
  357. return Stopwatch.GetTimestamp();
  358. }
  359. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  360. public static double TimeStampTicksToMS(long ticks)
  361. {
  362. return ticks * TimeStampClockPeriodMS;
  363. }
  364. }
  365. }