XEngine.cs 90 KB

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