OpenSimBase.cs 43 KB

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