OpenSimBase.cs 35 KB

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