OpenSimBase.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. m_httpServerPort = m_networkServersInfo.HttpListenerPort;
  296. SceneManager.OnRestartSim += HandleRestartRegion;
  297. // Only enable the watchdogs when all regions are ready. Otherwise we get false positives when cpu is
  298. // heavily used during initial startup.
  299. //
  300. // FIXME: It's also possible that region ready status should be flipped during an OAR load since this
  301. // also makes heavy use of the CPU.
  302. SceneManager.OnRegionsReadyStatusChange
  303. += sm => { MemoryWatchdog.Enabled = sm.AllRegionsReady; Watchdog.Enabled = sm.AllRegionsReady; };
  304. }
  305. /// <summary>
  306. /// Execute the region creation process. This includes setting up scene infrastructure.
  307. /// </summary>
  308. /// <param name="regionInfo"></param>
  309. /// <param name="portadd_flag"></param>
  310. /// <returns></returns>
  311. public void CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene)
  312. {
  313. CreateRegion(regionInfo, portadd_flag, false, out scene);
  314. }
  315. /// <summary>
  316. /// Execute the region creation process. This includes setting up scene infrastructure.
  317. /// </summary>
  318. /// <param name="regionInfo"></param>
  319. /// <returns></returns>
  320. public void CreateRegion(RegionInfo regionInfo, out IScene scene)
  321. {
  322. CreateRegion(regionInfo, false, true, 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. /// <param name="portadd_flag"></param>
  329. /// <param name="do_post_init"></param>
  330. /// <returns></returns>
  331. public void CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene)
  332. {
  333. int port = regionInfo.InternalEndPoint.Port;
  334. // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims)
  335. // Commented this out because otherwise regions can't register with
  336. // the grid as there is already another region with the same UUID
  337. // at those coordinates. This is required for the load balancer to work.
  338. // --Mike, 2009.02.25
  339. //regionInfo.originRegionID = regionInfo.RegionID;
  340. // set initial ServerURI
  341. regionInfo.HttpPort = m_httpServerPort;
  342. regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort.ToString() + "/";
  343. regionInfo.osSecret = m_osSecret;
  344. if ((proxyUrl.Length > 0) && (portadd_flag))
  345. {
  346. // set proxy url to RegionInfo
  347. regionInfo.proxyUrl = proxyUrl;
  348. regionInfo.ProxyOffset = proxyOffset;
  349. Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName);
  350. }
  351. Scene scene = SetupScene(regionInfo, proxyOffset, Config);
  352. m_log.Info("[MODULES]: Loading Region's modules (old style)");
  353. // Use this in the future, the line above will be deprecated soon
  354. m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)");
  355. IRegionModulesController controller;
  356. if (ApplicationRegistry.TryGet(out controller))
  357. {
  358. controller.AddRegionToModules(scene);
  359. }
  360. else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing...");
  361. if (m_securePermissionsLoading)
  362. {
  363. foreach (string s in m_permsModules)
  364. {
  365. if (!scene.RegionModules.ContainsKey(s))
  366. {
  367. m_log.Fatal("[MODULES]: Required module " + s + " not found.");
  368. Environment.Exit(0);
  369. }
  370. }
  371. m_log.InfoFormat("[SCENE]: Secure permissions loading enabled, modules loaded: {0}", String.Join(" ", m_permsModules.ToArray()));
  372. }
  373. scene.SetModuleInterfaces();
  374. // First Step of bootreport sequence
  375. if (scene.SnmpService != null)
  376. {
  377. scene.SnmpService.ColdStart(1,scene);
  378. scene.SnmpService.LinkDown(scene);
  379. }
  380. if (scene.SnmpService != null)
  381. {
  382. scene.SnmpService.BootInfo("Loading prins", scene);
  383. }
  384. while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
  385. SetUpEstateOwner(scene);
  386. scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
  387. // Prims have to be loaded after module configuration since some modules may be invoked during the load
  388. scene.LoadPrimsFromStorage(regionInfo.originRegionID);
  389. // TODO : Try setting resource for region xstats here on scene
  390. MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo));
  391. if (scene.SnmpService != null)
  392. {
  393. scene.SnmpService.BootInfo("Grid Registration in progress", scene);
  394. }
  395. try
  396. {
  397. scene.RegisterRegionWithGrid();
  398. }
  399. catch (Exception e)
  400. {
  401. m_log.ErrorFormat(
  402. "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}",
  403. e.Message, e.StackTrace);
  404. if (scene.SnmpService != null)
  405. {
  406. scene.SnmpService.Critical("Grid registration failed. Startup aborted.", scene);
  407. }
  408. // Carrying on now causes a lot of confusion down the
  409. // line - we need to get the user's attention
  410. Environment.Exit(1);
  411. }
  412. if (scene.SnmpService != null)
  413. {
  414. scene.SnmpService.BootInfo("Grid Registration done", scene);
  415. }
  416. // We need to do this after we've initialized the
  417. // scripting engines.
  418. scene.CreateScriptInstances();
  419. if (scene.SnmpService != null)
  420. {
  421. scene.SnmpService.BootInfo("ScriptEngine started", scene);
  422. }
  423. SceneManager.Add(scene);
  424. //if (m_autoCreateClientStack)
  425. //{
  426. // foreach (IClientNetworkServer clientserver in clientServers)
  427. // {
  428. // m_clientServers.Add(clientserver);
  429. // clientserver.Start();
  430. // }
  431. //}
  432. if (scene.SnmpService != null)
  433. {
  434. scene.SnmpService.BootInfo("Initializing region modules", scene);
  435. }
  436. scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };
  437. mscene = scene;
  438. if (scene.SnmpService != null)
  439. {
  440. scene.SnmpService.BootInfo("The region is operational", scene);
  441. scene.SnmpService.LinkUp(scene);
  442. }
  443. //return clientServers;
  444. }
  445. /// <summary>
  446. /// Try to set up the estate owner for the given scene.
  447. /// </summary>
  448. /// <remarks>
  449. /// The involves asking the user for information about the user on the console. If the user does not already
  450. /// exist then it is created.
  451. /// </remarks>
  452. /// <param name="scene"></param>
  453. private void SetUpEstateOwner(Scene scene)
  454. {
  455. RegionInfo regionInfo = scene.RegionInfo;
  456. string estateOwnerFirstName = null;
  457. string estateOwnerLastName = null;
  458. string estateOwnerEMail = null;
  459. string estateOwnerPassword = null;
  460. string rawEstateOwnerUuid = null;
  461. if (Config.Configs[ESTATE_SECTION_NAME] != null)
  462. {
  463. string defaultEstateOwnerName
  464. = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerName", "").Trim();
  465. string[] ownerNames = defaultEstateOwnerName.Split(' ');
  466. if (ownerNames.Length >= 2)
  467. {
  468. estateOwnerFirstName = ownerNames[0];
  469. estateOwnerLastName = ownerNames[1];
  470. }
  471. // Info to be used only on Standalone Mode
  472. rawEstateOwnerUuid = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerUUID", null);
  473. estateOwnerEMail = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerEMail", null);
  474. estateOwnerPassword = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerPassword", null);
  475. }
  476. MainConsole.Instance.OutputFormat("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName);
  477. List<char> excluded = new List<char>(new char[1]{' '});
  478. if (estateOwnerFirstName == null || estateOwnerLastName == null)
  479. {
  480. estateOwnerFirstName = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test", excluded);
  481. estateOwnerLastName = MainConsole.Instance.CmdPrompt("Estate owner last name", "User", excluded);
  482. }
  483. UserAccount account
  484. = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, estateOwnerFirstName, estateOwnerLastName);
  485. if (account == null)
  486. {
  487. // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than
  488. // itself!
  489. // if (scene.UserAccountService is LocalUserAccountServicesConnector)
  490. // {
  491. // IUserAccountService innerUas
  492. // = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService;
  493. //
  494. // m_log.DebugFormat("B {0}", innerUas.GetType());
  495. //
  496. // if (innerUas is UserAccountService)
  497. // {
  498. if (scene.UserAccountService is UserAccountService)
  499. {
  500. if (estateOwnerPassword == null)
  501. estateOwnerPassword = MainConsole.Instance.PasswdPrompt("Password");
  502. if (estateOwnerEMail == null)
  503. estateOwnerEMail = MainConsole.Instance.CmdPrompt("Email");
  504. if (rawEstateOwnerUuid == null)
  505. rawEstateOwnerUuid = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString());
  506. UUID estateOwnerUuid = UUID.Zero;
  507. if (!UUID.TryParse(rawEstateOwnerUuid, out estateOwnerUuid))
  508. {
  509. m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawEstateOwnerUuid);
  510. return;
  511. }
  512. // If we've been given a zero uuid then this signals that we should use a random user id
  513. if (estateOwnerUuid == UUID.Zero)
  514. estateOwnerUuid = UUID.Random();
  515. account
  516. = ((UserAccountService)scene.UserAccountService).CreateUser(
  517. regionInfo.ScopeID,
  518. estateOwnerUuid,
  519. estateOwnerFirstName,
  520. estateOwnerLastName,
  521. estateOwnerPassword,
  522. estateOwnerEMail);
  523. }
  524. }
  525. if (account == null)
  526. {
  527. m_log.ErrorFormat(
  528. "[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.");
  529. }
  530. else
  531. {
  532. regionInfo.EstateSettings.EstateOwner = account.PrincipalID;
  533. m_estateDataService.StoreEstateSettings(regionInfo.EstateSettings);
  534. }
  535. }
  536. private void ShutdownRegion(Scene scene)
  537. {
  538. m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName);
  539. if (scene.SnmpService != null)
  540. {
  541. scene.SnmpService.BootInfo("The region is shutting down", scene);
  542. scene.SnmpService.LinkDown(scene);
  543. }
  544. IRegionModulesController controller;
  545. if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller))
  546. {
  547. controller.RemoveRegionFromModules(scene);
  548. }
  549. }
  550. public void RemoveRegion(Scene scene, bool cleanup)
  551. {
  552. // only need to check this if we are not at the
  553. // root level
  554. if ((SceneManager.CurrentScene != null) &&
  555. (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  556. {
  557. SceneManager.TrySetCurrentScene("..");
  558. }
  559. scene.DeleteAllSceneObjects();
  560. SceneManager.CloseScene(scene);
  561. //ShutdownClientServer(scene.RegionInfo);
  562. if (!cleanup)
  563. return;
  564. if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile))
  565. {
  566. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml"))
  567. {
  568. File.Delete(scene.RegionInfo.RegionFile);
  569. m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile);
  570. }
  571. if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini"))
  572. {
  573. try
  574. {
  575. IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile);
  576. if (source.Configs[scene.RegionInfo.RegionName] != null)
  577. {
  578. source.Configs.Remove(scene.RegionInfo.RegionName);
  579. if (source.Configs.Count == 0)
  580. {
  581. File.Delete(scene.RegionInfo.RegionFile);
  582. }
  583. else
  584. {
  585. source.Save(scene.RegionInfo.RegionFile);
  586. }
  587. }
  588. }
  589. catch (Exception)
  590. {
  591. }
  592. }
  593. }
  594. }
  595. public void RemoveRegion(string name, bool cleanUp)
  596. {
  597. Scene target;
  598. if (SceneManager.TryGetScene(name, out target))
  599. RemoveRegion(target, cleanUp);
  600. }
  601. /// <summary>
  602. /// Remove a region from the simulator without deleting it permanently.
  603. /// </summary>
  604. /// <param name="scene"></param>
  605. /// <returns></returns>
  606. public void CloseRegion(Scene scene)
  607. {
  608. // only need to check this if we are not at the
  609. // root level
  610. if ((SceneManager.CurrentScene != null) &&
  611. (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
  612. {
  613. SceneManager.TrySetCurrentScene("..");
  614. }
  615. SceneManager.CloseScene(scene);
  616. //ShutdownClientServer(scene.RegionInfo);
  617. }
  618. /// <summary>
  619. /// Remove a region from the simulator without deleting it permanently.
  620. /// </summary>
  621. /// <param name="name"></param>
  622. /// <returns></returns>
  623. public void CloseRegion(string name)
  624. {
  625. Scene target;
  626. if (SceneManager.TryGetScene(name, out target))
  627. CloseRegion(target);
  628. }
  629. /// <summary>
  630. /// Create a scene and its initial base structures.
  631. /// </summary>
  632. /// <param name="regionInfo"></param>
  633. /// <param name="clientServer"> </param>
  634. /// <returns></returns>
  635. protected Scene SetupScene(RegionInfo regionInfo)
  636. {
  637. return SetupScene(regionInfo, 0, null);
  638. }
  639. /// <summary>
  640. /// Create a scene and its initial base structures.
  641. /// </summary>
  642. /// <param name="regionInfo"></param>
  643. /// <param name="proxyOffset"></param>
  644. /// <param name="configSource"></param>
  645. /// <param name="clientServer"> </param>
  646. /// <returns></returns>
  647. protected Scene SetupScene(RegionInfo regionInfo, int proxyOffset, IConfigSource configSource)
  648. {
  649. //List<IClientNetworkServer> clientNetworkServers = null;
  650. AgentCircuitManager circuitManager = new AgentCircuitManager();
  651. Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager);
  652. scene.LoadWorldMap();
  653. return scene;
  654. }
  655. protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
  656. IEstateDataService estateDataService, AgentCircuitManager circuitManager)
  657. {
  658. return new Scene(
  659. regionInfo, circuitManager,
  660. simDataService, estateDataService,
  661. Config, m_version);
  662. }
  663. protected virtual void HandleRestartRegion(RegionInfo whichRegion)
  664. {
  665. m_log.InfoFormat(
  666. "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})",
  667. whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY);
  668. //ShutdownClientServer(whichRegion);
  669. IScene scene;
  670. CreateRegion(whichRegion, true, out scene);
  671. scene.Start();
  672. }
  673. # region Setup methods
  674. /// <summary>
  675. /// Handler to supply the current status of this sim
  676. /// </summary>
  677. /// <remarks>
  678. /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
  679. /// </remarks>
  680. public class SimStatusHandler : BaseStreamHandler
  681. {
  682. public SimStatusHandler() : base("GET", "/simstatus", "SimStatus", "Simulator Status") {}
  683. protected override byte[] ProcessRequest(string path, Stream request,
  684. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  685. {
  686. return Util.UTF8.GetBytes("OK");
  687. }
  688. public override string ContentType
  689. {
  690. get { return "text/plain"; }
  691. }
  692. }
  693. /// <summary>
  694. /// Handler to supply the current extended status of this sim
  695. /// Sends the statistical data in a json serialization
  696. /// </summary>
  697. public class XSimStatusHandler : BaseStreamHandler
  698. {
  699. OpenSimBase m_opensim;
  700. public XSimStatusHandler(OpenSimBase sim)
  701. : base("GET", "/" + Util.SHA1Hash(sim.osSecret), "XSimStatus", "Simulator XStatus")
  702. {
  703. m_opensim = sim;
  704. }
  705. protected override byte[] ProcessRequest(string path, Stream request,
  706. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  707. {
  708. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  709. }
  710. public override string ContentType
  711. {
  712. get { return "text/plain"; }
  713. }
  714. }
  715. /// <summary>
  716. /// Handler to supply the current extended status of this sim to a user configured URI
  717. /// Sends the statistical data in a json serialization
  718. /// If the request contains a key, "callback" the response will be wrappend in the
  719. /// associated value for jsonp used with ajax/javascript
  720. /// </summary>
  721. protected class UXSimStatusHandler : BaseStreamHandler
  722. {
  723. OpenSimBase m_opensim;
  724. public UXSimStatusHandler(OpenSimBase sim)
  725. : base("GET", "/" + sim.userStatsURI, "UXSimStatus", "Simulator UXStatus")
  726. {
  727. m_opensim = sim;
  728. }
  729. protected override byte[] ProcessRequest(string path, Stream request,
  730. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  731. {
  732. return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
  733. }
  734. public override string ContentType
  735. {
  736. get { return "text/plain"; }
  737. }
  738. }
  739. /// <summary>
  740. /// handler to supply serving http://domainname:port/robots.txt
  741. /// </summary>
  742. public class SimRobotsHandler : BaseStreamHandler
  743. {
  744. public SimRobotsHandler() : base("GET", "/robots.txt", "SimRobots.txt", "Simulator Robots.txt") {}
  745. protected override byte[] ProcessRequest(string path, Stream request,
  746. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  747. {
  748. string robots = "# go away\nUser-agent: *\nDisallow: /\n";
  749. return Util.UTF8.GetBytes(robots);
  750. }
  751. public override string ContentType
  752. {
  753. get { return "text/plain"; }
  754. }
  755. }
  756. #endregion
  757. /// <summary>
  758. /// Performs any last-minute sanity checking and shuts down the region server
  759. /// </summary>
  760. protected override void ShutdownSpecific()
  761. {
  762. if (proxyUrl.Length > 0)
  763. {
  764. Util.XmlRpcCommand(proxyUrl, "Stop");
  765. }
  766. m_log.Info("[SHUTDOWN]: Closing all threads");
  767. m_log.Info("[SHUTDOWN]: Killing listener thread");
  768. m_log.Info("[SHUTDOWN]: Killing clients");
  769. m_log.Info("[SHUTDOWN]: Closing console and terminating");
  770. try
  771. {
  772. SceneManager.Close();
  773. foreach (IApplicationPlugin plugin in m_plugins)
  774. plugin.Dispose();
  775. }
  776. catch (Exception e)
  777. {
  778. m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e);
  779. }
  780. base.ShutdownSpecific();
  781. }
  782. /// <summary>
  783. /// Get the start time and up time of Region server
  784. /// </summary>
  785. /// <param name="starttime">The first out parameter describing when the Region server started</param>
  786. /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
  787. public void GetRunTime(out string starttime, out string uptime)
  788. {
  789. starttime = m_startuptime.ToString();
  790. uptime = (DateTime.Now - m_startuptime).ToString();
  791. }
  792. /// <summary>
  793. /// Get the number of the avatars in the Region server
  794. /// </summary>
  795. /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
  796. public void GetAvatarNumber(out int usernum)
  797. {
  798. usernum = SceneManager.GetCurrentSceneAvatars().Count;
  799. }
  800. /// <summary>
  801. /// Get the number of regions
  802. /// </summary>
  803. /// <param name="regionnum">The first out parameter describing the number of regions</param>
  804. public void GetRegionNumber(out int regionnum)
  805. {
  806. regionnum = SceneManager.Scenes.Count;
  807. }
  808. /// <summary>
  809. /// Create an estate with an initial region.
  810. /// </summary>
  811. /// <remarks>
  812. /// This method doesn't allow an estate to be created with the same name as existing estates.
  813. /// </remarks>
  814. /// <param name="regInfo"></param>
  815. /// <param name="estatesByName">A list of estate names that already exist.</param>
  816. /// <param name="estateName">Estate name to create if already known</param>
  817. /// <returns>true if the estate was created, false otherwise</returns>
  818. public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName)
  819. {
  820. // Create a new estate
  821. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);
  822. string newName;
  823. if (!string.IsNullOrEmpty(estateName))
  824. newName = estateName;
  825. else
  826. newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName);
  827. if (estatesByName.ContainsKey(newName))
  828. {
  829. MainConsole.Instance.OutputFormat("An estate named {0} already exists. Please try again.", newName);
  830. return false;
  831. }
  832. regInfo.EstateSettings.EstateName = newName;
  833. // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
  834. // Therefore, we need to do an initial save here otherwise the new estate name will be reset
  835. // back to the default. The reloading of estate settings by scene could be eliminated if it
  836. // knows that the passed in settings in RegionInfo are already valid. Also, it might be
  837. // possible to eliminate some additional later saves made by callers of this method.
  838. EstateDataService.StoreEstateSettings(regInfo.EstateSettings);
  839. return true;
  840. }
  841. /// <summary>
  842. /// Load the estate information for the provided RegionInfo object.
  843. /// </summary>
  844. /// <param name="regInfo"></param>
  845. public bool PopulateRegionEstateInfo(RegionInfo regInfo)
  846. {
  847. if (EstateDataService != null)
  848. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);
  849. if (regInfo.EstateSettings.EstateID != 0)
  850. return false; // estate info in the database did not change
  851. m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
  852. List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();
  853. Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>();
  854. foreach (EstateSettings estate in estates)
  855. estatesByName[estate.EstateName] = estate;
  856. string defaultEstateName = null;
  857. if (Config.Configs[ESTATE_SECTION_NAME] != null)
  858. {
  859. defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null);
  860. if (defaultEstateName != null)
  861. {
  862. EstateSettings defaultEstate;
  863. bool defaultEstateJoined = false;
  864. if (estatesByName.ContainsKey(defaultEstateName))
  865. {
  866. defaultEstate = estatesByName[defaultEstateName];
  867. if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID))
  868. defaultEstateJoined = true;
  869. }
  870. else
  871. {
  872. if (CreateEstate(regInfo, estatesByName, defaultEstateName))
  873. defaultEstateJoined = true;
  874. }
  875. if (defaultEstateJoined)
  876. return true; // need to update the database
  877. else
  878. m_log.ErrorFormat(
  879. "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName);
  880. }
  881. }
  882. // If we have no default estate or creation of the default estate failed then ask the user.
  883. while (true)
  884. {
  885. if (estates.Count == 0)
  886. {
  887. m_log.Info("[ESTATE]: No existing estates found. You must create a new one.");
  888. if (CreateEstate(regInfo, estatesByName, null))
  889. break;
  890. else
  891. continue;
  892. }
  893. else
  894. {
  895. string response
  896. = MainConsole.Instance.CmdPrompt(
  897. string.Format(
  898. "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
  899. "yes",
  900. new List<string>() { "yes", "no" });
  901. if (response == "no")
  902. {
  903. if (CreateEstate(regInfo, estatesByName, null))
  904. break;
  905. else
  906. continue;
  907. }
  908. else
  909. {
  910. string[] estateNames = estatesByName.Keys.ToArray();
  911. response
  912. = MainConsole.Instance.CmdPrompt(
  913. string.Format(
  914. "Name of estate to join. Existing estate names are ({0})",
  915. string.Join(", ", estateNames)),
  916. estateNames[0]);
  917. List<int> estateIDs = EstateDataService.GetEstates(response);
  918. if (estateIDs.Count < 1)
  919. {
  920. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again.");
  921. continue;
  922. }
  923. int estateID = estateIDs[0];
  924. regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);
  925. if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
  926. break;
  927. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  928. }
  929. }
  930. }
  931. return true; // need to update the database
  932. }
  933. }
  934. public class OpenSimConfigSource
  935. {
  936. public IConfigSource Source;
  937. }
  938. }