XEngine.cs 88 KB

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