OpenSim.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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. + " [--force-terrain] [--force-parcels]"
  230. + " [--no-objects]"
  231. + " [--rotation degrees] [--rotation-center \"<x,y,z>\"]"
  232. + " [--displacement \"<x,y,z>\"]"
  233. + " [<OAR path>]",
  234. "Load a region's data from an OAR archive.",
  235. "--merge will merge the OAR with the existing scene (suppresses terrain and parcel info loading)." + Environment.NewLine
  236. + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine
  237. + "--displacement will add this value to the position of every object loaded" + Environment.NewLine
  238. + "--force-terrain forces the loading of terrain from the oar (undoes suppression done by --merge)" + Environment.NewLine
  239. + "--force-parcels forces the loading of parcels from the oar (undoes suppression done by --merge)" + Environment.NewLine
  240. + "--rotation specified rotation to be applied to the oar. Specified in degrees." + Environment.NewLine
  241. + "--rotation-center Location (relative to original OAR) to apply rotation. Default is <128,128,0>" + Environment.NewLine
  242. + "--no-objects suppresses the addition of any objects (good for loading only the terrain)" + Environment.NewLine
  243. + "The path can be either a filesystem location or a URI."
  244. + " If this is not given then the command looks for an OAR named region.oar in the current directory.",
  245. LoadOar);
  246. m_console.Commands.AddCommand("Archiving", false, "save oar",
  247. //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]",
  248. "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]",
  249. "Save a region's data to an OAR archive.",
  250. // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine
  251. "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
  252. + "--noassets stops assets being saved to the OAR.\n"
  253. + "--publish saves an OAR stripped of owner and last owner information.\n"
  254. + " on reload, the estate owner will be the owner of all objects\n"
  255. + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n"
  256. + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n"
  257. + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n"
  258. + "--all saves all the regions in the simulator, instead of just the current region.\n"
  259. + "The OAR path must be a filesystem path."
  260. + " If this is not given then the oar is saved to region.oar in the current directory.",
  261. SaveOar);
  262. m_console.Commands.AddCommand("Objects", false, "edit scale",
  263. "edit scale <name> <x> <y> <z>",
  264. "Change the scale of a named prim",
  265. HandleEditScale);
  266. m_console.Commands.AddCommand("Objects", false, "rotate scene",
  267. "rotate scene <degrees> [centerX, centerY]",
  268. "Rotates all scene objects around centerX, centerY (defailt 128, 128) (please back up your region before using)",
  269. HandleRotateScene);
  270. m_console.Commands.AddCommand("Objects", false, "scale scene",
  271. "scale scene <factor>",
  272. "Scales the scene objects (please back up your region before using)",
  273. HandleScaleScene);
  274. m_console.Commands.AddCommand("Objects", false, "translate scene",
  275. "translate scene xOffset yOffset zOffset",
  276. "translates the scene objects (please back up your region before using)",
  277. HandleTranslateScene);
  278. m_console.Commands.AddCommand("Users", false, "kick user",
  279. "kick user <first> <last> [--force] [message]",
  280. "Kick a user off the simulator",
  281. "The --force option will kick the user without any checks to see whether it's already in the process of closing\n"
  282. + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them",
  283. KickUserCommand);
  284. m_console.Commands.AddCommand("Users", false, "show users",
  285. "show users [full]",
  286. "Show user data for users currently on the region",
  287. "Without the 'full' option, only users actually on the region are shown."
  288. + " With the 'full' option child agents of users in neighbouring regions are also shown.",
  289. HandleShow);
  290. m_console.Commands.AddCommand("Comms", false, "show connections",
  291. "show connections",
  292. "Show connection data",
  293. HandleShow);
  294. m_console.Commands.AddCommand("Comms", false, "show circuits",
  295. "show circuits",
  296. "Show agent circuit data",
  297. HandleShow);
  298. m_console.Commands.AddCommand("Comms", false, "show pending-objects",
  299. "show pending-objects",
  300. "Show # of objects on the pending queues of all scene viewers",
  301. HandleShow);
  302. m_console.Commands.AddCommand("General", false, "show modules",
  303. "show modules",
  304. "Show module data",
  305. HandleShow);
  306. m_console.Commands.AddCommand("Regions", false, "show regions",
  307. "show regions",
  308. "Show region data",
  309. HandleShow);
  310. m_console.Commands.AddCommand("Regions", false, "show ratings",
  311. "show ratings",
  312. "Show rating data",
  313. HandleShow);
  314. m_console.Commands.AddCommand("Objects", false, "backup",
  315. "backup",
  316. "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.",
  317. RunCommand);
  318. m_console.Commands.AddCommand("Regions", false, "create region",
  319. "create region [\"region name\"] <region_file.ini>",
  320. "Create a new region.",
  321. "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."
  322. + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine
  323. + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine
  324. + "If <region_file.ini> does not exist, it will be created.",
  325. HandleCreateRegion);
  326. m_console.Commands.AddCommand("Regions", false, "restart",
  327. "restart",
  328. "Restart all sims in this instance",
  329. RunCommand);
  330. m_console.Commands.AddCommand("General", false, "command-script",
  331. "command-script <script>",
  332. "Run a command script from file",
  333. RunCommand);
  334. m_console.Commands.AddCommand("Regions", false, "remove-region",
  335. "remove-region <name>",
  336. "Remove a region from this simulator",
  337. RunCommand);
  338. m_console.Commands.AddCommand("Regions", false, "delete-region",
  339. "delete-region <name>",
  340. "Delete a region from disk",
  341. RunCommand);
  342. }
  343. protected override void ShutdownSpecific()
  344. {
  345. if (m_shutdownCommandsFile != String.Empty)
  346. {
  347. RunCommandScript(m_shutdownCommandsFile);
  348. }
  349. base.ShutdownSpecific();
  350. }
  351. /// <summary>
  352. /// Timer to run a specific text file as console commands. Configured in in the main ini file
  353. /// </summary>
  354. /// <param name="sender"></param>
  355. /// <param name="e"></param>
  356. private void RunAutoTimerScript(object sender, EventArgs e)
  357. {
  358. if (m_timedScript != "disabled")
  359. {
  360. RunCommandScript(m_timedScript);
  361. }
  362. }
  363. private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi)
  364. {
  365. int now = Environment.TickCount & Int32.MaxValue;
  366. m_log.ErrorFormat(
  367. "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}",
  368. twi.Thread.Name,
  369. twi.Thread.ThreadState,
  370. now - twi.LastTick,
  371. twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : "");
  372. }
  373. #region Console Commands
  374. /// <summary>
  375. /// Kicks users off the region
  376. /// </summary>
  377. /// <param name="module"></param>
  378. /// <param name="cmdparams">name of avatar to kick</param>
  379. private void KickUserCommand(string module, string[] cmdparams)
  380. {
  381. bool force = false;
  382. OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; });
  383. List<string> mainParams = options.Parse(cmdparams);
  384. if (mainParams.Count < 4)
  385. return;
  386. string alert = null;
  387. if (mainParams.Count > 4)
  388. alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
  389. IList agents = SceneManager.GetCurrentSceneAvatars();
  390. foreach (ScenePresence presence in agents)
  391. {
  392. RegionInfo regionInfo = presence.Scene.RegionInfo;
  393. if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) &&
  394. presence.Lastname.ToLower().Equals(mainParams[3].ToLower()))
  395. {
  396. MainConsole.Instance.Output(
  397. String.Format(
  398. "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}",
  399. presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName));
  400. // kick client...
  401. if (alert != null)
  402. presence.ControllingClient.Kick(alert);
  403. else
  404. presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n");
  405. presence.Scene.CloseAgent(presence.UUID, force);
  406. break;
  407. }
  408. }
  409. MainConsole.Instance.Output("");
  410. }
  411. /// <summary>
  412. /// Opens a file and uses it as input to the console command parser.
  413. /// </summary>
  414. /// <param name="fileName">name of file to use as input to the console</param>
  415. private static void PrintFileToConsole(string fileName)
  416. {
  417. if (File.Exists(fileName))
  418. {
  419. StreamReader readFile = File.OpenText(fileName);
  420. string currentLine;
  421. while ((currentLine = readFile.ReadLine()) != null)
  422. {
  423. m_log.Info("[!]" + currentLine);
  424. }
  425. }
  426. }
  427. /// <summary>
  428. /// Force resending of all updates to all clients in active region(s)
  429. /// </summary>
  430. /// <param name="module"></param>
  431. /// <param name="args"></param>
  432. private void HandleForceUpdate(string module, string[] args)
  433. {
  434. MainConsole.Instance.Output("Updating all clients");
  435. SceneManager.ForceCurrentSceneClientUpdate();
  436. }
  437. /// <summary>
  438. /// Edits the scale of a primative with the name specified
  439. /// </summary>
  440. /// <param name="module"></param>
  441. /// <param name="args">0,1, name, x, y, z</param>
  442. private void HandleEditScale(string module, string[] args)
  443. {
  444. if (args.Length == 6)
  445. {
  446. SceneManager.HandleEditCommandOnCurrentScene(args);
  447. }
  448. else
  449. {
  450. MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>");
  451. }
  452. }
  453. private void HandleRotateScene(string module, string[] args)
  454. {
  455. string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2";
  456. float centerX = Constants.RegionSize * 0.5f;
  457. float centerY = Constants.RegionSize * 0.5f;
  458. if (args.Length < 3 || args.Length == 4)
  459. {
  460. MainConsole.Instance.Output(usage);
  461. return;
  462. }
  463. float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI);
  464. OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle);
  465. if (args.Length > 4)
  466. {
  467. centerX = Convert.ToSingle(args[3]);
  468. centerY = Convert.ToSingle(args[4]);
  469. }
  470. Vector3 center = new Vector3(centerX, centerY, 0.0f);
  471. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  472. {
  473. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  474. {
  475. if (!sog.IsAttachment)
  476. {
  477. sog.RootPart.UpdateRotation(rot * sog.GroupRotation);
  478. Vector3 offset = sog.AbsolutePosition - center;
  479. offset *= rot;
  480. sog.UpdateGroupPosition(center + offset);
  481. }
  482. });
  483. });
  484. }
  485. private void HandleScaleScene(string module, string[] args)
  486. {
  487. string usage = "Usage: scale scene <factor>";
  488. if (args.Length < 3)
  489. {
  490. MainConsole.Instance.Output(usage);
  491. return;
  492. }
  493. float factor = (float)(Convert.ToSingle(args[2]));
  494. float minZ = float.MaxValue;
  495. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  496. {
  497. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  498. {
  499. if (!sog.IsAttachment)
  500. {
  501. if (sog.RootPart.AbsolutePosition.Z < minZ)
  502. minZ = sog.RootPart.AbsolutePosition.Z;
  503. }
  504. });
  505. });
  506. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  507. {
  508. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  509. {
  510. if (!sog.IsAttachment)
  511. {
  512. Vector3 tmpRootPos = sog.RootPart.AbsolutePosition;
  513. tmpRootPos.Z -= minZ;
  514. tmpRootPos *= factor;
  515. tmpRootPos.Z += minZ;
  516. foreach (SceneObjectPart sop in sog.Parts)
  517. {
  518. if (sop.ParentID != 0)
  519. sop.OffsetPosition *= factor;
  520. sop.Scale *= factor;
  521. }
  522. sog.UpdateGroupPosition(tmpRootPos);
  523. }
  524. });
  525. });
  526. }
  527. private void HandleTranslateScene(string module, string[] args)
  528. {
  529. string usage = "Usage: translate scene <xOffset, yOffset, zOffset>";
  530. if (args.Length < 5)
  531. {
  532. MainConsole.Instance.Output(usage);
  533. return;
  534. }
  535. float xOFfset = (float)Convert.ToSingle(args[2]);
  536. float yOffset = (float)Convert.ToSingle(args[3]);
  537. float zOffset = (float)Convert.ToSingle(args[4]);
  538. Vector3 offset = new Vector3(xOFfset, yOffset, zOffset);
  539. SceneManager.ForEachSelectedScene(delegate(Scene scene)
  540. {
  541. scene.ForEachSOG(delegate(SceneObjectGroup sog)
  542. {
  543. if (!sog.IsAttachment)
  544. sog.UpdateGroupPosition(sog.AbsolutePosition + offset);
  545. });
  546. });
  547. }
  548. /// <summary>
  549. /// Creates a new region based on the parameters specified. This will ask the user questions on the console
  550. /// </summary>
  551. /// <param name="module"></param>
  552. /// <param name="cmd">0,1,region name, region ini or XML file</param>
  553. private void HandleCreateRegion(string module, string[] cmd)
  554. {
  555. string regionName = string.Empty;
  556. string regionFile = string.Empty;
  557. if (cmd.Length == 3)
  558. {
  559. regionFile = cmd[2];
  560. }
  561. else if (cmd.Length > 3)
  562. {
  563. regionName = cmd[2];
  564. regionFile = cmd[3];
  565. }
  566. string extension = Path.GetExtension(regionFile).ToLower();
  567. bool isXml = extension.Equals(".xml");
  568. bool isIni = extension.Equals(".ini");
  569. if (!isXml && !isIni)
  570. {
  571. MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>");
  572. return;
  573. }
  574. if (!Path.IsPathRooted(regionFile))
  575. {
  576. string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim();
  577. regionFile = Path.Combine(regionsDir, regionFile);
  578. }
  579. RegionInfo regInfo;
  580. if (isXml)
  581. {
  582. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source);
  583. }
  584. else
  585. {
  586. regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName);
  587. }
  588. Scene existingScene;
  589. if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene))
  590. {
  591. MainConsole.Instance.OutputFormat(
  592. "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}",
  593. regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName);
  594. return;
  595. }
  596. bool changed = PopulateRegionEstateInfo(regInfo);
  597. IScene scene;
  598. CreateRegion(regInfo, true, out scene);
  599. if (changed)
  600. regInfo.EstateSettings.Save();
  601. }
  602. /// <summary>
  603. /// Runs commands issued by the server console from the operator
  604. /// </summary>
  605. /// <param name="command">The first argument of the parameter (the command)</param>
  606. /// <param name="cmdparams">Additional arguments passed to the command</param>
  607. public void RunCommand(string module, string[] cmdparams)
  608. {
  609. List<string> args = new List<string>(cmdparams);
  610. if (args.Count < 1)
  611. return;
  612. string command = args[0];
  613. args.RemoveAt(0);
  614. cmdparams = args.ToArray();
  615. switch (command)
  616. {
  617. case "backup":
  618. MainConsole.Instance.Output("Triggering save of pending object updates to persistent store");
  619. SceneManager.BackupCurrentScene();
  620. break;
  621. case "remove-region":
  622. string regRemoveName = CombineParams(cmdparams, 0);
  623. Scene removeScene;
  624. if (SceneManager.TryGetScene(regRemoveName, out removeScene))
  625. RemoveRegion(removeScene, false);
  626. else
  627. MainConsole.Instance.Output("No region with that name");
  628. break;
  629. case "delete-region":
  630. string regDeleteName = CombineParams(cmdparams, 0);
  631. Scene killScene;
  632. if (SceneManager.TryGetScene(regDeleteName, out killScene))
  633. RemoveRegion(killScene, true);
  634. else
  635. MainConsole.Instance.Output("no region with that name");
  636. break;
  637. case "restart":
  638. SceneManager.RestartCurrentScene();
  639. break;
  640. }
  641. }
  642. /// <summary>
  643. /// Change the currently selected region. The selected region is that operated upon by single region commands.
  644. /// </summary>
  645. /// <param name="cmdParams"></param>
  646. protected void ChangeSelectedRegion(string module, string[] cmdparams)
  647. {
  648. if (cmdparams.Length > 2)
  649. {
  650. string newRegionName = CombineParams(cmdparams, 2);
  651. if (!SceneManager.TrySetCurrentScene(newRegionName))
  652. MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName));
  653. else
  654. RefreshPrompt();
  655. }
  656. else
  657. {
  658. MainConsole.Instance.Output("Usage: change region <region name>");
  659. }
  660. }
  661. /// <summary>
  662. /// Refreshs prompt with the current selection details.
  663. /// </summary>
  664. private void RefreshPrompt()
  665. {
  666. string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName);
  667. MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName));
  668. // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt);
  669. string prompt = m_consolePrompt;
  670. // Replace "\R" with the region name
  671. // Replace "\\" with "\"
  672. prompt = m_consolePromptRegex.Replace(prompt, m =>
  673. {
  674. // m_log.DebugFormat("Matched {0}", m.Groups[2].Value);
  675. if (m.Groups[2].Value == "R")
  676. return m.Groups[1].Value + regionName;
  677. else
  678. return m.Groups[0].Value;
  679. });
  680. m_console.DefaultPrompt = prompt;
  681. m_console.ConsoleScene = SceneManager.CurrentScene;
  682. }
  683. protected override void HandleRestartRegion(RegionInfo whichRegion)
  684. {
  685. base.HandleRestartRegion(whichRegion);
  686. // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the
  687. // m_console.ConsoleScene to null (indicating all scenes).
  688. if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name)
  689. SceneManager.TrySetCurrentScene(whichRegion.RegionName);
  690. RefreshPrompt();
  691. }
  692. // see BaseOpenSimServer
  693. /// <summary>
  694. /// Many commands list objects for debugging. Some of the types are listed here
  695. /// </summary>
  696. /// <param name="mod"></param>
  697. /// <param name="cmd"></param>
  698. public override void HandleShow(string mod, string[] cmd)
  699. {
  700. base.HandleShow(mod, cmd);
  701. List<string> args = new List<string>(cmd);
  702. args.RemoveAt(0);
  703. string[] showParams = args.ToArray();
  704. switch (showParams[0])
  705. {
  706. case "users":
  707. IList agents;
  708. if (showParams.Length > 1 && showParams[1] == "full")
  709. {
  710. agents = SceneManager.GetCurrentScenePresences();
  711. } else
  712. {
  713. agents = SceneManager.GetCurrentSceneAvatars();
  714. }
  715. MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count));
  716. MainConsole.Instance.Output(
  717. String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname",
  718. "Agent ID", "Root/Child", "Region", "Position")
  719. );
  720. foreach (ScenePresence presence in agents)
  721. {
  722. RegionInfo regionInfo = presence.Scene.RegionInfo;
  723. string regionName;
  724. if (regionInfo == null)
  725. {
  726. regionName = "Unresolvable";
  727. } else
  728. {
  729. regionName = regionInfo.RegionName;
  730. }
  731. MainConsole.Instance.Output(
  732. String.Format(
  733. "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}",
  734. presence.Firstname,
  735. presence.Lastname,
  736. presence.UUID,
  737. presence.IsChildAgent ? "Child" : "Root",
  738. regionName,
  739. presence.AbsolutePosition.ToString())
  740. );
  741. }
  742. MainConsole.Instance.Output(String.Empty);
  743. break;
  744. case "connections":
  745. HandleShowConnections();
  746. break;
  747. case "circuits":
  748. HandleShowCircuits();
  749. break;
  750. case "modules":
  751. SceneManager.ForEachSelectedScene(
  752. scene =>
  753. {
  754. MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name);
  755. List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>();
  756. List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>();
  757. foreach (IRegionModuleBase module in scene.RegionModules.Values)
  758. {
  759. if (module.GetType().GetInterface("ISharedRegionModule") != null)
  760. nonSharedModules.Add(module);
  761. else
  762. sharedModules.Add(module);
  763. }
  764. foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name))
  765. MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name);
  766. foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name))
  767. MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name);
  768. }
  769. );
  770. MainConsole.Instance.Output("");
  771. break;
  772. case "regions":
  773. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  774. cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize);
  775. cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize);
  776. cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize);
  777. cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize);
  778. cdt.AddColumn("Ready?", 6);
  779. cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize);
  780. SceneManager.ForEachScene(
  781. scene =>
  782. {
  783. RegionInfo ri = scene.RegionInfo;
  784. cdt.AddRow(
  785. ri.RegionName, ri.RegionID, string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY),
  786. ri.InternalEndPoint.Port, scene.Ready ? "Yes" : "No", ri.EstateSettings.EstateName);
  787. }
  788. );
  789. MainConsole.Instance.Output(cdt.ToString());
  790. break;
  791. case "ratings":
  792. SceneManager.ForEachScene(
  793. delegate(Scene scene)
  794. {
  795. string rating = "";
  796. if (scene.RegionInfo.RegionSettings.Maturity == 1)
  797. {
  798. rating = "MATURE";
  799. }
  800. else if (scene.RegionInfo.RegionSettings.Maturity == 2)
  801. {
  802. rating = "ADULT";
  803. }
  804. else
  805. {
  806. rating = "PG";
  807. }
  808. MainConsole.Instance.Output(String.Format(
  809. "Region Name: {0}, Region Rating {1}",
  810. scene.RegionInfo.RegionName,
  811. rating));
  812. });
  813. break;
  814. }
  815. }
  816. private void HandleShowCircuits()
  817. {
  818. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  819. cdt.AddColumn("Region", 20);
  820. cdt.AddColumn("Avatar name", 24);
  821. cdt.AddColumn("Type", 5);
  822. cdt.AddColumn("Code", 10);
  823. cdt.AddColumn("IP", 16);
  824. cdt.AddColumn("Viewer Name", 24);
  825. SceneManager.ForEachScene(
  826. s =>
  827. {
  828. foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values)
  829. cdt.AddRow(
  830. s.Name,
  831. aCircuit.Name,
  832. aCircuit.child ? "child" : "root",
  833. aCircuit.circuitcode.ToString(),
  834. aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set",
  835. Util.GetViewerName(aCircuit));
  836. });
  837. MainConsole.Instance.Output(cdt.ToString());
  838. }
  839. private void HandleShowConnections()
  840. {
  841. ConsoleDisplayTable cdt = new ConsoleDisplayTable();
  842. cdt.AddColumn("Region", 20);
  843. cdt.AddColumn("Avatar name", 24);
  844. cdt.AddColumn("Circuit code", 12);
  845. cdt.AddColumn("Endpoint", 23);
  846. cdt.AddColumn("Active?", 7);
  847. SceneManager.ForEachScene(
  848. s => s.ForEachClient(
  849. c => cdt.AddRow(
  850. s.Name,
  851. c.Name,
  852. c.CircuitCode.ToString(),
  853. c.RemoteEndPoint.ToString(),
  854. c.IsActive.ToString())));
  855. MainConsole.Instance.Output(cdt.ToString());
  856. }
  857. /// <summary>
  858. /// Use XML2 format to serialize data to a file
  859. /// </summary>
  860. /// <param name="module"></param>
  861. /// <param name="cmdparams"></param>
  862. protected void SavePrimsXml2(string module, string[] cmdparams)
  863. {
  864. if (cmdparams.Length > 5)
  865. {
  866. SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]);
  867. }
  868. else
  869. {
  870. SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME);
  871. }
  872. }
  873. /// <summary>
  874. /// Use XML format to serialize data to a file
  875. /// </summary>
  876. /// <param name="module"></param>
  877. /// <param name="cmdparams"></param>
  878. protected void SaveXml(string module, string[] cmdparams)
  879. {
  880. 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.");
  881. if (cmdparams.Length > 0)
  882. {
  883. SceneManager.SaveCurrentSceneToXml(cmdparams[2]);
  884. }
  885. else
  886. {
  887. SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME);
  888. }
  889. }
  890. /// <summary>
  891. /// Loads data and region objects from XML format.
  892. /// </summary>
  893. /// <param name="module"></param>
  894. /// <param name="cmdparams"></param>
  895. protected void LoadXml(string module, string[] cmdparams)
  896. {
  897. 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.");
  898. Vector3 loadOffset = new Vector3(0, 0, 0);
  899. if (cmdparams.Length > 2)
  900. {
  901. bool generateNewIDS = false;
  902. if (cmdparams.Length > 3)
  903. {
  904. if (cmdparams[3] == "-newUID")
  905. {
  906. generateNewIDS = true;
  907. }
  908. if (cmdparams.Length > 4)
  909. {
  910. loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo);
  911. if (cmdparams.Length > 5)
  912. {
  913. loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo);
  914. }
  915. if (cmdparams.Length > 6)
  916. {
  917. loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo);
  918. }
  919. MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z));
  920. }
  921. }
  922. SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset);
  923. }
  924. else
  925. {
  926. try
  927. {
  928. SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset);
  929. }
  930. catch (FileNotFoundException)
  931. {
  932. MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>");
  933. }
  934. }
  935. }
  936. /// <summary>
  937. /// Serialize region data to XML2Format
  938. /// </summary>
  939. /// <param name="module"></param>
  940. /// <param name="cmdparams"></param>
  941. protected void SaveXml2(string module, string[] cmdparams)
  942. {
  943. if (cmdparams.Length > 2)
  944. {
  945. SceneManager.SaveCurrentSceneToXml2(cmdparams[2]);
  946. }
  947. else
  948. {
  949. SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  950. }
  951. }
  952. /// <summary>
  953. /// Load region data from Xml2Format
  954. /// </summary>
  955. /// <param name="module"></param>
  956. /// <param name="cmdparams"></param>
  957. protected void LoadXml2(string module, string[] cmdparams)
  958. {
  959. if (cmdparams.Length > 2)
  960. {
  961. try
  962. {
  963. SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]);
  964. }
  965. catch (FileNotFoundException)
  966. {
  967. MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>");
  968. }
  969. }
  970. else
  971. {
  972. try
  973. {
  974. SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME);
  975. }
  976. catch (FileNotFoundException)
  977. {
  978. MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>");
  979. }
  980. }
  981. }
  982. /// <summary>
  983. /// Load a whole region from an opensimulator archive.
  984. /// </summary>
  985. /// <param name="cmdparams"></param>
  986. protected void LoadOar(string module, string[] cmdparams)
  987. {
  988. try
  989. {
  990. SceneManager.LoadArchiveToCurrentScene(cmdparams);
  991. }
  992. catch (Exception e)
  993. {
  994. MainConsole.Instance.Output(e.Message);
  995. }
  996. }
  997. /// <summary>
  998. /// Save a region to a file, including all the assets needed to restore it.
  999. /// </summary>
  1000. /// <param name="cmdparams"></param>
  1001. protected void SaveOar(string module, string[] cmdparams)
  1002. {
  1003. SceneManager.SaveCurrentSceneToArchive(cmdparams);
  1004. }
  1005. private static string CombineParams(string[] commandParams, int pos)
  1006. {
  1007. string result = String.Empty;
  1008. for (int i = pos; i < commandParams.Length; i++)
  1009. {
  1010. result += commandParams[i] + " ";
  1011. }
  1012. result = result.TrimEnd(' ');
  1013. return result;
  1014. }
  1015. #endregion
  1016. }
  1017. }