OpenSimBase.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName);
  582. scene.PhysicsScene.RequestAssetMethod = scene.PhysicsRequestAsset;
  583. scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised());
  584. scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);
  585. return scene;
  586. }
  587. protected override ClientStackManager CreateClientStackManager()
  588. {
  589. return new ClientStackManager(m_configSettings.ClientstackDll);
  590. }
  591. protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
  592. IEstateDataService estateDataService, AgentCircuitManager circuitManager)
  593. {
  594. SceneCommunicationService sceneGridService = new SceneCommunicationService();
  595. return new Scene(
  596. regionInfo, circuitManager, sceneGridService,
  597. simDataService, estateDataService,
  598. Config, m_version);
  599. }
  600. protected void ShutdownClientServer(RegionInfo whichRegion)
  601. {
  602. // Close and remove the clientserver for a region
  603. bool foundClientServer = false;
  604. int clientServerElement = 0;
  605. Location location = new Location(whichRegion.RegionHandle);
  606. for (int i = 0; i < m_clientServers.Count; i++)
  607. {
  608. if (m_clientServers[i].HandlesRegion(location))
  609. {
  610. clientServerElement = i;
  611. foundClientServer = true;
  612. break;
  613. }
  614. }
  615. if (foundClientServer)
  616. {
  617. m_clientServers[clientServerElement].Stop();
  618. m_clientServers.RemoveAt(clientServerElement);
  619. }
  620. }
  621. protected virtual void HandleRestartRegion(RegionInfo whichRegion)
  622. {
  623. m_log.InfoFormat(
  624. "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})",
  625. whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY);
  626. ShutdownClientServer(whichRegion);
  627. IScene scene;
  628. CreateRegion(whichRegion, true, out scene);
  629. scene.Start();
  630. }
  631. # region Setup methods
  632. protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier)
  633. {
  634. return GetPhysicsScene(
  635. m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, Config, osSceneIdentifier);
  636. }
  637. /// <summary>
  638. /// Handler to supply the current status of this sim
  639. /// </summary>
  640. /// <remarks>
  641. /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
  642. /// </remarks>
  643. public class SimStatusHandler : BaseStreamHandler
  644. {
  645. public SimStatusHandler() : base("GET", "/simstatus", "SimStatus", "Simulator Status") {}
  646. protected override byte[] ProcessRequest(string path, Stream request,
  647. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  648. {
  649. return Util.UTF8.GetBytes("OK");
  650. }
  651. public override string ContentType
  652. {
  653. get { return "text/plain"; }
  654. }
  655. }
  656. /// <summary>
  657. /// Handler to supply the current extended status of this sim
  658. /// Sends the statistical data in a json serialization
  659. /// </summary>
  660. public class XSimStatusHandler : BaseStreamHandler
  661. {
  662. OpenSimBase m_opensim;
  663. public XSimStatusHandler(OpenSimBase sim)
  664. : base("GET", "/" + Util.SHA1Hash(sim.osSecret), "XSimStatus", "Simulator XStatus")
  665. {
  666. m_opensim = sim;
  667. }
  668. protected override byte[] ProcessRequest(string path, Stream request,
  669. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  670. {
  671. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  672. }
  673. public override string ContentType
  674. {
  675. get { return "text/plain"; }
  676. }
  677. }
  678. /// <summary>
  679. /// Handler to supply the current extended status of this sim to a user configured URI
  680. /// Sends the statistical data in a json serialization
  681. /// If the request contains a key, "callback" the response will be wrappend in the
  682. /// associated value for jsonp used with ajax/javascript
  683. /// </summary>
  684. protected class UXSimStatusHandler : BaseStreamHandler
  685. {
  686. OpenSimBase m_opensim;
  687. public UXSimStatusHandler(OpenSimBase sim)
  688. : base("GET", "/" + sim.userStatsURI, "UXSimStatus", "Simulator UXStatus")
  689. {
  690. m_opensim = sim;
  691. }
  692. protected override byte[] ProcessRequest(string path, Stream request,
  693. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  694. {
  695. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  696. }
  697. public override string ContentType
  698. {
  699. get { return "text/plain"; }
  700. }
  701. }
  702. #endregion
  703. /// <summary>
  704. /// Performs any last-minute sanity checking and shuts down the region server
  705. /// </summary>
  706. protected override void ShutdownSpecific()
  707. {
  708. if (proxyUrl.Length > 0)
  709. {
  710. Util.XmlRpcCommand(proxyUrl, "Stop");
  711. }
  712. m_log.Info("[SHUTDOWN]: Closing all threads");
  713. m_log.Info("[SHUTDOWN]: Killing listener thread");
  714. m_log.Info("[SHUTDOWN]: Killing clients");
  715. m_log.Info("[SHUTDOWN]: Closing console and terminating");
  716. try
  717. {
  718. SceneManager.Close();
  719. }
  720. catch (Exception e)
  721. {
  722. m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e);
  723. }
  724. base.ShutdownSpecific();
  725. }
  726. /// <summary>
  727. /// Get the start time and up time of Region server
  728. /// </summary>
  729. /// <param name="starttime">The first out parameter describing when the Region server started</param>
  730. /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
  731. public void GetRunTime(out string starttime, out string uptime)
  732. {
  733. starttime = m_startuptime.ToString();
  734. uptime = (DateTime.Now - m_startuptime).ToString();
  735. }
  736. /// <summary>
  737. /// Get the number of the avatars in the Region server
  738. /// </summary>
  739. /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
  740. public void GetAvatarNumber(out int usernum)
  741. {
  742. usernum = SceneManager.GetCurrentSceneAvatars().Count;
  743. }
  744. /// <summary>
  745. /// Get the number of regions
  746. /// </summary>
  747. /// <param name="regionnum">The first out parameter describing the number of regions</param>
  748. public void GetRegionNumber(out int regionnum)
  749. {
  750. regionnum = SceneManager.Scenes.Count;
  751. }
  752. /// <summary>
  753. /// Create an estate with an initial region.
  754. /// </summary>
  755. /// <remarks>
  756. /// This method doesn't allow an estate to be created with the same name as existing estates.
  757. /// </remarks>
  758. /// <param name="regInfo"></param>
  759. /// <param name="estatesByName">A list of estate names that already exist.</param>
  760. /// <param name="estateName">Estate name to create if already known</param>
  761. /// <returns>true if the estate was created, false otherwise</returns>
  762. public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName)
  763. {
  764. // Create a new estate
  765. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);
  766. string newName;
  767. if (estateName != null && estateName != "")
  768. newName = estateName;
  769. else
  770. newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName);
  771. if (estatesByName.ContainsKey(newName))
  772. {
  773. MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName);
  774. return false;
  775. }
  776. regInfo.EstateSettings.EstateName = newName;
  777. // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
  778. // Therefore, we need to do an initial save here otherwise the new estate name will be reset
  779. // back to the default. The reloading of estate settings by scene could be eliminated if it
  780. // knows that the passed in settings in RegionInfo are already valid. Also, it might be
  781. // possible to eliminate some additional later saves made by callers of this method.
  782. regInfo.EstateSettings.Save();
  783. return true;
  784. }
  785. /// <summary>
  786. /// Load the estate information for the provided RegionInfo object.
  787. /// </summary>
  788. /// <param name="regInfo"></param>
  789. public bool PopulateRegionEstateInfo(RegionInfo regInfo)
  790. {
  791. if (EstateDataService != null)
  792. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);
  793. if (regInfo.EstateSettings.EstateID != 0)
  794. return false; // estate info in the database did not change
  795. m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
  796. List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();
  797. Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>();
  798. foreach (EstateSettings estate in estates)
  799. estatesByName[estate.EstateName] = estate;
  800. string defaultEstateName = null;
  801. if (Config.Configs[ESTATE_SECTION_NAME] != null)
  802. {
  803. defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null);
  804. if (defaultEstateName != null)
  805. {
  806. EstateSettings defaultEstate;
  807. bool defaultEstateJoined = false;
  808. if (estatesByName.ContainsKey(defaultEstateName))
  809. {
  810. defaultEstate = estatesByName[defaultEstateName];
  811. if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID))
  812. defaultEstateJoined = true;
  813. }
  814. else
  815. {
  816. if (CreateEstate(regInfo, estatesByName, defaultEstateName))
  817. defaultEstateJoined = true;
  818. }
  819. if (defaultEstateJoined)
  820. return true; // need to update the database
  821. else
  822. m_log.ErrorFormat(
  823. "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName);
  824. }
  825. }
  826. // If we have no default estate or creation of the default estate failed then ask the user.
  827. while (true)
  828. {
  829. if (estates.Count == 0)
  830. {
  831. m_log.Info("[ESTATE]: No existing estates found. You must create a new one.");
  832. if (CreateEstate(regInfo, estatesByName, null))
  833. break;
  834. else
  835. continue;
  836. }
  837. else
  838. {
  839. string response
  840. = MainConsole.Instance.CmdPrompt(
  841. string.Format(
  842. "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
  843. "yes",
  844. new List<string>() { "yes", "no" });
  845. if (response == "no")
  846. {
  847. if (CreateEstate(regInfo, estatesByName, null))
  848. break;
  849. else
  850. continue;
  851. }
  852. else
  853. {
  854. string[] estateNames = estatesByName.Keys.ToArray();
  855. response
  856. = MainConsole.Instance.CmdPrompt(
  857. string.Format(
  858. "Name of estate to join. Existing estate names are ({0})",
  859. string.Join(", ", estateNames)),
  860. estateNames[0]);
  861. List<int> estateIDs = EstateDataService.GetEstates(response);
  862. if (estateIDs.Count < 1)
  863. {
  864. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again.");
  865. continue;
  866. }
  867. int estateID = estateIDs[0];
  868. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);
  869. if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
  870. break;
  871. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  872. }
  873. }
  874. }
  875. return true; // need to update the database
  876. }
  877. }
  878. public class OpenSimConfigSource
  879. {
  880. public IConfigSource Source;
  881. }
  882. }