OpenSim.cs 44 KB

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