ScriptManager.cs 16 KB

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