XEngine.cs 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  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 OpenSimulator 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.Globalization;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Security;
  34. using System.Security.Policy;
  35. using System.Text;
  36. using System.Threading;
  37. using System.Xml;
  38. using OpenMetaverse;
  39. using OpenMetaverse.StructuredData;
  40. using log4net;
  41. using Nini.Config;
  42. using Amib.Threading;
  43. using OpenSim.Framework;
  44. using OpenSim.Framework.Console;
  45. using OpenSim.Region.Framework.Scenes;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.ScriptEngine.Shared;
  48. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  49. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  50. using OpenSim.Region.ScriptEngine.Shared.Instance;
  51. using OpenSim.Region.ScriptEngine.Shared.Api;
  52. using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
  53. using OpenSim.Region.ScriptEngine.Interfaces;
  54. using Timer = OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
  55. using ScriptCompileQueue = OpenSim.Framework.LocklessQueue<object[]>;
  56. namespace OpenSim.Region.ScriptEngine.XEngine
  57. {
  58. public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
  59. {
  60. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  61. /// <summary>
  62. /// Control the printing of certain debug messages.
  63. /// </summary>
  64. /// <remarks>
  65. /// If DebugLevel >= 1, then we log every time that a script is started.
  66. /// </remarks>
  67. // public int DebugLevel { get; set; }
  68. private SmartThreadPool m_ThreadPool;
  69. private int m_MaxScriptQueue;
  70. private Scene m_Scene;
  71. private IConfig m_ScriptConfig = null;
  72. private IConfigSource m_ConfigSource = null;
  73. private ICompiler m_Compiler;
  74. private int m_MinThreads;
  75. private int m_MaxThreads;
  76. /// <summary>
  77. /// Amount of time to delay before starting.
  78. /// </summary>
  79. private int m_StartDelay;
  80. private int m_IdleTimeout;
  81. private int m_StackSize;
  82. private int m_SleepTime;
  83. private int m_SaveTime;
  84. private ThreadPriority m_Prio;
  85. private bool m_Enabled = false;
  86. private bool m_InitialStartup = true;
  87. private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
  88. private string m_ScriptErrorMessage;
  89. private Dictionary<string, string> m_uniqueScripts = new Dictionary<string, string>();
  90. private bool m_AppDomainLoading;
  91. private Dictionary<UUID,ArrayList> m_ScriptErrors =
  92. new Dictionary<UUID,ArrayList>();
  93. // disable warning: need to keep a reference to XEngine.EventManager
  94. // alive to avoid it being garbage collected
  95. #pragma warning disable 414
  96. private EventManager m_EventManager;
  97. #pragma warning restore 414
  98. private IXmlRpcRouter m_XmlRpcRouter;
  99. private int m_EventLimit;
  100. private bool m_KillTimedOutScripts;
  101. private string m_ScriptEnginesPath = null;
  102. private ExpiringCache<UUID, bool> m_runFlags = new ExpiringCache<UUID, bool>();
  103. /// <summary>
  104. /// Is the entire simulator in the process of shutting down?
  105. /// </summary>
  106. private bool m_SimulatorShuttingDown;
  107. private static List<XEngine> m_ScriptEngines =
  108. new List<XEngine>();
  109. // Maps the local id to the script inventory items in it
  110. private Dictionary<uint, List<UUID> > m_PrimObjects =
  111. new Dictionary<uint, List<UUID> >();
  112. // Maps the UUID above to the script instance
  113. private Dictionary<UUID, IScriptInstance> m_Scripts =
  114. new Dictionary<UUID, IScriptInstance>();
  115. // Maps the asset ID to the assembly
  116. private Dictionary<UUID, string> m_Assemblies =
  117. new Dictionary<UUID, string>();
  118. private Dictionary<string, int> m_AddingAssemblies =
  119. new Dictionary<string, int>();
  120. // This will list AppDomains by script asset
  121. private Dictionary<UUID, AppDomain> m_AppDomains =
  122. new Dictionary<UUID, AppDomain>();
  123. // List the scripts running in each appdomain
  124. private Dictionary<UUID, List<UUID> > m_DomainScripts =
  125. new Dictionary<UUID, List<UUID> >();
  126. private ScriptCompileQueue m_CompileQueue = new ScriptCompileQueue();
  127. IWorkItemResult m_CurrentCompile = null;
  128. private Dictionary<UUID, int> m_CompileDict = new Dictionary<UUID, int>();
  129. public string ScriptEngineName
  130. {
  131. get { return "XEngine"; }
  132. }
  133. public Scene World
  134. {
  135. get { return m_Scene; }
  136. }
  137. public static List<XEngine> ScriptEngines
  138. {
  139. get { return m_ScriptEngines; }
  140. }
  141. public IScriptModule ScriptModule
  142. {
  143. get { return this; }
  144. }
  145. // private struct RezScriptParms
  146. // {
  147. // uint LocalID;
  148. // UUID ItemID;
  149. // string Script;
  150. // }
  151. public IConfig Config
  152. {
  153. get { return m_ScriptConfig; }
  154. }
  155. public string ScriptEnginePath
  156. {
  157. get { return m_ScriptEnginesPath; }
  158. }
  159. public IConfigSource ConfigSource
  160. {
  161. get { return m_ConfigSource; }
  162. }
  163. /// <summary>
  164. /// Event fired after the script engine has finished removing a script.
  165. /// </summary>
  166. public event ScriptRemoved OnScriptRemoved;
  167. /// <summary>
  168. /// Event fired after the script engine has finished removing a script from an object.
  169. /// </summary>
  170. public event ObjectRemoved OnObjectRemoved;
  171. public void Initialise(IConfigSource configSource)
  172. {
  173. if (configSource.Configs["XEngine"] == null)
  174. return;
  175. m_ScriptConfig = configSource.Configs["XEngine"];
  176. m_ConfigSource = configSource;
  177. }
  178. public void AddRegion(Scene scene)
  179. {
  180. if (m_ScriptConfig == null)
  181. return;
  182. m_ScriptFailCount = 0;
  183. m_ScriptErrorMessage = String.Empty;
  184. if (m_ScriptConfig == null)
  185. {
  186. // m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
  187. return;
  188. }
  189. m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
  190. if (!m_Enabled)
  191. return;
  192. AppDomain.CurrentDomain.AssemblyResolve +=
  193. OnAssemblyResolve;
  194. m_Scene = scene;
  195. m_log.InfoFormat("[XEngine]: Initializing scripts in region {0}", m_Scene.RegionInfo.RegionName);
  196. m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  197. m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
  198. m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  199. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  200. m_StartDelay = m_ScriptConfig.GetInt("StartDelay", 15000);
  201. m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  202. m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  203. m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
  204. m_AppDomainLoading = m_ScriptConfig.GetBoolean("AppDomainLoading", true);
  205. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  206. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
  207. m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
  208. m_ScriptEnginesPath = m_ScriptConfig.GetString("ScriptEnginesPath", "ScriptEngines");
  209. m_Prio = ThreadPriority.BelowNormal;
  210. switch (priority)
  211. {
  212. case "Lowest":
  213. m_Prio = ThreadPriority.Lowest;
  214. break;
  215. case "BelowNormal":
  216. m_Prio = ThreadPriority.BelowNormal;
  217. break;
  218. case "Normal":
  219. m_Prio = ThreadPriority.Normal;
  220. break;
  221. case "AboveNormal":
  222. m_Prio = ThreadPriority.AboveNormal;
  223. break;
  224. case "Highest":
  225. m_Prio = ThreadPriority.Highest;
  226. break;
  227. default:
  228. m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
  229. break;
  230. }
  231. lock (m_ScriptEngines)
  232. {
  233. m_ScriptEngines.Add(this);
  234. }
  235. // Needs to be here so we can queue the scripts that need starting
  236. //
  237. m_Scene.EventManager.OnRezScript += OnRezScript;
  238. // Complete basic setup of the thread pool
  239. //
  240. SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
  241. m_MaxScriptQueue, m_StackSize);
  242. m_Scene.StackModuleInterface<IScriptModule>(this);
  243. m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
  244. if (m_XmlRpcRouter != null)
  245. {
  246. OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
  247. OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
  248. }
  249. MainConsole.Instance.Commands.AddCommand(
  250. "Scripts", false, "xengine status", "xengine status", "Show status information",
  251. "Show status information on the script engine.",
  252. HandleShowStatus);
  253. MainConsole.Instance.Commands.AddCommand(
  254. "Scripts", false, "scripts show", "scripts show [<script-item-uuid>]", "Show script information",
  255. "Show information on all scripts known to the script engine."
  256. + "If a <script-item-uuid> is given then only information on that script will be shown.",
  257. HandleShowScripts);
  258. MainConsole.Instance.Commands.AddCommand(
  259. "Scripts", false, "show scripts", "show scripts [<script-item-uuid>]", "Show script information",
  260. "Synonym for scripts show command", HandleShowScripts);
  261. MainConsole.Instance.Commands.AddCommand(
  262. "Scripts", false, "scripts suspend", "scripts suspend [<script-item-uuid>]", "Suspends all running scripts",
  263. "Suspends all currently running scripts. This only suspends event delivery, it will not suspend a"
  264. + " script that is currently processing an event.\n"
  265. + "Suspended scripts will continue to accumulate events but won't process them.\n"
  266. + "If a <script-item-uuid> is given then only that script will be suspended. Otherwise, all suitable scripts are suspended.",
  267. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleSuspendScript));
  268. MainConsole.Instance.Commands.AddCommand(
  269. "Scripts", false, "scripts resume", "scripts resume [<script-item-uuid>]", "Resumes all suspended scripts",
  270. "Resumes all currently suspended scripts.\n"
  271. + "Resumed scripts will process all events accumulated whilst suspended."
  272. + "If a <script-item-uuid> is given then only that script will be resumed. Otherwise, all suitable scripts are resumed.",
  273. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleResumeScript));
  274. MainConsole.Instance.Commands.AddCommand(
  275. "Scripts", false, "scripts stop", "scripts stop [<script-item-uuid>]", "Stops all running scripts",
  276. "Stops all running scripts."
  277. + "If a <script-item-uuid> is given then only that script will be stopped. Otherwise, all suitable scripts are stopped.",
  278. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleStopScript));
  279. MainConsole.Instance.Commands.AddCommand(
  280. "Scripts", false, "scripts start", "scripts start [<script-item-uuid>]", "Starts all stopped scripts",
  281. "Starts all stopped scripts."
  282. + "If a <script-item-uuid> is given then only that script will be started. Otherwise, all suitable scripts are started.",
  283. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleStartScript));
  284. // MainConsole.Instance.Commands.AddCommand(
  285. // "Debug", false, "debug xengine", "debug xengine [<level>]",
  286. // "Turn on detailed xengine debugging.",
  287. // "If level <= 0, then no extra logging is done.\n"
  288. // + "If level >= 1, then we log every time that a script is started.",
  289. // HandleDebugLevelCommand);
  290. }
  291. /// <summary>
  292. /// Change debug level
  293. /// </summary>
  294. /// <param name="module"></param>
  295. /// <param name="args"></param>
  296. // private void HandleDebugLevelCommand(string module, string[] args)
  297. // {
  298. // if (args.Length == 3)
  299. // {
  300. // int newDebug;
  301. // if (int.TryParse(args[2], out newDebug))
  302. // {
  303. // DebugLevel = newDebug;
  304. // MainConsole.Instance.OutputFormat("Debug level set to {0}", newDebug);
  305. // }
  306. // }
  307. // else if (args.Length == 2)
  308. // {
  309. // MainConsole.Instance.OutputFormat("Current debug level is {0}", DebugLevel);
  310. // }
  311. // else
  312. // {
  313. // MainConsole.Instance.Output("Usage: debug xengine 0..1");
  314. // }
  315. // }
  316. /// <summary>
  317. /// Parse the raw item id into a script instance from the command params if it's present.
  318. /// </summary>
  319. /// <param name="cmdparams"></param>
  320. /// <param name="instance"></param>
  321. /// <returns>true if we're okay to proceed, false if not.</returns>
  322. private void HandleScriptsAction(string[] cmdparams, Action<IScriptInstance> action)
  323. {
  324. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  325. return;
  326. lock (m_Scripts)
  327. {
  328. string rawItemId;
  329. UUID itemId = UUID.Zero;
  330. if (cmdparams.Length == 2)
  331. {
  332. foreach (IScriptInstance instance in m_Scripts.Values)
  333. action(instance);
  334. return;
  335. }
  336. rawItemId = cmdparams[2];
  337. if (!UUID.TryParse(rawItemId, out itemId))
  338. {
  339. MainConsole.Instance.OutputFormat("Error - {0} is not a valid UUID", rawItemId);
  340. return;
  341. }
  342. if (itemId != UUID.Zero)
  343. {
  344. IScriptInstance instance = GetInstance(itemId);
  345. if (instance == null)
  346. {
  347. // Commented out for now since this will cause false reports on simulators with more than
  348. // one scene where the current command line set region is 'root' (which causes commands to
  349. // go to both regions... (sigh)
  350. // MainConsole.Instance.OutputFormat("Error - No item found with id {0}", itemId);
  351. return;
  352. }
  353. else
  354. {
  355. action(instance);
  356. return;
  357. }
  358. }
  359. }
  360. }
  361. private void HandleShowStatus(string module, string[] cmdparams)
  362. {
  363. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  364. return;
  365. MainConsole.Instance.OutputFormat(GetStatusReport());
  366. }
  367. public string GetStatusReport()
  368. {
  369. StringBuilder sb = new StringBuilder();
  370. sb.AppendFormat("Status of XEngine instance for {0}\n", m_Scene.RegionInfo.RegionName);
  371. lock (m_Scripts)
  372. sb.AppendFormat("Scripts loaded : {0}\n", m_Scripts.Count);
  373. sb.AppendFormat("Unique scripts : {0}\n", m_uniqueScripts.Count);
  374. sb.AppendFormat("Scripts waiting for load : {0}\n", m_CompileQueue.Count);
  375. sb.AppendFormat("Max threads : {0}\n", m_ThreadPool.MaxThreads);
  376. sb.AppendFormat("Min threads : {0}\n", m_ThreadPool.MinThreads);
  377. sb.AppendFormat("Allocated threads : {0}\n", m_ThreadPool.ActiveThreads);
  378. sb.AppendFormat("In use threads : {0}\n", m_ThreadPool.InUseThreads);
  379. sb.AppendFormat("Work items waiting : {0}\n", m_ThreadPool.WaitingCallbacks);
  380. // sb.AppendFormat("Assemblies loaded : {0}\n", m_Assemblies.Count);
  381. SensorRepeat sr = AsyncCommandManager.GetSensorRepeatPlugin(this);
  382. sb.AppendFormat("Sensors : {0}\n", sr != null ? sr.SensorsCount : 0);
  383. Dataserver ds = AsyncCommandManager.GetDataserverPlugin(this);
  384. sb.AppendFormat("Dataserver requests : {0}\n", ds != null ? ds.DataserverRequestsCount : 0);
  385. Timer t = AsyncCommandManager.GetTimerPlugin(this);
  386. sb.AppendFormat("Timers : {0}\n", t != null ? t.TimersCount : 0);
  387. Listener l = AsyncCommandManager.GetListenerPlugin(this);
  388. sb.AppendFormat("Listeners : {0}\n", l != null ? l.ListenerCount : 0);
  389. return sb.ToString();
  390. }
  391. public void HandleShowScripts(string module, string[] cmdparams)
  392. {
  393. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  394. return;
  395. if (cmdparams.Length == 2)
  396. {
  397. lock (m_Scripts)
  398. {
  399. MainConsole.Instance.OutputFormat(
  400. "Showing {0} scripts in {1}", m_Scripts.Count, m_Scene.RegionInfo.RegionName);
  401. }
  402. }
  403. HandleScriptsAction(cmdparams, HandleShowScript);
  404. }
  405. private void HandleShowScript(IScriptInstance instance)
  406. {
  407. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  408. string status;
  409. if (instance.ShuttingDown)
  410. {
  411. status = "shutting down";
  412. }
  413. else if (instance.Suspended)
  414. {
  415. status = "suspended";
  416. }
  417. else if (!instance.Running)
  418. {
  419. status = "stopped";
  420. }
  421. else
  422. {
  423. status = "running";
  424. }
  425. StringBuilder sb = new StringBuilder();
  426. Queue eq = instance.EventQueue;
  427. sb.AppendFormat("Script name : {0}\n", instance.ScriptName);
  428. sb.AppendFormat("Status : {0}\n", status);
  429. lock (eq)
  430. sb.AppendFormat("Queued events : {0}\n", eq.Count);
  431. sb.AppendFormat("Item UUID : {0}\n", instance.ItemID);
  432. sb.AppendFormat("Containing part name: {0}\n", instance.PrimName);
  433. sb.AppendFormat("Containing part UUID: {0}\n", instance.ObjectID);
  434. sb.AppendFormat("Position : {0}\n", sop.AbsolutePosition);
  435. MainConsole.Instance.OutputFormat(sb.ToString());
  436. }
  437. private void HandleSuspendScript(IScriptInstance instance)
  438. {
  439. if (!instance.Suspended)
  440. {
  441. instance.Suspend();
  442. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  443. MainConsole.Instance.OutputFormat(
  444. "Suspended {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  445. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  446. }
  447. }
  448. private void HandleResumeScript(IScriptInstance instance)
  449. {
  450. if (instance.Suspended)
  451. {
  452. instance.Resume();
  453. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  454. MainConsole.Instance.OutputFormat(
  455. "Resumed {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  456. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  457. }
  458. }
  459. private void HandleStartScript(IScriptInstance instance)
  460. {
  461. if (!instance.Running)
  462. {
  463. instance.Start();
  464. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  465. MainConsole.Instance.OutputFormat(
  466. "Started {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  467. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  468. }
  469. }
  470. private void HandleStopScript(IScriptInstance instance)
  471. {
  472. if (instance.Running)
  473. {
  474. instance.Stop(0);
  475. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  476. MainConsole.Instance.OutputFormat(
  477. "Stopped {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  478. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  479. }
  480. }
  481. public void RemoveRegion(Scene scene)
  482. {
  483. if (!m_Enabled)
  484. return;
  485. lock (m_Scripts)
  486. {
  487. m_log.InfoFormat(
  488. "[XEngine]: Shutting down {0} scripts in {1}", m_Scripts.Count, m_Scene.RegionInfo.RegionName);
  489. foreach (IScriptInstance instance in m_Scripts.Values)
  490. {
  491. // Force a final state save
  492. //
  493. if (m_Assemblies.ContainsKey(instance.AssetID))
  494. {
  495. string assembly = m_Assemblies[instance.AssetID];
  496. try
  497. {
  498. instance.SaveState(assembly);
  499. }
  500. catch (Exception e)
  501. {
  502. m_log.Error(
  503. string.Format(
  504. "[XEngine]: Failed final state save for script {0}.{1}, item UUID {2}, prim UUID {3} in {4}. Exception ",
  505. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, World.Name)
  506. , e);
  507. }
  508. }
  509. // Clear the event queue and abort the instance thread
  510. //
  511. instance.ClearQueue();
  512. instance.Stop(0);
  513. // Release events, timer, etc
  514. //
  515. instance.DestroyScriptInstance();
  516. // Unload scripts and app domains.
  517. // Must be done explicitly because they have infinite
  518. // lifetime.
  519. // However, don't bother to do this if the simulator is shutting
  520. // down since it takes a long time with many scripts.
  521. if (!m_SimulatorShuttingDown)
  522. {
  523. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  524. if (m_DomainScripts[instance.AppDomain].Count == 0)
  525. {
  526. m_DomainScripts.Remove(instance.AppDomain);
  527. UnloadAppDomain(instance.AppDomain);
  528. }
  529. }
  530. }
  531. m_Scripts.Clear();
  532. m_PrimObjects.Clear();
  533. m_Assemblies.Clear();
  534. m_DomainScripts.Clear();
  535. }
  536. lock (m_ScriptEngines)
  537. {
  538. m_ScriptEngines.Remove(this);
  539. }
  540. }
  541. public void RegionLoaded(Scene scene)
  542. {
  543. if (!m_Enabled)
  544. return;
  545. m_EventManager = new EventManager(this);
  546. m_Compiler = new Compiler(this);
  547. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  548. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  549. m_Scene.EventManager.OnStartScript += OnStartScript;
  550. m_Scene.EventManager.OnStopScript += OnStopScript;
  551. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  552. m_Scene.EventManager.OnShutdown += OnShutdown;
  553. // If region ready has been triggered, then the region had no scripts to compile and completed its other
  554. // work.
  555. m_Scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) m_InitialStartup = false; };
  556. if (m_SleepTime > 0)
  557. {
  558. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  559. new Object[]{ m_SleepTime });
  560. }
  561. if (m_SaveTime > 0)
  562. {
  563. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  564. new Object[] { m_SaveTime });
  565. }
  566. }
  567. public void StartProcessing()
  568. {
  569. m_ThreadPool.Start();
  570. }
  571. public void Close()
  572. {
  573. if (!m_Enabled)
  574. return;
  575. lock (m_ScriptEngines)
  576. {
  577. if (m_ScriptEngines.Contains(this))
  578. m_ScriptEngines.Remove(this);
  579. }
  580. }
  581. public object DoBackup(object o)
  582. {
  583. Object[] p = (Object[])o;
  584. int saveTime = (int)p[0];
  585. if (saveTime > 0)
  586. System.Threading.Thread.Sleep(saveTime);
  587. // m_log.Debug("[XEngine] Backing up script states");
  588. List<IScriptInstance> instances = new List<IScriptInstance>();
  589. lock (m_Scripts)
  590. {
  591. foreach (IScriptInstance instance in m_Scripts.Values)
  592. instances.Add(instance);
  593. }
  594. foreach (IScriptInstance i in instances)
  595. {
  596. string assembly = String.Empty;
  597. lock (m_Scripts)
  598. {
  599. if (!m_Assemblies.ContainsKey(i.AssetID))
  600. continue;
  601. assembly = m_Assemblies[i.AssetID];
  602. }
  603. try
  604. {
  605. i.SaveState(assembly);
  606. }
  607. catch (Exception e)
  608. {
  609. m_log.Error(
  610. string.Format(
  611. "[XEngine]: Failed to save state of script {0}.{1}, item UUID {2}, prim UUID {3} in {4}. Exception ",
  612. i.PrimName, i.ScriptName, i.ItemID, i.ObjectID, World.Name)
  613. , e);
  614. }
  615. }
  616. instances.Clear();
  617. if (saveTime > 0)
  618. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  619. new Object[] { saveTime });
  620. return 0;
  621. }
  622. public void SaveAllState()
  623. {
  624. foreach (IScriptInstance inst in m_Scripts.Values)
  625. {
  626. if (inst.EventTime() > m_EventLimit)
  627. {
  628. inst.Stop(100);
  629. if (!m_KillTimedOutScripts)
  630. inst.Start();
  631. }
  632. }
  633. }
  634. public object DoMaintenance(object p)
  635. {
  636. object[] parms = (object[])p;
  637. int sleepTime = (int)parms[0];
  638. SaveAllState();
  639. System.Threading.Thread.Sleep(sleepTime);
  640. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  641. new Object[]{ sleepTime });
  642. return 0;
  643. }
  644. public Type ReplaceableInterface
  645. {
  646. get { return null; }
  647. }
  648. public string Name
  649. {
  650. get { return "XEngine"; }
  651. }
  652. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  653. {
  654. // m_log.DebugFormat(
  655. // "[XEngine]: OnRezScript event triggered for script {0}, startParam {1}, postOnRez {2}, engine {3}, stateSource {4}, script\n{5}",
  656. // itemID, startParam, postOnRez, engine, stateSource, script);
  657. if (script.StartsWith("//MRM:"))
  658. return;
  659. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  660. List<string> names = new List<string>();
  661. foreach (IScriptModule m in engines)
  662. names.Add(m.ScriptEngineName);
  663. int lineEnd = script.IndexOf('\n');
  664. if (lineEnd > 1)
  665. {
  666. string firstline = script.Substring(0, lineEnd).Trim();
  667. int colon = firstline.IndexOf(':');
  668. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  669. {
  670. string engineName = firstline.Substring(2, colon - 2);
  671. if (names.Contains(engineName))
  672. {
  673. engine = engineName;
  674. script = "//" + script.Substring(colon + 1);
  675. }
  676. else
  677. {
  678. if (engine == ScriptEngineName)
  679. {
  680. // If we are falling back on XEngine as the default engine, then only complain to the user
  681. // if a script language has been explicitly set and it's one that we recognize or there are
  682. // no non-whitespace characters after the colon.
  683. //
  684. // If the script is
  685. // explicitly not allowed or the script is not in LSL then the user will be informed by a later compiler message.
  686. //
  687. // If the colon ends the line then we'll risk the false positive as this is more likely
  688. // to signal a real scriptengine line where the user wants to use the default compile language.
  689. //
  690. // This avoids the overwhelming number of false positives where we're in this code because
  691. // there's a colon in a comment in the first line of a script for entirely
  692. // unrelated reasons (e.g. vim settings).
  693. //
  694. // TODO: A better fix would be to deprecate simple : detection and look for some less likely
  695. // string to begin the comment (like #! in unix shell scripts).
  696. bool warnRunningInXEngine = false;
  697. string restOfFirstLine = firstline.Substring(colon + 1);
  698. // FIXME: These are hardcoded because they are currently hardcoded in Compiler.cs
  699. if (restOfFirstLine.StartsWith("c#")
  700. || restOfFirstLine.StartsWith("vb")
  701. || restOfFirstLine.StartsWith("lsl")
  702. || restOfFirstLine.StartsWith("js")
  703. || restOfFirstLine.StartsWith("yp")
  704. || restOfFirstLine.Length == 0)
  705. warnRunningInXEngine = true;
  706. if (warnRunningInXEngine)
  707. {
  708. SceneObjectPart part =
  709. m_Scene.GetSceneObjectPart(
  710. localID);
  711. TaskInventoryItem item =
  712. part.Inventory.GetInventoryItem(itemID);
  713. ScenePresence presence =
  714. m_Scene.GetScenePresence(
  715. item.OwnerID);
  716. if (presence != null)
  717. {
  718. presence.ControllingClient.SendAgentAlertMessage(
  719. "Selected engine unavailable. "+
  720. "Running script on "+
  721. ScriptEngineName,
  722. false);
  723. }
  724. }
  725. }
  726. }
  727. }
  728. }
  729. if (engine != ScriptEngineName)
  730. return;
  731. // If we've seen this exact script text before, use that reference instead
  732. if (m_uniqueScripts.ContainsKey(script))
  733. script = m_uniqueScripts[script];
  734. else
  735. m_uniqueScripts[script] = script;
  736. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  737. if (stateSource == (int)StateSource.ScriptedRez)
  738. {
  739. lock (m_CompileDict)
  740. {
  741. m_CompileDict[itemID] = 0;
  742. }
  743. DoOnRezScript(parms);
  744. }
  745. else
  746. {
  747. m_CompileQueue.Enqueue(parms);
  748. lock (m_CompileDict)
  749. {
  750. m_CompileDict[itemID] = 0;
  751. }
  752. // m_log.DebugFormat("[XEngine]: Added script {0} to compile queue", itemID);
  753. if (m_CurrentCompile == null)
  754. {
  755. // NOTE: Although we use a lockless queue, the lock here
  756. // is required. It ensures that there are never two
  757. // compile threads running, which, due to a race
  758. // conndition, might otherwise happen
  759. //
  760. lock (m_CompileQueue)
  761. {
  762. if (m_CurrentCompile == null)
  763. m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
  764. }
  765. }
  766. }
  767. }
  768. public Object DoOnRezScriptQueue(Object dummy)
  769. {
  770. if (m_InitialStartup)
  771. {
  772. // This delay exists to stop mono problems where script compilation and startup would stop the sim
  773. // working properly for the session.
  774. System.Threading.Thread.Sleep(m_StartDelay);
  775. m_log.InfoFormat("[XEngine]: Performing initial script startup on {0}", m_Scene.Name);
  776. }
  777. object[] o;
  778. int scriptsStarted = 0;
  779. while (m_CompileQueue.Dequeue(out o))
  780. {
  781. if (DoOnRezScript(o))
  782. {
  783. scriptsStarted++;
  784. if (m_InitialStartup)
  785. if (scriptsStarted % 50 == 0)
  786. m_log.InfoFormat(
  787. "[XEngine]: Started {0} scripts in {1}", scriptsStarted, m_Scene.Name);
  788. }
  789. }
  790. if (m_InitialStartup)
  791. m_log.InfoFormat(
  792. "[XEngine]: Completed starting {0} scripts on {1}", scriptsStarted, m_Scene.Name);
  793. // NOTE: Despite having a lockless queue, this lock is required
  794. // to make sure there is never no compile thread while there
  795. // are still scripts to compile. This could otherwise happen
  796. // due to a race condition
  797. //
  798. lock (m_CompileQueue)
  799. m_CurrentCompile = null;
  800. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  801. m_ScriptErrorMessage);
  802. m_ScriptFailCount = 0;
  803. m_InitialStartup = false;
  804. return null;
  805. }
  806. private bool DoOnRezScript(object[] parms)
  807. {
  808. Object[] p = parms;
  809. uint localID = (uint)p[0];
  810. UUID itemID = (UUID)p[1];
  811. string script =(string)p[2];
  812. int startParam = (int)p[3];
  813. bool postOnRez = (bool)p[4];
  814. StateSource stateSource = (StateSource)p[5];
  815. // m_log.DebugFormat("[XEngine]: DoOnRezScript called for script {0}", itemID);
  816. lock (m_CompileDict)
  817. {
  818. if (!m_CompileDict.ContainsKey(itemID))
  819. return false;
  820. m_CompileDict.Remove(itemID);
  821. }
  822. // Get the asset ID of the script, so we can check if we
  823. // already have it.
  824. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  825. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  826. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  827. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  828. if (part == null)
  829. {
  830. m_log.ErrorFormat("[Script]: SceneObjectPart with localID {0} unavailable. Script NOT started.", localID);
  831. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  832. m_ScriptFailCount++;
  833. return false;
  834. }
  835. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  836. if (item == null)
  837. {
  838. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  839. m_ScriptFailCount++;
  840. return false;
  841. }
  842. m_log.DebugFormat(
  843. "[XEngine] Loading script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
  844. part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
  845. part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  846. UUID assetID = item.AssetID;
  847. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  848. string assembly = "";
  849. CultureInfo USCulture = new CultureInfo("en-US");
  850. Thread.CurrentThread.CurrentCulture = USCulture;
  851. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  852. lock (m_ScriptErrors)
  853. {
  854. try
  855. {
  856. lock (m_AddingAssemblies)
  857. {
  858. m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assembly, out linemap);
  859. if (!m_AddingAssemblies.ContainsKey(assembly)) {
  860. m_AddingAssemblies[assembly] = 1;
  861. } else {
  862. m_AddingAssemblies[assembly]++;
  863. }
  864. }
  865. string[] warnings = m_Compiler.GetWarnings();
  866. if (warnings != null && warnings.Length != 0)
  867. {
  868. foreach (string warning in warnings)
  869. {
  870. if (!m_ScriptErrors.ContainsKey(itemID))
  871. m_ScriptErrors[itemID] = new ArrayList();
  872. m_ScriptErrors[itemID].Add(warning);
  873. // try
  874. // {
  875. // // DISPLAY WARNING INWORLD
  876. // string text = "Warning:\n" + warning;
  877. // if (text.Length > 1000)
  878. // text = text.Substring(0, 1000);
  879. // if (!ShowScriptSaveResponse(item.OwnerID,
  880. // assetID, text, true))
  881. // {
  882. // if (presence != null && (!postOnRez))
  883. // presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  884. //
  885. // World.SimChat(Utils.StringToBytes(text),
  886. // ChatTypeEnum.DebugChannel, 2147483647,
  887. // part.AbsolutePosition,
  888. // part.Name, part.UUID, false);
  889. // }
  890. // }
  891. // catch (Exception e2) // LEGIT: User Scripting
  892. // {
  893. // m_log.Error("[XEngine]: " +
  894. // "Error displaying warning in-world: " +
  895. // e2.ToString());
  896. // m_log.Error("[XEngine]: " +
  897. // "Warning:\r\n" +
  898. // warning);
  899. // }
  900. }
  901. }
  902. }
  903. catch (Exception e)
  904. {
  905. // m_log.ErrorFormat("[XEngine]: Exception when rezzing script {0}{1}", e.Message, e.StackTrace);
  906. // try
  907. // {
  908. if (!m_ScriptErrors.ContainsKey(itemID))
  909. m_ScriptErrors[itemID] = new ArrayList();
  910. // DISPLAY ERROR INWORLD
  911. // m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
  912. //
  913. m_ScriptFailCount++;
  914. m_ScriptErrors[itemID].Add(e.Message.ToString());
  915. // string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
  916. // if (text.Length > 1000)
  917. // text = text.Substring(0, 1000);
  918. // if (!ShowScriptSaveResponse(item.OwnerID,
  919. // assetID, text, false))
  920. // {
  921. // if (presence != null && (!postOnRez))
  922. // presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  923. // World.SimChat(Utils.StringToBytes(text),
  924. // ChatTypeEnum.DebugChannel, 2147483647,
  925. // part.AbsolutePosition,
  926. // part.Name, part.UUID, false);
  927. // }
  928. // }
  929. // catch (Exception e2) // LEGIT: User Scripting
  930. // {
  931. // m_log.Error("[XEngine]: "+
  932. // "Error displaying error in-world: " +
  933. // e2.ToString());
  934. // m_log.Error("[XEngine]: " +
  935. // "Errormessage: Error compiling script:\r\n" +
  936. // e.Message.ToString());
  937. // }
  938. return false;
  939. }
  940. }
  941. ScriptInstance instance = null;
  942. lock (m_Scripts)
  943. {
  944. // Create the object record
  945. if ((!m_Scripts.ContainsKey(itemID)) ||
  946. (m_Scripts[itemID].AssetID != assetID))
  947. {
  948. UUID appDomain = assetID;
  949. if (part.ParentGroup.IsAttachment)
  950. appDomain = part.ParentGroup.RootPart.UUID;
  951. if (!m_AppDomains.ContainsKey(appDomain))
  952. {
  953. try
  954. {
  955. AppDomainSetup appSetup = new AppDomainSetup();
  956. appSetup.PrivateBinPath = Path.Combine(
  957. m_ScriptEnginesPath,
  958. m_Scene.RegionInfo.RegionID.ToString());
  959. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  960. Evidence evidence = new Evidence(baseEvidence);
  961. AppDomain sandbox;
  962. if (m_AppDomainLoading)
  963. {
  964. sandbox = AppDomain.CreateDomain(
  965. m_Scene.RegionInfo.RegionID.ToString(),
  966. evidence, appSetup);
  967. sandbox.AssemblyResolve +=
  968. new ResolveEventHandler(
  969. AssemblyResolver.OnAssemblyResolve);
  970. }
  971. else
  972. {
  973. sandbox = AppDomain.CurrentDomain;
  974. }
  975. //PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  976. //AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  977. //PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  978. //PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  979. //CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  980. //sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  981. //sandbox.SetAppDomainPolicy(sandboxPolicy);
  982. m_AppDomains[appDomain] = sandbox;
  983. m_DomainScripts[appDomain] = new List<UUID>();
  984. }
  985. catch (Exception e)
  986. {
  987. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  988. m_ScriptErrorMessage += "Exception creating app domain:\n";
  989. m_ScriptFailCount++;
  990. lock (m_AddingAssemblies)
  991. {
  992. m_AddingAssemblies[assembly]--;
  993. }
  994. return false;
  995. }
  996. }
  997. m_DomainScripts[appDomain].Add(itemID);
  998. instance = new ScriptInstance(this, part,
  999. itemID, assetID, assembly,
  1000. m_AppDomains[appDomain],
  1001. part.ParentGroup.RootPart.Name,
  1002. item.Name, startParam, postOnRez,
  1003. stateSource, m_MaxScriptQueue);
  1004. // if (DebugLevel >= 1)
  1005. // m_log.DebugFormat(
  1006. // "[XEngine] Loaded script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
  1007. // part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
  1008. // part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  1009. if (presence != null)
  1010. {
  1011. ShowScriptSaveResponse(item.OwnerID,
  1012. assetID, "Compile successful", true);
  1013. }
  1014. instance.AppDomain = appDomain;
  1015. instance.LineMap = linemap;
  1016. m_Scripts[itemID] = instance;
  1017. }
  1018. }
  1019. lock (m_PrimObjects)
  1020. {
  1021. if (!m_PrimObjects.ContainsKey(localID))
  1022. m_PrimObjects[localID] = new List<UUID>();
  1023. if (!m_PrimObjects[localID].Contains(itemID))
  1024. m_PrimObjects[localID].Add(itemID);
  1025. }
  1026. if (!m_Assemblies.ContainsKey(assetID))
  1027. m_Assemblies[assetID] = assembly;
  1028. lock (m_AddingAssemblies)
  1029. {
  1030. m_AddingAssemblies[assembly]--;
  1031. }
  1032. if (instance != null)
  1033. instance.Init();
  1034. bool runIt;
  1035. if (m_runFlags.TryGetValue(itemID, out runIt))
  1036. {
  1037. if (!runIt)
  1038. StopScript(itemID);
  1039. m_runFlags.Remove(itemID);
  1040. }
  1041. return true;
  1042. }
  1043. public void OnRemoveScript(uint localID, UUID itemID)
  1044. {
  1045. // If it's not yet been compiled, make sure we don't try
  1046. lock (m_CompileDict)
  1047. {
  1048. if (m_CompileDict.ContainsKey(itemID))
  1049. m_CompileDict.Remove(itemID);
  1050. }
  1051. IScriptInstance instance = null;
  1052. lock (m_Scripts)
  1053. {
  1054. // Do we even have it?
  1055. if (!m_Scripts.ContainsKey(itemID))
  1056. return;
  1057. instance = m_Scripts[itemID];
  1058. m_Scripts.Remove(itemID);
  1059. }
  1060. instance.ClearQueue();
  1061. // Give the script some time to finish processing its last event. Simply aborting the script thread can
  1062. // cause issues on mono 2.6, 2.10 and possibly later where locks are not released properly on abort.
  1063. instance.Stop(1000);
  1064. // bool objectRemoved = false;
  1065. lock (m_PrimObjects)
  1066. {
  1067. // Remove the script from it's prim
  1068. if (m_PrimObjects.ContainsKey(localID))
  1069. {
  1070. // Remove inventory item record
  1071. if (m_PrimObjects[localID].Contains(itemID))
  1072. m_PrimObjects[localID].Remove(itemID);
  1073. // If there are no more scripts, remove prim
  1074. if (m_PrimObjects[localID].Count == 0)
  1075. {
  1076. m_PrimObjects.Remove(localID);
  1077. // objectRemoved = true;
  1078. }
  1079. }
  1080. }
  1081. instance.RemoveState();
  1082. instance.DestroyScriptInstance();
  1083. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  1084. if (m_DomainScripts[instance.AppDomain].Count == 0)
  1085. {
  1086. m_DomainScripts.Remove(instance.AppDomain);
  1087. UnloadAppDomain(instance.AppDomain);
  1088. }
  1089. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  1090. if (handlerObjectRemoved != null)
  1091. handlerObjectRemoved(instance.ObjectID);
  1092. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  1093. if (handlerScriptRemoved != null)
  1094. handlerScriptRemoved(itemID);
  1095. }
  1096. public void OnScriptReset(uint localID, UUID itemID)
  1097. {
  1098. ResetScript(itemID);
  1099. }
  1100. public void OnStartScript(uint localID, UUID itemID)
  1101. {
  1102. StartScript(itemID);
  1103. }
  1104. public void OnStopScript(uint localID, UUID itemID)
  1105. {
  1106. StopScript(itemID);
  1107. }
  1108. private void CleanAssemblies()
  1109. {
  1110. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  1111. foreach (IScriptInstance i in m_Scripts.Values)
  1112. {
  1113. if (assetIDList.Contains(i.AssetID))
  1114. assetIDList.Remove(i.AssetID);
  1115. }
  1116. lock (m_AddingAssemblies)
  1117. {
  1118. foreach (UUID assetID in assetIDList)
  1119. {
  1120. // Do not remove assembly files if another instance of the script
  1121. // is currently initialising
  1122. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  1123. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  1124. {
  1125. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  1126. try
  1127. {
  1128. if (File.Exists(m_Assemblies[assetID]))
  1129. File.Delete(m_Assemblies[assetID]);
  1130. if (File.Exists(m_Assemblies[assetID]+".text"))
  1131. File.Delete(m_Assemblies[assetID]+".text");
  1132. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  1133. File.Delete(m_Assemblies[assetID]+".mdb");
  1134. if (File.Exists(m_Assemblies[assetID]+".map"))
  1135. File.Delete(m_Assemblies[assetID]+".map");
  1136. }
  1137. catch (Exception)
  1138. {
  1139. }
  1140. m_Assemblies.Remove(assetID);
  1141. }
  1142. }
  1143. }
  1144. }
  1145. private void UnloadAppDomain(UUID id)
  1146. {
  1147. if (m_AppDomains.ContainsKey(id))
  1148. {
  1149. AppDomain domain = m_AppDomains[id];
  1150. m_AppDomains.Remove(id);
  1151. if (domain != AppDomain.CurrentDomain)
  1152. AppDomain.Unload(domain);
  1153. domain = null;
  1154. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  1155. }
  1156. }
  1157. //
  1158. // Start processing
  1159. //
  1160. private void SetupEngine(int minThreads, int maxThreads,
  1161. int idleTimeout, ThreadPriority threadPriority,
  1162. int maxScriptQueue, int stackSize)
  1163. {
  1164. m_MaxScriptQueue = maxScriptQueue;
  1165. STPStartInfo startInfo = new STPStartInfo();
  1166. startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
  1167. startInfo.MaxWorkerThreads = maxThreads;
  1168. startInfo.MinWorkerThreads = minThreads;
  1169. startInfo.ThreadPriority = threadPriority;;
  1170. startInfo.StackSize = stackSize;
  1171. startInfo.StartSuspended = true;
  1172. m_ThreadPool = new SmartThreadPool(startInfo);
  1173. }
  1174. //
  1175. // Used by script instances to queue event handler jobs
  1176. //
  1177. public IScriptWorkItem QueueEventHandler(object parms)
  1178. {
  1179. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  1180. new WorkItemCallback(this.ProcessEventHandler),
  1181. parms));
  1182. }
  1183. /// <summary>
  1184. /// Process a previously posted script event.
  1185. /// </summary>
  1186. /// <param name="parms"></param>
  1187. /// <returns></returns>
  1188. private object ProcessEventHandler(object parms)
  1189. {
  1190. CultureInfo USCulture = new CultureInfo("en-US");
  1191. Thread.CurrentThread.CurrentCulture = USCulture;
  1192. IScriptInstance instance = (ScriptInstance) parms;
  1193. //m_log.DebugFormat("[XEngine]: Processing event for {0}", instance);
  1194. return instance.EventProcessor();
  1195. }
  1196. /// <summary>
  1197. /// Post event to an entire prim
  1198. /// </summary>
  1199. /// <param name="localID"></param>
  1200. /// <param name="p"></param>
  1201. /// <returns></returns>
  1202. public bool PostObjectEvent(uint localID, EventParams p)
  1203. {
  1204. bool result = false;
  1205. List<UUID> uuids = null;
  1206. lock (m_PrimObjects)
  1207. {
  1208. if (!m_PrimObjects.ContainsKey(localID))
  1209. return false;
  1210. uuids = m_PrimObjects[localID];
  1211. foreach (UUID itemID in uuids)
  1212. {
  1213. IScriptInstance instance = null;
  1214. try
  1215. {
  1216. if (m_Scripts.ContainsKey(itemID))
  1217. instance = m_Scripts[itemID];
  1218. }
  1219. catch { /* ignore race conditions */ }
  1220. if (instance != null)
  1221. {
  1222. instance.PostEvent(p);
  1223. result = true;
  1224. }
  1225. }
  1226. }
  1227. return result;
  1228. }
  1229. /// <summary>
  1230. /// Post an event to a single script
  1231. /// </summary>
  1232. /// <param name="itemID"></param>
  1233. /// <param name="p"></param>
  1234. /// <returns></returns>
  1235. public bool PostScriptEvent(UUID itemID, EventParams p)
  1236. {
  1237. if (m_Scripts.ContainsKey(itemID))
  1238. {
  1239. IScriptInstance instance = m_Scripts[itemID];
  1240. if (instance != null)
  1241. instance.PostEvent(p);
  1242. return true;
  1243. }
  1244. return false;
  1245. }
  1246. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  1247. {
  1248. Object[] lsl_p = new Object[p.Length];
  1249. for (int i = 0; i < p.Length ; i++)
  1250. {
  1251. if (p[i] is int)
  1252. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  1253. else if (p[i] is string)
  1254. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  1255. else if (p[i] is Vector3)
  1256. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  1257. else if (p[i] is Quaternion)
  1258. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  1259. else if (p[i] is float)
  1260. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  1261. else
  1262. lsl_p[i] = p[i];
  1263. }
  1264. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  1265. }
  1266. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  1267. {
  1268. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  1269. if (part == null)
  1270. return false;
  1271. Object[] lsl_p = new Object[p.Length];
  1272. for (int i = 0; i < p.Length ; i++)
  1273. {
  1274. if (p[i] is int)
  1275. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  1276. else if (p[i] is string)
  1277. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  1278. else if (p[i] is Vector3)
  1279. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  1280. else if (p[i] is Quaternion)
  1281. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  1282. else if (p[i] is float)
  1283. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  1284. else
  1285. lsl_p[i] = p[i];
  1286. }
  1287. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  1288. }
  1289. public Assembly OnAssemblyResolve(object sender,
  1290. ResolveEventArgs args)
  1291. {
  1292. if (!(sender is System.AppDomain))
  1293. return null;
  1294. string[] pathList = new string[] {"bin", m_ScriptEnginesPath,
  1295. Path.Combine(m_ScriptEnginesPath,
  1296. m_Scene.RegionInfo.RegionID.ToString())};
  1297. string assemblyName = args.Name;
  1298. if (assemblyName.IndexOf(",") != -1)
  1299. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  1300. foreach (string s in pathList)
  1301. {
  1302. string path = Path.Combine(Directory.GetCurrentDirectory(),
  1303. Path.Combine(s, assemblyName))+".dll";
  1304. // Console.WriteLine("[XEngine]: Trying to resolve {0}", path);
  1305. if (File.Exists(path))
  1306. return Assembly.LoadFrom(path);
  1307. }
  1308. return null;
  1309. }
  1310. private IScriptInstance GetInstance(UUID itemID)
  1311. {
  1312. IScriptInstance instance;
  1313. lock (m_Scripts)
  1314. {
  1315. if (!m_Scripts.ContainsKey(itemID))
  1316. return null;
  1317. instance = m_Scripts[itemID];
  1318. }
  1319. return instance;
  1320. }
  1321. public void SetScriptState(UUID itemID, bool running)
  1322. {
  1323. IScriptInstance instance = GetInstance(itemID);
  1324. if (instance != null)
  1325. {
  1326. if (running)
  1327. instance.Start();
  1328. else
  1329. instance.Stop(100);
  1330. }
  1331. }
  1332. public bool GetScriptState(UUID itemID)
  1333. {
  1334. IScriptInstance instance = GetInstance(itemID);
  1335. if (instance != null)
  1336. return instance.Running;
  1337. return false;
  1338. }
  1339. public void ApiResetScript(UUID itemID)
  1340. {
  1341. IScriptInstance instance = GetInstance(itemID);
  1342. if (instance != null)
  1343. instance.ApiResetScript();
  1344. }
  1345. public void ResetScript(UUID itemID)
  1346. {
  1347. IScriptInstance instance = GetInstance(itemID);
  1348. if (instance != null)
  1349. instance.ResetScript();
  1350. }
  1351. public void StartScript(UUID itemID)
  1352. {
  1353. IScriptInstance instance = GetInstance(itemID);
  1354. if (instance != null)
  1355. instance.Start();
  1356. else
  1357. m_runFlags.AddOrUpdate(itemID, true, 240);
  1358. }
  1359. public void StopScript(UUID itemID)
  1360. {
  1361. IScriptInstance instance = GetInstance(itemID);
  1362. if (instance != null)
  1363. {
  1364. // Give the script some time to finish processing its last event. Simply aborting the script thread can
  1365. // cause issues on mono 2.6, 2.10 and possibly later where locks are not released properly on abort.
  1366. instance.Stop(1000);
  1367. }
  1368. else
  1369. {
  1370. m_runFlags.AddOrUpdate(itemID, false, 240);
  1371. }
  1372. }
  1373. public DetectParams GetDetectParams(UUID itemID, int idx)
  1374. {
  1375. IScriptInstance instance = GetInstance(itemID);
  1376. if (instance != null)
  1377. return instance.GetDetectParams(idx);
  1378. return null;
  1379. }
  1380. public void SetMinEventDelay(UUID itemID, double delay)
  1381. {
  1382. IScriptInstance instance = GetInstance(itemID);
  1383. if (instance != null)
  1384. instance.MinEventDelay = delay;
  1385. }
  1386. public UUID GetDetectID(UUID itemID, int idx)
  1387. {
  1388. IScriptInstance instance = GetInstance(itemID);
  1389. if (instance != null)
  1390. return instance.GetDetectID(idx);
  1391. return UUID.Zero;
  1392. }
  1393. public void SetState(UUID itemID, string newState)
  1394. {
  1395. IScriptInstance instance = GetInstance(itemID);
  1396. if (instance == null)
  1397. return;
  1398. instance.SetState(newState);
  1399. }
  1400. public int GetStartParameter(UUID itemID)
  1401. {
  1402. IScriptInstance instance = GetInstance(itemID);
  1403. if (instance == null)
  1404. return 0;
  1405. return instance.StartParam;
  1406. }
  1407. public void OnShutdown()
  1408. {
  1409. m_SimulatorShuttingDown = true;
  1410. List<IScriptInstance> instances = new List<IScriptInstance>();
  1411. lock (m_Scripts)
  1412. {
  1413. foreach (IScriptInstance instance in m_Scripts.Values)
  1414. instances.Add(instance);
  1415. }
  1416. foreach (IScriptInstance i in instances)
  1417. {
  1418. // Stop the script, even forcibly if needed. Then flag
  1419. // it as shutting down and restore the previous run state
  1420. // for serialization, so the scripts don't come back
  1421. // dead after region restart
  1422. //
  1423. bool prevRunning = i.Running;
  1424. i.Stop(50);
  1425. i.ShuttingDown = true;
  1426. i.Running = prevRunning;
  1427. }
  1428. DoBackup(new Object[] {0});
  1429. }
  1430. public IScriptApi GetApi(UUID itemID, string name)
  1431. {
  1432. IScriptInstance instance = GetInstance(itemID);
  1433. if (instance == null)
  1434. return null;
  1435. return instance.GetApi(name);
  1436. }
  1437. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1438. {
  1439. IScriptInstance instance = GetInstance(itemID);
  1440. if (instance == null)
  1441. return;
  1442. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1443. if (eq == null)
  1444. {
  1445. controllingClient.SendScriptRunningReply(objectID, itemID,
  1446. GetScriptState(itemID));
  1447. }
  1448. else
  1449. {
  1450. eq.Enqueue(eq.ScriptRunningEvent(objectID, itemID, GetScriptState(itemID), true),
  1451. controllingClient.AgentId);
  1452. }
  1453. }
  1454. public string GetXMLState(UUID itemID)
  1455. {
  1456. // m_log.DebugFormat("[XEngine]: Getting XML state for script instance {0}", itemID);
  1457. IScriptInstance instance = GetInstance(itemID);
  1458. if (instance == null)
  1459. {
  1460. // m_log.DebugFormat("[XEngine]: Found no script instance for {0}, returning empty string", itemID);
  1461. return "";
  1462. }
  1463. string xml = instance.GetXMLState();
  1464. XmlDocument sdoc = new XmlDocument();
  1465. bool loadedState = true;
  1466. try
  1467. {
  1468. sdoc.LoadXml(xml);
  1469. }
  1470. catch (System.Xml.XmlException)
  1471. {
  1472. loadedState = false;
  1473. }
  1474. XmlNodeList rootL = null;
  1475. XmlNode rootNode = null;
  1476. if (loadedState)
  1477. {
  1478. rootL = sdoc.GetElementsByTagName("ScriptState");
  1479. rootNode = rootL[0];
  1480. }
  1481. // Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
  1482. XmlDocument doc = new XmlDocument();
  1483. XmlElement stateData = doc.CreateElement("", "State", "");
  1484. XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
  1485. stateID.Value = itemID.ToString();
  1486. stateData.Attributes.Append(stateID);
  1487. XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
  1488. assetID.Value = instance.AssetID.ToString();
  1489. stateData.Attributes.Append(assetID);
  1490. XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
  1491. engineName.Value = ScriptEngineName;
  1492. stateData.Attributes.Append(engineName);
  1493. doc.AppendChild(stateData);
  1494. XmlNode xmlstate = null;
  1495. // Add <ScriptState>...</ScriptState>
  1496. if (loadedState)
  1497. {
  1498. xmlstate = doc.ImportNode(rootNode, true);
  1499. }
  1500. else
  1501. {
  1502. xmlstate = doc.CreateElement("", "ScriptState", "");
  1503. }
  1504. stateData.AppendChild(xmlstate);
  1505. string assemName = instance.GetAssemblyName();
  1506. string fn = Path.GetFileName(assemName);
  1507. string assem = String.Empty;
  1508. if (File.Exists(assemName + ".text"))
  1509. {
  1510. FileInfo tfi = new FileInfo(assemName + ".text");
  1511. if (tfi != null)
  1512. {
  1513. Byte[] tdata = new Byte[tfi.Length];
  1514. try
  1515. {
  1516. using (FileStream tfs = File.Open(assemName + ".text",
  1517. FileMode.Open, FileAccess.Read))
  1518. {
  1519. tfs.Read(tdata, 0, tdata.Length);
  1520. }
  1521. assem = Encoding.ASCII.GetString(tdata);
  1522. }
  1523. catch (Exception e)
  1524. {
  1525. m_log.ErrorFormat(
  1526. "[XEngine]: Unable to open script textfile {0}{1}, reason: {2}",
  1527. assemName, ".text", e.Message);
  1528. }
  1529. }
  1530. }
  1531. else
  1532. {
  1533. FileInfo fi = new FileInfo(assemName);
  1534. if (fi != null)
  1535. {
  1536. Byte[] data = new Byte[fi.Length];
  1537. try
  1538. {
  1539. using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
  1540. {
  1541. fs.Read(data, 0, data.Length);
  1542. }
  1543. assem = System.Convert.ToBase64String(data);
  1544. }
  1545. catch (Exception e)
  1546. {
  1547. m_log.ErrorFormat(
  1548. "[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
  1549. }
  1550. }
  1551. }
  1552. string map = String.Empty;
  1553. if (File.Exists(fn + ".map"))
  1554. {
  1555. using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
  1556. {
  1557. using (StreamReader msr = new StreamReader(mfs))
  1558. {
  1559. map = msr.ReadToEnd();
  1560. }
  1561. }
  1562. }
  1563. XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
  1564. XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
  1565. assemblyName.Value = fn;
  1566. assemblyData.Attributes.Append(assemblyName);
  1567. assemblyData.InnerText = assem;
  1568. stateData.AppendChild(assemblyData);
  1569. XmlElement mapData = doc.CreateElement("", "LineMap", "");
  1570. XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
  1571. mapName.Value = fn + ".map";
  1572. mapData.Attributes.Append(mapName);
  1573. mapData.InnerText = map;
  1574. stateData.AppendChild(mapData);
  1575. // m_log.DebugFormat("[XEngine]: Got XML state for {0}", itemID);
  1576. return doc.InnerXml;
  1577. }
  1578. private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
  1579. {
  1580. return false;
  1581. }
  1582. public bool SetXMLState(UUID itemID, string xml)
  1583. {
  1584. // m_log.DebugFormat("[XEngine]: Writing state for script item with ID {0}", itemID);
  1585. if (xml == String.Empty)
  1586. return false;
  1587. XmlDocument doc = new XmlDocument();
  1588. try
  1589. {
  1590. doc.LoadXml(xml);
  1591. }
  1592. catch (Exception)
  1593. {
  1594. m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
  1595. return false;
  1596. }
  1597. XmlNodeList rootL = doc.GetElementsByTagName("State");
  1598. if (rootL.Count < 1)
  1599. return false;
  1600. XmlElement rootE = (XmlElement)rootL[0];
  1601. if (rootE.GetAttribute("Engine") != ScriptEngineName)
  1602. return false;
  1603. // On rez from inventory, that ID will have changed. It was only
  1604. // advisory anyway. So we don't check it anymore.
  1605. //
  1606. // if (rootE.GetAttribute("UUID") != itemID.ToString())
  1607. // return;
  1608. XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
  1609. if (stateL.Count != 1)
  1610. return false;
  1611. XmlElement stateE = (XmlElement)stateL[0];
  1612. if (World.m_trustBinaries)
  1613. {
  1614. XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
  1615. if (assemL.Count != 1)
  1616. return false;
  1617. XmlElement assemE = (XmlElement)assemL[0];
  1618. string fn = assemE.GetAttribute("Filename");
  1619. string base64 = assemE.InnerText;
  1620. string path = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1621. path = Path.Combine(path, fn);
  1622. if (!File.Exists(path))
  1623. {
  1624. Byte[] filedata = Convert.FromBase64String(base64);
  1625. try
  1626. {
  1627. using (FileStream fs = File.Create(path))
  1628. {
  1629. // m_log.DebugFormat("[XEngine]: Writing assembly file {0}", path);
  1630. fs.Write(filedata, 0, filedata.Length);
  1631. }
  1632. }
  1633. catch (IOException ex)
  1634. {
  1635. // if there already exists a file at that location, it may be locked.
  1636. m_log.ErrorFormat("[XEngine]: Error whilst writing assembly file {0}, {1}", path, ex.Message);
  1637. }
  1638. string textpath = path + ".text";
  1639. try
  1640. {
  1641. using (FileStream fs = File.Create(textpath))
  1642. {
  1643. using (StreamWriter sw = new StreamWriter(fs))
  1644. {
  1645. // m_log.DebugFormat("[XEngine]: Writing .text file {0}", textpath);
  1646. sw.Write(base64);
  1647. }
  1648. }
  1649. }
  1650. catch (IOException ex)
  1651. {
  1652. // if there already exists a file at that location, it may be locked.
  1653. m_log.ErrorFormat("[XEngine]: Error whilst writing .text file {0}, {1}", textpath, ex.Message);
  1654. }
  1655. }
  1656. XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
  1657. if (mapL.Count > 0)
  1658. {
  1659. XmlElement mapE = (XmlElement)mapL[0];
  1660. string mappath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1661. mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
  1662. try
  1663. {
  1664. using (FileStream mfs = File.Create(mappath))
  1665. {
  1666. using (StreamWriter msw = new StreamWriter(mfs))
  1667. {
  1668. // m_log.DebugFormat("[XEngine]: Writing linemap file {0}", mappath);
  1669. msw.Write(mapE.InnerText);
  1670. }
  1671. }
  1672. }
  1673. catch (IOException ex)
  1674. {
  1675. // if there already exists a file at that location, it may be locked.
  1676. m_log.ErrorFormat("[XEngine]: Linemap file {0} already exists! {1}", mappath, ex.Message);
  1677. }
  1678. }
  1679. }
  1680. string statepath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1681. statepath = Path.Combine(statepath, itemID.ToString() + ".state");
  1682. try
  1683. {
  1684. using (FileStream sfs = File.Create(statepath))
  1685. {
  1686. using (StreamWriter ssw = new StreamWriter(sfs))
  1687. {
  1688. // m_log.DebugFormat("[XEngine]: Writing state file {0}", statepath);
  1689. ssw.Write(stateE.OuterXml);
  1690. }
  1691. }
  1692. }
  1693. catch (IOException ex)
  1694. {
  1695. // if there already exists a file at that location, it may be locked.
  1696. m_log.ErrorFormat("[XEngine]: Error whilst writing state file {0}, {1}", statepath, ex.Message);
  1697. }
  1698. return true;
  1699. }
  1700. public ArrayList GetScriptErrors(UUID itemID)
  1701. {
  1702. System.Threading.Thread.Sleep(1000);
  1703. lock (m_ScriptErrors)
  1704. {
  1705. if (m_ScriptErrors.ContainsKey(itemID))
  1706. {
  1707. ArrayList ret = m_ScriptErrors[itemID];
  1708. m_ScriptErrors.Remove(itemID);
  1709. return ret;
  1710. }
  1711. return new ArrayList();
  1712. }
  1713. }
  1714. public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
  1715. {
  1716. long tickNow = Util.EnvironmentTickCount();
  1717. Dictionary<uint, float> topScripts = new Dictionary<uint, float>();
  1718. lock (m_Scripts)
  1719. {
  1720. foreach (IScriptInstance si in m_Scripts.Values)
  1721. {
  1722. if (!topScripts.ContainsKey(si.LocalID))
  1723. topScripts[si.RootLocalID] = 0;
  1724. topScripts[si.RootLocalID] += CalculateAdjustedExectionTime(si, tickNow);
  1725. }
  1726. }
  1727. return topScripts;
  1728. }
  1729. public float GetScriptExecutionTime(List<UUID> itemIDs)
  1730. {
  1731. if (itemIDs == null|| itemIDs.Count == 0)
  1732. {
  1733. return 0.0f;
  1734. }
  1735. float time = 0.0f;
  1736. long tickNow = Util.EnvironmentTickCount();
  1737. IScriptInstance si;
  1738. // Calculate the time for all scripts that this engine is executing
  1739. // Ignore any others
  1740. foreach (UUID id in itemIDs)
  1741. {
  1742. si = GetInstance(id);
  1743. if (si != null && si.Running)
  1744. {
  1745. time += CalculateAdjustedExectionTime(si, tickNow);
  1746. }
  1747. }
  1748. return time;
  1749. }
  1750. private float CalculateAdjustedExectionTime(IScriptInstance si, long tickNow)
  1751. {
  1752. long ticksElapsed = tickNow - si.MeasurementPeriodTickStart;
  1753. // Avoid divide by zero
  1754. if (ticksElapsed == 0)
  1755. ticksElapsed = 1;
  1756. // Scale execution time to the ideal 55 fps frame time for these reasons.
  1757. //
  1758. // 1) XEngine does not execute scripts per frame, unlike other script engines. Hence, there is no
  1759. // 'script execution time per frame', which is the original purpose of this value.
  1760. //
  1761. // 2) Giving the raw execution times is misleading since scripts start at different times, making
  1762. // it impossible to compare scripts.
  1763. //
  1764. // 3) Scaling the raw execution time to the time that the script has been running is better but
  1765. // is still misleading since a script that has just been rezzed may appear to have been running
  1766. // for much longer.
  1767. //
  1768. // 4) Hence, we scale execution time to an idealised frame time (55 fps). This is also not perfect
  1769. // since the figure does not represent actual execution time and very hard running scripts will
  1770. // never exceed 18ms (though this is a very high number for script execution so is a warning sign).
  1771. return ((float)si.MeasurementPeriodExecutionTime / ticksElapsed) * 18.1818f;
  1772. }
  1773. public void SuspendScript(UUID itemID)
  1774. {
  1775. // m_log.DebugFormat("[XEngine]: Received request to suspend script with ID {0}", itemID);
  1776. IScriptInstance instance = GetInstance(itemID);
  1777. if (instance != null)
  1778. instance.Suspend();
  1779. // else
  1780. // m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
  1781. }
  1782. public void ResumeScript(UUID itemID)
  1783. {
  1784. // m_log.DebugFormat("[XEngine]: Received request to resume script with ID {0}", itemID);
  1785. IScriptInstance instance = GetInstance(itemID);
  1786. if (instance != null)
  1787. instance.Resume();
  1788. // else
  1789. // m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
  1790. }
  1791. public bool HasScript(UUID itemID, out bool running)
  1792. {
  1793. running = true;
  1794. IScriptInstance instance = GetInstance(itemID);
  1795. if (instance == null)
  1796. return false;
  1797. running = instance.Running;
  1798. return true;
  1799. }
  1800. }
  1801. }