OpenSim.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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.Diagnostics;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Reflection;
  34. using System.Text;
  35. using System.Text.RegularExpressions;
  36. using System.Timers;
  37. using log4net;
  38. using NDesk.Options;
  39. using Nini.Config;
  40. using OpenMetaverse;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Console;
  43. using OpenSim.Framework.Servers;
  44. using OpenSim.Framework.Monitoring;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.Framework.Scenes;
  47. namespace OpenSim
  48. {
  49. /// <summary>
  50. /// Interactive OpenSim region server
  51. /// </summary>
  52. public class OpenSim : OpenSimBase
  53. {
  54. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  55. protected string m_startupCommandsFile;
  56. protected string m_shutdownCommandsFile;
  57. protected bool m_gui = false;
  58. protected string m_consoleType = "local";
  59. protected uint m_consolePort = 0;
  60. /// <summary>
  61. /// Prompt to use for simulator command line.
  62. /// </summary>
  63. private string m_consolePrompt;
  64. /// <summary>
  65. /// Regex for parsing out special characters in the prompt.
  66. /// </summary>
  67. private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled);
  68. private string m_timedScript = "disabled";
  69. private int m_timeInterval = 1200;
  70. private Timer m_scriptTimer;
  71. public OpenSim(IConfigSource configSource) : base(configSource)
  72. {
  73. }
  74. protected override void ReadExtraConfigSettings()
  75. {
  76. base.ReadExtraConfigSettings();
  77. IConfig startupConfig = Config.Configs["Startup"];
  78. IConfig networkConfig = Config.Configs["Network"];
  79. int stpMinThreads = 2;
  80. int stpMaxThreads = 15;
  81. if (startupConfig != null)
  82. {
  83. m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt");
  84. m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt");
  85. if (startupConfig.GetString("console", String.Empty) == String.Empty)
  86. m_gui = startupConfig.GetBoolean("gui", false);
  87. else
  88. m_consoleType= startupConfig.GetString("console", String.Empty);
  89. if (networkConfig != null)
  90. m_consolePort = (uint)networkConfig.GetInt("console_port", 0);
  91. m_timedScript = startupConfig.GetString("timer_Script", "disabled");
  92. if (m_timedScript != "disabled")
  93. {
  94. m_timeInterval = startupConfig.GetInt("timer_Interval", 1200);
  95. }
  96. string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty);
  97. FireAndForgetMethod asyncCallMethod;
  98. if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod))
  99. Util.FireAndForgetMethod = asyncCallMethod;
  100. stpMinThreads = startupConfig.GetInt("MinPoolThreads", 15);
  101. stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15);
  102. m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) ");
  103. }
  104. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  105. Util.InitThreadPool(stpMinThreads, stpMaxThreads);
  106. m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod);
  107. }
  108. /// <summary>
  109. /// Performs initialisation of the scene, such as loading configuration from disk.
  110. /// </summary>
  111. protected override void StartupSpecific()
  112. {
  113. m_log.Info("====================================================================");
  114. m_log.Info("========================= STARTING OPENSIM =========================");
  115. m_log.Info("====================================================================");
  116. //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
  117. // http://msdn.microsoft.com/en-us/library/bb384202.aspx
  118. //GCSettings.LatencyMode = GCLatencyMode.Batch;
  119. //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString());
  120. if (m_gui) // Driven by external GUI
  121. {
  122. m_console = new CommandConsole("Region");
  123. }
  124. else
  125. {
  126. switch (m_consoleType)
  127. {
  128. case "basic":
  129. m_console = new CommandConsole("Region");
  130. break;
  131. case "rest":
  132. m_console = new RemoteConsole("Region");
  133. ((RemoteConsole)m_console).ReadConfig(Config);
  134. break;
  135. default:
  136. m_console = new LocalConsole("Region");
  137. break;
  138. }
  139. }
  140. MainConsole.Instance = m_console;
  141. LogEnvironmentInformation();
  142. RegisterCommonAppenders(Config.Configs["Startup"]);
  143. RegisterConsoleCommands();
  144. base.StartupSpecific();
  145. MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler());
  146. MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this));
  147. if (userStatsURI != String.Empty)
  148. MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this));
  149. if (managedStatsURI != String.Empty)
  150. {
  151. string urlBase = String.Format("/{0}/", managedStatsURI);
  152. MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest);
  153. m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase);
  154. }
  155. if (m_console is RemoteConsole)
  156. {
  157. if (m_consolePort == 0)
  158. {
  159. ((RemoteConsole)m_console).SetServer(m_httpServer);
  160. }
  161. else
  162. {
  163. ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort));
  164. }
  165. }
  166. // Hook up to the watchdog timer
  167. Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler;
  168. PrintFileToConsole("startuplogo.txt");
  169. // For now, start at the 'root' level by default
  170. if (SceneManager.Scenes.Count == 1) // If there is only one region, select it
  171. ChangeSelectedRegion("region",
  172. new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName});
  173. else
  174. ChangeSelectedRegion("region", new string[] {"change", "region", "root"});
  175. //Run Startup Commands
  176. if (String.IsNullOrEmpty(m_startupCommandsFile))
  177. {
  178. m_log.Info("[STARTUP]: No startup command script specified. Moving on...");
  179. }
  180. else
  181. {
  182. RunCommandScript(m_startupCommandsFile);
  183. }
  184. // Start timer script (run a script every xx seconds)
  185. if (m_timedScript != "disabled")
  186. {
  187. m_scriptTimer = new Timer();
  188. m_scriptTimer.Enabled = true;
  189. m_scriptTimer.Interval = m_timeInterval*1000;
  190. m_scriptTimer.Elapsed += RunAutoTimerScript;
  191. }
  192. }
  193. /// <summary>
  194. /// Register standard set of region console commands
  195. /// </summary>
  196. private void RegisterConsoleCommands()
  197. {
  198. MainServer.RegisterHttpConsoleCommands(m_console);
  199. m_console.Commands.AddCommand("Objects", false, "force update",
  200. "force update",
  201. "Force the update of all objects on clients",
  202. HandleForceUpdate);
  203. m_console.Commands.AddCommand("General", false, "change region",
  204. "change region <region name>",
  205. "Change current console region",
  206. ChangeSelectedRegion);
  207. m_console.Commands.AddCommand("Archiving", false, "save xml",
  208. "save xml",
  209. "Save a region's data in XML format",
  210. SaveXml);
  211. m_console.Commands.AddCommand("Archiving", false, "save xml2",
  212. "save xml2",
  213. "Save a region's data in XML2 format",
  214. SaveXml2);
  215. m_console.Commands.AddCommand("Archiving", false, "load xml",
  216. "load xml [-newIDs [<x> <y> <z>]]",
  217. "Load a region's data from XML format",
  218. LoadXml);
  219. m_console.Commands.AddCommand("Archiving", false, "load xml2",
  220. "load xml2",
  221. "Load a region's data from XML2 format",
  222. LoadXml2);
  223. m_console.Commands.AddCommand("Archiving", false, "save prims xml2",
  224. "save prims xml2 [<prim name> <file name>]",
  225. "Save named prim to XML2",
  226. SavePrimsXml2);
  227. m_console.Commands.AddCommand("Archiving", false, "load oar",
  228. "load oar [--merge] [--skip-assets]"
  229. + " [--forceterrain] [--forceparcels]"
  230. + " [--rotation degrees] [--rotationCenter \"<x,y,z>\"]"
  231. + " [--displacement \"<x,y,z>\"]"
  232. + " [<OAR path>]",
  233. "Load a region's data from an OAR archive.",
  234. "--merge will merge the OAR with the existing scene (suppresses terrain and parcel info loading)." + Environment.NewLine
  235. + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine
  236. + "--displacement will add this value to the position of every object loaded" + Environment.NewLine
  237. + "--forceterrain forces the loading of terrain from the oar (undoes suppression done by --merge)" + Environment.NewLine
  238. + "--forceparcels forces the loading of parcels from the oar (undoes suppression done by --merge)" + Environment.NewLine
  239. + "--rotation specified rotation to be applied to the oar. Specified in degrees." + Environment.NewLine
  240. + "--rotationcenter Location (relative to original OAR) to apply rotation. Default is <128,128,0>" + Environment.NewLine
  241. + "The path can be either a filesystem location or a URI."
  242. + " If this is not given then the command looks for an OAR named region.oar in the current directory.",
  243. LoadOar);
  244. m_console.Commands.AddCommand("Archiving", false, "save oar",
  245. //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]",
  246. "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]",
  247. "Save a region's data to an OAR archive.",
  248. // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine
  249. "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
  250. + "--noassets stops assets being saved to the OAR.\n"
  251. + "--publish saves an OAR stripped of owner and last owner information.\n"
  252. + " on reload, the estate owner will be the owner of all objects\n"
  253. + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n"
  254. + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n"
  255. + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n"
  256. + "--all saves all the regions in the simulator, instead of just the current region.\n"
  257. + "The OAR path must be a filesystem path."
  258. + " If this is not given then the oar is saved to region.oar in the current directory.",
  259. SaveOar);
  260. m_console.Commands.AddCommand("Objects", false, "edit scale",
  261. "edit scale <name> <x> <y> <z>",
  262. "Change the scale of a named prim",
  263. HandleEditScale);
  264. m_console.Commands.AddCommand("Objects", false, "rotate scene",
  265. "rotate scene <degrees> [centerX, centerY]",
  266. "Rotates all scene objects around centerX, centerY (defailt 128, 128) (please back up your region before using)",
  267. HandleRotateScene);
  268. m_console.Commands.AddCommand("Objects", false, "scale scene",
  269. "scale scene <factor>",
  270. "Scales the scene objects (please back up your region before using)",
  271. HandleScaleScene);
  272. m_console.Commands.AddCommand("Objects", false, "translate scene",
  273. "translate scene xOffset yOffset zOffset",
  274. "translates the scene objects (please back up your region before using)",
  275. HandleTranslateScene);
  276. m_console.Commands.AddCommand("Users", false, "kick user",
  277. "kick user <first> <last> [--force] [message]",
  278. "Kick a user off the simulator",
  279. "The --force option will kick the user without any checks to see whether it's already in the process of closing\n"
  280. + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them",
  281. KickUserCommand);
  282. m_console.Commands.AddCommand("Users", false, "show users",
  283. "show users [full]",
  284. "Show user data for users currently on the region",
  285. "Without the 'full' option, only users actually on the region are shown."
  286. + " With the 'full' option child agents of users in neighbouring regions are also shown.",
  287. HandleShow);
  288. m_console.Commands.AddCommand("Comms", false, "show connections",
  289. "show connections",
  290. "Show connection data",
  291. HandleShow);
  292. m_console.Commands.AddCommand("Comms", false, "show circuits",
  293. "show circuits",
  294. "Show agent circuit data",
  295. HandleShow);
  296. m_console.Commands.AddCommand("Comms", false, "show pending-objects",
  297. "show pending-objects",
  298. "Show # of objects on the pending queues of all scene viewers",
  299. HandleShow);
  300. m_console.Commands.AddCommand("General", false, "show modules",
  301. "show modules",
  302. "Show module data",
  303. HandleShow);
  304. m_console.Commands.AddCommand("Regions", false, "show regions",
  305. "show regions",
  306. "Show region data",
  307. HandleShow);
  308. m_console.Commands.AddCommand("Regions", false, "show ratings",
  309. "show ratings",
  310. "Show rating data",
  311. HandleShow);
  312. m_console.Commands.AddCommand("Objects", false, "backup",
  313. "backup",
  314. "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.",
  315. RunCommand);
  316. m_console.Commands.AddCommand("Regions", false, "create region",
  317. "create region [\"region name\"] <region_file.ini>",
  318. "Create a new region.",
  319. "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given."
  320. + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine
  321. + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine
  322. + "If <region_file.ini> does not exist, it will be created.",
  323. HandleCreateRegion);
  324. m_console.Commands.AddCommand("Regions", false, "restart",
  325. "restart",
  326. "Restart all sims in this instance",
  327. RunCommand);
  328. m_console.Commands.AddCommand("General", false, "command-script",
  329. "command-script <script>",
  330. "Run a command script from file",
  331. RunCommand);
  332. m_console.Commands.AddCommand("Regions", false, "remove-region",
  333. "remove-region <name>",
  334. "Remove a region from this simulator",
  335. RunCommand);
  336. m_console.Commands.AddCommand("Regions", false, "delete-region",
  337. "delete-region <name>",
  338. "Delete a region from disk",
  339. RunCommand);
  340. }
  341. protected override void ShutdownSpecific()
  342. {
  343. if (m_shutdownCommandsFile != String.Empty)
  344. {
  345. RunCommandScript(m_shutdownCommandsFile);
  346. }
  347. base.ShutdownSpecific();
  348. }
  349. /// <summary>
  350. /// Timer to run a specific text file as console commands. Configured in in the main ini file
  351. /// </summary>
  352. /// <param name="sender"></param>
  353. /// <param name="e"></param>
  354. private void RunAutoTimerScript(object sender, EventArgs e)
  355. {
  356. if (m_timedScript != "disabled")
  357. {
  358. RunCommandScript(m_timedScript);
  359. }
  360. }
  361. private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi)
  362. {
  363. int now = Environment.TickCount & Int32.MaxValue;
  364. m_log.ErrorFormat(
  365. "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}",
  366. twi.Thread.Name,
  367. twi.Thread.ThreadState,
  368. now - twi.LastTick,
  369. twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : "");
  370. }
  371. #region Console Commands
  372. /// <summary>
  373. /// Kicks users off the region
  374. /// </summary>
  375. /// <param name="module"></param>
  376. /// <param name="cmdparams">name of avatar to kick</param>
  377. private void KickUserCommand(string module, string[] cmdparams)
  378. {
  379. bool force = false;
  380. OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; });
  381. List<string> mainParams = options.Parse(cmdparams);
  382. if (mainParams.Count < 4)
  383. return;
  384. string alert = null;
  385. if (mainParams.Count > 4)
  386. alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
  387. IList agents = SceneManager.GetCurrentSceneAvatars();
  388. foreach (ScenePresence presence in agents)
  389. {
  390. RegionInfo regionInfo = presence.Scene.RegionInfo;
  391. if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) &&
  392. presence.Lastname.ToLower().Equals(mainParams[3].ToLower()))
  393. {
  394. MainConsole.Instance.Output(
  395. String.Format(
  396. "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}",
  397. presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName));
  398. // kick client...
  399. if (alert != null)
  400. presence.ControllingClient.Kick(alert);
  401. else
  402. presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n");
  403. presence.Scene.CloseAgent(presence.UUID, force);
  404. break;
  405. }
  406. }
  407. MainConsole.Instance.Output("");
  408. }
  409. /// <summary>
  410. /// Opens a file and uses it as input to the console command parser.
  411. /// </summary>
  412. /// <param name="fileName">name of file to use as input to the console</param>
  413. private static void PrintFileToConsole(string fileName)
  414. {
  415. if (File.Exists(fileName))
  416. {
  417. StreamReader readFile = File.OpenText(fileName);
  418. string currentLine;
  419. while ((currentLine = readFile.ReadLine()) != null)
  420. {
  421. m_log.Info("[!]" + currentLine);
  422. }
  423. }
  424. }
  425. /// <summary>
  426. /// Force resending of all updates to all clients in active region(s)
  427. /// </summary>
  428. /// <param name="module"></param>
  429. /// <param name="args"></param>
  430. private void HandleForceUpdate(string module, string[] args)
  431. {
  432. MainConsole.Instance.Output("Updating all clients");
  433. SceneManager.ForceCurrentSceneClientUpdate();
  434. }
  435. /// <summary>
  436. /// Edits the scale of a primative with the name specified
  437. /// </summary>
  438. /// <param name="module"></param>
  439. /// <param name="args">0,1, name, x, y, z</param>
  440. private void HandleEditScale(string module, string[] args)
  441. {
  442. if (args.Length == 6)
  443. {
  444. SceneManager.HandleEditCommandOnCurrentScene(args);
  445. }
  446. else
  447. {
  448. MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>");
  449. }
  450. }
  451. private void HandleRotateScene(string module, string[] args)
  452. {
  453. string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2";
  454. float centerX = Constants.RegionSize * 0.5f;
  455. float centerY = Constants.RegionSize * 0.5f;
  456. if (args.Length < 3 || args.Length == 4)
  457. {
  458. MainConsole.Instance.Output(usage);
  459. return;
  460. }
  461. float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI);
  462. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle);
  463. if (args.Length > 4)
  464. {
  465. centerX = Convert.ToSingle(args[3]);
  466. centerY = Convert.ToSingle(args[4]);
  467. }
  468. Vector3 center = new Vector3(centerX, centerY, 0.0f);
  469. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  470. {
  471. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  472. {
  473. if (sog.AttachmentPoint == 0)
  474. {
  475. sog.RootPart.UpdateRotation(rot * sog.GroupRotation);
  476. Vector3 offset = sog.AbsolutePosition - center;
  477. offset *= rot;
  478. sog.UpdateGroupPosition(center + offset);
  479. }
  480. });
  481. });
  482. }
  483. private void HandleScaleScene(string module, string[] args)
  484. {
  485. string usage = "Usage: scale scene <factor>";
  486. if (args.Length < 3)
  487. {
  488. MainConsole.Instance.Output(usage);
  489. return;
  490. }
  491. float factor = (float)(Convert.ToSingle(args[2]));
  492. float minZ = float.MaxValue;
  493. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  494. {
  495. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  496. {
  497. if (sog.AttachmentPoint == 0)
  498. {
  499. if (sog.RootPart.AbsolutePosition.Z < minZ)
  500. minZ = sog.RootPart.AbsolutePosition.Z;
  501. }
  502. });
  503. });
  504. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  505. {
  506. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  507. {
  508. if (sog.AttachmentPoint == 0)
  509. {
  510. Vector3 tmpRootPos = sog.RootPart.AbsolutePosition;
  511. tmpRootPos.Z -= minZ;
  512. tmpRootPos *= factor;
  513. tmpRootPos.Z += minZ;
  514. foreach (SceneObjectPart sop in sog.Parts)
  515. {
  516. if (sop.ParentID != 0)
  517. sop.OffsetPosition *= factor;
  518. sop.Scale *= factor;
  519. }
  520. sog.UpdateGroupPosition(tmpRootPos);
  521. }
  522. });
  523. });
  524. }
  525. private void HandleTranslateScene(string module, string[] args)
  526. {
  527. string usage = "Usage: translate scene <xOffset, yOffset, zOffset>";
  528. if (args.Length < 5)
  529. {
  530. MainConsole.Instance.Output(usage);
  531. return;
  532. }
  533. float xOFfset = (float)Convert.ToSingle(args[2]);
  534. float yOffset = (float)Convert.ToSingle(args[3]);
  535. float zOffset = (float)Convert.ToSingle(args[4]);
  536. Vector3 offset = new Vector3(xOFfset, yOffset, zOffset);
  537. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  538. {
  539. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  540. {
  541. if (sog.AttachmentPoint == 0)
  542. sog.UpdateGroupPosition(sog.AbsolutePosition + offset);
  543. });
  544. });
  545. }
  546. /// <summary>
  547. /// Creates a new region based on the parameters specified. This will ask the user questions on the console
  548. /// </summary>
  549. /// <param name="module"></param>
  550. /// <param name="cmd">0,1,region name, region ini or XML file</param>
  551. private void HandleCreateRegion(string module, string[] cmd)
  552. {
  553. string regionName = string.Empty;
  554. string regionFile = string.Empty;
  555. if (cmd.Length == 3)
  556. {
  557. regionFile = cmd[2];
  558. }
  559. else if (cmd.Length > 3)
  560. {
  561. regionName = cmd[2];
  562. regionFile = cmd[3];
  563. }
  564. string extension = Path.GetExtension(regionFile).ToLower();
  565. bool isXml = extension.Equals(".xml");
  566. bool isIni = extension.Equals(".ini");
  567. if (!isXml && !isIni)
  568. {
  569. MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>");
  570. return;
  571. }
  572. if (!Path.IsPathRooted(regionFile))
  573. {
  574. string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim();
  575. regionFile = Path.Combine(regionsDir, regionFile);
  576. }
  577. RegionInfo regInfo;
  578. if (isXml)
  579. {
  580. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source);
  581. }
  582. else
  583. {
  584. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName);
  585. }
  586. Scene existingScene;
  587. if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene))
  588. {
  589. MainConsole.Instance.OutputFormat(
  590. "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}",
  591. regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName);
  592. return;
  593. }
  594. bool changed = PopulateRegionEstateInfo(regInfo);
  595. IScene scene;
  596. CreateRegion(regInfo, true, out scene);
  597. if (changed)
  598. regInfo.EstateSettings.Save();
  599. }
  600. /// <summary>
  601. /// Runs commands issued by the server console from the operator
  602. /// </summary>
  603. /// <param name="command">The first argument of the parameter (the command)</param>
  604. /// <param name="cmdparams">Additional arguments passed to the command</param>
  605. public void RunCommand(string module, string[] cmdparams)
  606. {
  607. List<string> args = new List<string>(cmdparams);
  608. if (args.Count < 1)
  609. return;
  610. string command = args[0];
  611. args.RemoveAt(0);
  612. cmdparams = args.ToArray();
  613. switch (command)
  614. {
  615. case "backup":
  616. MainConsole.Instance.Output("Triggering save of pending object updates to persistent store");
  617. SceneManager.BackupCurrentScene();
  618. break;
  619. case "remove-region":
  620. string regRemoveName = CombineParams(cmdparams, 0);
  621. Scene removeScene;
  622. if (SceneManager.TryGetScene(regRemoveName, out removeScene))
  623. RemoveRegion(removeScene, false);
  624. else
  625. MainConsole.Instance.Output("No region with that name");
  626. break;
  627. case "delete-region":
  628. string regDeleteName = CombineParams(cmdparams, 0);
  629. Scene killScene;
  630. if (SceneManager.TryGetScene(regDeleteName, out killScene))
  631. RemoveRegion(killScene, true);
  632. else
  633. MainConsole.Instance.Output("no region with that name");
  634. break;
  635. case "restart":
  636. SceneManager.RestartCurrentScene();
  637. break;
  638. }
  639. }
  640. /// <summary>
  641. /// Change the currently selected region. The selected region is that operated upon by single region commands.
  642. /// </summary>
  643. /// <param name="cmdParams"></param>
  644. protected void ChangeSelectedRegion(string module, string[] cmdparams)
  645. {
  646. if (cmdparams.Length > 2)
  647. {
  648. string newRegionName = CombineParams(cmdparams, 2);
  649. if (!SceneManager.TrySetCurrentScene(newRegionName))
  650. MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName));
  651. else
  652. RefreshPrompt();
  653. }
  654. else
  655. {
  656. MainConsole.Instance.Output("Usage: change region <region name>");
  657. }
  658. }
  659. /// <summary>
  660. /// Refreshs prompt with the current selection details.
  661. /// </summary>
  662. private void RefreshPrompt()
  663. {
  664. string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName);
  665. MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName));
  666. // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt);
  667. string prompt = m_consolePrompt;
  668. // Replace "\R" with the region name
  669. // Replace "\\" with "\"
  670. prompt = m_consolePromptRegex.Replace(prompt, m =>
  671. {
  672. // m_log.DebugFormat("Matched {0}", m.Groups[2].Value);
  673. if (m.Groups[2].Value == "R")
  674. return m.Groups[1].Value + regionName;
  675. else
  676. return m.Groups[0].Value;
  677. });
  678. m_console.DefaultPrompt = prompt;
  679. m_console.ConsoleScene = SceneManager.CurrentScene;
  680. }
  681. protected override void HandleRestartRegion(RegionInfo whichRegion)
  682. {
  683. base.HandleRestartRegion(whichRegion);
  684. // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the
  685. // m_console.ConsoleScene to null (indicating all scenes).
  686. if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name)
  687. SceneManager.TrySetCurrentScene(whichRegion.RegionName);
  688. RefreshPrompt();
  689. }
  690. // see BaseOpenSimServer
  691. /// <summary>
  692. /// Many commands list objects for debugging. Some of the types are listed here
  693. /// </summary>
  694. /// <param name="mod"></param>
  695. /// <param name="cmd"></param>
  696. public override void HandleShow(string mod, string[] cmd)
  697. {
  698. base.HandleShow(mod, cmd);
  699. List<string> args = new List<string>(cmd);
  700. args.RemoveAt(0);
  701. string[] showParams = args.ToArray();
  702. switch (showParams[0])
  703. {
  704. case "users":
  705. IList agents;
  706. if (showParams.Length > 1 && showParams[1] == "full")
  707. {
  708. agents = SceneManager.GetCurrentScenePresences();
  709. } else
  710. {
  711. agents = SceneManager.GetCurrentSceneAvatars();
  712. }
  713. MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count));
  714. MainConsole.Instance.Output(
  715. String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname",
  716. "Agent ID", "Root/Child", "Region", "Position")
  717. );
  718. foreach (ScenePresence presence in agents)
  719. {
  720. RegionInfo regionInfo = presence.Scene.RegionInfo;
  721. string regionName;
  722. if (regionInfo == null)
  723. {
  724. regionName = "Unresolvable";
  725. } else
  726. {
  727. regionName = regionInfo.RegionName;
  728. }
  729. MainConsole.Instance.Output(
  730. String.Format(
  731. "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}",
  732. presence.Firstname,
  733. presence.Lastname,
  734. presence.UUID,
  735. presence.IsChildAgent ? "Child" : "Root",
  736. regionName,
  737. presence.AbsolutePosition.ToString())
  738. );
  739. }
  740. MainConsole.Instance.Output(String.Empty);
  741. break;
  742. case "connections":
  743. HandleShowConnections();
  744. break;
  745. case "circuits":
  746. HandleShowCircuits();
  747. break;
  748. case "modules":
  749. SceneManager.ForEachSelectedScene(
  750. scene =>
  751. {
  752. MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name);
  753. List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>();
  754. List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>();
  755. foreach (IRegionModuleBase module in scene.RegionModules.Values)
  756. {
  757. if (module.GetType().GetInterface("ISharedRegionModule") != null)
  758. nonSharedModules.Add(module);
  759. else
  760. sharedModules.Add(module);
  761. }
  762. foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name))
  763. MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name);
  764. foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name))
  765. MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name);
  766. }
  767. );
  768. MainConsole.Instance.Output("");
  769. break;
  770. case "regions":
  771. SceneManager.ForEachScene(
  772. delegate(Scene scene)
  773. {
  774. MainConsole.Instance.Output(String.Format(
  775. "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}, Estate Name: {4}",
  776. scene.RegionInfo.RegionName,
  777. scene.RegionInfo.RegionLocX,
  778. scene.RegionInfo.RegionLocY,
  779. scene.RegionInfo.InternalEndPoint.Port,
  780. scene.RegionInfo.EstateSettings.EstateName));
  781. });
  782. break;
  783. case "ratings":
  784. SceneManager.ForEachScene(
  785. delegate(Scene scene)
  786. {
  787. string rating = "";
  788. if (scene.RegionInfo.RegionSettings.Maturity == 1)
  789. {
  790. rating = "MATURE";
  791. }
  792. else if (scene.RegionInfo.RegionSettings.Maturity == 2)
  793. {
  794. rating = "ADULT";
  795. }
  796. else
  797. {
  798. rating = "PG";
  799. }
  800. MainConsole.Instance.Output(String.Format(
  801. "Region Name: {0}, Region Rating {1}",
  802. scene.RegionInfo.RegionName,
  803. rating));
  804. });
  805. break;
  806. }
  807. }
  808. private void HandleShowCircuits()
  809. {
  810. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  811. cdt.AddColumn("Region", 20);
  812. cdt.AddColumn("Avatar name", 24);
  813. cdt.AddColumn("Type", 5);
  814. cdt.AddColumn("Code", 10);
  815. cdt.AddColumn("IP", 16);
  816. cdt.AddColumn("Viewer Name", 24);
  817. SceneManager.ForEachScene(
  818. s =>
  819. {
  820. foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values)
  821. cdt.AddRow(
  822. s.Name,
  823. aCircuit.Name,
  824. aCircuit.child ? "child" : "root",
  825. aCircuit.circuitcode.ToString(),
  826. aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set",
  827. aCircuit.Viewer);
  828. });
  829. MainConsole.Instance.Output(cdt.ToString());
  830. }
  831. private void HandleShowConnections()
  832. {
  833. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  834. cdt.AddColumn("Region", 20);
  835. cdt.AddColumn("Avatar name", 24);
  836. cdt.AddColumn("Circuit code", 12);
  837. cdt.AddColumn("Endpoint", 23);
  838. cdt.AddColumn("Active?", 7);
  839. SceneManager.ForEachScene(
  840. s => s.ForEachClient(
  841. c => cdt.AddRow(
  842. s.Name,
  843. c.Name,
  844. c.CircuitCode.ToString(),
  845. c.RemoteEndPoint.ToString(),
  846. c.IsActive.ToString())));
  847. MainConsole.Instance.Output(cdt.ToString());
  848. }
  849. /// <summary>
  850. /// Use XML2 format to serialize data to a file
  851. /// </summary>
  852. /// <param name="module"></param>
  853. /// <param name="cmdparams"></param>
  854. protected void SavePrimsXml2(string module, string[] cmdparams)
  855. {
  856. if (cmdparams.Length > 5)
  857. {
  858. SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]);
  859. }
  860. else
  861. {
  862. SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME);
  863. }
  864. }
  865. /// <summary>
  866. /// Use XML format to serialize data to a file
  867. /// </summary>
  868. /// <param name="module"></param>
  869. /// <param name="cmdparams"></param>
  870. protected void SaveXml(string module, string[] cmdparams)
  871. {
  872. MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason.");
  873. if (cmdparams.Length > 0)
  874. {
  875. SceneManager.SaveCurrentSceneToXml(cmdparams[2]);
  876. }
  877. else
  878. {
  879. SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME);
  880. }
  881. }
  882. /// <summary>
  883. /// Loads data and region objects from XML format.
  884. /// </summary>
  885. /// <param name="module"></param>
  886. /// <param name="cmdparams"></param>
  887. protected void LoadXml(string module, string[] cmdparams)
  888. {
  889. MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason.");
  890. Vector3 loadOffset = new Vector3(0, 0, 0);
  891. if (cmdparams.Length > 2)
  892. {
  893. bool generateNewIDS = false;
  894. if (cmdparams.Length > 3)
  895. {
  896. if (cmdparams[3] == "-newUID")
  897. {
  898. generateNewIDS = true;
  899. }
  900. if (cmdparams.Length > 4)
  901. {
  902. loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo);
  903. if (cmdparams.Length > 5)
  904. {
  905. loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo);
  906. }
  907. if (cmdparams.Length > 6)
  908. {
  909. loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo);
  910. }
  911. MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z));
  912. }
  913. }
  914. SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset);
  915. }
  916. else
  917. {
  918. try
  919. {
  920. SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset);
  921. }
  922. catch (FileNotFoundException)
  923. {
  924. MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>");
  925. }
  926. }
  927. }
  928. /// <summary>
  929. /// Serialize region data to XML2Format
  930. /// </summary>
  931. /// <param name="module"></param>
  932. /// <param name="cmdparams"></param>
  933. protected void SaveXml2(string module, string[] cmdparams)
  934. {
  935. if (cmdparams.Length > 2)
  936. {
  937. SceneManager.SaveCurrentSceneToXml2(cmdparams[2]);
  938. }
  939. else
  940. {
  941. SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  942. }
  943. }
  944. /// <summary>
  945. /// Load region data from Xml2Format
  946. /// </summary>
  947. /// <param name="module"></param>
  948. /// <param name="cmdparams"></param>
  949. protected void LoadXml2(string module, string[] cmdparams)
  950. {
  951. if (cmdparams.Length > 2)
  952. {
  953. try
  954. {
  955. SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]);
  956. }
  957. catch (FileNotFoundException)
  958. {
  959. MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>");
  960. }
  961. }
  962. else
  963. {
  964. try
  965. {
  966. SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  967. }
  968. catch (FileNotFoundException)
  969. {
  970. MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>");
  971. }
  972. }
  973. }
  974. /// <summary>
  975. /// Load a whole region from an opensimulator archive.
  976. /// </summary>
  977. /// <param name="cmdparams"></param>
  978. protected void LoadOar(string module, string[] cmdparams)
  979. {
  980. try
  981. {
  982. SceneManager.LoadArchiveToCurrentScene(cmdparams);
  983. }
  984. catch (Exception e)
  985. {
  986. MainConsole.Instance.Output(e.Message);
  987. }
  988. }
  989. /// <summary>
  990. /// Save a region to a file, including all the assets needed to restore it.
  991. /// </summary>
  992. /// <param name="cmdparams"></param>
  993. protected void SaveOar(string module, string[] cmdparams)
  994. {
  995. SceneManager.SaveCurrentSceneToArchive(cmdparams);
  996. }
  997. private static string CombineParams(string[] commandParams, int pos)
  998. {
  999. string result = String.Empty;
  1000. for (int i = pos; i < commandParams.Length; i++)
  1001. {
  1002. result += commandParams[i] + " ";
  1003. }
  1004. result = result.TrimEnd(' ');
  1005. return result;
  1006. }
  1007. #endregion
  1008. }
  1009. }