ContextTimeoutManager.cs 15 KB

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