Application.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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.IO;
  29. using System.Net;
  30. using System.Reflection;
  31. using log4net;
  32. using log4net.Config;
  33. using Nini.Config;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Console;
  36. namespace OpenSim
  37. {
  38. /// <summary>
  39. /// Starting class for the OpenSimulator Region
  40. /// </summary>
  41. public class Application
  42. {
  43. /// <summary>
  44. /// Text Console Logger
  45. /// </summary>
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. /// <summary>
  48. /// Path to the main ini Configuration file
  49. /// </summary>
  50. public static string iniFilePath = "";
  51. /// <summary>
  52. /// Save Crashes in the bin/crashes folder. Configurable with m_crashDir
  53. /// </summary>
  54. public static bool m_saveCrashDumps = false;
  55. /// <summary>
  56. /// Directory to save crash reports to. Relative to bin/
  57. /// </summary>
  58. public static string m_crashDir = "crashes";
  59. /// <summary>
  60. /// Instance of the OpenSim class. This could be OpenSim or OpenSimBackground depending on the configuration
  61. /// </summary>
  62. protected static OpenSimBase m_sim = null;
  63. //could move our main function into OpenSimMain and kill this class
  64. public static void Main(string[] args)
  65. {
  66. // First line, hook the appdomain to the crash reporter
  67. AppDomain.CurrentDomain.UnhandledException +=
  68. new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  69. Culture.SetCurrentCulture();
  70. Culture.SetDefaultCurrentCulture();
  71. if(Util.IsWindows())
  72. ServicePointManager.DefaultConnectionLimit = 32;
  73. else
  74. {
  75. ServicePointManager.DefaultConnectionLimit = 12;
  76. }
  77. try { ServicePointManager.DnsRefreshTimeout = 300000; } catch { }
  78. ServicePointManager.Expect100Continue = false;
  79. ServicePointManager.UseNagleAlgorithm = false;
  80. // Add the arguments supplied when running the application to the configuration
  81. ArgvConfigSource configSource = new ArgvConfigSource(args);
  82. // Configure Log4Net
  83. configSource.AddSwitch("Startup", "logconfig");
  84. string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
  85. if (logConfigFile != String.Empty)
  86. {
  87. XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
  88. m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file",
  89. logConfigFile);
  90. }
  91. else
  92. {
  93. XmlConfigurator.Configure();
  94. m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config");
  95. }
  96. m_log.InfoFormat(
  97. "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture);
  98. string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU");
  99. m_log.InfoFormat(
  100. "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset");
  101. // Verify the Threadpool allocates or uses enough worker and IO completion threads
  102. // .NET 2.0, workerthreads default to 50 * numcores
  103. // .NET 3.0, workerthreads defaults to 250 * numcores
  104. // .NET 4.0, workerthreads are dynamic based on bitness and OS resources
  105. // Max IO Completion threads are 1000 on all 3 CLRs
  106. //
  107. // Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores
  108. int workerThreadsMin = 500;
  109. int workerThreadsMax = 1000; // may need further adjustment to match other CLR
  110. int iocpThreadsMin = 1000;
  111. int iocpThreadsMax = 2000; // may need further adjustment to match other CLR
  112. {
  113. int currentMinWorkerThreads, currentMinIocpThreads;
  114. System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads);
  115. m_log.InfoFormat(
  116. "[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads",
  117. currentMinWorkerThreads, currentMinIocpThreads);
  118. }
  119. int workerThreads, iocpThreads;
  120. System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  121. m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads);
  122. if (workerThreads < workerThreadsMin)
  123. {
  124. workerThreads = workerThreadsMin;
  125. m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max worker threads to {0}",workerThreads);
  126. }
  127. if (workerThreads > workerThreadsMax)
  128. {
  129. workerThreads = workerThreadsMax;
  130. m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}",workerThreads);
  131. }
  132. // Increase the number of IOCP threads available.
  133. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17)
  134. if (iocpThreads < iocpThreadsMin)
  135. {
  136. iocpThreads = iocpThreadsMin;
  137. m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}",iocpThreads);
  138. }
  139. // Make sure we don't overallocate IOCP threads and thrash system resources
  140. if ( iocpThreads > iocpThreadsMax )
  141. {
  142. iocpThreads = iocpThreadsMax;
  143. m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}",iocpThreads);
  144. }
  145. // set the resulting worker and IO completion thread counts back to ThreadPool
  146. if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) )
  147. {
  148. m_log.InfoFormat(
  149. "[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads",
  150. workerThreads, iocpThreads);
  151. }
  152. else
  153. {
  154. m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect.");
  155. }
  156. // Check if the system is compatible with OpenSimulator.
  157. // Ensures that the minimum system requirements are met
  158. string supported = String.Empty;
  159. if (Util.IsEnvironmentSupported(ref supported))
  160. {
  161. m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator.");
  162. }
  163. else
  164. {
  165. m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n");
  166. }
  167. m_log.InfoFormat("Default culture changed to {0}",Culture.GetDefaultCurrentCulture().DisplayName);
  168. // Configure nIni aliases and localles
  169. // Validate that the user has the most basic configuration done
  170. // If not, offer to do the most basic configuration for them warning them along the way of the importance of
  171. // reading these files.
  172. /*
  173. m_log.Info("Checking for reguired configuration...\n");
  174. bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini")))
  175. || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini")))
  176. || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini")))
  177. || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini")));
  178. bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
  179. bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini"));
  180. bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini"));
  181. bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini"));
  182. if ((OpenSim_Ini)
  183. && (
  184. (StanaloneCommon_ProperCased
  185. || StanaloneCommon_lowercased
  186. || GridCommon_ProperCased
  187. || GridCommon_lowerCased
  188. )))
  189. {
  190. m_log.Info("Required Configuration Files Found\n");
  191. }
  192. else
  193. {
  194. MainConsole.Instance = new LocalConsole("Region");
  195. string resp = MainConsole.Instance.CmdPrompt(
  196. "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?",
  197. "yes");
  198. if (resp == "yes")
  199. {
  200. if (!(OpenSim_Ini))
  201. {
  202. try
  203. {
  204. File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"),
  205. Path.Combine(Util.configDir(), "OpenSim.ini"));
  206. } catch (UnauthorizedAccessException)
  207. {
  208. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n");
  209. } catch (ArgumentException)
  210. {
  211. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
  212. } catch (System.IO.PathTooLongException)
  213. {
  214. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n");
  215. } catch (System.IO.DirectoryNotFoundException)
  216. {
  217. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n");
  218. } catch (System.IO.FileNotFoundException)
  219. {
  220. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
  221. } catch (System.IO.IOException)
  222. {
  223. // Destination file exists already or a hard drive failure... .. so we can just drop this one
  224. //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
  225. } catch (System.NotSupportedException)
  226. {
  227. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
  228. }
  229. }
  230. if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased))
  231. {
  232. try
  233. {
  234. File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"),
  235. Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
  236. }
  237. catch (UnauthorizedAccessException)
  238. {
  239. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n");
  240. }
  241. catch (ArgumentException)
  242. {
  243. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
  244. }
  245. catch (System.IO.PathTooLongException)
  246. {
  247. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n");
  248. }
  249. catch (System.IO.DirectoryNotFoundException)
  250. {
  251. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n");
  252. }
  253. catch (System.IO.FileNotFoundException)
  254. {
  255. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n");
  256. }
  257. catch (System.IO.IOException)
  258. {
  259. // Destination file exists already or a hard drive failure... .. so we can just drop this one
  260. //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
  261. }
  262. catch (System.NotSupportedException)
  263. {
  264. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
  265. }
  266. }
  267. }
  268. MainConsole.Instance = null;
  269. }
  270. */
  271. configSource.Alias.AddAlias("On", true);
  272. configSource.Alias.AddAlias("Off", false);
  273. configSource.Alias.AddAlias("True", true);
  274. configSource.Alias.AddAlias("False", false);
  275. configSource.Alias.AddAlias("Yes", true);
  276. configSource.Alias.AddAlias("No", false);
  277. configSource.AddSwitch("Startup", "background");
  278. configSource.AddSwitch("Startup", "inifile");
  279. configSource.AddSwitch("Startup", "inimaster");
  280. configSource.AddSwitch("Startup", "inidirectory");
  281. configSource.AddSwitch("Startup", "physics");
  282. configSource.AddSwitch("Startup", "gui");
  283. configSource.AddSwitch("Startup", "console");
  284. configSource.AddSwitch("Startup", "save_crashes");
  285. configSource.AddSwitch("Startup", "crash_dir");
  286. configSource.AddConfig("StandAlone");
  287. configSource.AddConfig("Network");
  288. // Check if we're running in the background or not
  289. bool background = configSource.Configs["Startup"].GetBoolean("background", false);
  290. // Check if we're saving crashes
  291. m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);
  292. // load Crash directory config
  293. m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
  294. if (background)
  295. {
  296. m_sim = new OpenSimBackground(configSource);
  297. m_sim.Startup();
  298. }
  299. else
  300. {
  301. m_sim = new OpenSim(configSource);
  302. m_sim.Startup();
  303. while (true)
  304. {
  305. try
  306. {
  307. // Block thread here for input
  308. MainConsole.Instance.Prompt();
  309. }
  310. catch (Exception e)
  311. {
  312. m_log.ErrorFormat("Command error: {0}", e);
  313. }
  314. }
  315. }
  316. }
  317. private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself
  318. /// <summary>
  319. /// Global exception handler -- all unhandlet exceptions end up here :)
  320. /// </summary>
  321. /// <param name="sender"></param>
  322. /// <param name="e"></param>
  323. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  324. {
  325. if (_IsHandlingException)
  326. {
  327. return;
  328. }
  329. _IsHandlingException = true;
  330. // TODO: Add config option to allow users to turn off error reporting
  331. // TODO: Post error report (disabled for now)
  332. string msg = String.Empty;
  333. msg += "\r\n";
  334. msg += "APPLICATION EXCEPTION DETECTED: " + e.ToString() + "\r\n";
  335. msg += "\r\n";
  336. msg += "Exception: " + e.ExceptionObject.ToString() + "\r\n";
  337. Exception ex = (Exception) e.ExceptionObject;
  338. if (ex.InnerException != null)
  339. {
  340. msg += "InnerException: " + ex.InnerException.ToString() + "\r\n";
  341. }
  342. msg += "\r\n";
  343. msg += "Application is terminating: " + e.IsTerminating.ToString() + "\r\n";
  344. m_log.ErrorFormat("[APPLICATION]: {0}", msg);
  345. if (m_saveCrashDumps)
  346. {
  347. // Log exception to disk
  348. try
  349. {
  350. if (!Directory.Exists(m_crashDir))
  351. {
  352. Directory.CreateDirectory(m_crashDir);
  353. }
  354. string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
  355. using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
  356. {
  357. m_crashLog.WriteLine(msg);
  358. }
  359. File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true);
  360. }
  361. catch (Exception e2)
  362. {
  363. m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2);
  364. }
  365. }
  366. _IsHandlingException = false;
  367. }
  368. }
  369. }