PollServiceRequestManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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;
  29. using System.Threading;
  30. using System.Reflection;
  31. using log4net;
  32. using OpenSim.Framework.Monitoring;
  33. using Amib.Threading;
  34. using System.Collections.Generic;
  35. using System.Collections.Concurrent;
  36. namespace OpenSim.Framework.Servers.HttpServer
  37. {
  38. public class PollServiceRequestManager
  39. {
  40. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. private Dictionary<int, Queue<PollServiceHttpRequest>> m_bycontext;
  42. private BlockingCollection<PollServiceHttpRequest> m_requests = new BlockingCollection<PollServiceHttpRequest>();
  43. private ConcurrentQueue<PollServiceHttpRequest> m_retryRequests = new ConcurrentQueue<PollServiceHttpRequest>();
  44. private uint m_WorkerThreadCount = 0;
  45. private Thread[] m_workerThreads;
  46. private Thread m_retrysThread;
  47. private bool m_running = false;
  48. private SmartThreadPool m_threadPool;
  49. public PollServiceRequestManager(
  50. bool performResponsesAsync, uint pWorkerThreadCount, int pTimeout)
  51. {
  52. m_WorkerThreadCount = pWorkerThreadCount;
  53. m_workerThreads = new Thread[m_WorkerThreadCount];
  54. m_bycontext = new Dictionary<int, Queue<PollServiceHttpRequest>>(256);
  55. STPStartInfo startInfo = new STPStartInfo();
  56. startInfo.IdleTimeout = 30000;
  57. startInfo.MaxWorkerThreads = 20;
  58. startInfo.MinWorkerThreads = 1;
  59. startInfo.ThreadPriority = ThreadPriority.Normal;
  60. startInfo.StartSuspended = true;
  61. startInfo.ThreadPoolName = "PoolService";
  62. m_threadPool = new SmartThreadPool(startInfo);
  63. }
  64. public void Start()
  65. {
  66. if(m_running)
  67. return;
  68. m_running = true;
  69. m_threadPool.Start();
  70. //startup worker threads
  71. for (uint i = 0; i < m_WorkerThreadCount; i++)
  72. {
  73. m_workerThreads[i]
  74. = WorkManager.StartThread(
  75. PoolWorkerJob,
  76. string.Format("PollServiceWorkerThread {0}", i),
  77. ThreadPriority.Normal,
  78. true,
  79. false,
  80. null,
  81. int.MaxValue);
  82. }
  83. m_retrysThread = WorkManager.StartThread(
  84. this.CheckRetries,
  85. string.Format("PollServiceWatcherThread"),
  86. ThreadPriority.Normal,
  87. true,
  88. true,
  89. null,
  90. 1000 * 60 * 10);
  91. }
  92. private void ReQueueEvent(PollServiceHttpRequest req)
  93. {
  94. if (m_running)
  95. m_retryRequests.Enqueue(req);
  96. }
  97. public void Enqueue(PollServiceHttpRequest req)
  98. {
  99. Queue<PollServiceHttpRequest> ctxQeueue;
  100. int rhash = req.contextHash;
  101. lock (m_bycontext)
  102. {
  103. if (m_bycontext.TryGetValue(rhash, out ctxQeueue))
  104. {
  105. ctxQeueue.Enqueue(req);
  106. }
  107. else
  108. {
  109. ctxQeueue = new Queue<PollServiceHttpRequest>();
  110. m_bycontext[rhash] = ctxQeueue;
  111. EnqueueInt(req);
  112. }
  113. }
  114. }
  115. public void byContextDequeue(PollServiceHttpRequest req)
  116. {
  117. Queue<PollServiceHttpRequest> ctxQeueue;
  118. int rhash = req.contextHash;
  119. lock (m_bycontext)
  120. {
  121. if (m_bycontext.TryGetValue(rhash, out ctxQeueue))
  122. {
  123. if (ctxQeueue.Count > 0)
  124. {
  125. PollServiceHttpRequest newreq = ctxQeueue.Dequeue();
  126. EnqueueInt(newreq);
  127. }
  128. else
  129. {
  130. m_bycontext.Remove(rhash);
  131. }
  132. }
  133. }
  134. }
  135. public void DropByContext(PollServiceHttpRequest req)
  136. {
  137. Queue<PollServiceHttpRequest> ctxQeueue;
  138. int rhash = req.contextHash;
  139. lock (m_bycontext)
  140. {
  141. if (m_bycontext.TryGetValue(rhash, out ctxQeueue))
  142. {
  143. ctxQeueue.Clear();
  144. m_bycontext.Remove(rhash);
  145. }
  146. }
  147. }
  148. public void EnqueueInt(PollServiceHttpRequest req)
  149. {
  150. if (m_running)
  151. m_requests.Add(req);
  152. }
  153. private void CheckRetries()
  154. {
  155. PollServiceHttpRequest preq;
  156. while (m_running)
  157. {
  158. Thread.Sleep(100);
  159. Watchdog.UpdateThread();
  160. while (m_running && m_retryRequests.TryDequeue(out preq))
  161. m_requests.Add(preq);
  162. }
  163. }
  164. public void Stop()
  165. {
  166. if(!m_running)
  167. return;
  168. m_running = false;
  169. Thread.Sleep(100); // let the world move
  170. foreach (Thread t in m_workerThreads)
  171. Watchdog.AbortThread(t.ManagedThreadId);
  172. m_threadPool.Shutdown();
  173. // any entry in m_bycontext should have a active request on the other queues
  174. // so just delete contents to easy GC
  175. foreach (Queue<PollServiceHttpRequest> qu in m_bycontext.Values)
  176. qu.Clear();
  177. m_bycontext.Clear();
  178. PollServiceHttpRequest req;
  179. try
  180. {
  181. while(m_retryRequests.TryDequeue(out req))
  182. req.DoHTTPstop();
  183. }
  184. catch
  185. {
  186. }
  187. try
  188. {
  189. while(m_requests.TryTake(out req, 0))
  190. req.DoHTTPstop();
  191. }
  192. catch
  193. {
  194. }
  195. m_requests.Dispose();
  196. }
  197. // work threads
  198. private void PoolWorkerJob()
  199. {
  200. PollServiceHttpRequest req;
  201. while (m_running)
  202. {
  203. try
  204. {
  205. req = null;
  206. if (!m_requests.TryTake(out req, 4500) || req == null)
  207. {
  208. Watchdog.UpdateThread();
  209. continue;
  210. }
  211. Watchdog.UpdateThread();
  212. if (!req.HttpContext.CanSend())
  213. {
  214. req.PollServiceArgs.Drop(req.RequestID, req.PollServiceArgs.Id);
  215. byContextDequeue(req);
  216. continue;
  217. }
  218. if (req.HttpContext.IsSending())
  219. {
  220. if ((Environment.TickCount - req.RequestTime) > req.PollServiceArgs.TimeOutms)
  221. {
  222. req.PollServiceArgs.Drop(req.RequestID, req.PollServiceArgs.Id);
  223. byContextDequeue(req);
  224. }
  225. else
  226. ReQueueEvent(req);
  227. continue;
  228. }
  229. if (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id))
  230. {
  231. PollServiceHttpRequest nreq = req;
  232. m_threadPool.QueueWorkItem(x =>
  233. {
  234. try
  235. {
  236. Hashtable responsedata = nreq.PollServiceArgs.GetEvents(nreq.RequestID, nreq.PollServiceArgs.Id);
  237. nreq.DoHTTPGruntWork(responsedata);
  238. }
  239. catch (ObjectDisposedException) { }
  240. finally
  241. {
  242. byContextDequeue(nreq);
  243. nreq = null;
  244. }
  245. return null;
  246. }, null);
  247. }
  248. else
  249. {
  250. if ((Environment.TickCount - req.RequestTime) > req.PollServiceArgs.TimeOutms)
  251. {
  252. PollServiceHttpRequest nreq = req;
  253. m_threadPool.QueueWorkItem(x =>
  254. {
  255. try
  256. {
  257. nreq.DoHTTPGruntWork(nreq.PollServiceArgs.NoEvents(nreq.RequestID, nreq.PollServiceArgs.Id));
  258. }
  259. catch (ObjectDisposedException) { }
  260. finally
  261. {
  262. byContextDequeue(nreq);
  263. nreq = null;
  264. }
  265. return null;
  266. }, null);
  267. }
  268. else
  269. {
  270. ReQueueEvent(req);
  271. }
  272. }
  273. }
  274. catch (ThreadAbortException)
  275. {
  276. Thread.ResetAbort();
  277. // Shouldn't set this to 'false', the normal shutdown should cause things to exit
  278. // but robust is still not normal neither is mono
  279. m_running = false;
  280. }
  281. catch (Exception e)
  282. {
  283. m_log.ErrorFormat("Exception in poll service thread: " + e.ToString());
  284. }
  285. }
  286. }
  287. }
  288. }