OpenSim.cs 43 KB

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