OpenSimBase.cs 42 KB

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