OpenSimBase.cs 38 KB

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