OpenSim.cs 47 KB

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