1
0

OpenSimBase.cs 38 KB

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