EventQueueManager.cs 18 KB

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