EventQueueManager.cs 18 KB

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