BaseOpenSimServer.cs 24 KB

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