1
0

OpenSim.cs 49 KB

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