XEngine.cs 99 KB

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