XEngine.cs 97 KB

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