1
0

OpenSim.cs 48 KB

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