EventQueueThreadClass.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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.Threading;
  30. using libsecondlife;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.Environment.Scenes.Scripting;
  33. namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
  34. {
  35. /// <summary>
  36. /// Because every thread needs some data set for it (time started to execute current function), it will do its work within a class
  37. /// </summary>
  38. public class EventQueueThreadClass : iScriptEngineFunctionModule
  39. {
  40. /// <summary>
  41. /// How many ms to sleep if queue is empty
  42. /// </summary>
  43. private static int nothingToDoSleepms;// = 50;
  44. private static ThreadPriority MyThreadPriority;
  45. public long LastExecutionStarted;
  46. public bool InExecution = false;
  47. public bool KillCurrentScript = false;
  48. //private EventQueueManager eventQueueManager;
  49. public Thread EventQueueThread;
  50. private static int ThreadCount = 0;
  51. private string ScriptEngineName = "ScriptEngine.Common";
  52. public EventQueueThreadClass()//EventQueueManager eqm
  53. {
  54. //eventQueueManager = eqm;
  55. ReadConfig();
  56. Start();
  57. }
  58. ~EventQueueThreadClass()
  59. {
  60. Stop();
  61. }
  62. public void ReadConfig()
  63. {
  64. lock (ScriptEngine.ScriptEngines)
  65. {
  66. foreach (ScriptEngine m_ScriptEngine in ScriptEngine.ScriptEngines)
  67. {
  68. ScriptEngineName = m_ScriptEngine.ScriptEngineName;
  69. nothingToDoSleepms = m_ScriptEngine.ScriptConfigSource.GetInt("SleepTimeIfNoScriptExecutionMs", 50);
  70. // Later with ScriptServer we might want to ask OS for stuff too, so doing this a bit manually
  71. string pri = m_ScriptEngine.ScriptConfigSource.GetString("ScriptThreadPriority", "BelowNormal");
  72. switch (pri.ToLower())
  73. {
  74. case "lowest":
  75. MyThreadPriority = ThreadPriority.Lowest;
  76. break;
  77. case "belownormal":
  78. MyThreadPriority = ThreadPriority.BelowNormal;
  79. break;
  80. case "normal":
  81. MyThreadPriority = ThreadPriority.Normal;
  82. break;
  83. case "abovenormal":
  84. MyThreadPriority = ThreadPriority.AboveNormal;
  85. break;
  86. case "highest":
  87. MyThreadPriority = ThreadPriority.Highest;
  88. break;
  89. default:
  90. MyThreadPriority = ThreadPriority.BelowNormal; // Default
  91. m_ScriptEngine.Log.Error("[ScriptEngineBase]: Unknown priority type \"" + pri +
  92. "\" in config file. Defaulting to \"BelowNormal\".");
  93. break;
  94. }
  95. }
  96. }
  97. // Now set that priority
  98. if (EventQueueThread != null)
  99. if (EventQueueThread.IsAlive)
  100. EventQueueThread.Priority = MyThreadPriority;
  101. }
  102. /// <summary>
  103. /// Start thread
  104. /// </summary>
  105. private void Start()
  106. {
  107. EventQueueThread = new Thread(EventQueueThreadLoop);
  108. EventQueueThread.IsBackground = true;
  109. EventQueueThread.Priority = MyThreadPriority;
  110. EventQueueThread.Name = "EventQueueManagerThread_" + ThreadCount;
  111. EventQueueThread.Start();
  112. ThreadTracker.Add(EventQueueThread);
  113. // Look at this... Don't you wish everyone did that solid coding everywhere? :P
  114. if (ThreadCount == int.MaxValue)
  115. ThreadCount = 0;
  116. ThreadCount++;
  117. }
  118. public void Stop()
  119. {
  120. //PleaseShutdown = true; // Set shutdown flag
  121. //Thread.Sleep(100); // Wait a bit
  122. if (EventQueueThread != null && EventQueueThread.IsAlive == true)
  123. {
  124. try
  125. {
  126. EventQueueThread.Abort(); // Send abort
  127. //EventQueueThread.Join(); // Wait for it
  128. }
  129. catch (Exception)
  130. {
  131. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: EventQueueManager Exception killing worker thread: " + e.ToString());
  132. }
  133. }
  134. }
  135. private EventQueueManager.QueueItemStruct BlankQIS = new EventQueueManager.QueueItemStruct();
  136. private ScriptEngine lastScriptEngine;
  137. /// <summary>
  138. /// Queue processing thread loop
  139. /// </summary>
  140. private void EventQueueThreadLoop()
  141. {
  142. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: EventQueueManager Worker thread spawned");
  143. try
  144. {
  145. while (true)
  146. {
  147. try
  148. {
  149. while (true)
  150. {
  151. DoProcessQueue();
  152. }
  153. }
  154. catch (ThreadAbortException)
  155. {
  156. if (lastScriptEngine != null)
  157. lastScriptEngine.Log.Info("[" + ScriptEngineName + "]: ThreadAbortException while executing function.");
  158. }
  159. catch (Exception e)
  160. {
  161. if (lastScriptEngine != null)
  162. lastScriptEngine.Log.Error("[" + ScriptEngineName + "]: Exception in EventQueueThreadLoop: " + e.ToString());
  163. }
  164. }
  165. }
  166. catch (ThreadAbortException)
  167. {
  168. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: EventQueueManager Worker thread killed: " + tae.Message);
  169. }
  170. }
  171. public void DoProcessQueue()
  172. {
  173. //lock (ScriptEngine.ScriptEngines)
  174. //{
  175. foreach (ScriptEngine m_ScriptEngine in new ArrayList(ScriptEngine.ScriptEngines))
  176. {
  177. lastScriptEngine = m_ScriptEngine;
  178. // Every now and then check if we should shut down
  179. //if (PleaseShutdown || EventQueueManager.ThreadsToExit > 0)
  180. //{
  181. // // Someone should shut down, lets get exclusive lock
  182. // lock (EventQueueManager.ThreadsToExitLock)
  183. // {
  184. // // Lets re-check in case someone grabbed it
  185. // if (EventQueueManager.ThreadsToExit > 0)
  186. // {
  187. // // Its crowded here so we'll shut down
  188. // EventQueueManager.ThreadsToExit--;
  189. // Stop();
  190. // return;
  191. // }
  192. // else
  193. // {
  194. // // We have been asked to shut down
  195. // Stop();
  196. // return;
  197. // }
  198. // }
  199. //}
  200. //try
  201. // {
  202. EventQueueManager.QueueItemStruct QIS = BlankQIS;
  203. bool GotItem = false;
  204. //if (PleaseShutdown)
  205. // return;
  206. if (m_ScriptEngine.m_EventQueueManager == null || m_ScriptEngine.m_EventQueueManager.eventQueue == null)
  207. continue;
  208. if (m_ScriptEngine.m_EventQueueManager.eventQueue.Count == 0)
  209. {
  210. // Nothing to do? Sleep a bit waiting for something to do
  211. Thread.Sleep(nothingToDoSleepms);
  212. }
  213. else
  214. {
  215. // Something in queue, process
  216. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: Processing event for localID: " + QIS.localID + ", itemID: " + QIS.itemID + ", FunctionName: " + QIS.FunctionName);
  217. // OBJECT BASED LOCK - TWO THREADS WORKING ON SAME OBJECT IS NOT GOOD
  218. lock (m_ScriptEngine.m_EventQueueManager.eventQueue)
  219. {
  220. GotItem = false;
  221. for (int qc = 0; qc < m_ScriptEngine.m_EventQueueManager.eventQueue.Count; qc++)
  222. {
  223. // Get queue item
  224. QIS = m_ScriptEngine.m_EventQueueManager.eventQueue.Dequeue();
  225. // Check if object is being processed by someone else
  226. if (m_ScriptEngine.m_EventQueueManager.TryLock(QIS.localID) == false)
  227. {
  228. // Object is already being processed, requeue it
  229. m_ScriptEngine.m_EventQueueManager.eventQueue.Enqueue(QIS);
  230. }
  231. else
  232. {
  233. // We have lock on an object and can process it
  234. GotItem = true;
  235. break;
  236. }
  237. }
  238. }
  239. if (GotItem == true)
  240. {
  241. // Execute function
  242. try
  243. {
  244. ///cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
  245. #if DEBUG
  246. //eventQueueManager.m_ScriptEngine.Log.Debug("[" + ScriptEngineName + "]: " +
  247. // "Executing event:\r\n"
  248. // + "QIS.localID: " + QIS.localID
  249. // + ", QIS.itemID: " + QIS.itemID
  250. // + ", QIS.functionName: " +
  251. // QIS.functionName);
  252. #endif
  253. // Only pipe event if land supports it.
  254. if (m_ScriptEngine.World.pipeEventsForScript(QIS.localID))
  255. {
  256. LastExecutionStarted = DateTime.Now.Ticks;
  257. KillCurrentScript = false;
  258. InExecution = true;
  259. m_ScriptEngine.m_ScriptManager.ExecuteEvent(QIS.localID,
  260. QIS.itemID,
  261. QIS.functionName,
  262. QIS.llDetectParams,
  263. QIS.param);
  264. InExecution = false;
  265. }
  266. }
  267. catch (Exception e)
  268. {
  269. InExecution = false;
  270. // DISPLAY ERROR INWORLD
  271. string text = "Error executing script function \"" + QIS.functionName +
  272. "\":\r\n";
  273. if (e.InnerException != null)
  274. {
  275. // Send inner exception
  276. string[] lines=e.InnerException.ToString().Replace("\r", "").Split('\n');
  277. string line = " (unknown line)";
  278. foreach (string t in lines)
  279. {
  280. int idx=t.IndexOf("SecondLife.Script.");
  281. if (idx != -1)
  282. {
  283. // Need to skip past windows paths that have "c:\" in them
  284. int colon=t.LastIndexOf(":");
  285. if (-1 != colon)
  286. {
  287. // Not sure why this is converted to an int then back to a string, either
  288. // way, need to skip the word "line " in the substring
  289. line = " at line " + Convert.ToInt32(t.Substring(colon + 6)).ToString();
  290. break;
  291. }
  292. }
  293. }
  294. text += e.InnerException.Message.ToString() + line;
  295. }
  296. else
  297. {
  298. text += "\r\n";
  299. // Send normal
  300. text += e.Message.ToString();
  301. }
  302. if (KillCurrentScript)
  303. text += "\r\nScript will be deactivated!";
  304. try
  305. {
  306. if (text.Length > 1500)
  307. text = text.Substring(0, 1500);
  308. IScriptHost m_host =
  309. m_ScriptEngine.World.GetSceneObjectPart(QIS.localID);
  310. //if (m_host != null)
  311. //{
  312. m_ScriptEngine.World.SimChat(Helpers.StringToField(text),
  313. ChatTypeEnum.DebugChannel, 2147483647,
  314. m_host.AbsolutePosition,
  315. m_host.Name, m_host.UUID, false);
  316. }
  317. catch (Exception)
  318. {
  319. //}
  320. //else
  321. //{
  322. // T oconsole
  323. m_ScriptEngine.m_EventQueueManager.m_ScriptEngine.Log.Error("[" + ScriptEngineName +
  324. "]: " +
  325. "Unable to send text in-world:\r\n" +
  326. text);
  327. }
  328. finally
  329. {
  330. // So we are done sending message in-world
  331. if (KillCurrentScript)
  332. {
  333. m_ScriptEngine.m_EventQueueManager.m_ScriptEngine.m_ScriptManager.StopScript(
  334. QIS.localID, QIS.itemID);
  335. }
  336. }
  337. // Pass it on so it's displayed on the console
  338. // and in the logs (mikem 2008.06.02).
  339. throw e.InnerException;
  340. }
  341. finally
  342. {
  343. InExecution = false;
  344. m_ScriptEngine.m_EventQueueManager.ReleaseLock(QIS.localID);
  345. }
  346. }
  347. }
  348. }
  349. // }
  350. }
  351. ///// <summary>
  352. ///// If set to true then threads and stuff should try to make a graceful exit
  353. ///// </summary>
  354. //public bool PleaseShutdown
  355. //{
  356. // get { return _PleaseShutdown; }
  357. // set { _PleaseShutdown = value; }
  358. //}
  359. //private bool _PleaseShutdown = false;
  360. }
  361. }