XEngine.cs 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457
  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.Stop(0);
  583. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  584. MainConsole.Instance.OutputFormat(
  585. "Stopped {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  586. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  587. }
  588. }
  589. public void RemoveRegion(Scene scene)
  590. {
  591. if (!m_Enabled)
  592. return;
  593. lock (m_Scripts)
  594. {
  595. m_log.InfoFormat(
  596. "[XEngine]: Shutting down {0} scripts in {1}", m_Scripts.Count, m_Scene.RegionInfo.RegionName);
  597. foreach (IScriptInstance instance in m_Scripts.Values)
  598. {
  599. // Force a final state save
  600. //
  601. try
  602. {
  603. if (instance.StatePersistedHere)
  604. instance.SaveState();
  605. }
  606. catch (Exception e)
  607. {
  608. m_log.Error(
  609. string.Format(
  610. "[XEngine]: Failed final state save for script {0}.{1}, item UUID {2}, prim UUID {3} in {4}. Exception ",
  611. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, World.Name)
  612. , e);
  613. }
  614. // Clear the event queue and abort the instance thread
  615. //
  616. instance.Stop(0, true);
  617. // Release events, timer, etc
  618. //
  619. instance.DestroyScriptInstance();
  620. // Unload scripts and app domains.
  621. // Must be done explicitly because they have infinite
  622. // lifetime.
  623. // However, don't bother to do this if the simulator is shutting
  624. // down since it takes a long time with many scripts.
  625. if (!m_SimulatorShuttingDown)
  626. {
  627. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  628. if (m_DomainScripts[instance.AppDomain].Count == 0)
  629. {
  630. m_DomainScripts.Remove(instance.AppDomain);
  631. UnloadAppDomain(instance.AppDomain);
  632. }
  633. }
  634. }
  635. m_Scripts.Clear();
  636. m_PrimObjects.Clear();
  637. m_Assemblies.Clear();
  638. m_DomainScripts.Clear();
  639. }
  640. lock (m_ScriptEngines)
  641. {
  642. m_ScriptEngines.Remove(this);
  643. }
  644. }
  645. public void RegionLoaded(Scene scene)
  646. {
  647. if (!m_Enabled)
  648. return;
  649. m_EventManager = new EventManager(this);
  650. m_Compiler = new Compiler(this);
  651. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  652. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  653. m_Scene.EventManager.OnStartScript += OnStartScript;
  654. m_Scene.EventManager.OnStopScript += OnStopScript;
  655. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  656. m_Scene.EventManager.OnShutdown += OnShutdown;
  657. // If region ready has been triggered, then the region had no scripts to compile and completed its other
  658. // work.
  659. m_Scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) m_InitialStartup = false; };
  660. if (m_SleepTime > 0)
  661. {
  662. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  663. new Object[]{ m_SleepTime });
  664. }
  665. if (m_SaveTime > 0)
  666. {
  667. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  668. new Object[] { m_SaveTime });
  669. }
  670. }
  671. public void StartProcessing()
  672. {
  673. m_ThreadPool.Start();
  674. }
  675. public void Close()
  676. {
  677. if (!m_Enabled)
  678. return;
  679. lock (m_ScriptEngines)
  680. {
  681. if (m_ScriptEngines.Contains(this))
  682. m_ScriptEngines.Remove(this);
  683. }
  684. }
  685. public object DoBackup(object o)
  686. {
  687. Object[] p = (Object[])o;
  688. int saveTime = (int)p[0];
  689. if (saveTime > 0)
  690. System.Threading.Thread.Sleep(saveTime);
  691. // m_log.Debug("[XEngine] Backing up script states");
  692. List<IScriptInstance> instances = new List<IScriptInstance>();
  693. lock (m_Scripts)
  694. {
  695. foreach (IScriptInstance instance in m_Scripts.Values)
  696. {
  697. if (instance.StatePersistedHere)
  698. {
  699. // m_log.DebugFormat(
  700. // "[XEngine]: Adding script {0}.{1}, item UUID {2}, prim UUID {3} in {4} for state persistence",
  701. // instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, World.Name);
  702. instances.Add(instance);
  703. }
  704. }
  705. }
  706. foreach (IScriptInstance i in instances)
  707. {
  708. try
  709. {
  710. i.SaveState();
  711. }
  712. catch (Exception e)
  713. {
  714. m_log.Error(
  715. string.Format(
  716. "[XEngine]: Failed to save state of script {0}.{1}, item UUID {2}, prim UUID {3} in {4}. Exception ",
  717. i.PrimName, i.ScriptName, i.ItemID, i.ObjectID, World.Name)
  718. , e);
  719. }
  720. }
  721. if (saveTime > 0)
  722. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  723. new Object[] { saveTime });
  724. return 0;
  725. }
  726. public void SaveAllState()
  727. {
  728. DoBackup(new object[] { 0 });
  729. }
  730. public object DoMaintenance(object p)
  731. {
  732. object[] parms = (object[])p;
  733. int sleepTime = (int)parms[0];
  734. foreach (IScriptInstance inst in m_Scripts.Values)
  735. {
  736. if (inst.EventTime() > m_EventLimit)
  737. {
  738. inst.Stop(100);
  739. if (!m_KillTimedOutScripts)
  740. inst.Start();
  741. }
  742. }
  743. System.Threading.Thread.Sleep(sleepTime);
  744. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  745. new Object[]{ sleepTime });
  746. return 0;
  747. }
  748. public Type ReplaceableInterface
  749. {
  750. get { return null; }
  751. }
  752. public string Name
  753. {
  754. get { return "XEngine"; }
  755. }
  756. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  757. {
  758. // m_log.DebugFormat(
  759. // "[XEngine]: OnRezScript event triggered for script {0}, startParam {1}, postOnRez {2}, engine {3}, stateSource {4}, script\n{5}",
  760. // itemID, startParam, postOnRez, engine, stateSource, script);
  761. if (script.StartsWith("//MRM:"))
  762. return;
  763. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  764. List<string> names = new List<string>();
  765. foreach (IScriptModule m in engines)
  766. names.Add(m.ScriptEngineName);
  767. int lineEnd = script.IndexOf('\n');
  768. if (lineEnd > 1)
  769. {
  770. string firstline = script.Substring(0, lineEnd).Trim();
  771. int colon = firstline.IndexOf(':');
  772. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  773. {
  774. string engineName = firstline.Substring(2, colon - 2);
  775. if (names.Contains(engineName))
  776. {
  777. engine = engineName;
  778. script = "//" + script.Substring(colon + 1);
  779. }
  780. else
  781. {
  782. if (engine == ScriptEngineName)
  783. {
  784. // If we are falling back on XEngine as the default engine, then only complain to the user
  785. // if a script language has been explicitly set and it's one that we recognize or there are
  786. // no non-whitespace characters after the colon.
  787. //
  788. // If the script is
  789. // explicitly not allowed or the script is not in LSL then the user will be informed by a later compiler message.
  790. //
  791. // If the colon ends the line then we'll risk the false positive as this is more likely
  792. // to signal a real scriptengine line where the user wants to use the default compile language.
  793. //
  794. // This avoids the overwhelming number of false positives where we're in this code because
  795. // there's a colon in a comment in the first line of a script for entirely
  796. // unrelated reasons (e.g. vim settings).
  797. //
  798. // TODO: A better fix would be to deprecate simple : detection and look for some less likely
  799. // string to begin the comment (like #! in unix shell scripts).
  800. bool warnRunningInXEngine = false;
  801. string restOfFirstLine = firstline.Substring(colon + 1);
  802. // FIXME: These are hardcoded because they are currently hardcoded in Compiler.cs
  803. if (restOfFirstLine.StartsWith("c#")
  804. || restOfFirstLine.StartsWith("vb")
  805. || restOfFirstLine.StartsWith("lsl")
  806. || restOfFirstLine.Length == 0)
  807. warnRunningInXEngine = true;
  808. if (warnRunningInXEngine)
  809. {
  810. SceneObjectPart part =
  811. m_Scene.GetSceneObjectPart(
  812. localID);
  813. TaskInventoryItem item =
  814. part.Inventory.GetInventoryItem(itemID);
  815. ScenePresence presence =
  816. m_Scene.GetScenePresence(
  817. item.OwnerID);
  818. if (presence != null)
  819. {
  820. presence.ControllingClient.SendAgentAlertMessage(
  821. "Selected engine unavailable. "+
  822. "Running script on "+
  823. ScriptEngineName,
  824. false);
  825. }
  826. }
  827. }
  828. }
  829. }
  830. }
  831. if (engine != ScriptEngineName)
  832. return;
  833. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  834. if (stateSource == (int)StateSource.ScriptedRez)
  835. {
  836. lock (m_CompileDict)
  837. {
  838. m_CompileDict[itemID] = 0;
  839. }
  840. DoOnRezScript(parms);
  841. }
  842. else
  843. {
  844. lock (m_CompileDict)
  845. m_CompileDict[itemID] = 0;
  846. // This must occur after the m_CompileDict so that an existing compile thread cannot hit the check
  847. // in DoOnRezScript() before m_CompileDict has been updated.
  848. m_CompileQueue.Enqueue(parms);
  849. // m_log.DebugFormat("[XEngine]: Added script {0} to compile queue", itemID);
  850. if (m_CurrentCompile == null)
  851. {
  852. // NOTE: Although we use a lockless queue, the lock here
  853. // is required. It ensures that there are never two
  854. // compile threads running, which, due to a race
  855. // conndition, might otherwise happen
  856. //
  857. lock (m_CompileQueue)
  858. {
  859. if (m_CurrentCompile == null)
  860. m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
  861. }
  862. }
  863. }
  864. }
  865. public Object DoOnRezScriptQueue(Object dummy)
  866. {
  867. try
  868. {
  869. if (m_InitialStartup)
  870. {
  871. // This delay exists to stop mono problems where script compilation and startup would stop the sim
  872. // working properly for the session.
  873. System.Threading.Thread.Sleep(m_StartDelay);
  874. m_log.InfoFormat("[XEngine]: Performing initial script startup on {0}", m_Scene.Name);
  875. }
  876. object[] o;
  877. int scriptsStarted = 0;
  878. while (m_CompileQueue.Dequeue(out o))
  879. {
  880. try
  881. {
  882. if (DoOnRezScript(o))
  883. {
  884. scriptsStarted++;
  885. if (m_InitialStartup)
  886. if (scriptsStarted % 50 == 0)
  887. m_log.InfoFormat(
  888. "[XEngine]: Started {0} scripts in {1}", scriptsStarted, m_Scene.Name);
  889. }
  890. }
  891. catch (Exception e)
  892. {
  893. m_log.Error(
  894. string.Format(
  895. "[XEngine]: Failure in DoOnRezScriptQueue() for item {0} in {1}. Continuing. Exception ",
  896. o[1], m_Scene.Name),
  897. e);
  898. }
  899. }
  900. if (m_InitialStartup)
  901. m_log.InfoFormat(
  902. "[XEngine]: Completed starting {0} scripts on {1}", scriptsStarted, m_Scene.Name);
  903. }
  904. catch (Exception e)
  905. {
  906. m_log.Error(
  907. string.Format("[XEngine]: Failure in DoOnRezScriptQueue() in {0}. Exception ", m_Scene.Name), e);
  908. }
  909. finally
  910. {
  911. // FIXME: On failure we must trigger this even if the compile queue is not actually empty so that the
  912. // RegionReadyModule is not forever waiting. This event really needs a different name.
  913. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  914. m_ScriptErrorMessage);
  915. m_ScriptFailCount = 0;
  916. m_InitialStartup = false;
  917. // NOTE: Despite having a lockless queue, this lock is required
  918. // to make sure there is never no compile thread while there
  919. // are still scripts to compile. This could otherwise happen
  920. // due to a race condition
  921. //
  922. lock (m_CompileQueue)
  923. {
  924. m_CurrentCompile = null;
  925. // This is to avoid a situation where the m_CompileQueue while loop above could complete but
  926. // OnRezScript() place a new script on the queue and check m_CurrentCompile = null before we hit
  927. // this section.
  928. if (m_CompileQueue.Count > 0)
  929. m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
  930. }
  931. }
  932. return null;
  933. }
  934. private bool DoOnRezScript(object[] parms)
  935. {
  936. Object[] p = parms;
  937. uint localID = (uint)p[0];
  938. UUID itemID = (UUID)p[1];
  939. string script =(string)p[2];
  940. int startParam = (int)p[3];
  941. bool postOnRez = (bool)p[4];
  942. StateSource stateSource = (StateSource)p[5];
  943. // m_log.DebugFormat("[XEngine]: DoOnRezScript called for script {0}", itemID);
  944. lock (m_CompileDict)
  945. {
  946. if (!m_CompileDict.ContainsKey(itemID))
  947. return false;
  948. m_CompileDict.Remove(itemID);
  949. }
  950. // Get the asset ID of the script, so we can check if we
  951. // already have it.
  952. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  953. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  954. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  955. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  956. if (part == null)
  957. {
  958. m_log.ErrorFormat("[Script]: SceneObjectPart with localID {0} unavailable. Script NOT started.", localID);
  959. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  960. m_ScriptFailCount++;
  961. return false;
  962. }
  963. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  964. if (item == null)
  965. {
  966. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  967. m_ScriptFailCount++;
  968. return false;
  969. }
  970. if (DebugLevel > 0)
  971. m_log.DebugFormat(
  972. "[XEngine]: Loading script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
  973. part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
  974. part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  975. UUID assetID = item.AssetID;
  976. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  977. string assemblyPath = "";
  978. Culture.SetCurrentCulture();
  979. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  980. lock (m_ScriptErrors)
  981. {
  982. try
  983. {
  984. lock (m_AddingAssemblies)
  985. {
  986. m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assemblyPath, out linemap);
  987. // m_log.DebugFormat(
  988. // "[XENGINE]: Found assembly path {0} onrez {1} in {2}",
  989. // assemblyPath, item.ItemID, World.Name);
  990. if (!m_AddingAssemblies.ContainsKey(assemblyPath)) {
  991. m_AddingAssemblies[assemblyPath] = 1;
  992. } else {
  993. m_AddingAssemblies[assemblyPath]++;
  994. }
  995. }
  996. string[] warnings = m_Compiler.GetWarnings();
  997. if (warnings != null && warnings.Length != 0)
  998. {
  999. foreach (string warning in warnings)
  1000. {
  1001. if (!m_ScriptErrors.ContainsKey(itemID))
  1002. m_ScriptErrors[itemID] = new ArrayList();
  1003. m_ScriptErrors[itemID].Add(warning);
  1004. // try
  1005. // {
  1006. // // DISPLAY WARNING INWORLD
  1007. // string text = "Warning:\n" + warning;
  1008. // if (text.Length > 1000)
  1009. // text = text.Substring(0, 1000);
  1010. // if (!ShowScriptSaveResponse(item.OwnerID,
  1011. // assetID, text, true))
  1012. // {
  1013. // if (presence != null && (!postOnRez))
  1014. // presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  1015. //
  1016. // World.SimChat(Utils.StringToBytes(text),
  1017. // ChatTypeEnum.DebugChannel, 2147483647,
  1018. // part.AbsolutePosition,
  1019. // part.Name, part.UUID, false);
  1020. // }
  1021. // }
  1022. // catch (Exception e2) // LEGIT: User Scripting
  1023. // {
  1024. // m_log.Error("[XEngine]: " +
  1025. // "Error displaying warning in-world: " +
  1026. // e2.ToString());
  1027. // m_log.Error("[XEngine]: " +
  1028. // "Warning:\r\n" +
  1029. // warning);
  1030. // }
  1031. }
  1032. }
  1033. }
  1034. catch (Exception e)
  1035. {
  1036. // m_log.ErrorFormat(
  1037. // "[XEngine]: Exception when rezzing script with item ID {0}, {1}{2}",
  1038. // itemID, e.Message, e.StackTrace);
  1039. // try
  1040. // {
  1041. if (!m_ScriptErrors.ContainsKey(itemID))
  1042. m_ScriptErrors[itemID] = new ArrayList();
  1043. // DISPLAY ERROR INWORLD
  1044. // m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
  1045. //
  1046. m_ScriptFailCount++;
  1047. m_ScriptErrors[itemID].Add(e.Message.ToString());
  1048. // string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
  1049. // if (text.Length > 1000)
  1050. // text = text.Substring(0, 1000);
  1051. // if (!ShowScriptSaveResponse(item.OwnerID,
  1052. // assetID, text, false))
  1053. // {
  1054. // if (presence != null && (!postOnRez))
  1055. // presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  1056. // World.SimChat(Utils.StringToBytes(text),
  1057. // ChatTypeEnum.DebugChannel, 2147483647,
  1058. // part.AbsolutePosition,
  1059. // part.Name, part.UUID, false);
  1060. // }
  1061. // }
  1062. // catch (Exception e2) // LEGIT: User Scripting
  1063. // {
  1064. // m_log.Error("[XEngine]: "+
  1065. // "Error displaying error in-world: " +
  1066. // e2.ToString());
  1067. // m_log.Error("[XEngine]: " +
  1068. // "Errormessage: Error compiling script:\r\n" +
  1069. // e.Message.ToString());
  1070. // }
  1071. return false;
  1072. }
  1073. }
  1074. ScriptInstance instance = null;
  1075. lock (m_Scripts)
  1076. {
  1077. // Create the object record
  1078. if ((!m_Scripts.ContainsKey(itemID)) ||
  1079. (m_Scripts[itemID].AssetID != assetID))
  1080. {
  1081. UUID appDomain = assetID;
  1082. if (part.ParentGroup.IsAttachment)
  1083. appDomain = part.ParentGroup.RootPart.UUID;
  1084. if (!m_AppDomains.ContainsKey(appDomain))
  1085. {
  1086. try
  1087. {
  1088. AppDomainSetup appSetup = new AppDomainSetup();
  1089. appSetup.PrivateBinPath = Path.Combine(
  1090. m_ScriptEnginesPath,
  1091. m_Scene.RegionInfo.RegionID.ToString());
  1092. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  1093. Evidence evidence = new Evidence(baseEvidence);
  1094. AppDomain sandbox;
  1095. if (m_AppDomainLoading)
  1096. {
  1097. sandbox = AppDomain.CreateDomain(
  1098. m_Scene.RegionInfo.RegionID.ToString(),
  1099. evidence, appSetup);
  1100. sandbox.AssemblyResolve +=
  1101. new ResolveEventHandler(
  1102. AssemblyResolver.OnAssemblyResolve);
  1103. }
  1104. else
  1105. {
  1106. sandbox = AppDomain.CurrentDomain;
  1107. }
  1108. //PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  1109. //AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  1110. //PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  1111. //PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  1112. //CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  1113. //sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  1114. //sandbox.SetAppDomainPolicy(sandboxPolicy);
  1115. m_AppDomains[appDomain] = sandbox;
  1116. m_DomainScripts[appDomain] = new List<UUID>();
  1117. }
  1118. catch (Exception e)
  1119. {
  1120. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  1121. m_ScriptErrorMessage += "Exception creating app domain:\n";
  1122. m_ScriptFailCount++;
  1123. lock (m_AddingAssemblies)
  1124. {
  1125. m_AddingAssemblies[assemblyPath]--;
  1126. }
  1127. return false;
  1128. }
  1129. }
  1130. m_DomainScripts[appDomain].Add(itemID);
  1131. IScript scriptObj = null;
  1132. EventWaitHandle coopSleepHandle;
  1133. bool coopTerminationForThisScript;
  1134. // Set up assembly name to point to the appropriate scriptEngines directory
  1135. AssemblyName assemblyName = new AssemblyName(Path.GetFileNameWithoutExtension(assemblyPath));
  1136. assemblyName.CodeBase = Path.GetDirectoryName(assemblyPath);
  1137. if (m_coopTermination)
  1138. {
  1139. try
  1140. {
  1141. coopSleepHandle = new XEngineEventWaitHandle(false, EventResetMode.AutoReset);
  1142. scriptObj
  1143. = (IScript)m_AppDomains[appDomain].CreateInstanceAndUnwrap(
  1144. assemblyName.FullName,
  1145. "SecondLife.XEngineScript",
  1146. false,
  1147. BindingFlags.Default,
  1148. null,
  1149. new object[] { coopSleepHandle },
  1150. null,
  1151. null);
  1152. coopTerminationForThisScript = true;
  1153. }
  1154. catch (TypeLoadException)
  1155. {
  1156. coopSleepHandle = null;
  1157. try
  1158. {
  1159. scriptObj
  1160. = (IScript)m_AppDomains[appDomain].CreateInstanceAndUnwrap(
  1161. assemblyName.FullName,
  1162. "SecondLife.Script",
  1163. false,
  1164. BindingFlags.Default,
  1165. null,
  1166. null,
  1167. null,
  1168. null);
  1169. }
  1170. catch (Exception e2)
  1171. {
  1172. m_log.Error(
  1173. string.Format(
  1174. "[XENGINE]: Could not load previous SecondLife.Script from assembly {0} in {1}. Not starting. Exception ",
  1175. assemblyName.FullName, World.Name),
  1176. e2);
  1177. return false;
  1178. }
  1179. coopTerminationForThisScript = false;
  1180. }
  1181. }
  1182. else
  1183. {
  1184. try
  1185. {
  1186. scriptObj
  1187. = (IScript)m_AppDomains[appDomain].CreateInstanceAndUnwrap(
  1188. assemblyName.FullName,
  1189. "SecondLife.Script",
  1190. false,
  1191. BindingFlags.Default,
  1192. null,
  1193. null,
  1194. null,
  1195. null);
  1196. coopSleepHandle = null;
  1197. coopTerminationForThisScript = false;
  1198. }
  1199. catch (TypeLoadException)
  1200. {
  1201. coopSleepHandle = new XEngineEventWaitHandle(false, EventResetMode.AutoReset);
  1202. try
  1203. {
  1204. scriptObj
  1205. = (IScript)m_AppDomains[appDomain].CreateInstanceAndUnwrap(
  1206. assemblyName.FullName,
  1207. "SecondLife.XEngineScript",
  1208. false,
  1209. BindingFlags.Default,
  1210. null,
  1211. new object[] { coopSleepHandle },
  1212. null,
  1213. null);
  1214. }
  1215. catch (Exception e2)
  1216. {
  1217. m_log.Error(
  1218. string.Format(
  1219. "[XENGINE]: Could not load previous SecondLife.XEngineScript from assembly {0} in {1}. Not starting. Exception ",
  1220. assemblyName.FullName, World.Name),
  1221. e2);
  1222. return false;
  1223. }
  1224. coopTerminationForThisScript = true;
  1225. }
  1226. }
  1227. if (m_coopTermination != coopTerminationForThisScript && !HaveNotifiedLogOfScriptStopMistmatch)
  1228. {
  1229. // Notify the log that there is at least one script compile that doesn't match the
  1230. // ScriptStopStrategy. Operator has to manually delete old DLLs - we can't do this on Windows
  1231. // once the assembly has been loaded evne if the instantiation of a class was unsuccessful.
  1232. m_log.WarnFormat(
  1233. "[XEngine]: At least one existing compiled script DLL in {0} has {1} as ScriptStopStrategy whereas config setting is {2}."
  1234. + "\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).",
  1235. World.Name, coopTerminationForThisScript ? "co-op" : "abort", m_coopTermination ? "co-op" : "abort");
  1236. HaveNotifiedLogOfScriptStopMistmatch = true;
  1237. }
  1238. instance = new ScriptInstance(this, part,
  1239. item,
  1240. startParam, postOnRez,
  1241. m_MaxScriptQueue);
  1242. if (
  1243. !instance.Load(
  1244. scriptObj, coopSleepHandle, assemblyPath,
  1245. Path.Combine(ScriptEnginePath, World.RegionInfo.RegionID.ToString()), stateSource, coopTerminationForThisScript))
  1246. return false;
  1247. // if (DebugLevel >= 1)
  1248. // m_log.DebugFormat(
  1249. // "[XEngine] Loaded script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
  1250. // part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
  1251. // part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  1252. if (presence != null)
  1253. {
  1254. ShowScriptSaveResponse(item.OwnerID,
  1255. assetID, "Compile successful", true);
  1256. }
  1257. instance.AppDomain = appDomain;
  1258. instance.LineMap = linemap;
  1259. m_Scripts[itemID] = instance;
  1260. }
  1261. }
  1262. lock (m_PrimObjects)
  1263. {
  1264. if (!m_PrimObjects.ContainsKey(localID))
  1265. m_PrimObjects[localID] = new List<UUID>();
  1266. if (!m_PrimObjects[localID].Contains(itemID))
  1267. m_PrimObjects[localID].Add(itemID);
  1268. }
  1269. if (!m_Assemblies.ContainsKey(assetID))
  1270. m_Assemblies[assetID] = assemblyPath;
  1271. lock (m_AddingAssemblies)
  1272. {
  1273. m_AddingAssemblies[assemblyPath]--;
  1274. }
  1275. if (instance != null)
  1276. instance.Init();
  1277. bool runIt;
  1278. if (m_runFlags.TryGetValue(itemID, out runIt))
  1279. {
  1280. if (!runIt)
  1281. StopScript(itemID);
  1282. m_runFlags.Remove(itemID);
  1283. }
  1284. return true;
  1285. }
  1286. public void OnRemoveScript(uint localID, UUID itemID)
  1287. {
  1288. // If it's not yet been compiled, make sure we don't try
  1289. lock (m_CompileDict)
  1290. {
  1291. if (m_CompileDict.ContainsKey(itemID))
  1292. m_CompileDict.Remove(itemID);
  1293. }
  1294. IScriptInstance instance = null;
  1295. lock (m_Scripts)
  1296. {
  1297. // Do we even have it?
  1298. if (!m_Scripts.ContainsKey(itemID))
  1299. return;
  1300. instance = m_Scripts[itemID];
  1301. m_Scripts.Remove(itemID);
  1302. }
  1303. instance.Stop(m_WaitForEventCompletionOnScriptStop, true);
  1304. lock (m_PrimObjects)
  1305. {
  1306. // Remove the script from it's prim
  1307. if (m_PrimObjects.ContainsKey(localID))
  1308. {
  1309. // Remove inventory item record
  1310. if (m_PrimObjects[localID].Contains(itemID))
  1311. m_PrimObjects[localID].Remove(itemID);
  1312. // If there are no more scripts, remove prim
  1313. if (m_PrimObjects[localID].Count == 0)
  1314. m_PrimObjects.Remove(localID);
  1315. }
  1316. }
  1317. if (instance.StatePersistedHere)
  1318. instance.RemoveState();
  1319. instance.DestroyScriptInstance();
  1320. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  1321. if (m_DomainScripts[instance.AppDomain].Count == 0)
  1322. {
  1323. m_DomainScripts.Remove(instance.AppDomain);
  1324. UnloadAppDomain(instance.AppDomain);
  1325. }
  1326. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  1327. if (handlerObjectRemoved != null)
  1328. handlerObjectRemoved(instance.ObjectID);
  1329. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  1330. if (handlerScriptRemoved != null)
  1331. handlerScriptRemoved(itemID);
  1332. }
  1333. public void OnScriptReset(uint localID, UUID itemID)
  1334. {
  1335. ResetScript(itemID);
  1336. }
  1337. public void OnStartScript(uint localID, UUID itemID)
  1338. {
  1339. StartScript(itemID);
  1340. }
  1341. public void OnStopScript(uint localID, UUID itemID)
  1342. {
  1343. StopScript(itemID);
  1344. }
  1345. private void CleanAssemblies()
  1346. {
  1347. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  1348. foreach (IScriptInstance i in m_Scripts.Values)
  1349. {
  1350. if (assetIDList.Contains(i.AssetID))
  1351. assetIDList.Remove(i.AssetID);
  1352. }
  1353. lock (m_AddingAssemblies)
  1354. {
  1355. foreach (UUID assetID in assetIDList)
  1356. {
  1357. // Do not remove assembly files if another instance of the script
  1358. // is currently initialising
  1359. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  1360. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  1361. {
  1362. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  1363. try
  1364. {
  1365. if (File.Exists(m_Assemblies[assetID]))
  1366. File.Delete(m_Assemblies[assetID]);
  1367. if (File.Exists(m_Assemblies[assetID]+".text"))
  1368. File.Delete(m_Assemblies[assetID]+".text");
  1369. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  1370. File.Delete(m_Assemblies[assetID]+".mdb");
  1371. if (File.Exists(m_Assemblies[assetID]+".map"))
  1372. File.Delete(m_Assemblies[assetID]+".map");
  1373. }
  1374. catch (Exception)
  1375. {
  1376. }
  1377. m_Assemblies.Remove(assetID);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. private void UnloadAppDomain(UUID id)
  1383. {
  1384. if (m_AppDomains.ContainsKey(id))
  1385. {
  1386. AppDomain domain = m_AppDomains[id];
  1387. m_AppDomains.Remove(id);
  1388. if (domain != AppDomain.CurrentDomain)
  1389. AppDomain.Unload(domain);
  1390. domain = null;
  1391. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  1392. }
  1393. }
  1394. //
  1395. // Start processing
  1396. //
  1397. private void SetupEngine(int minThreads, int maxThreads,
  1398. int idleTimeout, ThreadPriority threadPriority,
  1399. int maxScriptQueue, int stackSize)
  1400. {
  1401. m_MaxScriptQueue = maxScriptQueue;
  1402. STPStartInfo startInfo = new STPStartInfo();
  1403. startInfo.ThreadPoolName = "XEngine";
  1404. startInfo.IdleTimeout = idleTimeout * 1000; // convert to seconds as stated in .ini
  1405. startInfo.MaxWorkerThreads = maxThreads;
  1406. startInfo.MinWorkerThreads = minThreads;
  1407. startInfo.ThreadPriority = threadPriority;;
  1408. startInfo.MaxStackSize = stackSize;
  1409. startInfo.StartSuspended = true;
  1410. m_ThreadPool = new SmartThreadPool(startInfo);
  1411. }
  1412. //
  1413. // Used by script instances to queue event handler jobs
  1414. //
  1415. public IScriptWorkItem QueueEventHandler(object parms)
  1416. {
  1417. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  1418. new WorkItemCallback(this.ProcessEventHandler),
  1419. parms));
  1420. }
  1421. /// <summary>
  1422. /// Process a previously posted script event.
  1423. /// </summary>
  1424. /// <param name="parms"></param>
  1425. /// <returns></returns>
  1426. private object ProcessEventHandler(object parms)
  1427. {
  1428. Culture.SetCurrentCulture();
  1429. IScriptInstance instance = (ScriptInstance) parms;
  1430. // m_log.DebugFormat("[XEngine]: Processing event for {0}", instance);
  1431. return instance.EventProcessor();
  1432. }
  1433. /// <summary>
  1434. /// Post event to an entire prim
  1435. /// </summary>
  1436. /// <param name="localID"></param>
  1437. /// <param name="p"></param>
  1438. /// <returns></returns>
  1439. public bool PostObjectEvent(uint localID, EventParams p)
  1440. {
  1441. bool result = false;
  1442. List<UUID> uuids = null;
  1443. lock (m_PrimObjects)
  1444. {
  1445. if (!m_PrimObjects.ContainsKey(localID))
  1446. return false;
  1447. uuids = m_PrimObjects[localID];
  1448. foreach (UUID itemID in uuids)
  1449. {
  1450. IScriptInstance instance = null;
  1451. try
  1452. {
  1453. if (m_Scripts.ContainsKey(itemID))
  1454. instance = m_Scripts[itemID];
  1455. }
  1456. catch { /* ignore race conditions */ }
  1457. if (instance != null)
  1458. {
  1459. instance.PostEvent(p);
  1460. result = true;
  1461. }
  1462. }
  1463. }
  1464. return result;
  1465. }
  1466. /// <summary>
  1467. /// Post an event to a single script
  1468. /// </summary>
  1469. /// <param name="itemID"></param>
  1470. /// <param name="p"></param>
  1471. /// <returns></returns>
  1472. public bool PostScriptEvent(UUID itemID, EventParams p)
  1473. {
  1474. if (m_Scripts.ContainsKey(itemID))
  1475. {
  1476. IScriptInstance instance = m_Scripts[itemID];
  1477. if (instance != null)
  1478. instance.PostEvent(p);
  1479. return true;
  1480. }
  1481. return false;
  1482. }
  1483. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  1484. {
  1485. Object[] lsl_p = new Object[p.Length];
  1486. for (int i = 0; i < p.Length ; i++)
  1487. {
  1488. if (p[i] is int)
  1489. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  1490. else if (p[i] is string)
  1491. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  1492. else if (p[i] is Vector3)
  1493. lsl_p[i] = new LSL_Types.Vector3((Vector3)p[i]);
  1494. else if (p[i] is Quaternion)
  1495. lsl_p[i] = new LSL_Types.Quaternion((Quaternion)p[i]);
  1496. else if (p[i] is float)
  1497. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  1498. else
  1499. lsl_p[i] = p[i];
  1500. }
  1501. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  1502. }
  1503. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  1504. {
  1505. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  1506. if (part == null)
  1507. return false;
  1508. Object[] lsl_p = new Object[p.Length];
  1509. for (int i = 0; i < p.Length ; i++)
  1510. {
  1511. if (p[i] is int)
  1512. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  1513. else if (p[i] is string)
  1514. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  1515. else if (p[i] is Vector3)
  1516. lsl_p[i] = new LSL_Types.Vector3((Vector3)p[i]);
  1517. else if (p[i] is Quaternion)
  1518. lsl_p[i] = new LSL_Types.Quaternion((Quaternion)p[i]);
  1519. else if (p[i] is float)
  1520. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  1521. else
  1522. lsl_p[i] = p[i];
  1523. }
  1524. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  1525. }
  1526. public Assembly OnAssemblyResolve(object sender,
  1527. ResolveEventArgs args)
  1528. {
  1529. if (!(sender is System.AppDomain))
  1530. return null;
  1531. string[] pathList = new string[] {"bin", m_ScriptEnginesPath,
  1532. Path.Combine(m_ScriptEnginesPath,
  1533. m_Scene.RegionInfo.RegionID.ToString())};
  1534. string assemblyName = args.Name;
  1535. if (assemblyName.IndexOf(",") != -1)
  1536. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  1537. foreach (string s in pathList)
  1538. {
  1539. string path = Path.Combine(Directory.GetCurrentDirectory(),
  1540. Path.Combine(s, assemblyName))+".dll";
  1541. // Console.WriteLine("[XEngine]: Trying to resolve {0}", path);
  1542. if (File.Exists(path))
  1543. return Assembly.LoadFrom(path);
  1544. }
  1545. return null;
  1546. }
  1547. private IScriptInstance GetInstance(UUID itemID)
  1548. {
  1549. IScriptInstance instance;
  1550. lock (m_Scripts)
  1551. {
  1552. if (!m_Scripts.ContainsKey(itemID))
  1553. return null;
  1554. instance = m_Scripts[itemID];
  1555. }
  1556. return instance;
  1557. }
  1558. public void SetScriptState(UUID itemID, bool running)
  1559. {
  1560. IScriptInstance instance = GetInstance(itemID);
  1561. if (instance != null)
  1562. {
  1563. if (running)
  1564. instance.Start();
  1565. else
  1566. instance.Stop(100);
  1567. }
  1568. }
  1569. public bool GetScriptState(UUID itemID)
  1570. {
  1571. IScriptInstance instance = GetInstance(itemID);
  1572. return instance != null && instance.Running;
  1573. }
  1574. public void ApiResetScript(UUID itemID)
  1575. {
  1576. IScriptInstance instance = GetInstance(itemID);
  1577. if (instance != null)
  1578. instance.ApiResetScript();
  1579. // Send the new number of threads that are in use by the thread
  1580. // pool, I believe that by adding them to the locations where the
  1581. // script is changing states that I will catch all changes to the
  1582. // thread pool
  1583. m_Scene.setThreadCount(m_ThreadPool.InUseThreads);
  1584. }
  1585. public void ResetScript(UUID itemID)
  1586. {
  1587. IScriptInstance instance = GetInstance(itemID);
  1588. if (instance != null)
  1589. instance.ResetScript(m_WaitForEventCompletionOnScriptStop);
  1590. // Send the new number of threads that are in use by the thread
  1591. // pool, I believe that by adding them to the locations where the
  1592. // script is changing states that I will catch all changes to the
  1593. // thread pool
  1594. m_Scene.setThreadCount(m_ThreadPool.InUseThreads);
  1595. }
  1596. public void StartScript(UUID itemID)
  1597. {
  1598. IScriptInstance instance = GetInstance(itemID);
  1599. if (instance != null)
  1600. instance.Start();
  1601. else
  1602. m_runFlags.AddOrUpdate(itemID, true, 240);
  1603. // Send the new number of threads that are in use by the thread
  1604. // pool, I believe that by adding them to the locations where the
  1605. // script is changing states that I will catch all changes to the
  1606. // thread pool
  1607. m_Scene.setThreadCount(m_ThreadPool.InUseThreads);
  1608. }
  1609. public void StopScript(UUID itemID)
  1610. {
  1611. IScriptInstance instance = GetInstance(itemID);
  1612. if (instance != null)
  1613. {
  1614. instance.Stop(m_WaitForEventCompletionOnScriptStop);
  1615. }
  1616. else
  1617. {
  1618. // m_log.DebugFormat("[XENGINE]: Could not find script with ID {0} to stop in {1}", itemID, World.Name);
  1619. m_runFlags.AddOrUpdate(itemID, false, 240);
  1620. }
  1621. // Send the new number of threads that are in use by the thread
  1622. // pool, I believe that by adding them to the locations where the
  1623. // script is changing states that I will catch all changes to the
  1624. // thread pool
  1625. m_Scene.setThreadCount(m_ThreadPool.InUseThreads);
  1626. }
  1627. public DetectParams GetDetectParams(UUID itemID, int idx)
  1628. {
  1629. IScriptInstance instance = GetInstance(itemID);
  1630. return instance != null ? instance.GetDetectParams(idx) : null;
  1631. }
  1632. public void SetMinEventDelay(UUID itemID, double delay)
  1633. {
  1634. IScriptInstance instance = GetInstance(itemID);
  1635. if (instance != null)
  1636. instance.MinEventDelay = delay;
  1637. }
  1638. public UUID GetDetectID(UUID itemID, int idx)
  1639. {
  1640. IScriptInstance instance = GetInstance(itemID);
  1641. return instance != null ? instance.GetDetectID(idx) : UUID.Zero;
  1642. }
  1643. public void SetState(UUID itemID, string newState)
  1644. {
  1645. IScriptInstance instance = GetInstance(itemID);
  1646. if (instance == null)
  1647. return;
  1648. instance.SetState(newState);
  1649. }
  1650. public int GetStartParameter(UUID itemID)
  1651. {
  1652. IScriptInstance instance = GetInstance(itemID);
  1653. return instance == null ? 0 : instance.StartParam;
  1654. }
  1655. public void OnShutdown()
  1656. {
  1657. m_SimulatorShuttingDown = true;
  1658. List<IScriptInstance> instances = new List<IScriptInstance>();
  1659. lock (m_Scripts)
  1660. {
  1661. foreach (IScriptInstance instance in m_Scripts.Values)
  1662. instances.Add(instance);
  1663. }
  1664. foreach (IScriptInstance i in instances)
  1665. {
  1666. // Stop the script, even forcibly if needed. Then flag
  1667. // it as shutting down and restore the previous run state
  1668. // for serialization, so the scripts don't come back
  1669. // dead after region restart
  1670. //
  1671. bool prevRunning = i.Running;
  1672. i.Stop(50);
  1673. i.ShuttingDown = true;
  1674. i.Running = prevRunning;
  1675. }
  1676. DoBackup(new Object[] {0});
  1677. }
  1678. public IScriptApi GetApi(UUID itemID, string name)
  1679. {
  1680. IScriptInstance instance = GetInstance(itemID);
  1681. return instance == null ? null : instance.GetApi(name);
  1682. }
  1683. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1684. {
  1685. IScriptInstance instance = GetInstance(itemID);
  1686. if (instance == null)
  1687. return;
  1688. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1689. if (eq == null)
  1690. {
  1691. controllingClient.SendScriptRunningReply(objectID, itemID,
  1692. GetScriptState(itemID));
  1693. }
  1694. else
  1695. {
  1696. eq.Enqueue(eq.ScriptRunningEvent(objectID, itemID, GetScriptState(itemID), true),
  1697. controllingClient.AgentId);
  1698. }
  1699. }
  1700. public string GetXMLState(UUID itemID)
  1701. {
  1702. // m_log.DebugFormat("[XEngine]: Getting XML state for script instance {0}", itemID);
  1703. IScriptInstance instance = GetInstance(itemID);
  1704. if (instance == null)
  1705. {
  1706. // m_log.DebugFormat("[XEngine]: Found no script instance for {0}, returning empty string", itemID);
  1707. return "";
  1708. }
  1709. string xml = instance.GetXMLState();
  1710. XmlDocument sdoc = new XmlDocument();
  1711. bool loadedState = true;
  1712. try
  1713. {
  1714. sdoc.LoadXml(xml);
  1715. }
  1716. catch (System.Xml.XmlException)
  1717. {
  1718. loadedState = false;
  1719. }
  1720. XmlNodeList rootL = null;
  1721. XmlNode rootNode = null;
  1722. if (loadedState)
  1723. {
  1724. rootL = sdoc.GetElementsByTagName("ScriptState");
  1725. rootNode = rootL[0];
  1726. }
  1727. // Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
  1728. XmlDocument doc = new XmlDocument();
  1729. XmlElement stateData = doc.CreateElement("", "State", "");
  1730. XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
  1731. stateID.Value = itemID.ToString();
  1732. stateData.Attributes.Append(stateID);
  1733. XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
  1734. assetID.Value = instance.AssetID.ToString();
  1735. stateData.Attributes.Append(assetID);
  1736. XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
  1737. engineName.Value = ScriptEngineName;
  1738. stateData.Attributes.Append(engineName);
  1739. doc.AppendChild(stateData);
  1740. XmlNode xmlstate = null;
  1741. // Add <ScriptState>...</ScriptState>
  1742. if (loadedState)
  1743. {
  1744. xmlstate = doc.ImportNode(rootNode, true);
  1745. }
  1746. else
  1747. {
  1748. xmlstate = doc.CreateElement("", "ScriptState", "");
  1749. }
  1750. stateData.AppendChild(xmlstate);
  1751. string assemName = instance.GetAssemblyName();
  1752. string fn = Path.GetFileName(assemName);
  1753. string assem = String.Empty;
  1754. if (File.Exists(assemName + ".text"))
  1755. {
  1756. FileInfo tfi = new FileInfo(assemName + ".text");
  1757. if (tfi != null)
  1758. {
  1759. Byte[] tdata = new Byte[tfi.Length];
  1760. try
  1761. {
  1762. using (FileStream tfs = File.Open(assemName + ".text",
  1763. FileMode.Open, FileAccess.Read))
  1764. {
  1765. tfs.Read(tdata, 0, tdata.Length);
  1766. }
  1767. assem = Encoding.ASCII.GetString(tdata);
  1768. }
  1769. catch (Exception e)
  1770. {
  1771. m_log.ErrorFormat(
  1772. "[XEngine]: Unable to open script textfile {0}{1}, reason: {2}",
  1773. assemName, ".text", e.Message);
  1774. }
  1775. }
  1776. }
  1777. else
  1778. {
  1779. FileInfo fi = new FileInfo(assemName);
  1780. if (fi != null)
  1781. {
  1782. Byte[] data = new Byte[fi.Length];
  1783. try
  1784. {
  1785. using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
  1786. {
  1787. fs.Read(data, 0, data.Length);
  1788. }
  1789. assem = System.Convert.ToBase64String(data);
  1790. }
  1791. catch (Exception e)
  1792. {
  1793. m_log.ErrorFormat(
  1794. "[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
  1795. }
  1796. }
  1797. }
  1798. string map = String.Empty;
  1799. if (File.Exists(fn + ".map"))
  1800. {
  1801. using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
  1802. {
  1803. using (StreamReader msr = new StreamReader(mfs))
  1804. {
  1805. map = msr.ReadToEnd();
  1806. }
  1807. }
  1808. }
  1809. XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
  1810. XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
  1811. assemblyName.Value = fn;
  1812. assemblyData.Attributes.Append(assemblyName);
  1813. assemblyData.InnerText = assem;
  1814. stateData.AppendChild(assemblyData);
  1815. XmlElement mapData = doc.CreateElement("", "LineMap", "");
  1816. XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
  1817. mapName.Value = fn + ".map";
  1818. mapData.Attributes.Append(mapName);
  1819. mapData.InnerText = map;
  1820. stateData.AppendChild(mapData);
  1821. // m_log.DebugFormat("[XEngine]: Got XML state for {0}", itemID);
  1822. return doc.InnerXml;
  1823. }
  1824. private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
  1825. {
  1826. return false;
  1827. }
  1828. public bool SetXMLState(UUID itemID, string xml)
  1829. {
  1830. // m_log.DebugFormat("[XEngine]: Writing state for script item with ID {0}", itemID);
  1831. if (xml == String.Empty)
  1832. return false;
  1833. XmlDocument doc = new XmlDocument();
  1834. try
  1835. {
  1836. doc.LoadXml(xml);
  1837. }
  1838. catch (Exception)
  1839. {
  1840. m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
  1841. return false;
  1842. }
  1843. XmlNodeList rootL = doc.GetElementsByTagName("State");
  1844. if (rootL.Count < 1)
  1845. return false;
  1846. XmlElement rootE = (XmlElement)rootL[0];
  1847. if (rootE.GetAttribute("Engine") != ScriptEngineName)
  1848. return false;
  1849. // On rez from inventory, that ID will have changed. It was only
  1850. // advisory anyway. So we don't check it anymore.
  1851. //
  1852. // if (rootE.GetAttribute("UUID") != itemID.ToString())
  1853. // return;
  1854. XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
  1855. if (stateL.Count != 1)
  1856. return false;
  1857. XmlElement stateE = (XmlElement)stateL[0];
  1858. if (World.m_trustBinaries)
  1859. {
  1860. XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
  1861. if (assemL.Count != 1)
  1862. return false;
  1863. XmlElement assemE = (XmlElement)assemL[0];
  1864. string fn = assemE.GetAttribute("Filename");
  1865. string base64 = assemE.InnerText;
  1866. string path = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1867. path = Path.Combine(path, fn);
  1868. if (!File.Exists(path))
  1869. {
  1870. Byte[] filedata = Convert.FromBase64String(base64);
  1871. try
  1872. {
  1873. using (FileStream fs = File.Create(path))
  1874. {
  1875. // m_log.DebugFormat("[XEngine]: Writing assembly file {0}", path);
  1876. fs.Write(filedata, 0, filedata.Length);
  1877. }
  1878. }
  1879. catch (IOException ex)
  1880. {
  1881. // if there already exists a file at that location, it may be locked.
  1882. m_log.ErrorFormat("[XEngine]: Error whilst writing assembly file {0}, {1}", path, ex.Message);
  1883. }
  1884. string textpath = path + ".text";
  1885. try
  1886. {
  1887. using (FileStream fs = File.Create(textpath))
  1888. {
  1889. using (StreamWriter sw = new StreamWriter(fs))
  1890. {
  1891. // m_log.DebugFormat("[XEngine]: Writing .text file {0}", textpath);
  1892. sw.Write(base64);
  1893. }
  1894. }
  1895. }
  1896. catch (IOException ex)
  1897. {
  1898. // if there already exists a file at that location, it may be locked.
  1899. m_log.ErrorFormat("[XEngine]: Error whilst writing .text file {0}, {1}", textpath, ex.Message);
  1900. }
  1901. }
  1902. XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
  1903. if (mapL.Count > 0)
  1904. {
  1905. XmlElement mapE = (XmlElement)mapL[0];
  1906. string mappath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1907. mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
  1908. try
  1909. {
  1910. using (FileStream mfs = File.Create(mappath))
  1911. {
  1912. using (StreamWriter msw = new StreamWriter(mfs))
  1913. {
  1914. // m_log.DebugFormat("[XEngine]: Writing linemap file {0}", mappath);
  1915. msw.Write(mapE.InnerText);
  1916. }
  1917. }
  1918. }
  1919. catch (IOException ex)
  1920. {
  1921. // if there already exists a file at that location, it may be locked.
  1922. m_log.Error(
  1923. string.Format("[XEngine]: Linemap file {0} could not be written. Exception ", mappath), ex);
  1924. }
  1925. }
  1926. }
  1927. string statepath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1928. statepath = Path.Combine(statepath, itemID.ToString() + ".state");
  1929. try
  1930. {
  1931. using (FileStream sfs = File.Create(statepath))
  1932. {
  1933. using (StreamWriter ssw = new StreamWriter(sfs))
  1934. {
  1935. // m_log.DebugFormat("[XEngine]: Writing state file {0}", statepath);
  1936. ssw.Write(stateE.OuterXml);
  1937. }
  1938. }
  1939. }
  1940. catch (IOException ex)
  1941. {
  1942. // if there already exists a file at that location, it may be locked.
  1943. m_log.ErrorFormat("[XEngine]: Error whilst writing state file {0}, {1}", statepath, ex.Message);
  1944. }
  1945. // m_log.DebugFormat(
  1946. // "[XEngine]: Wrote state for script item with ID {0} at {1} in {2}", itemID, statepath, m_Scene.Name);
  1947. return true;
  1948. }
  1949. public ArrayList GetScriptErrors(UUID itemID)
  1950. {
  1951. System.Threading.Thread.Sleep(1000);
  1952. lock (m_ScriptErrors)
  1953. {
  1954. if (m_ScriptErrors.ContainsKey(itemID))
  1955. {
  1956. ArrayList ret = m_ScriptErrors[itemID];
  1957. m_ScriptErrors.Remove(itemID);
  1958. return ret;
  1959. }
  1960. return new ArrayList();
  1961. }
  1962. }
  1963. public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
  1964. {
  1965. long tickNow = Util.EnvironmentTickCount();
  1966. Dictionary<uint, float> topScripts = new Dictionary<uint, float>();
  1967. lock (m_Scripts)
  1968. {
  1969. foreach (IScriptInstance si in m_Scripts.Values)
  1970. {
  1971. if (!topScripts.ContainsKey(si.LocalID))
  1972. topScripts[si.RootLocalID] = 0;
  1973. topScripts[si.RootLocalID] += CalculateAdjustedExectionTime(si, tickNow);
  1974. }
  1975. }
  1976. return topScripts;
  1977. }
  1978. public float GetScriptExecutionTime(List<UUID> itemIDs)
  1979. {
  1980. if (itemIDs == null|| itemIDs.Count == 0)
  1981. {
  1982. return 0.0f;
  1983. }
  1984. float time = 0.0f;
  1985. long tickNow = Util.EnvironmentTickCount();
  1986. IScriptInstance si;
  1987. // Calculate the time for all scripts that this engine is executing
  1988. // Ignore any others
  1989. foreach (UUID id in itemIDs)
  1990. {
  1991. si = GetInstance(id);
  1992. if (si != null && si.Running)
  1993. {
  1994. time += CalculateAdjustedExectionTime(si, tickNow);
  1995. }
  1996. }
  1997. return time;
  1998. }
  1999. private float CalculateAdjustedExectionTime(IScriptInstance si, long tickNow)
  2000. {
  2001. long ticksElapsed = tickNow - si.MeasurementPeriodTickStart;
  2002. // Avoid divide by zero
  2003. if (ticksElapsed == 0)
  2004. ticksElapsed = 1;
  2005. // Scale execution time to the ideal 55 fps frame time for these reasons.
  2006. //
  2007. // 1) XEngine does not execute scripts per frame, unlike other script engines. Hence, there is no
  2008. // 'script execution time per frame', which is the original purpose of this value.
  2009. //
  2010. // 2) Giving the raw execution times is misleading since scripts start at different times, making
  2011. // it impossible to compare scripts.
  2012. //
  2013. // 3) Scaling the raw execution time to the time that the script has been running is better but
  2014. // is still misleading since a script that has just been rezzed may appear to have been running
  2015. // for much longer.
  2016. //
  2017. // 4) Hence, we scale execution time to an idealised frame time (55 fps). This is also not perfect
  2018. // since the figure does not represent actual execution time and very hard running scripts will
  2019. // never exceed 18ms (though this is a very high number for script execution so is a warning sign).
  2020. return ((float)si.MeasurementPeriodExecutionTime / ticksElapsed) * 18.1818f;
  2021. }
  2022. public void SuspendScript(UUID itemID)
  2023. {
  2024. // m_log.DebugFormat("[XEngine]: Received request to suspend script with ID {0}", itemID);
  2025. IScriptInstance instance = GetInstance(itemID);
  2026. if (instance != null)
  2027. instance.Suspend();
  2028. // else
  2029. // m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
  2030. // Send the new number of threads that are in use by the thread
  2031. // pool, I believe that by adding them to the locations where the
  2032. // script is changing states that I will catch all changes to the
  2033. // thread pool
  2034. m_Scene.setThreadCount(m_ThreadPool.InUseThreads);
  2035. }
  2036. public void ResumeScript(UUID itemID)
  2037. {
  2038. // m_log.DebugFormat("[XEngine]: Received request to resume script with ID {0}", itemID);
  2039. IScriptInstance instance = GetInstance(itemID);
  2040. if (instance != null)
  2041. instance.Resume();
  2042. // else
  2043. // m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
  2044. // Send the new number of threads that are in use by the thread
  2045. // pool, I believe that by adding them to the locations where the
  2046. // script is changing states that I will catch all changes to the
  2047. // thread pool
  2048. m_Scene.setThreadCount(m_ThreadPool.InUseThreads);
  2049. }
  2050. public bool HasScript(UUID itemID, out bool running)
  2051. {
  2052. running = true;
  2053. IScriptInstance instance = GetInstance(itemID);
  2054. if (instance == null)
  2055. return false;
  2056. running = instance.Running;
  2057. return true;
  2058. }
  2059. }
  2060. }