EventQueueManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. /* Original code: Tedd Hansen */
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Threading;
  32. using libsecondlife;
  33. using OpenSim.Framework;
  34. using OpenSim.Grid.ScriptEngine.DotNetEngine.Compiler.LSL;
  35. using OpenSim.Region.Environment.Scenes.Scripting;
  36. namespace OpenSim.Grid.ScriptEngine.DotNetEngine
  37. {
  38. /// <summary>
  39. /// EventQueueManager handles event queues
  40. /// Events are queued and executed in separate thread
  41. /// </summary>
  42. [Serializable]
  43. internal class EventQueueManager
  44. {
  45. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  46. /// <summary>
  47. /// List of threads processing event queue
  48. /// </summary>
  49. private List<Thread> eventQueueThreads = new List<Thread>();
  50. private object queueLock = new object(); // Mutex lock object
  51. /// <summary>
  52. /// How many ms to sleep if queue is empty
  53. /// </summary>
  54. private int nothingToDoSleepms = 50;
  55. /// <summary>
  56. /// How many threads to process queue with
  57. /// </summary>
  58. private int numberOfThreads = 2;
  59. /// <summary>
  60. /// Queue containing events waiting to be executed
  61. /// </summary>
  62. private Queue<QueueItemStruct> eventQueue = new Queue<QueueItemStruct>();
  63. /// <summary>
  64. /// Queue item structure
  65. /// </summary>
  66. private struct QueueItemStruct
  67. {
  68. public uint localID;
  69. public LLUUID itemID;
  70. public string functionName;
  71. public object[] param;
  72. }
  73. /// <summary>
  74. /// List of localID locks for mutex processing of script events
  75. /// </summary>
  76. private List<uint> objectLocks = new List<uint>();
  77. private object tryLockLock = new object(); // Mutex lock object
  78. private ScriptEngine m_ScriptEngine;
  79. public EventQueueManager(ScriptEngine _ScriptEngine)
  80. {
  81. m_ScriptEngine = _ScriptEngine;
  82. //
  83. // Start event queue processing threads (worker threads)
  84. //
  85. for (int ThreadCount = 0; ThreadCount <= numberOfThreads; ThreadCount++)
  86. {
  87. Thread EventQueueThread = new Thread(EventQueueThreadLoop);
  88. eventQueueThreads.Add(EventQueueThread);
  89. EventQueueThread.IsBackground = true;
  90. EventQueueThread.Priority = ThreadPriority.BelowNormal;
  91. EventQueueThread.Name = "EventQueueManagerThread_" + ThreadCount;
  92. EventQueueThread.Start();
  93. }
  94. }
  95. ~EventQueueManager()
  96. {
  97. // Kill worker threads
  98. foreach (Thread EventQueueThread in new ArrayList(eventQueueThreads))
  99. {
  100. if (EventQueueThread != null && EventQueueThread.IsAlive == true)
  101. {
  102. try
  103. {
  104. EventQueueThread.Abort();
  105. EventQueueThread.Join();
  106. }
  107. catch (Exception)
  108. {
  109. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Exception killing worker thread: " + e.ToString());
  110. }
  111. }
  112. }
  113. eventQueueThreads.Clear();
  114. // Todo: Clean up our queues
  115. eventQueue.Clear();
  116. }
  117. /// <summary>
  118. /// Queue processing thread loop
  119. /// </summary>
  120. private void EventQueueThreadLoop()
  121. {
  122. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Worker thread spawned");
  123. try
  124. {
  125. QueueItemStruct BlankQIS = new QueueItemStruct();
  126. while (true)
  127. {
  128. try
  129. {
  130. QueueItemStruct QIS = BlankQIS;
  131. bool GotItem = false;
  132. if (eventQueue.Count == 0)
  133. {
  134. // Nothing to do? Sleep a bit waiting for something to do
  135. Thread.Sleep(nothingToDoSleepms);
  136. }
  137. else
  138. {
  139. // Something in queue, process
  140. //myScriptEngine.m_log.Info("[ScriptEngine]: Processing event for localID: " + QIS.localID + ", itemID: " + QIS.itemID + ", FunctionName: " + QIS.FunctionName);
  141. // OBJECT BASED LOCK - TWO THREADS WORKING ON SAME OBJECT IS NOT GOOD
  142. lock (queueLock)
  143. {
  144. GotItem = false;
  145. for (int qc = 0; qc < eventQueue.Count; qc++)
  146. {
  147. // Get queue item
  148. QIS = eventQueue.Dequeue();
  149. // Check if object is being processed by someone else
  150. if (TryLock(QIS.localID) == false)
  151. {
  152. // Object is already being processed, requeue it
  153. eventQueue.Enqueue(QIS);
  154. }
  155. else
  156. {
  157. // We have lock on an object and can process it
  158. GotItem = true;
  159. break;
  160. }
  161. }
  162. }
  163. if (GotItem == true)
  164. {
  165. // Execute function
  166. try
  167. {
  168. m_ScriptEngine.m_ScriptManager.ExecuteEvent(QIS.localID, QIS.itemID,
  169. QIS.functionName, QIS.param);
  170. }
  171. catch (Exception e)
  172. {
  173. // DISPLAY ERROR INWORLD
  174. string text = "Error executing script function \"" + QIS.functionName + "\":\r\n";
  175. if (e.InnerException != null)
  176. {
  177. // Send inner exception
  178. text += e.InnerException.Message.ToString();
  179. }
  180. else
  181. {
  182. // Send normal
  183. text += e.Message.ToString();
  184. }
  185. try
  186. {
  187. if (text.Length > 1500)
  188. text = text.Substring(0, 1500);
  189. IScriptHost m_host = m_ScriptEngine.World.GetSceneObjectPart(QIS.localID);
  190. //if (m_host != null)
  191. //{
  192. m_ScriptEngine.World.SimChat(Helpers.StringToField(text), ChatTypeEnum.Say, 0,
  193. m_host.AbsolutePosition, m_host.Name, m_host.UUID);
  194. }
  195. catch
  196. {
  197. //}
  198. //else
  199. //{
  200. // T oconsole
  201. Console.WriteLine("Unable to send text in-world:\r\n" + text);
  202. }
  203. }
  204. finally
  205. {
  206. ReleaseLock(QIS.localID);
  207. }
  208. }
  209. }
  210. }
  211. catch (ThreadAbortException tae)
  212. {
  213. throw tae;
  214. }
  215. catch (Exception e)
  216. {
  217. Console.WriteLine("Exception in EventQueueThreadLoop: " + e.ToString());
  218. }
  219. }
  220. }
  221. catch (ThreadAbortException)
  222. {
  223. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Worker thread killed: " + tae.Message);
  224. }
  225. }
  226. /// <summary>
  227. /// Try to get a mutex lock on localID
  228. /// </summary>
  229. /// <param name="localID"></param>
  230. /// <returns></returns>
  231. private 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. private void ReleaseLock(uint localID)
  251. {
  252. lock (tryLockLock)
  253. {
  254. if (objectLocks.Contains(localID) == true)
  255. {
  256. objectLocks.Remove(localID);
  257. }
  258. }
  259. }
  260. /// <summary>
  261. /// Add event to event execution queue
  262. /// </summary>
  263. /// <param name="localID"></param>
  264. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  265. /// <param name="param">Array of parameters to match event mask</param>
  266. public void AddToObjectQueue(uint localID, string FunctionName, object[] param)
  267. {
  268. // Determine all scripts in Object and add to their queue
  269. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Adding localID: " + localID + ", FunctionName: " + FunctionName);
  270. // Do we have any scripts in this object at all? If not, return
  271. if (m_ScriptEngine.m_ScriptManager.Scripts.ContainsKey(localID) == false)
  272. {
  273. //Console.WriteLine("Event \"" + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
  274. return;
  275. }
  276. Dictionary<LLUUID, LSL_BaseClass>.KeyCollection scriptKeys =
  277. m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
  278. foreach (LLUUID itemID in scriptKeys)
  279. {
  280. // Add to each script in that object
  281. // TODO: Some scripts may not subscribe to this event. Should we NOT add it? Does it matter?
  282. AddToScriptQueue(localID, itemID, FunctionName, param);
  283. }
  284. }
  285. /// <summary>
  286. /// Add event to event execution queue
  287. /// </summary>
  288. /// <param name="localID"></param>
  289. /// <param name="itemID"></param>
  290. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  291. /// <param name="param">Array of parameters to match event mask</param>
  292. public void AddToScriptQueue(uint localID, LLUUID itemID, string FunctionName, object[] param)
  293. {
  294. lock (queueLock)
  295. {
  296. // Create a structure and add data
  297. QueueItemStruct QIS = new QueueItemStruct();
  298. QIS.localID = localID;
  299. QIS.itemID = itemID;
  300. QIS.functionName = FunctionName;
  301. QIS.param = param;
  302. // Add it to queue
  303. eventQueue.Enqueue(QIS);
  304. }
  305. }
  306. }
  307. }