OpenSimBase.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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.Generic;
  29. using System.IO;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Text;
  33. using log4net;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Communications;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Framework.Servers;
  40. using OpenSim.Framework.Servers.HttpServer;
  41. using OpenSim.Framework.Statistics;
  42. using OpenSim.Region.ClientStack;
  43. using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
  44. using OpenSim.Region.Framework;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.Framework.Scenes;
  47. using OpenSim.Region.Physics.Manager;
  48. using OpenSim.Server.Base;
  49. using OpenSim.Services.Base;
  50. using OpenSim.Services.Interfaces;
  51. using OpenSim.Services.UserAccountService;
  52. namespace OpenSim
  53. {
  54. /// <summary>
  55. /// Common OpenSimulator simulator code
  56. /// </summary>
  57. public class OpenSimBase : RegionApplicationBase
  58. {
  59. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  60. // These are the names of the plugin-points extended by this
  61. // class during system startup.
  62. //
  63. private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache";
  64. private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient";
  65. protected string proxyUrl;
  66. protected int proxyOffset = 0;
  67. public string userStatsURI = String.Empty;
  68. protected bool m_autoCreateClientStack = true;
  69. /// <value>
  70. /// The file used to load and save prim backup xml if no filename has been specified
  71. /// </value>
  72. protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml";
  73. public ConfigSettings ConfigurationSettings
  74. {
  75. get { return m_configSettings; }
  76. set { m_configSettings = value; }
  77. }
  78. protected ConfigSettings m_configSettings;
  79. protected ConfigurationLoader m_configLoader;
  80. public ConsoleCommand CreateAccount = null;
  81. protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();
  82. /// <value>
  83. /// The config information passed into the OpenSimulator region server.
  84. /// </value>
  85. public OpenSimConfigSource ConfigSource
  86. {
  87. get { return m_config; }
  88. set { m_config = value; }
  89. }
  90. protected OpenSimConfigSource m_config;
  91. public List<IClientNetworkServer> ClientServers
  92. {
  93. get { return m_clientServers; }
  94. }
  95. protected EnvConfigSource m_EnvConfigSource = new EnvConfigSource();
  96. public EnvConfigSource envConfigSource
  97. {
  98. get { return m_EnvConfigSource; }
  99. }
  100. protected List<IClientNetworkServer> m_clientServers = new List<IClientNetworkServer>();
  101. public uint HttpServerPort
  102. {
  103. get { return m_httpServerPort; }
  104. }
  105. public ModuleLoader ModuleLoader
  106. {
  107. get { return m_moduleLoader; }
  108. set { m_moduleLoader = value; }
  109. }
  110. protected ModuleLoader m_moduleLoader;
  111. protected IRegistryCore m_applicationRegistry = new RegistryCore();
  112. public IRegistryCore ApplicationRegistry
  113. {
  114. get { return m_applicationRegistry; }
  115. }
  116. /// <summary>
  117. /// Constructor.
  118. /// </summary>
  119. /// <param name="configSource"></param>
  120. public OpenSimBase(IConfigSource configSource) : base()
  121. {
  122. LoadConfigSettings(configSource);
  123. }
  124. protected virtual void LoadConfigSettings(IConfigSource configSource)
  125. {
  126. m_configLoader = new ConfigurationLoader();
  127. m_config = m_configLoader.LoadConfigSettings(configSource, envConfigSource, out m_configSettings, out m_networkServersInfo);
  128. ReadExtraConfigSettings();
  129. }
  130. protected virtual void ReadExtraConfigSettings()
  131. {
  132. IConfig networkConfig = m_config.Source.Configs["Network"];
  133. if (networkConfig != null)
  134. {
  135. proxyUrl = networkConfig.GetString("proxy_url", "");
  136. proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0"));
  137. }
  138. }
  139. protected virtual void LoadPlugins()
  140. {
  141. using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this)))
  142. {
  143. loader.Load("/OpenSim/Startup");
  144. m_plugins = loader.Plugins;
  145. }
  146. }
  147. protected override List<string> GetHelpTopics()
  148. {
  149. List<string> topics = base.GetHelpTopics();
  150. Scene s = SceneManager.CurrentOrFirstScene;
  151. if (s != null && s.GetCommanders() != null)
  152. topics.AddRange(s.GetCommanders().Keys);
  153. return topics;
  154. }
  155. /// <summary>
  156. /// Performs startup specific to the region server, including initialization of the scene
  157. /// such as loading configuration from disk.
  158. /// </summary>
  159. protected override void StartupSpecific()
  160. {
  161. IConfig startupConfig = m_config.Source.Configs["Startup"];
  162. if (startupConfig != null)
  163. {
  164. string pidFile = startupConfig.GetString("PIDFile", String.Empty);
  165. if (pidFile != String.Empty)
  166. CreatePIDFile(pidFile);
  167. userStatsURI = startupConfig.GetString("Stats_URI", String.Empty);
  168. }
  169. // Load the simulation data service
  170. IConfig simDataConfig = m_config.Source.Configs["SimulationDataStore"];
  171. if (simDataConfig == null)
  172. throw new Exception("Configuration file is missing the [SimulationDataStore] section. Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");
  173. string module = simDataConfig.GetString("LocalServiceModule", String.Empty);
  174. if (String.IsNullOrEmpty(module))
  175. throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section.");
  176. m_simulationDataService = ServerUtils.LoadPlugin<ISimulationDataService>(module, new object[] { m_config.Source });
  177. // Load the estate data service
  178. IConfig estateDataConfig = m_config.Source.Configs["EstateDataStore"];
  179. if (estateDataConfig == null)
  180. throw new Exception("Configuration file is missing the [EstateDataStore] section. Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");
  181. module = estateDataConfig.GetString("LocalServiceModule", String.Empty);
  182. if (String.IsNullOrEmpty(module))
  183. throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] section");
  184. m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { m_config.Source });
  185. base.StartupSpecific();
  186. m_stats = StatsManager.SimExtraStats;
  187. // Create a ModuleLoader instance
  188. m_moduleLoader = new ModuleLoader(m_config.Source);
  189. LoadPlugins();
  190. foreach (IApplicationPlugin plugin in m_plugins)
  191. {
  192. plugin.PostInitialise();
  193. }
  194. AddPluginCommands();
  195. }
  196. protected virtual void AddPluginCommands()
  197. {
  198. // If console exists add plugin commands.
  199. if (m_console != null)
  200. {
  201. List<string> topics = GetHelpTopics();
  202. foreach (string topic in topics)
  203. {
  204. string capitalizedTopic = char.ToUpper(topic[0]) + topic.Substring(1);
  205. // This is a hack to allow the user to enter the help command in upper or lowercase. This will go
  206. // away at some point.
  207. m_console.Commands.AddCommand(capitalizedTopic, false, "help " + topic,
  208. "help " + capitalizedTopic,
  209. "Get help on plugin command '" + topic + "'",
  210. HandleCommanderHelp);
  211. m_console.Commands.AddCommand(capitalizedTopic, false, "help " + capitalizedTopic,
  212. "help " + capitalizedTopic,
  213. "Get help on plugin command '" + topic + "'",
  214. HandleCommanderHelp);
  215. ICommander commander = null;
  216. Scene s = SceneManager.CurrentOrFirstScene;
  217. if (s != null && s.GetCommanders() != null)
  218. {
  219. if (s.GetCommanders().ContainsKey(topic))
  220. commander = s.GetCommanders()[topic];
  221. }
  222. if (commander == null)
  223. continue;
  224. foreach (string command in commander.Commands.Keys)
  225. {
  226. m_console.Commands.AddCommand(capitalizedTopic, false,
  227. topic + " " + command,
  228. topic + " " + commander.Commands[command].ShortHelp(),
  229. String.Empty, HandleCommanderCommand);
  230. }
  231. }
  232. }
  233. }
  234. private void HandleCommanderCommand(string module, string[] cmd)
  235. {
  236. SceneManager.SendCommandToPluginModules(cmd);
  237. }
  238. private void HandleCommanderHelp(string module, string[] cmd)
  239. {
  240. // Only safe for the interactive console, since it won't
  241. // let us come here unless both scene and commander exist
  242. //
  243. ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1].ToLower());
  244. if (moduleCommander != null)
  245. m_console.Output(moduleCommander.Help);
  246. }
  247. protected override void Initialize()
  248. {
  249. // Called from base.StartUp()
  250. m_httpServerPort = m_networkServersInfo.HttpListenerPort;
  251. SceneManager.OnRestartSim += handleRestartRegion;
  252. // Only start the memory watchdog once all regions are ready
  253. SceneManager.OnRegionsReadyStatusChange += sm => MemoryWatchdog.Enabled = sm.AllRegionsReady;
  254. }
  255. /// <summary>
  256. /// Execute the region creation process. This includes setting up scene infrastructure.
  257. /// </summary>
  258. /// <param name="regionInfo"></param>
  259. /// <param name="portadd_flag"></param>
  260. /// <returns></returns>
  261. public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene)
  262. {
  263. return CreateRegion(regionInfo, portadd_flag, false, out scene);
  264. }
  265. /// <summary>
  266. /// Execute the region creation process. This includes setting up scene infrastructure.
  267. /// </summary>
  268. /// <param name="regionInfo"></param>
  269. /// <returns></returns>
  270. public IClientNetworkServer CreateRegion(RegionInfo regionInfo, out IScene scene)
  271. {
  272. return CreateRegion(regionInfo, false, true, out scene);
  273. }
  274. /// <summary>
  275. /// Execute the region creation process. This includes setting up scene infrastructure.
  276. /// </summary>
  277. /// <param name="regionInfo"></param>
  278. /// <param name="portadd_flag"></param>
  279. /// <param name="do_post_init"></param>
  280. /// <returns></returns>
  281. public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene)
  282. {
  283. int port = regionInfo.InternalEndPoint.Port;
  284. // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims)
  285. // Commented this out because otherwise regions can't register with
  286. // the grid as there is already another region with the same UUID
  287. // at those coordinates. This is required for the load balancer to work.
  288. // --Mike, 2009.02.25
  289. //regionInfo.originRegionID = regionInfo.RegionID;
  290. // set initial ServerURI
  291. regionInfo.HttpPort = m_httpServerPort;
  292. regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort.ToString() + "/";
  293. regionInfo.osSecret = m_osSecret;
  294. if ((proxyUrl.Length > 0) && (portadd_flag))
  295. {
  296. // set proxy url to RegionInfo
  297. regionInfo.proxyUrl = proxyUrl;
  298. regionInfo.ProxyOffset = proxyOffset;
  299. Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName);
  300. }
  301. IClientNetworkServer clientServer;
  302. Scene scene = SetupScene(regionInfo, proxyOffset, m_config.Source, out clientServer);
  303. m_log.Info("[MODULES]: Loading Region's modules (old style)");
  304. List<IRegionModule> modules = m_moduleLoader.PickupModules(scene, ".");
  305. // This needs to be ahead of the script engine load, so the
  306. // script module can pick up events exposed by a module
  307. m_moduleLoader.InitialiseSharedModules(scene);
  308. // Use this in the future, the line above will be deprecated soon
  309. m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)");
  310. IRegionModulesController controller;
  311. if (ApplicationRegistry.TryGet(out controller))
  312. {
  313. controller.AddRegionToModules(scene);
  314. }
  315. else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing...");
  316. scene.SetModuleInterfaces();
  317. while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
  318. SetUpEstateOwner(scene);
  319. // Prims have to be loaded after module configuration since some modules may be invoked during the load
  320. scene.LoadPrimsFromStorage(regionInfo.originRegionID);
  321. // TODO : Try setting resource for region xstats here on scene
  322. MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo));
  323. scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
  324. scene.EventManager.TriggerParcelPrimCountUpdate();
  325. try
  326. {
  327. scene.RegisterRegionWithGrid();
  328. }
  329. catch (Exception e)
  330. {
  331. m_log.ErrorFormat(
  332. "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}",
  333. e.Message, e.StackTrace);
  334. // Carrying on now causes a lot of confusion down the
  335. // line - we need to get the user's attention
  336. Environment.Exit(1);
  337. }
  338. // We need to do this after we've initialized the
  339. // scripting engines.
  340. scene.CreateScriptInstances();
  341. SceneManager.Add(scene);
  342. if (m_autoCreateClientStack)
  343. {
  344. m_clientServers.Add(clientServer);
  345. clientServer.Start();
  346. }
  347. if (do_post_init)
  348. {
  349. foreach (IRegionModule module in modules)
  350. {
  351. module.PostInitialise();
  352. }
  353. }
  354. scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };
  355. mscene = scene;
  356. scene.Start();
  357. scene.StartScripts();
  358. return clientServer;
  359. }
  360. /// <summary>
  361. /// Try to set up the estate owner for the given scene.
  362. /// </summary>
  363. /// <remarks>
  364. /// The involves asking the user for information about the user on the console. If the user does not already
  365. /// exist then it is created.
  366. /// </remarks>
  367. /// <param name="scene"></param>
  368. private void SetUpEstateOwner(Scene scene)
  369. {
  370. RegionInfo regionInfo = scene.RegionInfo;
  371. MainConsole.Instance.OutputFormat("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName);
  372. List<char> excluded = new List<char>(new char[1]{' '});
  373. string first = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test", excluded);
  374. string last = MainConsole.Instance.CmdPrompt("Estate owner last name", "User", excluded);
  375. UserAccount account = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, first, last);
  376. if (account == null)
  377. {
  378. // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than
  379. // itself!
  380. // if (scene.UserAccountService is LocalUserAccountServicesConnector)
  381. // {
  382. // IUserAccountService innerUas
  383. // = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService;
  384. //
  385. // m_log.DebugFormat("B {0}", innerUas.GetType());
  386. //
  387. // if (innerUas is UserAccountService)
  388. // {
  389. if (scene.UserAccountService is UserAccountService)
  390. {
  391. string password = MainConsole.Instance.PasswdPrompt("Password");
  392. string email = MainConsole.Instance.CmdPrompt("Email", "");
  393. string rawPrincipalId = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString());
  394. UUID principalId = UUID.Zero;
  395. if (!UUID.TryParse(rawPrincipalId, out principalId))
  396. {
  397. m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawPrincipalId);
  398. return;
  399. }
  400. account
  401. = ((UserAccountService)scene.UserAccountService).CreateUser(
  402. regionInfo.ScopeID, principalId, first, last, password, email);
  403. }
  404. // }
  405. }
  406. if (account == null)
  407. {
  408. m_log.ErrorFormat(
  409. "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first.");
  410. }
  411. else
  412. {
  413. regionInfo.EstateSettings.EstateOwner = account.PrincipalID;
  414. regionInfo.EstateSettings.Save();
  415. }
  416. }
  417. private void ShutdownRegion(Scene scene)
  418. {
  419. m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName);
  420. IRegionModulesController controller;
  421. if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller))
  422. {
  423. controller.RemoveRegionFromModules(scene);
  424. }
  425. }
  426. public void RemoveRegion(Scene scene, bool cleanup)
  427. {
  428. // only need to check this if we are not at the
  429. // root level
  430. if ((SceneManager.CurrentScene != null) &&
  431. (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  432. {
  433. SceneManager.TrySetCurrentScene("..");
  434. }
  435. scene.DeleteAllSceneObjects();
  436. SceneManager.CloseScene(scene);
  437. ShutdownClientServer(scene.RegionInfo);
  438. if (!cleanup)
  439. return;
  440. if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile))
  441. {
  442. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml"))
  443. {
  444. File.Delete(scene.RegionInfo.RegionFile);
  445. m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile);
  446. }
  447. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini"))
  448. {
  449. try
  450. {
  451. IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile);
  452. if (source.Configs[scene.RegionInfo.RegionName] != null)
  453. {
  454. source.Configs.Remove(scene.RegionInfo.RegionName);
  455. if (source.Configs.Count == 0)
  456. {
  457. File.Delete(scene.RegionInfo.RegionFile);
  458. }
  459. else
  460. {
  461. source.Save(scene.RegionInfo.RegionFile);
  462. }
  463. }
  464. }
  465. catch (Exception)
  466. {
  467. }
  468. }
  469. }
  470. }
  471. public void RemoveRegion(string name, bool cleanUp)
  472. {
  473. Scene target;
  474. if (SceneManager.TryGetScene(name, out target))
  475. RemoveRegion(target, cleanUp);
  476. }
  477. /// <summary>
  478. /// Remove a region from the simulator without deleting it permanently.
  479. /// </summary>
  480. /// <param name="scene"></param>
  481. /// <returns></returns>
  482. public void CloseRegion(Scene scene)
  483. {
  484. // only need to check this if we are not at the
  485. // root level
  486. if ((SceneManager.CurrentScene != null) &&
  487. (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  488. {
  489. SceneManager.TrySetCurrentScene("..");
  490. }
  491. SceneManager.CloseScene(scene);
  492. ShutdownClientServer(scene.RegionInfo);
  493. }
  494. /// <summary>
  495. /// Remove a region from the simulator without deleting it permanently.
  496. /// </summary>
  497. /// <param name="name"></param>
  498. /// <returns></returns>
  499. public void CloseRegion(string name)
  500. {
  501. Scene target;
  502. if (SceneManager.TryGetScene(name, out target))
  503. CloseRegion(target);
  504. }
  505. /// <summary>
  506. /// Create a scene and its initial base structures.
  507. /// </summary>
  508. /// <param name="regionInfo"></param>
  509. /// <param name="clientServer"> </param>
  510. /// <returns></returns>
  511. protected Scene SetupScene(RegionInfo regionInfo, out IClientNetworkServer clientServer)
  512. {
  513. return SetupScene(regionInfo, 0, null, out clientServer);
  514. }
  515. /// <summary>
  516. /// Create a scene and its initial base structures.
  517. /// </summary>
  518. /// <param name="regionInfo"></param>
  519. /// <param name="proxyOffset"></param>
  520. /// <param name="configSource"></param>
  521. /// <param name="clientServer"> </param>
  522. /// <returns></returns>
  523. protected Scene SetupScene(
  524. RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out IClientNetworkServer clientServer)
  525. {
  526. AgentCircuitManager circuitManager = new AgentCircuitManager();
  527. IPAddress listenIP = regionInfo.InternalEndPoint.Address;
  528. //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP))
  529. // listenIP = IPAddress.Parse("0.0.0.0");
  530. uint port = (uint) regionInfo.InternalEndPoint.Port;
  531. if (m_autoCreateClientStack)
  532. {
  533. clientServer
  534. = m_clientStackManager.CreateServer(
  535. listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource,
  536. circuitManager);
  537. }
  538. else
  539. {
  540. clientServer = null;
  541. }
  542. regionInfo.InternalEndPoint.Port = (int) port;
  543. Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager);
  544. if (m_autoCreateClientStack)
  545. {
  546. clientServer.AddScene(scene);
  547. }
  548. scene.LoadWorldMap();
  549. scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName);
  550. scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised());
  551. scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);
  552. return scene;
  553. }
  554. protected override ClientStackManager CreateClientStackManager()
  555. {
  556. return new ClientStackManager(m_configSettings.ClientstackDll);
  557. }
  558. protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
  559. IEstateDataService estateDataService, AgentCircuitManager circuitManager)
  560. {
  561. SceneCommunicationService sceneGridService = new SceneCommunicationService();
  562. return new Scene(
  563. regionInfo, circuitManager, sceneGridService,
  564. simDataService, estateDataService, m_moduleLoader, false,
  565. m_config.Source, m_version);
  566. }
  567. protected void ShutdownClientServer(RegionInfo whichRegion)
  568. {
  569. // Close and remove the clientserver for a region
  570. bool foundClientServer = false;
  571. int clientServerElement = 0;
  572. Location location = new Location(whichRegion.RegionHandle);
  573. for (int i = 0; i < m_clientServers.Count; i++)
  574. {
  575. if (m_clientServers[i].HandlesRegion(location))
  576. {
  577. clientServerElement = i;
  578. foundClientServer = true;
  579. break;
  580. }
  581. }
  582. if (foundClientServer)
  583. {
  584. m_clientServers[clientServerElement].NetworkStop();
  585. m_clientServers.RemoveAt(clientServerElement);
  586. }
  587. }
  588. public void handleRestartRegion(RegionInfo whichRegion)
  589. {
  590. m_log.Info("[OPENSIM]: Got restart signal from SceneManager");
  591. ShutdownClientServer(whichRegion);
  592. IScene scene;
  593. CreateRegion(whichRegion, true, out scene);
  594. }
  595. # region Setup methods
  596. protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier)
  597. {
  598. return GetPhysicsScene(
  599. m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, m_config.Source, osSceneIdentifier);
  600. }
  601. /// <summary>
  602. /// Handler to supply the current status of this sim
  603. /// </summary>
  604. /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
  605. public class SimStatusHandler : IStreamedRequestHandler
  606. {
  607. public byte[] Handle(string path, Stream request,
  608. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  609. {
  610. return Util.UTF8.GetBytes("OK");
  611. }
  612. public string Name { get { return "SimStatus"; } }
  613. public string Description { get { return "Simulator Status"; } }
  614. public string ContentType
  615. {
  616. get { return "text/plain"; }
  617. }
  618. public string HttpMethod
  619. {
  620. get { return "GET"; }
  621. }
  622. public string Path
  623. {
  624. get { return "/simstatus"; }
  625. }
  626. }
  627. /// <summary>
  628. /// Handler to supply the current extended status of this sim
  629. /// Sends the statistical data in a json serialization
  630. /// </summary>
  631. public class XSimStatusHandler : IStreamedRequestHandler
  632. {
  633. OpenSimBase m_opensim;
  634. string osXStatsURI = String.Empty;
  635. public string Name { get { return "XSimStatus"; } }
  636. public string Description { get { return "Simulator XStatus"; } }
  637. public XSimStatusHandler(OpenSimBase sim)
  638. {
  639. m_opensim = sim;
  640. osXStatsURI = Util.SHA1Hash(sim.osSecret);
  641. }
  642. public byte[] Handle(string path, Stream request,
  643. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  644. {
  645. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  646. }
  647. public string ContentType
  648. {
  649. get { return "text/plain"; }
  650. }
  651. public string HttpMethod
  652. {
  653. get { return "GET"; }
  654. }
  655. public string Path
  656. {
  657. // This is for the OpenSimulator instance and is the osSecret hashed
  658. get { return "/" + osXStatsURI; }
  659. }
  660. }
  661. /// <summary>
  662. /// Handler to supply the current extended status of this sim to a user configured URI
  663. /// Sends the statistical data in a json serialization
  664. /// If the request contains a key, "callback" the response will be wrappend in the
  665. /// associated value for jsonp used with ajax/javascript
  666. /// </summary>
  667. public class UXSimStatusHandler : IStreamedRequestHandler
  668. {
  669. OpenSimBase m_opensim;
  670. string osUXStatsURI = String.Empty;
  671. public string Name { get { return "UXSimStatus"; } }
  672. public string Description { get { return "Simulator UXStatus"; } }
  673. public UXSimStatusHandler(OpenSimBase sim)
  674. {
  675. m_opensim = sim;
  676. osUXStatsURI = sim.userStatsURI;
  677. }
  678. public byte[] Handle(string path, Stream request,
  679. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  680. {
  681. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  682. }
  683. public string ContentType
  684. {
  685. get { return "text/plain"; }
  686. }
  687. public string HttpMethod
  688. {
  689. get { return "GET"; }
  690. }
  691. public string Path
  692. {
  693. // This is for the OpenSimulator instance and is the user provided URI
  694. get { return "/" + osUXStatsURI; }
  695. }
  696. }
  697. #endregion
  698. /// <summary>
  699. /// Performs any last-minute sanity checking and shuts down the region server
  700. /// </summary>
  701. public override void ShutdownSpecific()
  702. {
  703. if (proxyUrl.Length > 0)
  704. {
  705. Util.XmlRpcCommand(proxyUrl, "Stop");
  706. }
  707. m_log.Info("[SHUTDOWN]: Closing all threads");
  708. m_log.Info("[SHUTDOWN]: Killing listener thread");
  709. m_log.Info("[SHUTDOWN]: Killing clients");
  710. // TODO: implement this
  711. m_log.Info("[SHUTDOWN]: Closing console and terminating");
  712. try
  713. {
  714. SceneManager.Close();
  715. }
  716. catch (Exception e)
  717. {
  718. m_log.ErrorFormat("[SHUTDOWN]: Ignoring failure during shutdown - {0}", e);
  719. }
  720. }
  721. /// <summary>
  722. /// Get the start time and up time of Region server
  723. /// </summary>
  724. /// <param name="starttime">The first out parameter describing when the Region server started</param>
  725. /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
  726. public void GetRunTime(out string starttime, out string uptime)
  727. {
  728. starttime = m_startuptime.ToString();
  729. uptime = (DateTime.Now - m_startuptime).ToString();
  730. }
  731. /// <summary>
  732. /// Get the number of the avatars in the Region server
  733. /// </summary>
  734. /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
  735. public void GetAvatarNumber(out int usernum)
  736. {
  737. usernum = SceneManager.GetCurrentSceneAvatars().Count;
  738. }
  739. /// <summary>
  740. /// Get the number of regions
  741. /// </summary>
  742. /// <param name="regionnum">The first out parameter describing the number of regions</param>
  743. public void GetRegionNumber(out int regionnum)
  744. {
  745. regionnum = SceneManager.Scenes.Count;
  746. }
  747. /// <summary>
  748. /// Create an estate with an initial region.
  749. /// </summary>
  750. /// <remarks>
  751. /// This method doesn't allow an estate to be created with the same name as existing estates.
  752. /// </remarks>
  753. /// <param name="regInfo"></param>
  754. /// <param name="existingName">A list of estate names that already exist.</param>
  755. /// <returns>true if the estate was created, false otherwise</returns>
  756. public bool CreateEstate(RegionInfo regInfo, List<string> existingNames)
  757. {
  758. // Create a new estate
  759. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);
  760. string newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName);
  761. if (existingNames.Contains(newName))
  762. {
  763. MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName);
  764. return false;
  765. }
  766. regInfo.EstateSettings.EstateName = newName;
  767. // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
  768. // Therefore, we need to do an initial save here otherwise the new estate name will be reset
  769. // back to the default. The reloading of estate settings by scene could be eliminated if it
  770. // knows that the passed in settings in RegionInfo are already valid. Also, it might be
  771. // possible to eliminate some additional later saves made by callers of this method.
  772. regInfo.EstateSettings.Save();
  773. return true;
  774. }
  775. /// <summary>
  776. /// Load the estate information for the provided RegionInfo object.
  777. /// </summary>
  778. /// <param name="regInfo"></param>
  779. public void PopulateRegionEstateInfo(RegionInfo regInfo)
  780. {
  781. if (EstateDataService != null)
  782. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);
  783. if (regInfo.EstateSettings.EstateID == 0) // No record at all
  784. {
  785. m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
  786. List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();
  787. List<string> estateNames = new List<string>();
  788. foreach (EstateSettings estate in estates)
  789. estateNames.Add(estate.EstateName);
  790. while (true)
  791. {
  792. if (estates.Count == 0)
  793. {
  794. m_log.Info("[ESTATE] No existing estates found. You must create a new one.");
  795. if (CreateEstate(regInfo, estateNames))
  796. break;
  797. else
  798. continue;
  799. }
  800. else
  801. {
  802. string response
  803. = MainConsole.Instance.CmdPrompt(
  804. string.Format(
  805. "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
  806. "yes",
  807. new List<string>() { "yes", "no" });
  808. if (response == "no")
  809. {
  810. if (CreateEstate(regInfo, estateNames))
  811. break;
  812. else
  813. continue;
  814. }
  815. else
  816. {
  817. response
  818. = MainConsole.Instance.CmdPrompt(
  819. string.Format(
  820. "Name of estate to join. Existing estate names are ({0})", string.Join(", ", estateNames.ToArray())),
  821. estateNames[0]);
  822. List<int> estateIDs = EstateDataService.GetEstates(response);
  823. if (estateIDs.Count < 1)
  824. {
  825. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again.");
  826. continue;
  827. }
  828. int estateID = estateIDs[0];
  829. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);
  830. if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
  831. break;
  832. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  833. }
  834. }
  835. }
  836. }
  837. }
  838. }
  839. public class OpenSimConfigSource
  840. {
  841. public IConfigSource Source;
  842. public void Save(string path)
  843. {
  844. if (Source is IniConfigSource)
  845. {
  846. IniConfigSource iniCon = (IniConfigSource) Source;
  847. iniCon.Save(path);
  848. }
  849. else if (Source is XmlConfigSource)
  850. {
  851. XmlConfigSource xmlCon = (XmlConfigSource) Source;
  852. xmlCon.Save(path);
  853. }
  854. }
  855. }
  856. }