OpenSimBase.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. {
  196. StatsManager.RegisterConsoleCommands(m_console);
  197. AddPluginCommands(m_console);
  198. }
  199. }
  200. protected virtual void AddPluginCommands(ICommandConsole console)
  201. {
  202. List<string> topics = GetHelpTopics();
  203. foreach (string topic in topics)
  204. {
  205. string capitalizedTopic = char.ToUpper(topic[0]) + topic.Substring(1);
  206. // This is a hack to allow the user to enter the help command in upper or lowercase. This will go
  207. // away at some point.
  208. console.Commands.AddCommand(capitalizedTopic, false, "help " + topic,
  209. "help " + capitalizedTopic,
  210. "Get help on plugin command '" + topic + "'",
  211. HandleCommanderHelp);
  212. console.Commands.AddCommand(capitalizedTopic, false, "help " + capitalizedTopic,
  213. "help " + capitalizedTopic,
  214. "Get help on plugin command '" + topic + "'",
  215. HandleCommanderHelp);
  216. ICommander commander = null;
  217. Scene s = SceneManager.CurrentOrFirstScene;
  218. if (s != null && s.GetCommanders() != null)
  219. {
  220. if (s.GetCommanders().ContainsKey(topic))
  221. commander = s.GetCommanders()[topic];
  222. }
  223. if (commander == null)
  224. continue;
  225. foreach (string command in commander.Commands.Keys)
  226. {
  227. console.Commands.AddCommand(capitalizedTopic, false,
  228. topic + " " + command,
  229. topic + " " + commander.Commands[command].ShortHelp(),
  230. String.Empty, HandleCommanderCommand);
  231. }
  232. }
  233. }
  234. private void HandleCommanderCommand(string module, string[] cmd)
  235. {
  236. SceneManager.SendCommandToPluginModules(cmd);
  237. }
  238. private void HandleCommanderHelp(string module, string[] cmd)
  239. {
  240. // Only safe for the interactive console, since it won't
  241. // let us come here unless both scene and commander exist
  242. //
  243. ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1].ToLower());
  244. if (moduleCommander != null)
  245. m_console.Output(moduleCommander.Help);
  246. }
  247. protected override void Initialize()
  248. {
  249. // Called from base.StartUp()
  250. m_httpServerPort = m_networkServersInfo.HttpListenerPort;
  251. SceneManager.OnRestartSim += HandleRestartRegion;
  252. // Only enable the watchdogs when all regions are ready. Otherwise we get false positives when cpu is
  253. // heavily used during initial startup.
  254. //
  255. // FIXME: It's also possible that region ready status should be flipped during an OAR load since this
  256. // also makes heavy use of the CPU.
  257. SceneManager.OnRegionsReadyStatusChange
  258. += sm => { MemoryWatchdog.Enabled = sm.AllRegionsReady; Watchdog.Enabled = sm.AllRegionsReady; };
  259. }
  260. /// <summary>
  261. /// Execute the region creation process. This includes setting up scene infrastructure.
  262. /// </summary>
  263. /// <param name="regionInfo"></param>
  264. /// <param name="portadd_flag"></param>
  265. /// <returns></returns>
  266. public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene)
  267. {
  268. return CreateRegion(regionInfo, portadd_flag, false, out scene);
  269. }
  270. /// <summary>
  271. /// Execute the region creation process. This includes setting up scene infrastructure.
  272. /// </summary>
  273. /// <param name="regionInfo"></param>
  274. /// <returns></returns>
  275. public IClientNetworkServer CreateRegion(RegionInfo regionInfo, out IScene scene)
  276. {
  277. return CreateRegion(regionInfo, false, true, out scene);
  278. }
  279. /// <summary>
  280. /// Execute the region creation process. This includes setting up scene infrastructure.
  281. /// </summary>
  282. /// <param name="regionInfo"></param>
  283. /// <param name="portadd_flag"></param>
  284. /// <param name="do_post_init"></param>
  285. /// <returns></returns>
  286. public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene)
  287. {
  288. int port = regionInfo.InternalEndPoint.Port;
  289. // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims)
  290. // Commented this out because otherwise regions can't register with
  291. // the grid as there is already another region with the same UUID
  292. // at those coordinates. This is required for the load balancer to work.
  293. // --Mike, 2009.02.25
  294. //regionInfo.originRegionID = regionInfo.RegionID;
  295. // set initial ServerURI
  296. regionInfo.HttpPort = m_httpServerPort;
  297. regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort.ToString() + "/";
  298. regionInfo.osSecret = m_osSecret;
  299. if ((proxyUrl.Length > 0) && (portadd_flag))
  300. {
  301. // set proxy url to RegionInfo
  302. regionInfo.proxyUrl = proxyUrl;
  303. regionInfo.ProxyOffset = proxyOffset;
  304. Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName);
  305. }
  306. IClientNetworkServer clientServer;
  307. Scene scene = SetupScene(regionInfo, proxyOffset, Config, out clientServer);
  308. m_log.Info("[MODULES]: Loading Region's modules (old style)");
  309. // Use this in the future, the line above will be deprecated soon
  310. m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)");
  311. IRegionModulesController controller;
  312. if (ApplicationRegistry.TryGet(out controller))
  313. {
  314. controller.AddRegionToModules(scene);
  315. }
  316. else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing...");
  317. scene.SetModuleInterfaces();
  318. while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
  319. SetUpEstateOwner(scene);
  320. // Prims have to be loaded after module configuration since some modules may be invoked during the load
  321. scene.LoadPrimsFromStorage(regionInfo.originRegionID);
  322. // TODO : Try setting resource for region xstats here on scene
  323. MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo));
  324. scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
  325. scene.EventManager.TriggerParcelPrimCountUpdate();
  326. try
  327. {
  328. scene.RegisterRegionWithGrid();
  329. }
  330. catch (Exception e)
  331. {
  332. m_log.ErrorFormat(
  333. "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}",
  334. e.Message, e.StackTrace);
  335. // Carrying on now causes a lot of confusion down the
  336. // line - we need to get the user's attention
  337. Environment.Exit(1);
  338. }
  339. // We need to do this after we've initialized the
  340. // scripting engines.
  341. scene.CreateScriptInstances();
  342. SceneManager.Add(scene);
  343. if (m_autoCreateClientStack)
  344. {
  345. m_clientServers.Add(clientServer);
  346. clientServer.Start();
  347. }
  348. scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };
  349. mscene = scene;
  350. scene.Start();
  351. scene.StartScripts();
  352. return clientServer;
  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 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 IClientNetworkServer clientServer)
  553. {
  554. AgentCircuitManager circuitManager = new AgentCircuitManager();
  555. IPAddress listenIP = regionInfo.InternalEndPoint.Address;
  556. //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP))
  557. // listenIP = IPAddress.Parse("0.0.0.0");
  558. uint port = (uint) regionInfo.InternalEndPoint.Port;
  559. if (m_autoCreateClientStack)
  560. {
  561. clientServer
  562. = m_clientStackManager.CreateServer(
  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. clientServer.AddScene(scene);
  575. }
  576. scene.LoadWorldMap();
  577. scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName);
  578. scene.PhysicsScene.RequestAssetMethod = scene.PhysicsRequestAsset;
  579. scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised());
  580. scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);
  581. return scene;
  582. }
  583. protected override ClientStackManager CreateClientStackManager()
  584. {
  585. return new ClientStackManager(m_configSettings.ClientstackDll);
  586. }
  587. protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
  588. IEstateDataService estateDataService, AgentCircuitManager circuitManager)
  589. {
  590. SceneCommunicationService sceneGridService = new SceneCommunicationService();
  591. return new Scene(
  592. regionInfo, circuitManager, sceneGridService,
  593. simDataService, estateDataService, false,
  594. Config, m_version);
  595. }
  596. protected void ShutdownClientServer(RegionInfo whichRegion)
  597. {
  598. // Close and remove the clientserver for a region
  599. bool foundClientServer = false;
  600. int clientServerElement = 0;
  601. Location location = new Location(whichRegion.RegionHandle);
  602. for (int i = 0; i < m_clientServers.Count; i++)
  603. {
  604. if (m_clientServers[i].HandlesRegion(location))
  605. {
  606. clientServerElement = i;
  607. foundClientServer = true;
  608. break;
  609. }
  610. }
  611. if (foundClientServer)
  612. {
  613. m_clientServers[clientServerElement].NetworkStop();
  614. m_clientServers.RemoveAt(clientServerElement);
  615. }
  616. }
  617. protected virtual void HandleRestartRegion(RegionInfo whichRegion)
  618. {
  619. m_log.InfoFormat(
  620. "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})",
  621. whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY);
  622. ShutdownClientServer(whichRegion);
  623. IScene scene;
  624. CreateRegion(whichRegion, true, out scene);
  625. }
  626. # region Setup methods
  627. protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier)
  628. {
  629. return GetPhysicsScene(
  630. m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, Config, osSceneIdentifier);
  631. }
  632. /// <summary>
  633. /// Handler to supply the current status of this sim
  634. /// </summary>
  635. /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
  636. public class SimStatusHandler : IStreamedRequestHandler
  637. {
  638. public byte[] Handle(string path, Stream request,
  639. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  640. {
  641. return Util.UTF8.GetBytes("OK");
  642. }
  643. public string Name { get { return "SimStatus"; } }
  644. public string Description { get { return "Simulator Status"; } }
  645. public string ContentType
  646. {
  647. get { return "text/plain"; }
  648. }
  649. public string HttpMethod
  650. {
  651. get { return "GET"; }
  652. }
  653. public string Path
  654. {
  655. get { return "/simstatus"; }
  656. }
  657. }
  658. /// <summary>
  659. /// Handler to supply the current extended status of this sim
  660. /// Sends the statistical data in a json serialization
  661. /// </summary>
  662. public class XSimStatusHandler : IStreamedRequestHandler
  663. {
  664. OpenSimBase m_opensim;
  665. string osXStatsURI = String.Empty;
  666. public string Name { get { return "XSimStatus"; } }
  667. public string Description { get { return "Simulator XStatus"; } }
  668. public XSimStatusHandler(OpenSimBase sim)
  669. {
  670. m_opensim = sim;
  671. osXStatsURI = Util.SHA1Hash(sim.osSecret);
  672. }
  673. public byte[] Handle(string path, Stream request,
  674. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  675. {
  676. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  677. }
  678. public string ContentType
  679. {
  680. get { return "text/plain"; }
  681. }
  682. public string HttpMethod
  683. {
  684. get { return "GET"; }
  685. }
  686. public string Path
  687. {
  688. // This is for the OpenSimulator instance and is the osSecret hashed
  689. get { return "/" + osXStatsURI; }
  690. }
  691. }
  692. /// <summary>
  693. /// Handler to supply the current extended status of this sim to a user configured URI
  694. /// Sends the statistical data in a json serialization
  695. /// If the request contains a key, "callback" the response will be wrappend in the
  696. /// associated value for jsonp used with ajax/javascript
  697. /// </summary>
  698. public class UXSimStatusHandler : IStreamedRequestHandler
  699. {
  700. OpenSimBase m_opensim;
  701. string osUXStatsURI = String.Empty;
  702. public string Name { get { return "UXSimStatus"; } }
  703. public string Description { get { return "Simulator UXStatus"; } }
  704. public UXSimStatusHandler(OpenSimBase sim)
  705. {
  706. m_opensim = sim;
  707. osUXStatsURI = sim.userStatsURI;
  708. }
  709. public byte[] Handle(string path, Stream request,
  710. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  711. {
  712. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  713. }
  714. public string ContentType
  715. {
  716. get { return "text/plain"; }
  717. }
  718. public string HttpMethod
  719. {
  720. get { return "GET"; }
  721. }
  722. public string Path
  723. {
  724. // This is for the OpenSimulator instance and is the user provided URI
  725. get { return "/" + osUXStatsURI; }
  726. }
  727. }
  728. #endregion
  729. /// <summary>
  730. /// Performs any last-minute sanity checking and shuts down the region server
  731. /// </summary>
  732. public override void ShutdownSpecific()
  733. {
  734. if (proxyUrl.Length > 0)
  735. {
  736. Util.XmlRpcCommand(proxyUrl, "Stop");
  737. }
  738. m_log.Info("[SHUTDOWN]: Closing all threads");
  739. m_log.Info("[SHUTDOWN]: Killing listener thread");
  740. m_log.Info("[SHUTDOWN]: Killing clients");
  741. m_log.Info("[SHUTDOWN]: Closing console and terminating");
  742. try
  743. {
  744. SceneManager.Close();
  745. }
  746. catch (Exception e)
  747. {
  748. m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e);
  749. }
  750. }
  751. /// <summary>
  752. /// Get the start time and up time of Region server
  753. /// </summary>
  754. /// <param name="starttime">The first out parameter describing when the Region server started</param>
  755. /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
  756. public void GetRunTime(out string starttime, out string uptime)
  757. {
  758. starttime = m_startuptime.ToString();
  759. uptime = (DateTime.Now - m_startuptime).ToString();
  760. }
  761. /// <summary>
  762. /// Get the number of the avatars in the Region server
  763. /// </summary>
  764. /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
  765. public void GetAvatarNumber(out int usernum)
  766. {
  767. usernum = SceneManager.GetCurrentSceneAvatars().Count;
  768. }
  769. /// <summary>
  770. /// Get the number of regions
  771. /// </summary>
  772. /// <param name="regionnum">The first out parameter describing the number of regions</param>
  773. public void GetRegionNumber(out int regionnum)
  774. {
  775. regionnum = SceneManager.Scenes.Count;
  776. }
  777. /// <summary>
  778. /// Create an estate with an initial region.
  779. /// </summary>
  780. /// <remarks>
  781. /// This method doesn't allow an estate to be created with the same name as existing estates.
  782. /// </remarks>
  783. /// <param name="regInfo"></param>
  784. /// <param name="estatesByName">A list of estate names that already exist.</param>
  785. /// <param name="estateName">Estate name to create if already known</param>
  786. /// <returns>true if the estate was created, false otherwise</returns>
  787. public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName)
  788. {
  789. // Create a new estate
  790. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);
  791. string newName;
  792. if (estateName != null && estateName != "")
  793. newName = estateName;
  794. else
  795. newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName);
  796. if (estatesByName.ContainsKey(newName))
  797. {
  798. MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName);
  799. return false;
  800. }
  801. regInfo.EstateSettings.EstateName = newName;
  802. // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
  803. // Therefore, we need to do an initial save here otherwise the new estate name will be reset
  804. // back to the default. The reloading of estate settings by scene could be eliminated if it
  805. // knows that the passed in settings in RegionInfo are already valid. Also, it might be
  806. // possible to eliminate some additional later saves made by callers of this method.
  807. regInfo.EstateSettings.Save();
  808. return true;
  809. }
  810. /// <summary>
  811. /// Load the estate information for the provided RegionInfo object.
  812. /// </summary>
  813. /// <param name="regInfo"></param>
  814. public bool PopulateRegionEstateInfo(RegionInfo regInfo)
  815. {
  816. if (EstateDataService != null)
  817. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);
  818. if (regInfo.EstateSettings.EstateID != 0)
  819. return false; // estate info in the database did not change
  820. m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
  821. List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();
  822. Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>();
  823. foreach (EstateSettings estate in estates)
  824. estatesByName[estate.EstateName] = estate;
  825. string defaultEstateName = null;
  826. if (Config.Configs[ESTATE_SECTION_NAME] != null)
  827. {
  828. defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null);
  829. if (defaultEstateName != null)
  830. {
  831. EstateSettings defaultEstate;
  832. bool defaultEstateJoined = false;
  833. if (estatesByName.ContainsKey(defaultEstateName))
  834. {
  835. defaultEstate = estatesByName[defaultEstateName];
  836. if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID))
  837. defaultEstateJoined = true;
  838. }
  839. else
  840. {
  841. if (CreateEstate(regInfo, estatesByName, defaultEstateName))
  842. defaultEstateJoined = true;
  843. }
  844. if (defaultEstateJoined)
  845. return true; // need to update the database
  846. else
  847. m_log.ErrorFormat(
  848. "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName);
  849. }
  850. }
  851. // If we have no default estate or creation of the default estate failed then ask the user.
  852. while (true)
  853. {
  854. if (estates.Count == 0)
  855. {
  856. m_log.Info("[ESTATE]: No existing estates found. You must create a new one.");
  857. if (CreateEstate(regInfo, estatesByName, null))
  858. break;
  859. else
  860. continue;
  861. }
  862. else
  863. {
  864. string response
  865. = MainConsole.Instance.CmdPrompt(
  866. string.Format(
  867. "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
  868. "yes",
  869. new List<string>() { "yes", "no" });
  870. if (response == "no")
  871. {
  872. if (CreateEstate(regInfo, estatesByName, null))
  873. break;
  874. else
  875. continue;
  876. }
  877. else
  878. {
  879. string[] estateNames = estatesByName.Keys.ToArray();
  880. response
  881. = MainConsole.Instance.CmdPrompt(
  882. string.Format(
  883. "Name of estate to join. Existing estate names are ({0})",
  884. string.Join(", ", estateNames)),
  885. estateNames[0]);
  886. List<int> estateIDs = EstateDataService.GetEstates(response);
  887. if (estateIDs.Count < 1)
  888. {
  889. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again.");
  890. continue;
  891. }
  892. int estateID = estateIDs[0];
  893. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);
  894. if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
  895. break;
  896. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  897. }
  898. }
  899. }
  900. return true; // need to update the database
  901. }
  902. }
  903. public class OpenSimConfigSource
  904. {
  905. public IConfigSource Source;
  906. }
  907. }