JobEngine.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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.Reflection;
  30. using System.Threading;
  31. using log4net;
  32. using OpenSim.Framework;
  33. namespace OpenSim.Framework.Monitoring
  34. {
  35. public class Job
  36. {
  37. public string Name;
  38. public WaitCallback Callback;
  39. public object O;
  40. public Job(string name, WaitCallback callback, object o)
  41. {
  42. Name = name;
  43. Callback = callback;
  44. O = o;
  45. }
  46. }
  47. public class JobEngine
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. public int LogLevel { get; set; }
  51. public bool IsRunning { get; private set; }
  52. /// <summary>
  53. /// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
  54. /// </summary>
  55. public int RequestProcessTimeoutOnStop { get; set; }
  56. /// <summary>
  57. /// Controls whether we need to warn in the log about exceeding the max queue size.
  58. /// </summary>
  59. /// <remarks>
  60. /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
  61. /// order to avoid spamming the log with lots of warnings.
  62. /// </remarks>
  63. private bool m_warnOverMaxQueue = true;
  64. private BlockingCollection<Job> m_requestQueue;
  65. private CancellationTokenSource m_cancelSource = new CancellationTokenSource();
  66. private Stat m_requestsWaitingStat;
  67. private Job m_currentJob;
  68. /// <summary>
  69. /// Used to signal that we are ready to complete stop.
  70. /// </summary>
  71. private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
  72. public JobEngine()
  73. {
  74. RequestProcessTimeoutOnStop = 5000;
  75. MainConsole.Instance.Commands.AddCommand(
  76. "Debug",
  77. false,
  78. "debug jobengine",
  79. "debug jobengine <start|stop|status|log>",
  80. "Start, stop, get status or set logging level of the job engine.",
  81. "If stopped then all outstanding jobs are processed immediately.",
  82. HandleControlCommand);
  83. }
  84. public void Start()
  85. {
  86. lock (this)
  87. {
  88. if (IsRunning)
  89. return;
  90. IsRunning = true;
  91. m_finishedProcessingAfterStop.Reset();
  92. m_requestQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000);
  93. m_requestsWaitingStat =
  94. new Stat(
  95. "JobsWaiting",
  96. "Number of jobs waiting for processing.",
  97. "",
  98. "",
  99. "server",
  100. "jobengine",
  101. StatType.Pull,
  102. MeasuresOfInterest.None,
  103. stat => stat.Value = m_requestQueue.Count,
  104. StatVerbosity.Debug);
  105. StatsManager.RegisterStat(m_requestsWaitingStat);
  106. Watchdog.StartThread(
  107. ProcessRequests,
  108. "JobEngineThread",
  109. ThreadPriority.Normal,
  110. false,
  111. true,
  112. null,
  113. int.MaxValue);
  114. }
  115. }
  116. public void Stop()
  117. {
  118. lock (this)
  119. {
  120. try
  121. {
  122. if (!IsRunning)
  123. return;
  124. IsRunning = false;
  125. int requestsLeft = m_requestQueue.Count;
  126. if (requestsLeft <= 0)
  127. {
  128. m_cancelSource.Cancel();
  129. }
  130. else
  131. {
  132. m_log.InfoFormat("[JOB ENGINE]: Waiting to write {0} events after stop.", requestsLeft);
  133. while (requestsLeft > 0)
  134. {
  135. if (!m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
  136. {
  137. // After timeout no events have been written
  138. if (requestsLeft == m_requestQueue.Count)
  139. {
  140. m_log.WarnFormat(
  141. "[JOB ENGINE]: No requests processed after {0} ms wait. Discarding remaining {1} requests",
  142. RequestProcessTimeoutOnStop, requestsLeft);
  143. break;
  144. }
  145. }
  146. requestsLeft = m_requestQueue.Count;
  147. }
  148. }
  149. }
  150. finally
  151. {
  152. m_cancelSource.Dispose();
  153. StatsManager.DeregisterStat(m_requestsWaitingStat);
  154. m_requestsWaitingStat = null;
  155. m_requestQueue = null;
  156. }
  157. }
  158. }
  159. public bool QueueRequest(string name, WaitCallback req, object o)
  160. {
  161. if (LogLevel >= 1)
  162. m_log.DebugFormat("[JOB ENGINE]: Queued job {0}", name);
  163. if (m_requestQueue.Count < m_requestQueue.BoundedCapacity)
  164. {
  165. // m_log.DebugFormat(
  166. // "[OUTGOING QUEUE REFILL ENGINE]: Adding request for categories {0} for {1} in {2}",
  167. // categories, client.AgentID, m_udpServer.Scene.Name);
  168. m_requestQueue.Add(new Job(name, req, o));
  169. if (!m_warnOverMaxQueue)
  170. m_warnOverMaxQueue = true;
  171. return true;
  172. }
  173. else
  174. {
  175. if (m_warnOverMaxQueue)
  176. {
  177. // m_log.WarnFormat(
  178. // "[JOB ENGINE]: Request queue at maximum capacity, not recording request from {0} in {1}",
  179. // client.AgentID, m_udpServer.Scene.Name);
  180. m_log.WarnFormat("[JOB ENGINE]: Request queue at maximum capacity, not recording job");
  181. m_warnOverMaxQueue = false;
  182. }
  183. return false;
  184. }
  185. }
  186. private void ProcessRequests()
  187. {
  188. try
  189. {
  190. while (IsRunning || m_requestQueue.Count > 0)
  191. {
  192. m_currentJob = m_requestQueue.Take(m_cancelSource.Token);
  193. // QueueEmpty callback = req.Client.OnQueueEmpty;
  194. //
  195. // if (callback != null)
  196. // {
  197. // try
  198. // {
  199. // callback(req.Categories);
  200. // }
  201. // catch (Exception e)
  202. // {
  203. // m_log.Error("[OUTGOING QUEUE REFILL ENGINE]: ProcessRequests(" + req.Categories + ") threw an exception: " + e.Message, e);
  204. // }
  205. // }
  206. if (LogLevel >= 1)
  207. m_log.DebugFormat("[JOB ENGINE]: Processing job {0}", m_currentJob.Name);
  208. try
  209. {
  210. m_currentJob.Callback.Invoke(m_currentJob.O);
  211. }
  212. catch (Exception e)
  213. {
  214. m_log.Error(
  215. string.Format(
  216. "[JOB ENGINE]: Job {0} failed, continuing. Exception ", m_currentJob.Name), e);
  217. }
  218. if (LogLevel >= 1)
  219. m_log.DebugFormat("[JOB ENGINE]: Processed job {0}", m_currentJob.Name);
  220. m_currentJob = null;
  221. }
  222. }
  223. catch (OperationCanceledException)
  224. {
  225. }
  226. m_finishedProcessingAfterStop.Set();
  227. }
  228. private void HandleControlCommand(string module, string[] args)
  229. {
  230. // if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene)
  231. // return;
  232. if (args.Length < 3)
  233. {
  234. MainConsole.Instance.Output("Usage: debug jobengine <stop|start|status|log>");
  235. return;
  236. }
  237. string subCommand = args[2];
  238. if (subCommand == "stop")
  239. {
  240. Stop();
  241. MainConsole.Instance.OutputFormat("Stopped job engine.");
  242. }
  243. else if (subCommand == "start")
  244. {
  245. Start();
  246. MainConsole.Instance.OutputFormat("Started job engine.");
  247. }
  248. else if (subCommand == "status")
  249. {
  250. MainConsole.Instance.OutputFormat("Job engine running: {0}", IsRunning);
  251. MainConsole.Instance.OutputFormat("Current job {0}", m_currentJob != null ? m_currentJob.Name : "none");
  252. MainConsole.Instance.OutputFormat(
  253. "Jobs waiting: {0}", IsRunning ? m_requestQueue.Count.ToString() : "n/a");
  254. MainConsole.Instance.OutputFormat("Log Level: {0}", LogLevel);
  255. }
  256. else if (subCommand == "log")
  257. {
  258. // int logLevel;
  259. int logLevel = int.Parse(args[3]);
  260. // if (ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out logLevel))
  261. // {
  262. LogLevel = logLevel;
  263. MainConsole.Instance.OutputFormat("Set debug log level to {0}", LogLevel);
  264. // }
  265. }
  266. else
  267. {
  268. MainConsole.Instance.OutputFormat("Unrecognized job engine subcommand {0}", subCommand);
  269. }
  270. }
  271. }
  272. }