OpenSimBase.cs 38 KB

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