OpenSimBase.cs 35 KB

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