OpenSimBase.cs 42 KB

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