ScriptManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Runtime.Serialization.Formatters.Binary;
  32. using System.Threading;
  33. using libsecondlife;
  34. using OpenSim.Region.Environment.Scenes;
  35. namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
  36. {
  37. /// <summary>
  38. /// Loads scripts
  39. /// Compiles them if necessary
  40. /// Execute functions for EventQueueManager (Sends them to script on other AppDomain for execution)
  41. /// </summary>
  42. ///
  43. // This class is as close as you get to the script without being inside script class. It handles all the dirty work for other classes.
  44. // * Keeps track of running scripts
  45. // * Compiles script if necessary (through "Compiler")
  46. // * Loads script (through "AppDomainManager" called from for example "EventQueueManager")
  47. // * Executes functions inside script (called from for example "EventQueueManager" class)
  48. // * Unloads script (through "AppDomainManager" called from for example "EventQueueManager")
  49. // * Dedicated load/unload thread, and queues loading/unloading.
  50. // This so that scripts starting or stopping will not slow down other theads or whole system.
  51. //
  52. [Serializable]
  53. public abstract class ScriptManager : iScriptEngineFunctionModule
  54. {
  55. #region Declares
  56. private Thread scriptLoadUnloadThread;
  57. private static Thread staticScriptLoadUnloadThread;
  58. private int scriptLoadUnloadThread_IdleSleepms;
  59. private Queue<LUStruct> LUQueue = new Queue<LUStruct>();
  60. private static bool PrivateThread;
  61. private int LoadUnloadMaxQueueSize;
  62. private Object scriptLock = new Object();
  63. // Load/Unload structure
  64. private struct LUStruct
  65. {
  66. public uint localID;
  67. public LLUUID itemID;
  68. public string script;
  69. public LUType Action;
  70. }
  71. private enum LUType
  72. {
  73. Unknown = 0,
  74. Load = 1,
  75. Unload = 2
  76. }
  77. // Object<string, Script<string, script>>
  78. // IMPORTANT: Types and MemberInfo-derived objects require a LOT of memory.
  79. // Instead use RuntimeTypeHandle, RuntimeFieldHandle and RunTimeHandle (IntPtr) instead!
  80. public Dictionary<uint, Dictionary<LLUUID, IScript>> Scripts =
  81. new Dictionary<uint, Dictionary<LLUUID, IScript>>();
  82. public Scene World
  83. {
  84. get { return m_scriptEngine.World; }
  85. }
  86. #endregion
  87. public void ReadConfig()
  88. {
  89. scriptLoadUnloadThread_IdleSleepms = m_scriptEngine.ScriptConfigSource.GetInt("ScriptLoadUnloadLoopms", 30);
  90. // TODO: Requires sharing of all ScriptManagers to single thread
  91. PrivateThread = true; // m_scriptEngine.ScriptConfigSource.GetBoolean("PrivateScriptLoadUnloadThread", false);
  92. LoadUnloadMaxQueueSize = m_scriptEngine.ScriptConfigSource.GetInt("LoadUnloadMaxQueueSize", 100);
  93. }
  94. #region Object init/shutdown
  95. public ScriptEngine m_scriptEngine;
  96. public ScriptManager(ScriptEngine scriptEngine)
  97. {
  98. m_scriptEngine = scriptEngine;
  99. }
  100. public abstract void Initialize();
  101. public void Start()
  102. {
  103. ReadConfig();
  104. Initialize();
  105. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  106. //
  107. // CREATE THREAD
  108. // Private or shared
  109. //
  110. if (PrivateThread)
  111. {
  112. // Assign one thread per region
  113. //scriptLoadUnloadThread = StartScriptLoadUnloadThread();
  114. }
  115. else
  116. {
  117. // Shared thread - make sure one exist, then assign it to the private
  118. if (staticScriptLoadUnloadThread == null)
  119. {
  120. //staticScriptLoadUnloadThread = StartScriptLoadUnloadThread();
  121. }
  122. scriptLoadUnloadThread = staticScriptLoadUnloadThread;
  123. }
  124. }
  125. private static int privateThreadCount = 0;
  126. // TODO: unused
  127. // private Thread StartScriptLoadUnloadThread()
  128. // {
  129. // Thread t = new Thread(ScriptLoadUnloadThreadLoop);
  130. // string name = "ScriptLoadUnloadThread:";
  131. // if (PrivateThread)
  132. // {
  133. // name += "Private:" + privateThreadCount;
  134. // privateThreadCount++;
  135. // }
  136. // else
  137. // {
  138. // name += "Shared";
  139. // }
  140. // t.Name = name;
  141. // t.IsBackground = true;
  142. // t.Priority = ThreadPriority.Normal;
  143. // t.Start();
  144. // OpenSim.Framework.ThreadTracker.Add(t);
  145. // return t;
  146. // }
  147. ~ScriptManager()
  148. {
  149. // Abort load/unload thread
  150. try
  151. {
  152. //PleaseShutdown = true;
  153. //Thread.Sleep(100);
  154. if (scriptLoadUnloadThread != null && scriptLoadUnloadThread.IsAlive == true)
  155. {
  156. scriptLoadUnloadThread.Abort();
  157. //scriptLoadUnloadThread.Join();
  158. }
  159. }
  160. catch
  161. {
  162. }
  163. }
  164. #endregion
  165. #region Load / Unload scripts (Thread loop)
  166. // TODO: unused
  167. // private void ScriptLoadUnloadThreadLoop()
  168. // {
  169. // try
  170. // {
  171. // while (true)
  172. // {
  173. // if (LUQueue.Count == 0)
  174. // Thread.Sleep(scriptLoadUnloadThread_IdleSleepms);
  175. // //if (PleaseShutdown)
  176. // // return;
  177. // DoScriptLoadUnload();
  178. // }
  179. // }
  180. // catch (ThreadAbortException tae)
  181. // {
  182. // string a = tae.ToString();
  183. // a = String.Empty;
  184. // // Expected
  185. // }
  186. // }
  187. public void DoScriptLoadUnload()
  188. {
  189. if (LUQueue.Count > 0)
  190. {
  191. LUStruct item = LUQueue.Dequeue();
  192. lock (startStopLock) // Lock so we have only 1 thread working on loading/unloading of scripts
  193. {
  194. if (item.Action == LUType.Unload)
  195. {
  196. _StopScript(item.localID, item.itemID);
  197. }
  198. if (item.Action == LUType.Load)
  199. {
  200. _StartScript(item.localID, item.itemID, item.script);
  201. }
  202. }
  203. }
  204. }
  205. #endregion
  206. #region Helper functions
  207. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  208. {
  209. //Console.WriteLine("ScriptManager.CurrentDomain_AssemblyResolve: " + args.Name);
  210. return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
  211. }
  212. #endregion
  213. #region Start/Stop/Reset script
  214. private readonly Object startStopLock = new Object();
  215. /// <summary>
  216. /// Fetches, loads and hooks up a script to an objects events
  217. /// </summary>
  218. /// <param name="itemID"></param>
  219. /// <param name="localID"></param>
  220. public void StartScript(uint localID, LLUUID itemID, string Script)
  221. {
  222. if (LUQueue.Count >= LoadUnloadMaxQueueSize)
  223. {
  224. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: ERROR: Load/unload queue item count is at " + LUQueue.Count + ". Config variable \"LoadUnloadMaxQueueSize\" is set to " + LoadUnloadMaxQueueSize + ", so ignoring new script.");
  225. return;
  226. }
  227. LUStruct ls = new LUStruct();
  228. ls.localID = localID;
  229. ls.itemID = itemID;
  230. ls.script = Script;
  231. ls.Action = LUType.Load;
  232. LUQueue.Enqueue(ls);
  233. }
  234. /// <summary>
  235. /// Disables and unloads a script
  236. /// </summary>
  237. /// <param name="localID"></param>
  238. /// <param name="itemID"></param>
  239. public void StopScript(uint localID, LLUUID itemID)
  240. {
  241. LUStruct ls = new LUStruct();
  242. ls.localID = localID;
  243. ls.itemID = itemID;
  244. ls.Action = LUType.Unload;
  245. LUQueue.Enqueue(ls);
  246. }
  247. // Create a new instance of the compiler (reuse)
  248. //private Compiler.LSL.Compiler LSLCompiler = new Compiler.LSL.Compiler();
  249. public abstract void _StartScript(uint localID, LLUUID itemID, string Script);
  250. public abstract void _StopScript(uint localID, LLUUID itemID);
  251. #endregion
  252. #region Perform event execution in script
  253. /// <summary>
  254. /// Execute a LL-event-function in Script
  255. /// </summary>
  256. /// <param name="localID">Object the script is located in</param>
  257. /// <param name="itemID">Script ID</param>
  258. /// <param name="FunctionName">Name of function</param>
  259. /// <param name="args">Arguments to pass to function</param>
  260. internal void ExecuteEvent(uint localID, LLUUID itemID, string FunctionName, EventQueueManager.Queue_llDetectParams_Struct qParams, object[] args)
  261. {
  262. //cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
  263. ///#if DEBUG
  264. /// Console.WriteLine("ScriptEngine: Inside ExecuteEvent for event " + FunctionName);
  265. ///#endif
  266. // Execute a function in the script
  267. //m_scriptEngine.Log.Info("[" + ScriptEngineName + "]: Executing Function localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
  268. //ScriptBaseInterface Script = (ScriptBaseInterface)GetScript(localID, itemID);
  269. IScript Script = GetScript(localID, itemID);
  270. if (Script == null)
  271. {
  272. return;
  273. }
  274. //cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
  275. ///#if DEBUG
  276. /// Console.WriteLine("ScriptEngine: Executing event: " + FunctionName);
  277. ///#endif
  278. // Must be done in correct AppDomain, so leaving it up to the script itself
  279. Script.llDetectParams = qParams;
  280. Script.Exec.ExecuteEvent(FunctionName, args);
  281. }
  282. public int GetStateEventFlags(uint localID, LLUUID itemID)
  283. {
  284. // Console.WriteLine("GetStateEventFlags for <" + localID + "," + itemID + ">");
  285. try
  286. {
  287. IScript Script = GetScript(localID, itemID);
  288. if (Script == null)
  289. {
  290. return 0;
  291. }
  292. ExecutorBase.scriptEvents evflags = Script.Exec.GetStateEventFlags();
  293. return (int)evflags;
  294. }
  295. catch (Exception e)
  296. {
  297. // Console.WriteLine("Failed to get script reference for <" + localID + "," + itemID + ">");
  298. // Console.WriteLine(e.ToString());
  299. }
  300. return 0;
  301. }
  302. #endregion
  303. #region Internal functions to keep track of script
  304. public Dictionary<LLUUID, IScript>.KeyCollection GetScriptKeys(uint localID)
  305. {
  306. if (Scripts.ContainsKey(localID) == false)
  307. return null;
  308. Dictionary<LLUUID, IScript> Obj;
  309. Scripts.TryGetValue(localID, out Obj);
  310. return Obj.Keys;
  311. }
  312. public IScript GetScript(uint localID, LLUUID itemID)
  313. {
  314. lock (scriptLock)
  315. {
  316. if (Scripts.ContainsKey(localID) == false)
  317. return null;
  318. Dictionary<LLUUID, IScript> Obj;
  319. Scripts.TryGetValue(localID, out Obj);
  320. if (Obj.ContainsKey(itemID) == false)
  321. return null;
  322. // Get script
  323. IScript Script;
  324. Obj.TryGetValue(itemID, out Script);
  325. return Script;
  326. }
  327. }
  328. public void SetScript(uint localID, LLUUID itemID, IScript Script)
  329. {
  330. lock (scriptLock)
  331. {
  332. // Create object if it doesn't exist
  333. if (Scripts.ContainsKey(localID) == false)
  334. {
  335. Scripts.Add(localID, new Dictionary<LLUUID, IScript>());
  336. }
  337. // Delete script if it exists
  338. Dictionary<LLUUID, IScript> Obj;
  339. Scripts.TryGetValue(localID, out Obj);
  340. if (Obj.ContainsKey(itemID) == true)
  341. Obj.Remove(itemID);
  342. // Add to object
  343. Obj.Add(itemID, Script);
  344. }
  345. }
  346. public void RemoveScript(uint localID, LLUUID itemID)
  347. {
  348. // Don't have that object?
  349. if (Scripts.ContainsKey(localID) == false)
  350. return;
  351. // Delete script if it exists
  352. Dictionary<LLUUID, IScript> Obj;
  353. Scripts.TryGetValue(localID, out Obj);
  354. if (Obj.ContainsKey(itemID) == true)
  355. Obj.Remove(itemID);
  356. }
  357. #endregion
  358. public void ResetScript(uint localID, LLUUID itemID)
  359. {
  360. string script = GetScript(localID, itemID).Source;
  361. StopScript(localID, itemID);
  362. StartScript(localID, itemID, script);
  363. }
  364. #region Script serialization/deserialization
  365. public void GetSerializedScript(uint localID, LLUUID itemID)
  366. {
  367. // Serialize the script and return it
  368. // Should not be a problem
  369. FileStream fs = File.Create("SERIALIZED_SCRIPT_" + itemID);
  370. BinaryFormatter b = new BinaryFormatter();
  371. b.Serialize(fs, GetScript(localID, itemID));
  372. fs.Close();
  373. }
  374. public void PutSerializedScript(uint localID, LLUUID itemID)
  375. {
  376. // Deserialize the script and inject it into an AppDomain
  377. // How to inject into an AppDomain?
  378. }
  379. #endregion
  380. ///// <summary>
  381. ///// If set to true then threads and stuff should try to make a graceful exit
  382. ///// </summary>
  383. //public bool PleaseShutdown
  384. //{
  385. // get { return _PleaseShutdown; }
  386. // set { _PleaseShutdown = value; }
  387. //}
  388. //private bool _PleaseShutdown = false;
  389. }
  390. }