EventQueueManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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.Collections.Generic;
  30. using System.Reflection;
  31. using OpenMetaverse;
  32. using OpenSim.Region.ScriptEngine.Shared;
  33. using log4net;
  34. namespace OpenSim.Region.ScriptEngine.DotNetEngine
  35. {
  36. /// <summary>
  37. /// EventQueueManager handles event queues
  38. /// Events are queued and executed in separate thread
  39. /// </summary>
  40. [Serializable]
  41. public class EventQueueManager
  42. {
  43. //
  44. // Class is instanced in "ScriptEngine" and used by "EventManager" which is also instanced in "ScriptEngine".
  45. //
  46. // Class purpose is to queue and execute functions that are received by "EventManager":
  47. // - allowing "EventManager" to release its event thread immediately, thus not interrupting server execution.
  48. // - allowing us to prioritize and control execution of script functions.
  49. // Class can use multiple threads for simultaneous execution. Mutexes are used for thread safety.
  50. //
  51. // 1. Hold an execution queue for scripts
  52. // 2. Use threads to process queue, each thread executes one script function on each pass.
  53. // 3. Catch any script error and process it
  54. //
  55. //
  56. // Notes:
  57. // * Current execution load balancing is optimized for 1 thread, and can cause unfair execute balancing between scripts.
  58. // Not noticeable unless server is under high load.
  59. //
  60. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  61. public ScriptEngine m_ScriptEngine;
  62. /// <summary>
  63. /// List of threads (classes) processing event queue
  64. /// Note that this may or may not be a reference to a static object depending on PrivateRegionThreads config setting.
  65. /// </summary>
  66. internal static List<EventQueueThreadClass> eventQueueThreads = new List<EventQueueThreadClass>(); // Thread pool that we work on
  67. /// <summary>
  68. /// Locking access to eventQueueThreads AND staticGlobalEventQueueThreads.
  69. /// </summary>
  70. // private object eventQueueThreadsLock = new object();
  71. // Static objects for referencing the objects above if we don't have private threads:
  72. //internal static List<EventQueueThreadClass> staticEventQueueThreads; // A static reference used if we don't use private threads
  73. // internal static object staticEventQueueThreadsLock; // Statick lock object reference for same reason
  74. /// <summary>
  75. /// Global static list of all threads (classes) processing event queue -- used by max enforcment thread
  76. /// </summary>
  77. //private List<EventQueueThreadClass> staticGlobalEventQueueThreads = new List<EventQueueThreadClass>();
  78. /// <summary>
  79. /// Used internally to specify how many threads should exit gracefully
  80. /// </summary>
  81. public static int ThreadsToExit;
  82. public static object ThreadsToExitLock = new object();
  83. //public object queueLock = new object(); // Mutex lock object
  84. /// <summary>
  85. /// How many threads to process queue with
  86. /// </summary>
  87. internal static int numberOfThreads;
  88. internal static int EventExecutionMaxQueueSize;
  89. /// <summary>
  90. /// Maximum time one function can use for execution before we perform a thread kill.
  91. /// </summary>
  92. private static int maxFunctionExecutionTimems
  93. {
  94. get { return (int)(maxFunctionExecutionTimens / 10000); }
  95. set { maxFunctionExecutionTimens = value * 10000; }
  96. }
  97. /// <summary>
  98. /// Contains nanoseconds version of maxFunctionExecutionTimems so that it matches time calculations better (performance reasons).
  99. /// WARNING! ONLY UPDATE maxFunctionExecutionTimems, NEVER THIS DIRECTLY.
  100. /// </summary>
  101. public static long maxFunctionExecutionTimens;
  102. /// <summary>
  103. /// Enforce max execution time
  104. /// </summary>
  105. public static bool EnforceMaxExecutionTime;
  106. /// <summary>
  107. /// Kill script (unload) when it exceeds execution time
  108. /// </summary>
  109. private static bool KillScriptOnMaxFunctionExecutionTime;
  110. /// <summary>
  111. /// List of localID locks for mutex processing of script events
  112. /// </summary>
  113. private List<uint> objectLocks = new List<uint>();
  114. private object tryLockLock = new object(); // Mutex lock object
  115. /// <summary>
  116. /// Queue containing events waiting to be executed
  117. /// </summary>
  118. public Queue<QueueItemStruct> eventQueue = new Queue<QueueItemStruct>();
  119. #region " Queue structures "
  120. /// <summary>
  121. /// Queue item structure
  122. /// </summary>
  123. public struct QueueItemStruct
  124. {
  125. public uint localID;
  126. public UUID itemID;
  127. public string functionName;
  128. public DetectParams[] llDetectParams;
  129. public object[] param;
  130. public Dictionary<KeyValuePair<int,int>,KeyValuePair<int,int>>
  131. LineMap;
  132. }
  133. #endregion
  134. #region " Initialization / Startup "
  135. public EventQueueManager(ScriptEngine _ScriptEngine)
  136. {
  137. m_ScriptEngine = _ScriptEngine;
  138. ReadConfig();
  139. AdjustNumberOfScriptThreads();
  140. }
  141. public void ReadConfig()
  142. {
  143. // Refresh config
  144. numberOfThreads = m_ScriptEngine.ScriptConfigSource.GetInt("NumberOfScriptThreads", 2);
  145. maxFunctionExecutionTimems = m_ScriptEngine.ScriptConfigSource.GetInt("MaxEventExecutionTimeMs", 5000);
  146. EnforceMaxExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("EnforceMaxEventExecutionTime", true);
  147. KillScriptOnMaxFunctionExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("DeactivateScriptOnTimeout", false);
  148. EventExecutionMaxQueueSize = m_ScriptEngine.ScriptConfigSource.GetInt("EventExecutionMaxQueueSize", 300);
  149. // Now refresh config in all threads
  150. lock (eventQueueThreads)
  151. {
  152. foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
  153. {
  154. EventQueueThread.ReadConfig();
  155. }
  156. }
  157. }
  158. #endregion
  159. #region " Shutdown all threads "
  160. ~EventQueueManager()
  161. {
  162. Stop();
  163. }
  164. private void Stop()
  165. {
  166. if (eventQueueThreads != null)
  167. {
  168. // Kill worker threads
  169. lock (eventQueueThreads)
  170. {
  171. foreach (EventQueueThreadClass EventQueueThread in new ArrayList(eventQueueThreads))
  172. {
  173. AbortThreadClass(EventQueueThread);
  174. }
  175. //eventQueueThreads.Clear();
  176. //staticGlobalEventQueueThreads.Clear();
  177. }
  178. }
  179. // Remove all entries from our event queue
  180. lock (eventQueue)
  181. {
  182. eventQueue.Clear();
  183. }
  184. }
  185. #endregion
  186. #region " Start / stop script execution threads (ThreadClasses) "
  187. private void StartNewThreadClass()
  188. {
  189. EventQueueThreadClass eqtc = new EventQueueThreadClass();
  190. eventQueueThreads.Add(eqtc);
  191. //m_log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Started new script execution thread. Current thread count: " + eventQueueThreads.Count);
  192. }
  193. private void AbortThreadClass(EventQueueThreadClass threadClass)
  194. {
  195. if (eventQueueThreads.Contains(threadClass))
  196. eventQueueThreads.Remove(threadClass);
  197. try
  198. {
  199. threadClass.Stop();
  200. }
  201. catch (Exception)
  202. {
  203. //m_log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: If you see this, could you please report it to Tedd:");
  204. //m_log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: Script thread execution timeout kill ended in exception: " + ex.ToString());
  205. }
  206. //m_log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Killed script execution thread. Remaining thread count: " + eventQueueThreads.Count);
  207. }
  208. #endregion
  209. #region " Mutex locks for queue access "
  210. /// <summary>
  211. /// Try to get a mutex lock on localID
  212. /// </summary>
  213. /// <param name="localID"></param>
  214. /// <returns></returns>
  215. public bool TryLock(uint localID)
  216. {
  217. lock (tryLockLock)
  218. {
  219. if (objectLocks.Contains(localID) == true)
  220. {
  221. return false;
  222. }
  223. else
  224. {
  225. objectLocks.Add(localID);
  226. return true;
  227. }
  228. }
  229. }
  230. /// <summary>
  231. /// Release mutex lock on localID
  232. /// </summary>
  233. /// <param name="localID"></param>
  234. public void ReleaseLock(uint localID)
  235. {
  236. lock (tryLockLock)
  237. {
  238. if (objectLocks.Contains(localID) == true)
  239. {
  240. objectLocks.Remove(localID);
  241. }
  242. }
  243. }
  244. #endregion
  245. #region " Check execution queue for a specified Event"
  246. /// <summary>
  247. /// checks to see if a specified event type is already in the queue
  248. /// </summary>
  249. /// <param name="localID">Region object ID</param>
  250. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  251. /// <returns>true if event is found , false if not found</returns>
  252. ///
  253. public bool CheckEeventQueueForEvent(uint localID, string FunctionName)
  254. {
  255. if (eventQueue.Count > 0)
  256. {
  257. lock (eventQueue)
  258. {
  259. foreach (EventQueueManager.QueueItemStruct QIS in eventQueue)
  260. {
  261. if ((QIS.functionName == FunctionName) && (QIS.localID == localID))
  262. return true;
  263. }
  264. }
  265. }
  266. return false;
  267. }
  268. #endregion
  269. #region " Add events to execution queue "
  270. /// <summary>
  271. /// Add event to event execution queue
  272. /// </summary>
  273. /// <param name="localID">Region object ID</param>
  274. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  275. /// <param name="param">Array of parameters to match event mask</param>
  276. public bool AddToObjectQueue(uint localID, string FunctionName, DetectParams[] qParams, params object[] param)
  277. {
  278. // Determine all scripts in Object and add to their queue
  279. //myScriptEngine.log.Info("[" + ScriptEngineName + "]: EventQueueManager Adding localID: " + localID + ", FunctionName: " + FunctionName);
  280. // Do we have any scripts in this object at all? If not, return
  281. if (m_ScriptEngine.m_ScriptManager.Scripts.ContainsKey(localID) == false)
  282. {
  283. //m_log.Debug("Event \String.Empty + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
  284. return false;
  285. }
  286. List<UUID> scriptKeys =
  287. m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
  288. foreach (UUID itemID in scriptKeys)
  289. {
  290. // Add to each script in that object
  291. // TODO: Some scripts may not subscribe to this event. Should we NOT add it? Does it matter?
  292. AddToScriptQueue(localID, itemID, FunctionName, qParams, param);
  293. }
  294. return true;
  295. }
  296. /// <summary>
  297. /// Add event to event execution queue
  298. /// </summary>
  299. /// <param name="localID">Region object ID</param>
  300. /// <param name="itemID">Region script ID</param>
  301. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  302. /// <param name="param">Array of parameters to match event mask</param>
  303. public bool AddToScriptQueue(uint localID, UUID itemID, string FunctionName, DetectParams[] qParams, params object[] param)
  304. {
  305. List<UUID> keylist = m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
  306. if (!keylist.Contains(itemID)) // We don't manage that script
  307. {
  308. return false;
  309. }
  310. lock (eventQueue)
  311. {
  312. if (eventQueue.Count >= EventExecutionMaxQueueSize)
  313. {
  314. m_log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: ERROR: Event execution queue item count is at " + eventQueue.Count + ". Config variable \"EventExecutionMaxQueueSize\" is set to " + EventExecutionMaxQueueSize + ", so ignoring new event.");
  315. m_log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: Event ignored: localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
  316. return false;
  317. }
  318. InstanceData id = m_ScriptEngine.m_ScriptManager.GetScript(
  319. localID, itemID);
  320. // Create a structure and add data
  321. QueueItemStruct QIS = new QueueItemStruct();
  322. QIS.localID = localID;
  323. QIS.itemID = itemID;
  324. QIS.functionName = FunctionName;
  325. QIS.llDetectParams = qParams;
  326. QIS.param = param;
  327. if (id != null)
  328. QIS.LineMap = id.LineMap;
  329. // Add it to queue
  330. eventQueue.Enqueue(QIS);
  331. }
  332. return true;
  333. }
  334. #endregion
  335. #region " Maintenance thread "
  336. /// <summary>
  337. /// Adjust number of script thread classes. It can start new, but if it needs to stop it will just set number of threads in "ThreadsToExit" and threads will have to exit themselves.
  338. /// Called from MaintenanceThread
  339. /// </summary>
  340. public void AdjustNumberOfScriptThreads()
  341. {
  342. // Is there anything here for us to do?
  343. if (eventQueueThreads.Count == numberOfThreads)
  344. return;
  345. lock (eventQueueThreads)
  346. {
  347. int diff = numberOfThreads - eventQueueThreads.Count;
  348. // Positive number: Start
  349. // Negative number: too many are running
  350. if (diff > 0)
  351. {
  352. // We need to add more threads
  353. for (int ThreadCount = eventQueueThreads.Count; ThreadCount < numberOfThreads; ThreadCount++)
  354. {
  355. StartNewThreadClass();
  356. }
  357. }
  358. if (diff < 0)
  359. {
  360. // We need to kill some threads
  361. lock (ThreadsToExitLock)
  362. {
  363. ThreadsToExit = Math.Abs(diff);
  364. }
  365. }
  366. }
  367. }
  368. /// <summary>
  369. /// Check if any thread class has been executing an event too long
  370. /// </summary>
  371. public void CheckScriptMaxExecTime()
  372. {
  373. // Iterate through all ScriptThreadClasses and check how long their current function has been executing
  374. lock (eventQueueThreads)
  375. {
  376. foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
  377. {
  378. // Is thread currently executing anything?
  379. if (EventQueueThread.InExecution)
  380. {
  381. // Has execution time expired?
  382. if (DateTime.Now.Ticks - EventQueueThread.LastExecutionStarted >
  383. maxFunctionExecutionTimens)
  384. {
  385. // Yes! We need to kill this thread!
  386. // Set flag if script should be removed or not
  387. EventQueueThread.KillCurrentScript = KillScriptOnMaxFunctionExecutionTime;
  388. // Abort this thread
  389. AbortThreadClass(EventQueueThread);
  390. // We do not need to start another, MaintenenceThread will do that for us
  391. //StartNewThreadClass();
  392. }
  393. }
  394. }
  395. }
  396. }
  397. #endregion
  398. ///// <summary>
  399. ///// If set to true then threads and stuff should try to make a graceful exit
  400. ///// </summary>
  401. //public bool PleaseShutdown
  402. //{
  403. // get { return _PleaseShutdown; }
  404. // set { _PleaseShutdown = value; }
  405. //}
  406. //private bool _PleaseShutdown = false;
  407. }
  408. }