Application.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  68. Culture.SetCurrentCulture();
  69. Culture.SetDefaultCurrentCulture();
  70. AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);
  71. /*
  72. // pre load System.Drawing.Common.dll for the platform
  73. // this will fail if a newer version is present on GAC, bin folder, etc, since LoadFrom only accepts the path, if it cannot find it elsewhere
  74. string targetdll = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"lib",
  75. (Util.IsWindows() ? "win" : "linux"), "System.Drawing.Common.dll");
  76. try
  77. {
  78. Assembly asmb = Assembly.LoadFrom(targetdll);
  79. }
  80. catch (Exception e)
  81. {
  82. m_log.Error("Failed to load System.Drawing.Common.dll for current platform" + e.Message);
  83. throw;
  84. }
  85. */
  86. string targetdll = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
  87. "System.Drawing.Common.dll");
  88. string src = targetdll + (Util.IsWindows() ? ".win" : ".linux");
  89. try
  90. {
  91. if (!File.Exists(targetdll))
  92. File.Copy(src, targetdll);
  93. else
  94. {
  95. FileInfo targetInfo = new(targetdll);
  96. FileInfo srcInfo = new(src);
  97. if(targetInfo.Length != srcInfo.Length)
  98. File.Copy(src, targetdll, true);
  99. }
  100. }
  101. catch (Exception e)
  102. {
  103. m_log.Error("Failed to copy System.Drawing.Common.dll for current platform" + e.Message);
  104. throw;
  105. }
  106. ServicePointManager.DefaultConnectionLimit = 32;
  107. ServicePointManager.MaxServicePointIdleTime = 30000;
  108. try { ServicePointManager.DnsRefreshTimeout = 5000; } catch { }
  109. ServicePointManager.Expect100Continue = false;
  110. ServicePointManager.UseNagleAlgorithm = false;
  111. // Add the arguments supplied when running the application to the configuration
  112. ArgvConfigSource configSource = new ArgvConfigSource(args);
  113. // Configure Log4Net
  114. configSource.AddSwitch("Startup", "logconfig");
  115. string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
  116. if (!string.IsNullOrEmpty(logConfigFile))
  117. {
  118. XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
  119. m_log.Info($"[OPENSIM MAIN]: configured log4net using \"{logConfigFile}\" as configuration file");
  120. }
  121. else
  122. {
  123. XmlConfigurator.Configure(new System.IO.FileInfo("OpenSim.exe.config"));
  124. m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config");
  125. }
  126. m_log.Info($"[OPENSIM MAIN]: System Locale is {System.Threading.Thread.CurrentThread.CurrentCulture}");
  127. int workerThreadsMin = 500;
  128. int workerThreadsMax = 1000;
  129. int iocpThreadsMin = 1000;
  130. int iocpThreadsMax = 2000;
  131. System.Threading.ThreadPool.GetMinThreads(out int currentMinWorkerThreads, out int currentMinIocpThreads);
  132. m_log.Info(
  133. $"[OPENSIM MAIN]: Runtime gave us {currentMinWorkerThreads} min worker threads and {currentMinIocpThreads} min IOCP threads");
  134. System.Threading.ThreadPool.GetMaxThreads(out int workerThreads, out int iocpThreads);
  135. m_log.Info($"[OPENSIM MAIN]: Runtime gave us {workerThreads} max worker threads and {iocpThreads} max IOCP threads");
  136. if (workerThreads < workerThreadsMin)
  137. {
  138. workerThreads = workerThreadsMin;
  139. m_log.Info($"[OPENSIM MAIN]: Bumping up max worker threads to {workerThreads}");
  140. }
  141. if (workerThreads > workerThreadsMax)
  142. {
  143. workerThreads = workerThreadsMax;
  144. m_log.Info($"[OPENSIM MAIN]: Limiting max worker threads to {workerThreads}");
  145. }
  146. // Increase the number of IOCP threads available.
  147. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17)
  148. if (iocpThreads < iocpThreadsMin)
  149. {
  150. iocpThreads = iocpThreadsMin;
  151. m_log.Info($"[OPENSIM MAIN]: Bumping up max IOCP threads to {iocpThreads}");
  152. }
  153. // Make sure we don't overallocate IOCP threads and thrash system resources
  154. if ( iocpThreads > iocpThreadsMax )
  155. {
  156. iocpThreads = iocpThreadsMax;
  157. m_log.Info($"[OPENSIM MAIN]: Limiting max IOCP completion threads to {iocpThreads}");
  158. }
  159. // set the resulting worker and IO completion thread counts back to ThreadPool
  160. if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) )
  161. {
  162. m_log.Info(
  163. $"[OPENSIM MAIN]: Threadpool set to {workerThreads} max worker threads and {iocpThreads} max IOCP threads");
  164. }
  165. else
  166. {
  167. m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect.");
  168. }
  169. // Check if the system is compatible with OpenSimulator.
  170. // Ensures that the minimum system requirements are met
  171. string error = string.Empty;
  172. if (Util.IsEnvironmentSupported(ref error))
  173. {
  174. m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator.");
  175. }
  176. else
  177. {
  178. m_log.Warn($"[OPENSIM MAIN]: Environment is not supported by OpenSimulator: {error}\n");
  179. }
  180. m_log.Info($"Default culture changed to {Culture.GetDefaultCurrentCulture().DisplayName}");
  181. // Configure nIni aliases and localles
  182. // Validate that the user has the most basic configuration done
  183. // If not, offer to do the most basic configuration for them warning them along the way of the importance of
  184. // reading these files.
  185. /*
  186. m_log.Info("Checking for reguired configuration...\n");
  187. bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini")))
  188. || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini")))
  189. || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini")))
  190. || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini")));
  191. bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
  192. bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini"));
  193. bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini"));
  194. bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini"));
  195. if ((OpenSim_Ini)
  196. && (
  197. (StanaloneCommon_ProperCased
  198. || StanaloneCommon_lowercased
  199. || GridCommon_ProperCased
  200. || GridCommon_lowerCased
  201. )))
  202. {
  203. m_log.Info("Required Configuration Files Found\n");
  204. }
  205. else
  206. {
  207. MainConsole.Instance = new LocalConsole("Region");
  208. string resp = MainConsole.Instance.CmdPrompt(
  209. "\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?",
  210. "yes");
  211. if (resp == "yes")
  212. {
  213. if (!(OpenSim_Ini))
  214. {
  215. try
  216. {
  217. File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"),
  218. Path.Combine(Util.configDir(), "OpenSim.ini"));
  219. } catch (UnauthorizedAccessException)
  220. {
  221. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n");
  222. } catch (ArgumentException)
  223. {
  224. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
  225. } catch (System.IO.PathTooLongException)
  226. {
  227. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n");
  228. } catch (System.IO.DirectoryNotFoundException)
  229. {
  230. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n");
  231. } catch (System.IO.FileNotFoundException)
  232. {
  233. 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");
  234. } catch (System.IO.IOException)
  235. {
  236. // Destination file exists already or a hard drive failure... .. so we can just drop this one
  237. //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");
  238. } catch (System.NotSupportedException)
  239. {
  240. MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
  241. }
  242. }
  243. if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased))
  244. {
  245. try
  246. {
  247. File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"),
  248. Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
  249. }
  250. catch (UnauthorizedAccessException)
  251. {
  252. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n");
  253. }
  254. catch (ArgumentException)
  255. {
  256. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
  257. }
  258. catch (System.IO.PathTooLongException)
  259. {
  260. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n");
  261. }
  262. catch (System.IO.DirectoryNotFoundException)
  263. {
  264. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n");
  265. }
  266. catch (System.IO.FileNotFoundException)
  267. {
  268. 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");
  269. }
  270. catch (System.IO.IOException)
  271. {
  272. // Destination file exists already or a hard drive failure... .. so we can just drop this one
  273. //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");
  274. }
  275. catch (System.NotSupportedException)
  276. {
  277. MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
  278. }
  279. }
  280. }
  281. MainConsole.Instance = null;
  282. }
  283. */
  284. configSource.Alias.AddAlias("On", true);
  285. configSource.Alias.AddAlias("Off", false);
  286. configSource.Alias.AddAlias("True", true);
  287. configSource.Alias.AddAlias("False", false);
  288. configSource.Alias.AddAlias("Yes", true);
  289. configSource.Alias.AddAlias("No", false);
  290. configSource.AddSwitch("Startup", "background");
  291. configSource.AddSwitch("Startup", "inifile");
  292. configSource.AddSwitch("Startup", "inimaster");
  293. configSource.AddSwitch("Startup", "inidirectory");
  294. configSource.AddSwitch("Startup", "physics");
  295. configSource.AddSwitch("Startup", "gui");
  296. configSource.AddSwitch("Startup", "console");
  297. configSource.AddSwitch("Startup", "save_crashes");
  298. configSource.AddSwitch("Startup", "crash_dir");
  299. configSource.AddConfig("StandAlone");
  300. configSource.AddConfig("Network");
  301. // Check if we're running in the background or not
  302. bool background = configSource.Configs["Startup"].GetBoolean("background", false);
  303. // Check if we're saving crashes
  304. m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);
  305. // load Crash directory config
  306. m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
  307. if (background)
  308. {
  309. m_sim = new OpenSimBackground(configSource);
  310. m_sim.Startup();
  311. }
  312. else
  313. {
  314. m_sim = new OpenSim(configSource);
  315. m_sim.Startup();
  316. while (true)
  317. {
  318. try
  319. {
  320. // Block thread here for input
  321. MainConsole.Instance.Prompt();
  322. }
  323. catch (Exception e)
  324. {
  325. m_log.Error($"Command error: {e}");
  326. }
  327. }
  328. }
  329. }
  330. private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself
  331. /// <summary>
  332. /// Global exception handler -- all unhandlet exceptions end up here :)
  333. /// </summary>
  334. /// <param name="sender"></param>
  335. /// <param name="e"></param>
  336. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  337. {
  338. if (_IsHandlingException)
  339. {
  340. return;
  341. }
  342. _IsHandlingException = true;
  343. // TODO: Add config option to allow users to turn off error reporting
  344. // TODO: Post error report (disabled for now)
  345. string msg = $"\r\nAPPLICATION EXCEPTION DETECTED: {e}\r\n\r\n";
  346. Exception ex = (Exception)e.ExceptionObject;
  347. msg += $"Exception: {ex}\r\n";
  348. if (ex.InnerException != null)
  349. {
  350. msg += $"InnerException: {ex.InnerException}\r\n";
  351. }
  352. msg += $"\r\nApplication is terminating: {e.IsTerminating}\r\n";
  353. m_log.Error("[APPLICATION]: + msg");
  354. if (m_saveCrashDumps)
  355. {
  356. // Log exception to disk
  357. try
  358. {
  359. if (!Directory.Exists(m_crashDir))
  360. {
  361. Directory.CreateDirectory(m_crashDir);
  362. }
  363. string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
  364. using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
  365. {
  366. m_crashLog.WriteLine(msg);
  367. }
  368. File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true);
  369. }
  370. catch (Exception e2)
  371. {
  372. m_log.Error($"[CRASH LOGGER CRASHED]: {e2}");
  373. }
  374. }
  375. _IsHandlingException = false;
  376. }
  377. }
  378. }