OpenSimBase.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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.Linq;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Text;
  34. using log4net;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Framework.Servers;
  40. using OpenSim.Framework.Servers.HttpServer;
  41. using OpenSim.Framework.Monitoring;
  42. using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
  43. using OpenSim.Region.Framework;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. using OpenSim.Region.PhysicsModules.SharedBase;
  47. using OpenSim.Server.Base;
  48. using OpenSim.Services.Base;
  49. using OpenSim.Services.Interfaces;
  50. using OpenSim.Services.UserAccountService;
  51. namespace OpenSim
  52. {
  53. /// <summary>
  54. /// Common OpenSimulator simulator code
  55. /// </summary>
  56. public class OpenSimBase : RegionApplicationBase
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. // These are the names of the plugin-points extended by this
  60. // class during system startup.
  61. //
  62. private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache";
  63. private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient";
  64. // OpenSim.ini Section name for ESTATES Settings
  65. public const string ESTATE_SECTION_NAME = "Estates";
  66. /// <summary>
  67. /// Allow all plugin loading to be disabled for tests/debug.
  68. /// </summary>
  69. /// <remarks>
  70. /// true by default
  71. /// </remarks>
  72. public bool EnableInitialPluginLoad { get; set; }
  73. /// <summary>
  74. /// Control whether we attempt to load an estate data service.
  75. /// </summary>
  76. /// <remarks>For tests/debugging</remarks>
  77. public bool LoadEstateDataService { get; set; }
  78. protected string proxyUrl;
  79. protected int proxyOffset = 0;
  80. public string userStatsURI = String.Empty;
  81. public string managedStatsURI = String.Empty;
  82. public string managedStatsPassword = String.Empty;
  83. protected bool m_autoCreateClientStack = true;
  84. /// <value>
  85. /// The file used to load and save prim backup xml if no filename has been specified
  86. /// </value>
  87. protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml";
  88. public ConfigSettings ConfigurationSettings
  89. {
  90. get { return m_configSettings; }
  91. set { m_configSettings = value; }
  92. }
  93. protected ConfigSettings m_configSettings;
  94. protected ConfigurationLoader m_configLoader;
  95. public ConsoleCommand CreateAccount = null;
  96. public List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();
  97. private List<string> m_permsModules;
  98. private bool m_securePermissionsLoading = true;
  99. /// <value>
  100. /// The config information passed into the OpenSimulator region server.
  101. /// </value>
  102. public OpenSimConfigSource ConfigSource { get; private set; }
  103. protected EnvConfigSource m_EnvConfigSource = new EnvConfigSource();
  104. public EnvConfigSource envConfigSource
  105. {
  106. get { return m_EnvConfigSource; }
  107. }
  108. public uint HttpServerPort
  109. {
  110. get { return m_httpServerPort; }
  111. }
  112. protected IRegistryCore m_applicationRegistry = new RegistryCore();
  113. public IRegistryCore ApplicationRegistry
  114. {
  115. get { return m_applicationRegistry; }
  116. }
  117. /// <summary>
  118. /// Constructor.
  119. /// </summary>
  120. /// <param name="configSource"></param>
  121. public OpenSimBase(IConfigSource configSource) : base()
  122. {
  123. EnableInitialPluginLoad = true;
  124. LoadEstateDataService = true;
  125. LoadConfigSettings(configSource);
  126. }
  127. protected virtual void LoadConfigSettings(IConfigSource configSource)
  128. {
  129. m_configLoader = new ConfigurationLoader();
  130. ConfigSource = m_configLoader.LoadConfigSettings(configSource, envConfigSource, out m_configSettings, out m_networkServersInfo);
  131. Config = ConfigSource.Source;
  132. ReadExtraConfigSettings();
  133. }
  134. protected virtual void ReadExtraConfigSettings()
  135. {
  136. IConfig networkConfig = Config.Configs["Network"];
  137. if (networkConfig != null)
  138. {
  139. proxyUrl = networkConfig.GetString("proxy_url", "");
  140. proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0"));
  141. }
  142. IConfig startupConfig = Config.Configs["Startup"];
  143. if (startupConfig != null)
  144. {
  145. Util.LogOverloads = startupConfig.GetBoolean("LogOverloads", true);
  146. }
  147. }
  148. protected virtual void LoadPlugins()
  149. {
  150. IConfig startupConfig = Config.Configs["Startup"];
  151. string registryLocation = (startupConfig != null) ? startupConfig.GetString("RegistryLocation", String.Empty) : String.Empty;
  152. // The location can also be specified in the environment. If there
  153. // is no location in the configuration, we must call the constructor
  154. // without a location parameter to allow that to happen.
  155. if (registryLocation == String.Empty)
  156. {
  157. using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this)))
  158. {
  159. loader.Load("/OpenSim/Startup");
  160. m_plugins = loader.Plugins;
  161. }
  162. }
  163. else
  164. {
  165. using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this), registryLocation))
  166. {
  167. loader.Load("/OpenSim/Startup");
  168. m_plugins = loader.Plugins;
  169. }
  170. }
  171. }
  172. protected override List<string> GetHelpTopics()
  173. {
  174. List<string> topics = base.GetHelpTopics();
  175. Scene s = SceneManager.CurrentOrFirstScene;
  176. if (s != null && s.GetCommanders() != null)
  177. topics.AddRange(s.GetCommanders().Keys);
  178. return topics;
  179. }
  180. /// <summary>
  181. /// Performs startup specific to the region server, including initialization of the scene
  182. /// such as loading configuration from disk.
  183. /// </summary>
  184. protected override void StartupSpecific()
  185. {
  186. IConfig startupConfig = Config.Configs["Startup"];
  187. if (startupConfig != null)
  188. {
  189. // refuse to run MegaRegions
  190. if(startupConfig.GetBoolean("CombineContiguousRegions", false))
  191. {
  192. m_log.Fatal("CombineContiguousRegions (MegaRegions) option is no longer suported. Use a older version to save region contents as OAR, then import into a fresh install of this new version");
  193. throw new Exception("CombineContiguousRegions not suported");
  194. }
  195. string pidFile = startupConfig.GetString("PIDFile", String.Empty);
  196. if (pidFile != String.Empty)
  197. CreatePIDFile(pidFile);
  198. userStatsURI = startupConfig.GetString("Stats_URI", String.Empty);
  199. m_securePermissionsLoading = startupConfig.GetBoolean("SecurePermissionsLoading", true);
  200. string permissionModules = Util.GetConfigVarFromSections<string>(Config, "permissionmodules",
  201. new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule");
  202. m_permsModules = new List<string>(permissionModules.Split(',').Select(m => m.Trim()));
  203. managedStatsURI = startupConfig.GetString("ManagedStatsRemoteFetchURI", String.Empty);
  204. managedStatsPassword = startupConfig.GetString("ManagedStatsRemoteFetchPassword", String.Empty);
  205. }
  206. // Load the simulation data service
  207. IConfig simDataConfig = Config.Configs["SimulationDataStore"];
  208. if (simDataConfig == null)
  209. throw new Exception("Configuration file is missing the [SimulationDataStore] section. Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");
  210. string module = simDataConfig.GetString("LocalServiceModule", String.Empty);
  211. if (String.IsNullOrEmpty(module))
  212. throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section.");
  213. m_simulationDataService = ServerUtils.LoadPlugin<ISimulationDataService>(module, new object[] { Config });
  214. if (m_simulationDataService == null)
  215. throw new Exception(
  216. string.Format(
  217. "Could not load an ISimulationDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [SimulationDataStore] config section.",
  218. module));
  219. // Load the estate data service
  220. module = Util.GetConfigVarFromSections<string>(Config, "LocalServiceModule", new string[]{"EstateDataStore", "EstateService"}, String.Empty);
  221. if (String.IsNullOrEmpty(module))
  222. throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] or [EstateService] section");
  223. if (LoadEstateDataService)
  224. {
  225. m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { Config });
  226. if (m_estateDataService == null)
  227. throw new Exception(
  228. string.Format(
  229. "Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.",
  230. module));
  231. }
  232. base.StartupSpecific();
  233. if (EnableInitialPluginLoad)
  234. LoadPlugins();
  235. // We still want to post initalize any plugins even if loading has been disabled since a test may have
  236. // inserted them manually.
  237. foreach (IApplicationPlugin plugin in m_plugins)
  238. plugin.PostInitialise();
  239. if (m_console != null)
  240. AddPluginCommands(m_console);
  241. }
  242. protected virtual void AddPluginCommands(ICommandConsole console)
  243. {
  244. List<string> topics = GetHelpTopics();
  245. foreach (string topic in topics)
  246. {
  247. string capitalizedTopic = char.ToUpper(topic[0]) + topic.Substring(1);
  248. // This is a hack to allow the user to enter the help command in upper or lowercase. This will go
  249. // away at some point.
  250. console.Commands.AddCommand(capitalizedTopic, false, "help " + topic,
  251. "help " + capitalizedTopic,
  252. "Get help on plugin command '" + topic + "'",
  253. HandleCommanderHelp);
  254. console.Commands.AddCommand(capitalizedTopic, false, "help " + capitalizedTopic,
  255. "help " + capitalizedTopic,
  256. "Get help on plugin command '" + topic + "'",
  257. HandleCommanderHelp);
  258. ICommander commander = null;
  259. Scene s = SceneManager.CurrentOrFirstScene;
  260. if (s != null && s.GetCommanders() != null)
  261. {
  262. if (s.GetCommanders().ContainsKey(topic))
  263. commander = s.GetCommanders()[topic];
  264. }
  265. if (commander == null)
  266. continue;
  267. foreach (string command in commander.Commands.Keys)
  268. {
  269. console.Commands.AddCommand(capitalizedTopic, false,
  270. topic + " " + command,
  271. topic + " " + commander.Commands[command].ShortHelp(),
  272. String.Empty, HandleCommanderCommand);
  273. }
  274. }
  275. }
  276. private void HandleCommanderCommand(string module, string[] cmd)
  277. {
  278. SceneManager.SendCommandToPluginModules(cmd);
  279. }
  280. private void HandleCommanderHelp(string module, string[] cmd)
  281. {
  282. // Only safe for the interactive console, since it won't
  283. // let us come here unless both scene and commander exist
  284. //
  285. ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1].ToLower());
  286. if (moduleCommander != null)
  287. m_console.Output(moduleCommander.Help);
  288. }
  289. protected override void Initialize()
  290. {
  291. // Called from base.StartUp()
  292. IConfig startupConfig = Config.Configs["Startup"];
  293. if (startupConfig == null || startupConfig.GetBoolean("JobEngineEnabled", true))
  294. WorkManager.JobEngine.Start();
  295. if(m_networkServersInfo.HttpUsesSSL)
  296. {
  297. m_httpServerSSL = true;
  298. m_httpServerPort = m_networkServersInfo.httpSSLPort;
  299. }
  300. else
  301. {
  302. m_httpServerSSL = false;
  303. m_httpServerPort = m_networkServersInfo.HttpListenerPort;
  304. }
  305. SceneManager.OnRestartSim += HandleRestartRegion;
  306. // Only enable the watchdogs when all regions are ready. Otherwise we get false positives when cpu is
  307. // heavily used during initial startup.
  308. //
  309. // FIXME: It's also possible that region ready status should be flipped during an OAR load since this
  310. // also makes heavy use of the CPU.
  311. SceneManager.OnRegionsReadyStatusChange
  312. += sm => { MemoryWatchdog.Enabled = sm.AllRegionsReady; Watchdog.Enabled = sm.AllRegionsReady; };
  313. }
  314. /// <summary>
  315. /// Execute the region creation process. This includes setting up scene infrastructure.
  316. /// </summary>
  317. /// <param name="regionInfo"></param>
  318. /// <param name="portadd_flag"></param>
  319. /// <returns></returns>
  320. public void CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene)
  321. {
  322. CreateRegion(regionInfo, portadd_flag, false, out scene);
  323. }
  324. /// <summary>
  325. /// Execute the region creation process. This includes setting up scene infrastructure.
  326. /// </summary>
  327. /// <param name="regionInfo"></param>
  328. /// <returns></returns>
  329. public void CreateRegion(RegionInfo regionInfo, out IScene scene)
  330. {
  331. CreateRegion(regionInfo, false, true, out scene);
  332. }
  333. /// <summary>
  334. /// Execute the region creation process. This includes setting up scene infrastructure.
  335. /// </summary>
  336. /// <param name="regionInfo"></param>
  337. /// <param name="portadd_flag"></param>
  338. /// <param name="do_post_init"></param>
  339. /// <returns></returns>
  340. public void CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene)
  341. {
  342. int port = regionInfo.InternalEndPoint.Port;
  343. // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims)
  344. // Commented this out because otherwise regions can't register with
  345. // the grid as there is already another region with the same UUID
  346. // at those coordinates. This is required for the load balancer to work.
  347. // --Mike, 2009.02.25
  348. //regionInfo.originRegionID = regionInfo.RegionID;
  349. // set initial ServerURI
  350. regionInfo.HttpPort = m_httpServerPort;
  351. if(m_httpServerSSL)
  352. {
  353. if(!m_httpServer.CheckSSLCertHost(regionInfo.ExternalHostName))
  354. throw new Exception("main http cert CN doesn't match region External IP");
  355. regionInfo.ServerURI = "https://" + regionInfo.ExternalHostName +
  356. ":" + regionInfo.HttpPort.ToString() + "/";
  357. }
  358. else
  359. regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName +
  360. ":" + regionInfo.HttpPort.ToString() + "/";
  361. regionInfo.osSecret = m_osSecret;
  362. if ((proxyUrl.Length > 0) && (portadd_flag))
  363. {
  364. // set proxy url to RegionInfo
  365. regionInfo.proxyUrl = proxyUrl;
  366. regionInfo.ProxyOffset = proxyOffset;
  367. Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName);
  368. }
  369. Scene scene = SetupScene(regionInfo, proxyOffset, Config);
  370. m_log.Info("[MODULES]: Loading Region's modules (old style)");
  371. // Use this in the future, the line above will be deprecated soon
  372. m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)");
  373. IRegionModulesController controller;
  374. if (ApplicationRegistry.TryGet(out controller))
  375. {
  376. controller.AddRegionToModules(scene);
  377. }
  378. else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing...");
  379. if (m_securePermissionsLoading)
  380. {
  381. foreach (string s in m_permsModules)
  382. {
  383. if (!scene.RegionModules.ContainsKey(s))
  384. {
  385. m_log.Fatal("[MODULES]: Required module " + s + " not found.");
  386. Environment.Exit(0);
  387. }
  388. }
  389. m_log.InfoFormat("[SCENE]: Secure permissions loading enabled, modules loaded: {0}", String.Join(" ", m_permsModules.ToArray()));
  390. }
  391. scene.SetModuleInterfaces();
  392. // First Step of bootreport sequence
  393. if (scene.SnmpService != null)
  394. {
  395. scene.SnmpService.ColdStart(1,scene);
  396. scene.SnmpService.LinkDown(scene);
  397. }
  398. if (scene.SnmpService != null)
  399. {
  400. scene.SnmpService.BootInfo("Loading prims", scene);
  401. }
  402. while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
  403. SetUpEstateOwner(scene);
  404. scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
  405. // Prims have to be loaded after module configuration since some modules may be invoked during the load
  406. scene.LoadPrimsFromStorage(regionInfo.originRegionID);
  407. // TODO : Try setting resource for region xstats here on scene
  408. MainServer.Instance.AddSimpleStreamHandler(new RegionStatsSimpleHandler(regionInfo));
  409. if (scene.SnmpService != null)
  410. {
  411. scene.SnmpService.BootInfo("Grid Registration in progress", scene);
  412. }
  413. try
  414. {
  415. scene.RegisterRegionWithGrid();
  416. }
  417. catch (Exception e)
  418. {
  419. m_log.ErrorFormat(
  420. "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}",
  421. e.Message, e.StackTrace);
  422. if (scene.SnmpService != null)
  423. {
  424. scene.SnmpService.Critical("Grid registration failed. Startup aborted.", scene);
  425. }
  426. // Carrying on now causes a lot of confusion down the
  427. // line - we need to get the user's attention
  428. Environment.Exit(1);
  429. }
  430. if (scene.SnmpService != null)
  431. {
  432. scene.SnmpService.BootInfo("Grid Registration done", scene);
  433. }
  434. // We need to do this after we've initialized the
  435. // scripting engines.
  436. scene.CreateScriptInstances();
  437. if (scene.SnmpService != null)
  438. {
  439. scene.SnmpService.BootInfo("ScriptEngine started", scene);
  440. }
  441. SceneManager.Add(scene);
  442. //if (m_autoCreateClientStack)
  443. //{
  444. // foreach (IClientNetworkServer clientserver in clientServers)
  445. // {
  446. // m_clientServers.Add(clientserver);
  447. // clientserver.Start();
  448. // }
  449. //}
  450. if (scene.SnmpService != null)
  451. {
  452. scene.SnmpService.BootInfo("Initializing region modules", scene);
  453. }
  454. scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };
  455. mscene = scene;
  456. if (scene.SnmpService != null)
  457. {
  458. scene.SnmpService.BootInfo("The region is operational", scene);
  459. scene.SnmpService.LinkUp(scene);
  460. }
  461. //return clientServers;
  462. }
  463. /// <summary>
  464. /// Try to set up the estate owner for the given scene.
  465. /// </summary>
  466. /// <remarks>
  467. /// The involves asking the user for information about the user on the console. If the user does not already
  468. /// exist then it is created.
  469. /// </remarks>
  470. /// <param name="scene"></param>
  471. private void SetUpEstateOwner(Scene scene)
  472. {
  473. RegionInfo regionInfo = scene.RegionInfo;
  474. string estateOwnerFirstName = null;
  475. string estateOwnerLastName = null;
  476. string estateOwnerEMail = null;
  477. string estateOwnerPassword = null;
  478. string rawEstateOwnerUuid = null;
  479. if (Config.Configs[ESTATE_SECTION_NAME] != null)
  480. {
  481. string defaultEstateOwnerName
  482. = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerName", "").Trim();
  483. string[] ownerNames = defaultEstateOwnerName.Split(' ');
  484. if (ownerNames.Length >= 2)
  485. {
  486. estateOwnerFirstName = ownerNames[0];
  487. estateOwnerLastName = ownerNames[1];
  488. }
  489. // Info to be used only on Standalone Mode
  490. rawEstateOwnerUuid = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerUUID", null);
  491. estateOwnerEMail = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerEMail", null);
  492. estateOwnerPassword = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerPassword", null);
  493. }
  494. MainConsole.Instance.Output("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName);
  495. List<char> excluded = new List<char>(new char[1]{' '});
  496. if (estateOwnerFirstName == null || estateOwnerLastName == null)
  497. {
  498. estateOwnerFirstName = MainConsole.Instance.Prompt("Estate owner first name", "Test", excluded);
  499. estateOwnerLastName = MainConsole.Instance.Prompt("Estate owner last name", "User", excluded);
  500. }
  501. UserAccount account
  502. = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, estateOwnerFirstName, estateOwnerLastName);
  503. if (account == null)
  504. {
  505. // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than
  506. // itself!
  507. // if (scene.UserAccountService is LocalUserAccountServicesConnector)
  508. // {
  509. // IUserAccountService innerUas
  510. // = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService;
  511. //
  512. // m_log.DebugFormat("B {0}", innerUas.GetType());
  513. //
  514. // if (innerUas is UserAccountService)
  515. // {
  516. if (scene.UserAccountService is UserAccountService)
  517. {
  518. if (estateOwnerPassword == null)
  519. estateOwnerPassword = MainConsole.Instance.Prompt("Password", null, null, false);
  520. if (estateOwnerEMail == null)
  521. estateOwnerEMail = MainConsole.Instance.Prompt("Email");
  522. if (rawEstateOwnerUuid == null)
  523. rawEstateOwnerUuid = MainConsole.Instance.Prompt("User ID", UUID.Random().ToString());
  524. UUID estateOwnerUuid = UUID.Zero;
  525. if (!UUID.TryParse(rawEstateOwnerUuid, out estateOwnerUuid))
  526. {
  527. m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawEstateOwnerUuid);
  528. return;
  529. }
  530. // If we've been given a zero uuid then this signals that we should use a random user id
  531. if (estateOwnerUuid == UUID.Zero)
  532. estateOwnerUuid = UUID.Random();
  533. account
  534. = ((UserAccountService)scene.UserAccountService).CreateUser(
  535. regionInfo.ScopeID,
  536. estateOwnerUuid,
  537. estateOwnerFirstName,
  538. estateOwnerLastName,
  539. estateOwnerPassword,
  540. estateOwnerEMail);
  541. }
  542. }
  543. if (account == null)
  544. {
  545. m_log.ErrorFormat(
  546. "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first at the grid level.");
  547. }
  548. else
  549. {
  550. regionInfo.EstateSettings.EstateOwner = account.PrincipalID;
  551. m_estateDataService.StoreEstateSettings(regionInfo.EstateSettings);
  552. }
  553. }
  554. private void ShutdownRegion(Scene scene)
  555. {
  556. m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName);
  557. if (scene.SnmpService != null)
  558. {
  559. scene.SnmpService.BootInfo("The region is shutting down", scene);
  560. scene.SnmpService.LinkDown(scene);
  561. }
  562. IRegionModulesController controller;
  563. if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller))
  564. {
  565. controller.RemoveRegionFromModules(scene);
  566. }
  567. }
  568. public void RemoveRegion(Scene scene, bool cleanup)
  569. {
  570. // only need to check this if we are not at the
  571. // root level
  572. if ((SceneManager.CurrentScene != null) &&
  573. (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  574. {
  575. SceneManager.TrySetCurrentScene("..");
  576. }
  577. scene.DeleteAllSceneObjects();
  578. SceneManager.CloseScene(scene);
  579. //ShutdownClientServer(scene.RegionInfo);
  580. if (!cleanup)
  581. return;
  582. if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile))
  583. {
  584. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml"))
  585. {
  586. File.Delete(scene.RegionInfo.RegionFile);
  587. m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile);
  588. }
  589. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini"))
  590. {
  591. try
  592. {
  593. IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile);
  594. if (source.Configs[scene.RegionInfo.RegionName] != null)
  595. {
  596. source.Configs.Remove(scene.RegionInfo.RegionName);
  597. if (source.Configs.Count == 0)
  598. {
  599. File.Delete(scene.RegionInfo.RegionFile);
  600. }
  601. else
  602. {
  603. source.Save(scene.RegionInfo.RegionFile);
  604. }
  605. }
  606. }
  607. catch (Exception)
  608. {
  609. }
  610. }
  611. }
  612. }
  613. public void RemoveRegion(string name, bool cleanUp)
  614. {
  615. Scene target;
  616. if (SceneManager.TryGetScene(name, out target))
  617. RemoveRegion(target, cleanUp);
  618. }
  619. /// <summary>
  620. /// Remove a region from the simulator without deleting it permanently.
  621. /// </summary>
  622. /// <param name="scene"></param>
  623. /// <returns></returns>
  624. public void CloseRegion(Scene scene)
  625. {
  626. // only need to check this if we are not at the
  627. // root level
  628. if ((SceneManager.CurrentScene != null) &&
  629. (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  630. {
  631. SceneManager.TrySetCurrentScene("..");
  632. }
  633. SceneManager.CloseScene(scene);
  634. //ShutdownClientServer(scene.RegionInfo);
  635. }
  636. /// <summary>
  637. /// Remove a region from the simulator without deleting it permanently.
  638. /// </summary>
  639. /// <param name="name"></param>
  640. /// <returns></returns>
  641. public void CloseRegion(string name)
  642. {
  643. Scene target;
  644. if (SceneManager.TryGetScene(name, out target))
  645. CloseRegion(target);
  646. }
  647. /// <summary>
  648. /// Create a scene and its initial base structures.
  649. /// </summary>
  650. /// <param name="regionInfo"></param>
  651. /// <param name="clientServer"> </param>
  652. /// <returns></returns>
  653. protected Scene SetupScene(RegionInfo regionInfo)
  654. {
  655. return SetupScene(regionInfo, 0, null);
  656. }
  657. /// <summary>
  658. /// Create a scene and its initial base structures.
  659. /// </summary>
  660. /// <param name="regionInfo"></param>
  661. /// <param name="proxyOffset"></param>
  662. /// <param name="configSource"></param>
  663. /// <param name="clientServer"> </param>
  664. /// <returns></returns>
  665. protected Scene SetupScene(RegionInfo regionInfo, int proxyOffset, IConfigSource configSource)
  666. {
  667. //List<IClientNetworkServer> clientNetworkServers = null;
  668. AgentCircuitManager circuitManager = new AgentCircuitManager();
  669. Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager);
  670. scene.LoadWorldMap();
  671. return scene;
  672. }
  673. protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
  674. IEstateDataService estateDataService, AgentCircuitManager circuitManager)
  675. {
  676. return new Scene(
  677. regionInfo, circuitManager,
  678. simDataService, estateDataService,
  679. Config, m_version);
  680. }
  681. protected virtual void HandleRestartRegion(RegionInfo whichRegion)
  682. {
  683. m_log.InfoFormat(
  684. "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})",
  685. whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY);
  686. //ShutdownClientServer(whichRegion);
  687. IScene scene;
  688. CreateRegion(whichRegion, true, out scene);
  689. scene.Start();
  690. }
  691. # region Setup methods
  692. /// <summary>
  693. /// Handler to supply the current status of this sim
  694. /// </summary>
  695. /// <remarks>
  696. /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
  697. /// </remarks>
  698. public class SimStatusHandler : SimpleStreamHandler
  699. {
  700. public SimStatusHandler() : base("/simstatus", "SimStatus") {}
  701. protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  702. {
  703. httpResponse.KeepAlive = false;
  704. httpResponse.RawBuffer = Util.UTF8.GetBytes("OK");
  705. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  706. }
  707. }
  708. /// <summary>
  709. /// Handler to supply the current extended status of this sim
  710. /// Sends the statistical data in a json serialization
  711. /// </summary>
  712. public class XSimStatusHandler : SimpleStreamHandler
  713. {
  714. OpenSimBase m_opensim;
  715. public XSimStatusHandler(OpenSimBase sim)
  716. : base("/" + Util.SHA1Hash(sim.osSecret), "XSimStatus")
  717. {
  718. m_opensim = sim;
  719. }
  720. protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  721. {
  722. httpResponse.KeepAlive = false;
  723. try
  724. {
  725. httpResponse.RawBuffer = Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  726. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  727. }
  728. catch
  729. {
  730. httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
  731. }
  732. }
  733. }
  734. /// <summary>
  735. /// Handler to supply the current extended status of this sim to a user configured URI
  736. /// Sends the statistical data in a json serialization
  737. /// If the request contains a key, "callback" the response will be wrappend in the
  738. /// associated value for jsonp used with ajax/javascript
  739. /// </summary>
  740. protected class UXSimStatusHandler : SimpleStreamHandler
  741. {
  742. OpenSimBase m_opensim;
  743. public UXSimStatusHandler(OpenSimBase sim)
  744. : base("/" + sim.userStatsURI, "UXSimStatus")
  745. {
  746. m_opensim = sim;
  747. }
  748. protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  749. {
  750. httpResponse.KeepAlive = false;
  751. try
  752. {
  753. httpResponse.RawBuffer = Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  754. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  755. }
  756. catch
  757. {
  758. httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
  759. }
  760. }
  761. }
  762. /// <summary>
  763. /// handler to supply serving http://domainname:port/robots.txt
  764. /// </summary>
  765. public class SimRobotsHandler : SimpleStreamHandler
  766. {
  767. private readonly byte[] binmsg;
  768. public SimRobotsHandler() : base("/robots.txt", "SimRobots")
  769. {
  770. binmsg = Util.UTF8.GetBytes("# go away\nUser-agent: *\nDisallow: /\n");
  771. }
  772. protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  773. {
  774. httpResponse.KeepAlive = false;
  775. httpResponse.RawBuffer = binmsg;
  776. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  777. return;
  778. }
  779. }
  780. #endregion
  781. /// <summary>
  782. /// Performs any last-minute sanity checking and shuts down the region server
  783. /// </summary>
  784. protected override void ShutdownSpecific()
  785. {
  786. if (proxyUrl.Length > 0)
  787. {
  788. Util.XmlRpcCommand(proxyUrl, "Stop");
  789. }
  790. m_log.Info("[SHUTDOWN]: Closing all threads");
  791. m_log.Info("[SHUTDOWN]: Killing listener thread");
  792. m_log.Info("[SHUTDOWN]: Killing clients");
  793. m_log.Info("[SHUTDOWN]: Closing console and terminating");
  794. try
  795. {
  796. SceneManager.Close();
  797. foreach (IApplicationPlugin plugin in m_plugins)
  798. plugin.Dispose();
  799. }
  800. catch (Exception e)
  801. {
  802. m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e);
  803. }
  804. base.ShutdownSpecific();
  805. }
  806. /// <summary>
  807. /// Get the start time and up time of Region server
  808. /// </summary>
  809. /// <param name="starttime">The first out parameter describing when the Region server started</param>
  810. /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
  811. public void GetRunTime(out string starttime, out string uptime)
  812. {
  813. starttime = m_startuptime.ToString();
  814. uptime = (DateTime.Now - m_startuptime).ToString();
  815. }
  816. /// <summary>
  817. /// Get the number of the avatars in the Region server
  818. /// </summary>
  819. /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
  820. public void GetAvatarNumber(out int usernum)
  821. {
  822. usernum = SceneManager.GetCurrentSceneAvatars().Count;
  823. }
  824. /// <summary>
  825. /// Get the number of regions
  826. /// </summary>
  827. /// <param name="regionnum">The first out parameter describing the number of regions</param>
  828. public void GetRegionNumber(out int regionnum)
  829. {
  830. regionnum = SceneManager.Scenes.Count;
  831. }
  832. /// <summary>
  833. /// Create an estate with an initial region.
  834. /// </summary>
  835. /// <remarks>
  836. /// This method doesn't allow an estate to be created with the same name as existing estates.
  837. /// </remarks>
  838. /// <param name="regInfo"></param>
  839. /// <param name="estatesByName">A list of estate names that already exist.</param>
  840. /// <param name="estateName">Estate name to create if already known</param>
  841. /// <returns>true if the estate was created, false otherwise</returns>
  842. public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName)
  843. {
  844. // Create a new estate
  845. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);
  846. string newName;
  847. if (!string.IsNullOrEmpty(estateName))
  848. newName = estateName;
  849. else
  850. newName = MainConsole.Instance.Prompt("New estate name", regInfo.EstateSettings.EstateName);
  851. if (estatesByName.ContainsKey(newName))
  852. {
  853. MainConsole.Instance.Output("An estate named {0} already exists. Please try again.", newName);
  854. return false;
  855. }
  856. regInfo.EstateSettings.EstateName = newName;
  857. // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
  858. // Therefore, we need to do an initial save here otherwise the new estate name will be reset
  859. // back to the default. The reloading of estate settings by scene could be eliminated if it
  860. // knows that the passed in settings in RegionInfo are already valid. Also, it might be
  861. // possible to eliminate some additional later saves made by callers of this method.
  862. EstateDataService.StoreEstateSettings(regInfo.EstateSettings);
  863. return true;
  864. }
  865. /// <summary>
  866. /// Load the estate information for the provided RegionInfo object.
  867. /// </summary>
  868. /// <param name="regInfo"></param>
  869. public bool PopulateRegionEstateInfo(RegionInfo regInfo)
  870. {
  871. if (EstateDataService != null)
  872. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);
  873. if (regInfo.EstateSettings.EstateID != 0)
  874. return false; // estate info in the database did not change
  875. m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
  876. List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();
  877. Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>();
  878. foreach (EstateSettings estate in estates)
  879. estatesByName[estate.EstateName] = estate;
  880. string defaultEstateName = null;
  881. if (Config.Configs[ESTATE_SECTION_NAME] != null)
  882. {
  883. defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null);
  884. if (defaultEstateName != null)
  885. {
  886. EstateSettings defaultEstate;
  887. bool defaultEstateJoined = false;
  888. if (estatesByName.ContainsKey(defaultEstateName))
  889. {
  890. defaultEstate = estatesByName[defaultEstateName];
  891. if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID))
  892. defaultEstateJoined = true;
  893. }
  894. else
  895. {
  896. if (CreateEstate(regInfo, estatesByName, defaultEstateName))
  897. defaultEstateJoined = true;
  898. }
  899. if (defaultEstateJoined)
  900. return true; // need to update the database
  901. else
  902. m_log.ErrorFormat(
  903. "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName);
  904. }
  905. }
  906. // If we have no default estate or creation of the default estate failed then ask the user.
  907. while (true)
  908. {
  909. if (estates.Count == 0)
  910. {
  911. m_log.Info("[ESTATE]: No existing estates found. You must create a new one.");
  912. if (CreateEstate(regInfo, estatesByName, null))
  913. break;
  914. else
  915. continue;
  916. }
  917. else
  918. {
  919. string response
  920. = MainConsole.Instance.Prompt(
  921. string.Format(
  922. "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
  923. "yes",
  924. new List<string>() { "yes", "no" });
  925. if (response == "no")
  926. {
  927. if (CreateEstate(regInfo, estatesByName, null))
  928. break;
  929. else
  930. continue;
  931. }
  932. else
  933. {
  934. string[] estateNames = estatesByName.Keys.ToArray();
  935. response
  936. = MainConsole.Instance.Prompt(
  937. string.Format(
  938. "Name of estate to join. Existing estate names are ({0})",
  939. string.Join(", ", estateNames)),
  940. estateNames[0]);
  941. List<int> estateIDs = EstateDataService.GetEstates(response);
  942. if (estateIDs.Count < 1)
  943. {
  944. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again.");
  945. continue;
  946. }
  947. int estateID = estateIDs[0];
  948. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);
  949. if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
  950. break;
  951. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  952. }
  953. }
  954. }
  955. return true; // need to update the database
  956. }
  957. }
  958. public class OpenSimConfigSource
  959. {
  960. public IConfigSource Source;
  961. }
  962. }