OpenSimBase.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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. // FIXME: Put me into a separate method!
  306. while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
  307. {
  308. MainConsole.Instance.OutputFormat("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName);
  309. List<char> excluded = new List<char>(new char[1]{' '});
  310. string first = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test", excluded);
  311. string last = MainConsole.Instance.CmdPrompt("Estate owner last name", "User", excluded);
  312. UserAccount account = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, first, last);
  313. if (account == null)
  314. {
  315. m_log.DebugFormat("A {0}", scene.UserAccountService.GetType());
  316. // if (scene.UserAccountService is LocalUserAccountServicesConnector)
  317. // {
  318. // IUserAccountService innerUas
  319. // = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService;
  320. //
  321. // m_log.DebugFormat("B {0}", innerUas.GetType());
  322. //
  323. // if (innerUas is UserAccountService)
  324. // {
  325. if (scene.UserAccountService is UserAccountService)
  326. {
  327. string password = MainConsole.Instance.PasswdPrompt("Password");
  328. string email = MainConsole.Instance.CmdPrompt("Email", "");
  329. // TODO: Where do we put m_regInfo.ScopeID?
  330. account = ((UserAccountService)scene.UserAccountService).CreateUser(first, last, password, email);
  331. }
  332. // }
  333. }
  334. if (account == null)
  335. {
  336. m_log.ErrorFormat(
  337. "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first.");
  338. }
  339. else
  340. {
  341. regionInfo.EstateSettings.EstateOwner = account.PrincipalID;
  342. regionInfo.EstateSettings.Save();
  343. }
  344. }
  345. // Prims have to be loaded after module configuration since some modules may be invoked during the load
  346. scene.LoadPrimsFromStorage(regionInfo.originRegionID);
  347. // TODO : Try setting resource for region xstats here on scene
  348. MainServer.Instance.AddStreamHandler(new Region.Framework.Scenes.RegionStatsHandler(regionInfo));
  349. try
  350. {
  351. scene.RegisterRegionWithGrid();
  352. }
  353. catch (Exception e)
  354. {
  355. m_log.ErrorFormat(
  356. "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}",
  357. e.Message, e.StackTrace);
  358. // Carrying on now causes a lot of confusion down the
  359. // line - we need to get the user's attention
  360. Environment.Exit(1);
  361. }
  362. scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
  363. scene.EventManager.TriggerParcelPrimCountUpdate();
  364. // We need to do this after we've initialized the
  365. // scripting engines.
  366. scene.CreateScriptInstances();
  367. m_sceneManager.Add(scene);
  368. if (m_autoCreateClientStack)
  369. {
  370. m_clientServers.Add(clientServer);
  371. clientServer.Start();
  372. }
  373. if (do_post_init)
  374. {
  375. foreach (IRegionModule module in modules)
  376. {
  377. module.PostInitialise();
  378. }
  379. }
  380. scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };
  381. mscene = scene;
  382. scene.StartTimer();
  383. scene.StartScripts();
  384. return clientServer;
  385. }
  386. private void ShutdownRegion(Scene scene)
  387. {
  388. m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName);
  389. IRegionModulesController controller;
  390. if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller))
  391. {
  392. controller.RemoveRegionFromModules(scene);
  393. }
  394. }
  395. public void RemoveRegion(Scene scene, bool cleanup)
  396. {
  397. // only need to check this if we are not at the
  398. // root level
  399. if ((m_sceneManager.CurrentScene != null) &&
  400. (m_sceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  401. {
  402. m_sceneManager.TrySetCurrentScene("..");
  403. }
  404. scene.DeleteAllSceneObjects();
  405. m_sceneManager.CloseScene(scene);
  406. ShutdownClientServer(scene.RegionInfo);
  407. if (!cleanup)
  408. return;
  409. if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile))
  410. {
  411. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml"))
  412. {
  413. File.Delete(scene.RegionInfo.RegionFile);
  414. m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile);
  415. }
  416. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini"))
  417. {
  418. try
  419. {
  420. IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile);
  421. if (source.Configs[scene.RegionInfo.RegionName] != null)
  422. {
  423. source.Configs.Remove(scene.RegionInfo.RegionName);
  424. if (source.Configs.Count == 0)
  425. {
  426. File.Delete(scene.RegionInfo.RegionFile);
  427. }
  428. else
  429. {
  430. source.Save(scene.RegionInfo.RegionFile);
  431. }
  432. }
  433. }
  434. catch (Exception)
  435. {
  436. }
  437. }
  438. }
  439. }
  440. public void RemoveRegion(string name, bool cleanUp)
  441. {
  442. Scene target;
  443. if (m_sceneManager.TryGetScene(name, out target))
  444. RemoveRegion(target, cleanUp);
  445. }
  446. /// <summary>
  447. /// Remove a region from the simulator without deleting it permanently.
  448. /// </summary>
  449. /// <param name="scene"></param>
  450. /// <returns></returns>
  451. public void CloseRegion(Scene scene)
  452. {
  453. // only need to check this if we are not at the
  454. // root level
  455. if ((m_sceneManager.CurrentScene != null) &&
  456. (m_sceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  457. {
  458. m_sceneManager.TrySetCurrentScene("..");
  459. }
  460. m_sceneManager.CloseScene(scene);
  461. ShutdownClientServer(scene.RegionInfo);
  462. }
  463. /// <summary>
  464. /// Remove a region from the simulator without deleting it permanently.
  465. /// </summary>
  466. /// <param name="name"></param>
  467. /// <returns></returns>
  468. public void CloseRegion(string name)
  469. {
  470. Scene target;
  471. if (m_sceneManager.TryGetScene(name, out target))
  472. CloseRegion(target);
  473. }
  474. /// <summary>
  475. /// Create a scene and its initial base structures.
  476. /// </summary>
  477. /// <param name="regionInfo"></param>
  478. /// <param name="clientServer"> </param>
  479. /// <returns></returns>
  480. protected Scene SetupScene(RegionInfo regionInfo, out IClientNetworkServer clientServer)
  481. {
  482. return SetupScene(regionInfo, 0, null, out clientServer);
  483. }
  484. /// <summary>
  485. /// Create a scene and its initial base structures.
  486. /// </summary>
  487. /// <param name="regionInfo"></param>
  488. /// <param name="proxyOffset"></param>
  489. /// <param name="configSource"></param>
  490. /// <param name="clientServer"> </param>
  491. /// <returns></returns>
  492. protected Scene SetupScene(
  493. RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out IClientNetworkServer clientServer)
  494. {
  495. AgentCircuitManager circuitManager = new AgentCircuitManager();
  496. IPAddress listenIP = regionInfo.InternalEndPoint.Address;
  497. //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP))
  498. // listenIP = IPAddress.Parse("0.0.0.0");
  499. uint port = (uint) regionInfo.InternalEndPoint.Port;
  500. if (m_autoCreateClientStack)
  501. {
  502. clientServer
  503. = m_clientStackManager.CreateServer(
  504. listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource,
  505. circuitManager);
  506. }
  507. else
  508. {
  509. clientServer = null;
  510. }
  511. regionInfo.InternalEndPoint.Port = (int) port;
  512. Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager);
  513. if (m_autoCreateClientStack)
  514. {
  515. clientServer.AddScene(scene);
  516. }
  517. scene.LoadWorldMap();
  518. scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName);
  519. scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised());
  520. scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);
  521. return scene;
  522. }
  523. protected override ClientStackManager CreateClientStackManager()
  524. {
  525. return new ClientStackManager(m_configSettings.ClientstackDll);
  526. }
  527. protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
  528. IEstateDataService estateDataService, AgentCircuitManager circuitManager)
  529. {
  530. SceneCommunicationService sceneGridService = new SceneCommunicationService();
  531. return new Scene(
  532. regionInfo, circuitManager, sceneGridService,
  533. simDataService, estateDataService, m_moduleLoader, false, m_configSettings.PhysicalPrim,
  534. m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
  535. }
  536. protected void ShutdownClientServer(RegionInfo whichRegion)
  537. {
  538. // Close and remove the clientserver for a region
  539. bool foundClientServer = false;
  540. int clientServerElement = 0;
  541. Location location = new Location(whichRegion.RegionHandle);
  542. for (int i = 0; i < m_clientServers.Count; i++)
  543. {
  544. if (m_clientServers[i].HandlesRegion(location))
  545. {
  546. clientServerElement = i;
  547. foundClientServer = true;
  548. break;
  549. }
  550. }
  551. if (foundClientServer)
  552. {
  553. m_clientServers[clientServerElement].NetworkStop();
  554. m_clientServers.RemoveAt(clientServerElement);
  555. }
  556. }
  557. public void handleRestartRegion(RegionInfo whichRegion)
  558. {
  559. m_log.Info("[OPENSIM]: Got restart signal from SceneManager");
  560. ShutdownClientServer(whichRegion);
  561. IScene scene;
  562. CreateRegion(whichRegion, true, out scene);
  563. }
  564. # region Setup methods
  565. protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier)
  566. {
  567. return GetPhysicsScene(
  568. m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, m_config.Source, osSceneIdentifier);
  569. }
  570. /// <summary>
  571. /// Handler to supply the current status of this sim
  572. /// </summary>
  573. /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
  574. public class SimStatusHandler : IStreamedRequestHandler
  575. {
  576. public byte[] Handle(string path, Stream request,
  577. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  578. {
  579. return Util.UTF8.GetBytes("OK");
  580. }
  581. public string ContentType
  582. {
  583. get { return "text/plain"; }
  584. }
  585. public string HttpMethod
  586. {
  587. get { return "GET"; }
  588. }
  589. public string Path
  590. {
  591. get { return "/simstatus/"; }
  592. }
  593. }
  594. /// <summary>
  595. /// Handler to supply the current extended status of this sim
  596. /// Sends the statistical data in a json serialization
  597. /// </summary>
  598. public class XSimStatusHandler : IStreamedRequestHandler
  599. {
  600. OpenSimBase m_opensim;
  601. string osXStatsURI = String.Empty;
  602. public XSimStatusHandler(OpenSimBase sim)
  603. {
  604. m_opensim = sim;
  605. osXStatsURI = Util.SHA1Hash(sim.osSecret);
  606. }
  607. public byte[] Handle(string path, Stream request,
  608. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  609. {
  610. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  611. }
  612. public string ContentType
  613. {
  614. get { return "text/plain"; }
  615. }
  616. public string HttpMethod
  617. {
  618. get { return "GET"; }
  619. }
  620. public string Path
  621. {
  622. // This is for the OpenSimulator instance and is the osSecret hashed
  623. get { return "/" + osXStatsURI + "/"; }
  624. }
  625. }
  626. /// <summary>
  627. /// Handler to supply the current extended status of this sim to a user configured URI
  628. /// Sends the statistical data in a json serialization
  629. /// If the request contains a key, "callback" the response will be wrappend in the
  630. /// associated value for jsonp used with ajax/javascript
  631. /// </summary>
  632. public class UXSimStatusHandler : IStreamedRequestHandler
  633. {
  634. OpenSimBase m_opensim;
  635. string osUXStatsURI = String.Empty;
  636. public UXSimStatusHandler(OpenSimBase sim)
  637. {
  638. m_opensim = sim;
  639. osUXStatsURI = sim.userStatsURI;
  640. }
  641. public byte[] Handle(string path, Stream request,
  642. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  643. {
  644. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  645. }
  646. public string ContentType
  647. {
  648. get { return "text/plain"; }
  649. }
  650. public string HttpMethod
  651. {
  652. get { return "GET"; }
  653. }
  654. public string Path
  655. {
  656. // This is for the OpenSimulator instance and is the user provided URI
  657. get { return "/" + osUXStatsURI + "/"; }
  658. }
  659. }
  660. #endregion
  661. /// <summary>
  662. /// Performs any last-minute sanity checking and shuts down the region server
  663. /// </summary>
  664. public override void ShutdownSpecific()
  665. {
  666. if (proxyUrl.Length > 0)
  667. {
  668. Util.XmlRpcCommand(proxyUrl, "Stop");
  669. }
  670. m_log.Info("[SHUTDOWN]: Closing all threads");
  671. m_log.Info("[SHUTDOWN]: Killing listener thread");
  672. m_log.Info("[SHUTDOWN]: Killing clients");
  673. // TODO: implement this
  674. m_log.Info("[SHUTDOWN]: Closing console and terminating");
  675. try
  676. {
  677. m_sceneManager.Close();
  678. }
  679. catch (Exception e)
  680. {
  681. m_log.ErrorFormat("[SHUTDOWN]: Ignoring failure during shutdown - {0}", e);
  682. }
  683. }
  684. /// <summary>
  685. /// Get the start time and up time of Region server
  686. /// </summary>
  687. /// <param name="starttime">The first out parameter describing when the Region server started</param>
  688. /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
  689. public void GetRunTime(out string starttime, out string uptime)
  690. {
  691. starttime = m_startuptime.ToString();
  692. uptime = (DateTime.Now - m_startuptime).ToString();
  693. }
  694. /// <summary>
  695. /// Get the number of the avatars in the Region server
  696. /// </summary>
  697. /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
  698. public void GetAvatarNumber(out int usernum)
  699. {
  700. usernum = m_sceneManager.GetCurrentSceneAvatars().Count;
  701. }
  702. /// <summary>
  703. /// Get the number of regions
  704. /// </summary>
  705. /// <param name="regionnum">The first out parameter describing the number of regions</param>
  706. public void GetRegionNumber(out int regionnum)
  707. {
  708. regionnum = m_sceneManager.Scenes.Count;
  709. }
  710. /// <summary>
  711. /// Create an estate with an initial region.
  712. /// </summary>
  713. /// <remarks>
  714. /// This method doesn't allow an estate to be created with the same name as existing estates.
  715. /// </remarks>
  716. /// <param name="regInfo"></param>
  717. /// <param name="existingName">A list of estate names that already exist.</param>
  718. /// <returns>true if the estate was created, false otherwise</returns>
  719. public bool CreateEstate(RegionInfo regInfo, List<string> existingNames)
  720. {
  721. // Create a new estate
  722. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);
  723. string newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName);
  724. if (existingNames.Contains(newName))
  725. {
  726. MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName);
  727. return false;
  728. }
  729. regInfo.EstateSettings.EstateName = newName;
  730. // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
  731. // Therefore, we need to do an initial save here otherwise the new estate name will be reset
  732. // back to the default. The reloading of estate settings by scene could be eliminated if it
  733. // knows that the passed in settings in RegionInfo are already valid. Also, it might be
  734. // possible to eliminate some additional later saves made by callers of this method.
  735. regInfo.EstateSettings.Save();
  736. return true;
  737. }
  738. /// <summary>
  739. /// Load the estate information for the provided RegionInfo object.
  740. /// </summary>
  741. /// <param name="regInfo"></param>
  742. public void PopulateRegionEstateInfo(RegionInfo regInfo)
  743. {
  744. if (EstateDataService != null)
  745. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);
  746. if (regInfo.EstateSettings.EstateID == 0) // No record at all
  747. {
  748. m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
  749. List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();
  750. List<string> estateNames = new List<string>();
  751. foreach (EstateSettings estate in estates)
  752. estateNames.Add(estate.EstateName);
  753. while (true)
  754. {
  755. if (estates.Count == 0)
  756. {
  757. m_log.Info("[ESTATE] No existing estates found. You must create a new one.");
  758. if (CreateEstate(regInfo, estateNames))
  759. break;
  760. else
  761. continue;
  762. }
  763. else
  764. {
  765. string response
  766. = MainConsole.Instance.CmdPrompt(
  767. string.Format(
  768. "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
  769. "yes",
  770. new List<string>() { "yes", "no" });
  771. if (response == "no")
  772. {
  773. if (CreateEstate(regInfo, estateNames))
  774. break;
  775. else
  776. continue;
  777. }
  778. else
  779. {
  780. response
  781. = MainConsole.Instance.CmdPrompt(
  782. string.Format(
  783. "Name of estate to join. Existing estate names are ({0})", string.Join(", ", estateNames.ToArray())),
  784. estateNames[0]);
  785. List<int> estateIDs = EstateDataService.GetEstates(response);
  786. if (estateIDs.Count < 1)
  787. {
  788. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again.");
  789. continue;
  790. }
  791. int estateID = estateIDs[0];
  792. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);
  793. if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
  794. break;
  795. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  796. }
  797. }
  798. }
  799. }
  800. }
  801. }
  802. public class OpenSimConfigSource
  803. {
  804. public IConfigSource Source;
  805. public void Save(string path)
  806. {
  807. if (Source is IniConfigSource)
  808. {
  809. IniConfigSource iniCon = (IniConfigSource) Source;
  810. iniCon.Save(path);
  811. }
  812. else if (Source is XmlConfigSource)
  813. {
  814. XmlConfigSource xmlCon = (XmlConfigSource) Source;
  815. xmlCon.Save(path);
  816. }
  817. }
  818. }
  819. }