OpenSimBase.cs 37 KB

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