BaseOpenSimServer.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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.Diagnostics;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Text;
  33. using System.Text.RegularExpressions;
  34. using System.Threading;
  35. using System.Timers;
  36. using log4net;
  37. using log4net.Appender;
  38. using log4net.Core;
  39. using log4net.Repository;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Console;
  42. using OpenSim.Framework.Monitoring;
  43. using OpenSim.Framework.Servers;
  44. using OpenSim.Framework.Servers.HttpServer;
  45. using Timer=System.Timers.Timer;
  46. using OpenMetaverse;
  47. using OpenMetaverse.StructuredData;
  48. namespace OpenSim.Framework.Servers
  49. {
  50. /// <summary>
  51. /// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
  52. /// </summary>
  53. public abstract class BaseOpenSimServer
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. /// <summary>
  57. /// This will control a periodic log printout of the current 'show stats' (if they are active) for this
  58. /// server.
  59. /// </summary>
  60. private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
  61. protected CommandConsole m_console;
  62. protected OpenSimAppender m_consoleAppender;
  63. protected IAppender m_logFileAppender = null;
  64. /// <summary>
  65. /// Time at which this server was started
  66. /// </summary>
  67. protected DateTime m_startuptime;
  68. /// <summary>
  69. /// Record the initial startup directory for info purposes
  70. /// </summary>
  71. protected string m_startupDirectory = Environment.CurrentDirectory;
  72. /// <summary>
  73. /// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
  74. /// </summary>
  75. protected string m_version;
  76. protected string m_pidFile = String.Empty;
  77. /// <summary>
  78. /// Random uuid for private data
  79. /// </summary>
  80. protected string m_osSecret = String.Empty;
  81. protected BaseHttpServer m_httpServer;
  82. public BaseHttpServer HttpServer
  83. {
  84. get { return m_httpServer; }
  85. }
  86. public BaseOpenSimServer()
  87. {
  88. m_startuptime = DateTime.Now;
  89. m_version = VersionInfo.Version;
  90. // Random uuid for private data
  91. m_osSecret = UUID.Random().ToString();
  92. m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
  93. m_periodicDiagnosticsTimer.Enabled = true;
  94. // This thread will go on to become the console listening thread
  95. Thread.CurrentThread.Name = "ConsoleThread";
  96. ILoggerRepository repository = LogManager.GetRepository();
  97. IAppender[] appenders = repository.GetAppenders();
  98. foreach (IAppender appender in appenders)
  99. {
  100. if (appender.Name == "LogFileAppender")
  101. {
  102. m_logFileAppender = appender;
  103. }
  104. }
  105. }
  106. /// <summary>
  107. /// Must be overriden by child classes for their own server specific startup behaviour.
  108. /// </summary>
  109. protected virtual void StartupSpecific()
  110. {
  111. if (m_console != null)
  112. {
  113. ILoggerRepository repository = LogManager.GetRepository();
  114. IAppender[] appenders = repository.GetAppenders();
  115. foreach (IAppender appender in appenders)
  116. {
  117. if (appender.Name == "Console")
  118. {
  119. m_consoleAppender = (OpenSimAppender)appender;
  120. break;
  121. }
  122. }
  123. if (null == m_consoleAppender)
  124. {
  125. Notice("No appender named Console found (see the log4net config file for this executable)!");
  126. }
  127. else
  128. {
  129. m_consoleAppender.Console = m_console;
  130. // If there is no threshold set then the threshold is effectively everything.
  131. if (null == m_consoleAppender.Threshold)
  132. m_consoleAppender.Threshold = Level.All;
  133. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  134. }
  135. m_console.Commands.AddCommand("General", false, "quit",
  136. "quit",
  137. "Quit the application", HandleQuit);
  138. m_console.Commands.AddCommand("General", false, "shutdown",
  139. "shutdown",
  140. "Quit the application", HandleQuit);
  141. m_console.Commands.AddCommand("General", false, "set log level",
  142. "set log level <level>",
  143. "Set the console logging level", HandleLogLevel);
  144. m_console.Commands.AddCommand("General", false, "show info",
  145. "show info",
  146. "Show general information about the server", HandleShow);
  147. m_console.Commands.AddCommand("General", false, "show threads",
  148. "show threads",
  149. "Show thread status", HandleShow);
  150. m_console.Commands.AddCommand("General", false, "show uptime",
  151. "show uptime",
  152. "Show server uptime", HandleShow);
  153. m_console.Commands.AddCommand("General", false, "show version",
  154. "show version",
  155. "Show server version", HandleShow);
  156. m_console.Commands.AddCommand("General", false, "threads abort",
  157. "threads abort <thread-id>",
  158. "Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort);
  159. m_console.Commands.AddCommand("General", false, "threads show",
  160. "threads show",
  161. "Show thread status. Synonym for \"show threads\"",
  162. (string module, string[] args) => Notice(GetThreadsReport()));
  163. m_console.Commands.AddCommand("General", false, "force gc",
  164. "force gc",
  165. "Manually invoke runtime garbage collection. For debugging purposes",
  166. HandleForceGc);
  167. }
  168. }
  169. private void HandleForceGc(string module, string[] args)
  170. {
  171. MainConsole.Instance.Output("Manually invoking runtime garbage collection");
  172. GC.Collect();
  173. }
  174. /// <summary>
  175. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  176. /// </summary>
  177. public virtual void ShutdownSpecific() {}
  178. /// <summary>
  179. /// Provides a list of help topics that are available. Overriding classes should append their topics to the
  180. /// information returned when the base method is called.
  181. /// </summary>
  182. ///
  183. /// <returns>
  184. /// A list of strings that represent different help topics on which more information is available
  185. /// </returns>
  186. protected virtual List<string> GetHelpTopics() { return new List<string>(); }
  187. /// <summary>
  188. /// Print statistics to the logfile, if they are active
  189. /// </summary>
  190. protected void LogDiagnostics(object source, ElapsedEventArgs e)
  191. {
  192. StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n");
  193. sb.Append(GetUptimeReport());
  194. sb.Append(StatsManager.SimExtraStats.Report());
  195. sb.Append(Environment.NewLine);
  196. sb.Append(GetThreadsReport());
  197. m_log.Debug(sb);
  198. }
  199. /// <summary>
  200. /// Get a report about the registered threads in this server.
  201. /// </summary>
  202. protected string GetThreadsReport()
  203. {
  204. // This should be a constant field.
  205. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
  206. StringBuilder sb = new StringBuilder();
  207. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
  208. sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
  209. int timeNow = Environment.TickCount & Int32.MaxValue;
  210. sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
  211. sb.Append(Environment.NewLine);
  212. foreach (Watchdog.ThreadWatchdogInfo twi in threads)
  213. {
  214. Thread t = twi.Thread;
  215. sb.AppendFormat(
  216. reportFormat,
  217. t.ManagedThreadId,
  218. t.Name,
  219. timeNow - twi.LastTick,
  220. timeNow - twi.FirstTick,
  221. t.Priority,
  222. t.ThreadState);
  223. sb.Append("\n");
  224. }
  225. sb.Append("\n");
  226. // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
  227. // zero active threads.
  228. int totalThreads = Process.GetCurrentProcess().Threads.Count;
  229. if (totalThreads > 0)
  230. sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
  231. sb.Append("Main threadpool (excluding script engine pools)\n");
  232. sb.Append(Util.GetThreadPoolReport());
  233. return sb.ToString();
  234. }
  235. /// <summary>
  236. /// Return a report about the uptime of this server
  237. /// </summary>
  238. /// <returns></returns>
  239. protected string GetUptimeReport()
  240. {
  241. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  242. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  243. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  244. return sb.ToString();
  245. }
  246. /// <summary>
  247. /// Performs initialisation of the scene, such as loading configuration from disk.
  248. /// </summary>
  249. public virtual void Startup()
  250. {
  251. m_log.Info("[STARTUP]: Beginning startup processing");
  252. EnhanceVersionInformation();
  253. m_log.Info("[STARTUP]: OpenSimulator version: " + m_version + Environment.NewLine);
  254. // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
  255. // the clr version number doesn't match the project version number under Mono.
  256. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
  257. m_log.InfoFormat(
  258. "[STARTUP]: Operating system version: {0}, .NET platform {1}, {2}-bit\n",
  259. Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32");
  260. StartupSpecific();
  261. TimeSpan timeTaken = DateTime.Now - m_startuptime;
  262. m_log.InfoFormat(
  263. "[STARTUP]: Non-script portion of startup took {0}m {1}s. PLEASE WAIT FOR LOGINS TO BE ENABLED ON REGIONS ONCE SCRIPTS HAVE STARTED.",
  264. timeTaken.Minutes, timeTaken.Seconds);
  265. }
  266. /// <summary>
  267. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  268. /// </summary>
  269. public virtual void Shutdown()
  270. {
  271. ShutdownSpecific();
  272. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  273. RemovePIDFile();
  274. Environment.Exit(0);
  275. }
  276. private void HandleQuit(string module, string[] args)
  277. {
  278. Shutdown();
  279. }
  280. private void HandleLogLevel(string module, string[] cmd)
  281. {
  282. if (null == m_consoleAppender)
  283. {
  284. Notice("No appender named Console found (see the log4net config file for this executable)!");
  285. return;
  286. }
  287. if (cmd.Length > 3)
  288. {
  289. string rawLevel = cmd[3];
  290. ILoggerRepository repository = LogManager.GetRepository();
  291. Level consoleLevel = repository.LevelMap[rawLevel];
  292. if (consoleLevel != null)
  293. m_consoleAppender.Threshold = consoleLevel;
  294. else
  295. Notice(
  296. String.Format(
  297. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  298. rawLevel));
  299. }
  300. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  301. }
  302. /// <summary>
  303. /// Show help information
  304. /// </summary>
  305. /// <param name="helpArgs"></param>
  306. protected virtual void ShowHelp(string[] helpArgs)
  307. {
  308. Notice("");
  309. if (helpArgs.Length == 0)
  310. {
  311. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  312. Notice("show info - show server information (e.g. startup path).");
  313. Notice("show threads - list tracked threads");
  314. Notice("show uptime - show server startup time and uptime.");
  315. Notice("show version - show server version.");
  316. Notice("");
  317. return;
  318. }
  319. }
  320. public virtual void HandleShow(string module, string[] cmd)
  321. {
  322. List<string> args = new List<string>(cmd);
  323. args.RemoveAt(0);
  324. string[] showParams = args.ToArray();
  325. switch (showParams[0])
  326. {
  327. case "info":
  328. ShowInfo();
  329. break;
  330. case "threads":
  331. Notice(GetThreadsReport());
  332. break;
  333. case "uptime":
  334. Notice(GetUptimeReport());
  335. break;
  336. case "version":
  337. Notice(GetVersionText());
  338. break;
  339. }
  340. }
  341. public virtual void HandleThreadsAbort(string module, string[] cmd)
  342. {
  343. if (cmd.Length != 3)
  344. {
  345. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  346. return;
  347. }
  348. int threadId;
  349. if (!int.TryParse(cmd[2], out threadId))
  350. {
  351. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  352. return;
  353. }
  354. if (Watchdog.AbortThread(threadId))
  355. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  356. else
  357. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  358. }
  359. protected void ShowInfo()
  360. {
  361. Notice(GetVersionText());
  362. Notice("Startup directory: " + m_startupDirectory);
  363. if (null != m_consoleAppender)
  364. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  365. }
  366. protected string GetVersionText()
  367. {
  368. return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
  369. }
  370. /// <summary>
  371. /// Console output is only possible if a console has been established.
  372. /// That is something that cannot be determined within this class. So
  373. /// all attempts to use the console MUST be verified.
  374. /// </summary>
  375. /// <param name="msg"></param>
  376. protected void Notice(string msg)
  377. {
  378. if (m_console != null)
  379. {
  380. m_console.Output(msg);
  381. }
  382. }
  383. /// <summary>
  384. /// Console output is only possible if a console has been established.
  385. /// That is something that cannot be determined within this class. So
  386. /// all attempts to use the console MUST be verified.
  387. /// </summary>
  388. /// <param name="format"></param>
  389. /// <param name="components"></param>
  390. protected void Notice(string format, params string[] components)
  391. {
  392. if (m_console != null)
  393. m_console.OutputFormat(format, components);
  394. }
  395. /// <summary>
  396. /// Enhance the version string with extra information if it's available.
  397. /// </summary>
  398. protected void EnhanceVersionInformation()
  399. {
  400. string buildVersion = string.Empty;
  401. // The subversion information is deprecated and will be removed at a later date
  402. // Add subversion revision information if available
  403. // Try file "svn_revision" in the current directory first, then the .svn info.
  404. // This allows to make the revision available in simulators not running from the source tree.
  405. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  406. // elsewhere as well
  407. string gitDir = "../.git/";
  408. string gitRefPointerPath = gitDir + "HEAD";
  409. string svnRevisionFileName = "svn_revision";
  410. string svnFileName = ".svn/entries";
  411. string manualVersionFileName = ".version";
  412. string inputLine;
  413. int strcmp;
  414. if (File.Exists(manualVersionFileName))
  415. {
  416. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  417. buildVersion = CommitFile.ReadLine();
  418. m_version += buildVersion ?? "";
  419. }
  420. else if (File.Exists(gitRefPointerPath))
  421. {
  422. // m_log.DebugFormat("[OPENSIM]: Found {0}", gitRefPointerPath);
  423. string rawPointer = "";
  424. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  425. rawPointer = pointerFile.ReadLine();
  426. // m_log.DebugFormat("[OPENSIM]: rawPointer [{0}]", rawPointer);
  427. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  428. if (m.Success)
  429. {
  430. // m_log.DebugFormat("[OPENSIM]: Matched [{0}]", m.Groups[1].Value);
  431. string gitRef = m.Groups[1].Value;
  432. string gitRefPath = gitDir + gitRef;
  433. if (File.Exists(gitRefPath))
  434. {
  435. // m_log.DebugFormat("[OPENSIM]: Found gitRefPath [{0}]", gitRefPath);
  436. using (StreamReader refFile = File.OpenText(gitRefPath))
  437. {
  438. string gitHash = refFile.ReadLine();
  439. m_version += gitHash.Substring(0, 7);
  440. }
  441. }
  442. }
  443. }
  444. else
  445. {
  446. // Remove the else logic when subversion mirror is no longer used
  447. if (File.Exists(svnRevisionFileName))
  448. {
  449. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  450. buildVersion = RevisionFile.ReadLine();
  451. buildVersion.Trim();
  452. RevisionFile.Close();
  453. }
  454. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  455. {
  456. StreamReader EntriesFile = File.OpenText(svnFileName);
  457. inputLine = EntriesFile.ReadLine();
  458. while (inputLine != null)
  459. {
  460. // using the dir svn revision at the top of entries file
  461. strcmp = String.Compare(inputLine, "dir");
  462. if (strcmp == 0)
  463. {
  464. buildVersion = EntriesFile.ReadLine();
  465. break;
  466. }
  467. else
  468. {
  469. inputLine = EntriesFile.ReadLine();
  470. }
  471. }
  472. EntriesFile.Close();
  473. }
  474. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  475. }
  476. }
  477. protected void CreatePIDFile(string path)
  478. {
  479. try
  480. {
  481. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  482. FileStream fs = File.Create(path);
  483. Byte[] buf = Encoding.ASCII.GetBytes(pidstring);
  484. fs.Write(buf, 0, buf.Length);
  485. fs.Close();
  486. m_pidFile = path;
  487. }
  488. catch (Exception)
  489. {
  490. }
  491. }
  492. public string osSecret {
  493. // Secret uuid for the simulator
  494. get { return m_osSecret; }
  495. }
  496. public string StatReport(IOSHttpRequest httpRequest)
  497. {
  498. // If we catch a request for "callback", wrap the response in the value for jsonp
  499. if (httpRequest.Query.ContainsKey("callback"))
  500. {
  501. return httpRequest.Query["callback"].ToString() + "(" + StatsManager.SimExtraStats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
  502. }
  503. else
  504. {
  505. return StatsManager.SimExtraStats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
  506. }
  507. }
  508. protected void RemovePIDFile()
  509. {
  510. if (m_pidFile != String.Empty)
  511. {
  512. try
  513. {
  514. File.Delete(m_pidFile);
  515. m_pidFile = String.Empty;
  516. }
  517. catch (Exception)
  518. {
  519. }
  520. }
  521. }
  522. }
  523. }