OpenSimBase.cs 44 KB

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