1
0

BaseOpenSimServer.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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("base", false, "quit",
  140. "quit",
  141. "Quit the application", HandleQuit);
  142. m_console.Commands.AddCommand("base", false, "shutdown",
  143. "shutdown",
  144. "Quit the application", HandleQuit);
  145. m_console.Commands.AddCommand("base", false, "set log level",
  146. "set log level <level>",
  147. "Set the console logging level", HandleLogLevel);
  148. m_console.Commands.AddCommand("base", false, "show info",
  149. "show info",
  150. "Show general information about the server", HandleShow);
  151. m_console.Commands.AddCommand("base", false, "show stats",
  152. "show stats",
  153. "Show statistics", HandleShow);
  154. m_console.Commands.AddCommand("base", false, "show threads",
  155. "show threads",
  156. "Show thread status", HandleShow);
  157. m_console.Commands.AddCommand("base", false, "show uptime",
  158. "show uptime",
  159. "Show server uptime", HandleShow);
  160. m_console.Commands.AddCommand("base", false, "show version",
  161. "show version",
  162. "Show server version", HandleShow);
  163. m_console.Commands.AddCommand("base", 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("base", 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("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
  264. }
  265. /// <summary>
  266. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  267. /// </summary>
  268. public virtual void Shutdown()
  269. {
  270. ShutdownSpecific();
  271. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  272. RemovePIDFile();
  273. Environment.Exit(0);
  274. }
  275. private void HandleQuit(string module, string[] args)
  276. {
  277. Shutdown();
  278. }
  279. private void HandleLogLevel(string module, string[] cmd)
  280. {
  281. if (null == m_consoleAppender)
  282. {
  283. Notice("No appender named Console found (see the log4net config file for this executable)!");
  284. return;
  285. }
  286. if (cmd.Length > 3)
  287. {
  288. string rawLevel = cmd[3];
  289. ILoggerRepository repository = LogManager.GetRepository();
  290. Level consoleLevel = repository.LevelMap[rawLevel];
  291. if (consoleLevel != null)
  292. m_consoleAppender.Threshold = consoleLevel;
  293. else
  294. Notice(
  295. String.Format(
  296. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  297. rawLevel));
  298. }
  299. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  300. }
  301. /// <summary>
  302. /// Show help information
  303. /// </summary>
  304. /// <param name="helpArgs"></param>
  305. protected virtual void ShowHelp(string[] helpArgs)
  306. {
  307. Notice("");
  308. if (helpArgs.Length == 0)
  309. {
  310. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  311. Notice("show info - show server information (e.g. startup path).");
  312. if (m_stats != null)
  313. Notice("show stats - show statistical information for this server");
  314. Notice("show threads - list tracked threads");
  315. Notice("show uptime - show server startup time and uptime.");
  316. Notice("show version - show server version.");
  317. Notice("");
  318. return;
  319. }
  320. }
  321. public virtual void HandleShow(string module, string[] cmd)
  322. {
  323. List<string> args = new List<string>(cmd);
  324. args.RemoveAt(0);
  325. string[] showParams = args.ToArray();
  326. switch (showParams[0])
  327. {
  328. case "info":
  329. ShowInfo();
  330. break;
  331. case "stats":
  332. if (m_stats != null)
  333. Notice(m_stats.Report());
  334. break;
  335. case "threads":
  336. Notice(GetThreadsReport());
  337. break;
  338. case "uptime":
  339. Notice(GetUptimeReport());
  340. break;
  341. case "version":
  342. Notice(GetVersionText());
  343. break;
  344. }
  345. }
  346. public virtual void HandleThreadsAbort(string module, string[] cmd)
  347. {
  348. if (cmd.Length != 3)
  349. {
  350. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  351. return;
  352. }
  353. int threadId;
  354. if (!int.TryParse(cmd[2], out threadId))
  355. {
  356. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  357. return;
  358. }
  359. if (Watchdog.AbortThread(threadId))
  360. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  361. else
  362. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  363. }
  364. protected void ShowInfo()
  365. {
  366. Notice(GetVersionText());
  367. Notice("Startup directory: " + m_startupDirectory);
  368. if (null != m_consoleAppender)
  369. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  370. }
  371. protected string GetVersionText()
  372. {
  373. return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
  374. }
  375. /// <summary>
  376. /// Console output is only possible if a console has been established.
  377. /// That is something that cannot be determined within this class. So
  378. /// all attempts to use the console MUST be verified.
  379. /// </summary>
  380. /// <param name="msg"></param>
  381. protected void Notice(string msg)
  382. {
  383. if (m_console != null)
  384. {
  385. m_console.Output(msg);
  386. }
  387. }
  388. /// <summary>
  389. /// Console output is only possible if a console has been established.
  390. /// That is something that cannot be determined within this class. So
  391. /// all attempts to use the console MUST be verified.
  392. /// </summary>
  393. /// <param name="format"></param>
  394. /// <param name="components"></param>
  395. protected void Notice(string format, params string[] components)
  396. {
  397. if (m_console != null)
  398. m_console.OutputFormat(format, components);
  399. }
  400. /// <summary>
  401. /// Enhance the version string with extra information if it's available.
  402. /// </summary>
  403. protected void EnhanceVersionInformation()
  404. {
  405. string buildVersion = string.Empty;
  406. // The subversion information is deprecated and will be removed at a later date
  407. // Add subversion revision information if available
  408. // Try file "svn_revision" in the current directory first, then the .svn info.
  409. // This allows to make the revision available in simulators not running from the source tree.
  410. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  411. // elsewhere as well
  412. string gitDir = "../.git/";
  413. string gitRefPointerPath = gitDir + "HEAD";
  414. string svnRevisionFileName = "svn_revision";
  415. string svnFileName = ".svn/entries";
  416. string manualVersionFileName = ".version";
  417. string inputLine;
  418. int strcmp;
  419. if (File.Exists(manualVersionFileName))
  420. {
  421. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  422. buildVersion = CommitFile.ReadLine();
  423. m_version += buildVersion ?? "";
  424. }
  425. else if (File.Exists(gitRefPointerPath))
  426. {
  427. // m_log.DebugFormat("[OPENSIM]: Found {0}", gitRefPointerPath);
  428. string rawPointer = "";
  429. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  430. rawPointer = pointerFile.ReadLine();
  431. // m_log.DebugFormat("[OPENSIM]: rawPointer [{0}]", rawPointer);
  432. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  433. if (m.Success)
  434. {
  435. // m_log.DebugFormat("[OPENSIM]: Matched [{0}]", m.Groups[1].Value);
  436. string gitRef = m.Groups[1].Value;
  437. string gitRefPath = gitDir + gitRef;
  438. if (File.Exists(gitRefPath))
  439. {
  440. // m_log.DebugFormat("[OPENSIM]: Found gitRefPath [{0}]", gitRefPath);
  441. using (StreamReader refFile = File.OpenText(gitRefPath))
  442. {
  443. string gitHash = refFile.ReadLine();
  444. m_version += gitHash.Substring(0, 7);
  445. }
  446. }
  447. }
  448. }
  449. else
  450. {
  451. // Remove the else logic when subversion mirror is no longer used
  452. if (File.Exists(svnRevisionFileName))
  453. {
  454. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  455. buildVersion = RevisionFile.ReadLine();
  456. buildVersion.Trim();
  457. RevisionFile.Close();
  458. }
  459. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  460. {
  461. StreamReader EntriesFile = File.OpenText(svnFileName);
  462. inputLine = EntriesFile.ReadLine();
  463. while (inputLine != null)
  464. {
  465. // using the dir svn revision at the top of entries file
  466. strcmp = String.Compare(inputLine, "dir");
  467. if (strcmp == 0)
  468. {
  469. buildVersion = EntriesFile.ReadLine();
  470. break;
  471. }
  472. else
  473. {
  474. inputLine = EntriesFile.ReadLine();
  475. }
  476. }
  477. EntriesFile.Close();
  478. }
  479. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  480. }
  481. }
  482. protected void CreatePIDFile(string path)
  483. {
  484. try
  485. {
  486. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  487. FileStream fs = File.Create(path);
  488. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  489. Byte[] buf = enc.GetBytes(pidstring);
  490. fs.Write(buf, 0, buf.Length);
  491. fs.Close();
  492. m_pidFile = path;
  493. }
  494. catch (Exception)
  495. {
  496. }
  497. }
  498. public string osSecret {
  499. // Secret uuid for the simulator
  500. get { return m_osSecret; }
  501. }
  502. public string StatReport(IOSHttpRequest httpRequest)
  503. {
  504. // If we catch a request for "callback", wrap the response in the value for jsonp
  505. if (httpRequest.Query.ContainsKey("callback"))
  506. {
  507. return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
  508. }
  509. else
  510. {
  511. return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
  512. }
  513. }
  514. protected void RemovePIDFile()
  515. {
  516. if (m_pidFile != String.Empty)
  517. {
  518. try
  519. {
  520. File.Delete(m_pidFile);
  521. m_pidFile = String.Empty;
  522. }
  523. catch (Exception)
  524. {
  525. }
  526. }
  527. }
  528. }
  529. }