JobEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 JobEngine
  36. {
  37. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  38. public int LogLevel { get; set; }
  39. private object JobLock = new object();
  40. public string Name { get; private set; }
  41. public string LoggingName { get; private set; }
  42. /// <summary>
  43. /// Is this engine running?
  44. /// </summary>
  45. public bool IsRunning { get; private set; }
  46. /// <summary>
  47. /// Number of jobs waiting to be processed.
  48. /// </summary>
  49. public int JobsWaiting { get { return m_jobQueue.Count; } }
  50. /// <summary>
  51. /// Controls whether we need to warn in the log about exceeding the max queue size.
  52. /// </summary>
  53. /// <remarks>
  54. /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
  55. /// order to avoid spamming the log with lots of warnings.
  56. /// </remarks>
  57. private bool m_warnOverMaxQueue = true;
  58. private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(5000);
  59. private CancellationTokenSource m_cancelSource;
  60. private int m_timeout = -1;
  61. private int m_concurrency = 1;
  62. private int m_numberThreads = 0;
  63. public JobEngine(string name, string loggingName, int timeout = -1, int concurrency = 1)
  64. {
  65. Name = name;
  66. LoggingName = loggingName;
  67. m_timeout = timeout;
  68. m_concurrency = concurrency;
  69. }
  70. public void Start()
  71. {
  72. lock (JobLock)
  73. {
  74. if (IsRunning)
  75. return;
  76. if(m_concurrency < 1)
  77. m_concurrency = 1;
  78. IsRunning = true;
  79. m_cancelSource = new CancellationTokenSource();
  80. }
  81. }
  82. public void Stop()
  83. {
  84. lock (JobLock)
  85. {
  86. try
  87. {
  88. if (!IsRunning)
  89. return;
  90. m_log.DebugFormat("[JobEngine] Stopping {0}", Name);
  91. IsRunning = false;
  92. if(m_numberThreads > 0)
  93. {
  94. m_cancelSource.Cancel();
  95. Thread.Yield();
  96. }
  97. }
  98. finally
  99. {
  100. if(m_cancelSource != null)
  101. {
  102. m_cancelSource.Dispose();
  103. m_cancelSource = null;
  104. }
  105. if (m_jobQueue != null)
  106. {
  107. m_jobQueue.Dispose();
  108. m_jobQueue = null;
  109. }
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// Make a job.
  115. /// </summary>
  116. /// <remarks>
  117. /// We provide this method to replace the constructor so that we can later pool job objects if necessary to
  118. /// reduce memory churn. Normally one would directly call QueueJob() with parameters anyway.
  119. /// </remarks>
  120. /// <returns></returns>
  121. /// <param name="name">Name.</param>
  122. /// <param name="action">Action.</param>
  123. /// <param name="commonId">Common identifier.</param>
  124. public static Job MakeJob(string name, Action action, string commonId = null)
  125. {
  126. return Job.MakeJob(name, action, commonId);
  127. }
  128. /// <summary>
  129. /// Remove the next job queued for processing.
  130. /// </summary>
  131. /// <remarks>
  132. /// Returns null if there is no next job.
  133. /// Will not remove a job currently being performed.
  134. /// </remarks>
  135. public Job RemoveNextJob()
  136. {
  137. Job nextJob;
  138. m_jobQueue.TryTake(out nextJob);
  139. return nextJob;
  140. }
  141. /// <summary>
  142. /// Queue the job for processing.
  143. /// </summary>
  144. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  145. /// <param name="name">Name of job. This appears on the console and in logging.</param>
  146. /// <param name="action">Action to perform.</param>
  147. /// <param name="commonId">
  148. /// Common identifier for a set of jobs. This is allows a set of jobs to be removed
  149. /// if required (e.g. all jobs for a given agent. Optional.
  150. /// </param>
  151. public bool QueueJob(string name, Action action, string commonId = null)
  152. {
  153. return QueueJob(MakeJob(name, action, commonId));
  154. }
  155. /// <summary>
  156. /// Queue the job for processing.
  157. /// </summary>
  158. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  159. /// <param name="job">The job</param>
  160. /// </param>
  161. public bool QueueJob(Job job)
  162. {
  163. if (!IsRunning)
  164. return false;
  165. if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
  166. {
  167. lock (JobLock)
  168. {
  169. m_jobQueue.Add(job);
  170. if (m_numberThreads < m_concurrency && m_numberThreads < m_jobQueue.Count)
  171. {
  172. Util.FireAndForget(ProcessRequests, null, Name, false);
  173. ++m_numberThreads;
  174. }
  175. }
  176. if (!m_warnOverMaxQueue)
  177. m_warnOverMaxQueue = true;
  178. return true;
  179. }
  180. else
  181. {
  182. if (m_warnOverMaxQueue)
  183. {
  184. m_log.WarnFormat(
  185. "[{0}]: Job queue at maximum capacity, not recording job from {1} in {2}",
  186. LoggingName, job.Name, Name);
  187. m_warnOverMaxQueue = false;
  188. }
  189. return false;
  190. }
  191. }
  192. private void ProcessRequests(object o)
  193. {
  194. Job currentJob;
  195. while (IsRunning)
  196. {
  197. try
  198. {
  199. if(!m_jobQueue.TryTake(out currentJob, m_timeout, m_cancelSource.Token))
  200. {
  201. lock (JobLock)
  202. {
  203. if (m_jobQueue.Count > 0)
  204. continue;
  205. --m_numberThreads;
  206. return;
  207. }
  208. }
  209. }
  210. catch
  211. {
  212. break;
  213. }
  214. if(LogLevel >= 1)
  215. m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,currentJob.Name);
  216. try
  217. {
  218. currentJob.Action();
  219. }
  220. catch(Exception e)
  221. {
  222. m_log.ErrorFormat(
  223. "[{0}]: Job {1} failed, continuing. Exception {2}",LoggingName, currentJob.Name, e);
  224. }
  225. if(LogLevel >= 1)
  226. m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,currentJob.Name);
  227. currentJob.Action = null;
  228. }
  229. lock (JobLock)
  230. --m_numberThreads;
  231. }
  232. public class Job
  233. {
  234. /// <summary>
  235. /// Name of the job.
  236. /// </summary>
  237. /// <remarks>
  238. /// This appears on console and debug output.
  239. /// </remarks>
  240. public string Name { get; private set; }
  241. /// <summary>
  242. /// Common ID for this job.
  243. /// </summary>
  244. /// <remarks>
  245. /// This allows all jobs with a certain common ID (e.g. a client UUID) to be removed en-masse if required.
  246. /// Can be null if this is not required.
  247. /// </remarks>
  248. public string CommonId { get; private set; }
  249. /// <summary>
  250. /// Action to perform when this job is processed.
  251. /// </summary>
  252. public Action Action { get; set; }
  253. private Job(string name, string commonId, Action action)
  254. {
  255. Name = name;
  256. CommonId = commonId;
  257. Action = action;
  258. }
  259. /// <summary>
  260. /// Make a job. It needs to be separately queued.
  261. /// </summary>
  262. /// <remarks>
  263. /// We provide this method to replace the constructor so that we can pool job objects if necessary to
  264. /// to reduce memory churn. Normally one would directly call JobEngine.QueueJob() with parameters anyway.
  265. /// </remarks>
  266. /// <returns></returns>
  267. /// <param name="name">Name.</param>
  268. /// <param name="action">Action.</param>
  269. /// <param name="commonId">Common identifier.</param>
  270. public static Job MakeJob(string name, Action action, string commonId = null)
  271. {
  272. return new Job(name, commonId, action);
  273. }
  274. }
  275. }
  276. }