BaseOpenSimServer.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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,10} {4,30}";
  207. StringBuilder sb = new StringBuilder();
  208. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreads();
  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)", "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, t.Name, string.Format("{0} ms", timeNow - twi.LastTick), t.Priority, t.ThreadState);
  219. t.ManagedThreadId, t.Name, timeNow - twi.LastTick, t.Priority, t.ThreadState);
  220. sb.Append(Environment.NewLine);
  221. }
  222. int workers = 0, ports = 0, maxWorkers = 0, maxPorts = 0;
  223. ThreadPool.GetAvailableThreads(out workers, out ports);
  224. ThreadPool.GetMaxThreads(out maxWorkers, out maxPorts);
  225. sb.Append(Environment.NewLine + "*** ThreadPool threads ***" + Environment.NewLine);
  226. sb.Append("workers: " + (maxWorkers - workers) + " (" + maxWorkers + "); ports: " + (maxPorts - ports) + " (" + maxPorts + ")" + Environment.NewLine);
  227. return sb.ToString();
  228. }
  229. /// <summary>
  230. /// Return a report about the uptime of this server
  231. /// </summary>
  232. /// <returns></returns>
  233. protected string GetUptimeReport()
  234. {
  235. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  236. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  237. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  238. return sb.ToString();
  239. }
  240. /// <summary>
  241. /// Performs initialisation of the scene, such as loading configuration from disk.
  242. /// </summary>
  243. public virtual void Startup()
  244. {
  245. m_log.Info("[STARTUP]: Beginning startup processing");
  246. EnhanceVersionInformation();
  247. m_log.Info("[STARTUP]: OpenSimulator version: " + m_version + Environment.NewLine);
  248. // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
  249. // the clr version number doesn't match the project version number under Mono.
  250. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
  251. m_log.Info("[STARTUP]: Operating system version: " + Environment.OSVersion + Environment.NewLine);
  252. StartupSpecific();
  253. TimeSpan timeTaken = DateTime.Now - m_startuptime;
  254. m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
  255. }
  256. /// <summary>
  257. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  258. /// </summary>
  259. public virtual void Shutdown()
  260. {
  261. ShutdownSpecific();
  262. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  263. RemovePIDFile();
  264. Environment.Exit(0);
  265. }
  266. private void HandleQuit(string module, string[] args)
  267. {
  268. Shutdown();
  269. }
  270. private void HandleLogLevel(string module, string[] cmd)
  271. {
  272. if (null == m_consoleAppender)
  273. {
  274. Notice("No appender named Console found (see the log4net config file for this executable)!");
  275. return;
  276. }
  277. if (cmd.Length > 3)
  278. {
  279. string rawLevel = cmd[3];
  280. ILoggerRepository repository = LogManager.GetRepository();
  281. Level consoleLevel = repository.LevelMap[rawLevel];
  282. if (consoleLevel != null)
  283. m_consoleAppender.Threshold = consoleLevel;
  284. else
  285. Notice(
  286. String.Format(
  287. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  288. rawLevel));
  289. }
  290. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  291. }
  292. /// <summary>
  293. /// Show help information
  294. /// </summary>
  295. /// <param name="helpArgs"></param>
  296. protected virtual void ShowHelp(string[] helpArgs)
  297. {
  298. Notice("");
  299. if (helpArgs.Length == 0)
  300. {
  301. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  302. Notice("show info - show server information (e.g. startup path).");
  303. if (m_stats != null)
  304. Notice("show stats - show statistical information for this server");
  305. Notice("show threads - list tracked threads");
  306. Notice("show uptime - show server startup time and uptime.");
  307. Notice("show version - show server version.");
  308. Notice("");
  309. return;
  310. }
  311. }
  312. public virtual void HandleShow(string module, string[] cmd)
  313. {
  314. List<string> args = new List<string>(cmd);
  315. args.RemoveAt(0);
  316. string[] showParams = args.ToArray();
  317. switch (showParams[0])
  318. {
  319. case "info":
  320. ShowInfo();
  321. break;
  322. case "stats":
  323. if (m_stats != null)
  324. Notice(m_stats.Report());
  325. break;
  326. case "threads":
  327. Notice(GetThreadsReport());
  328. break;
  329. case "uptime":
  330. Notice(GetUptimeReport());
  331. break;
  332. case "version":
  333. Notice(GetVersionText());
  334. break;
  335. }
  336. }
  337. public virtual void HandleThreadsAbort(string module, string[] cmd)
  338. {
  339. if (cmd.Length != 3)
  340. {
  341. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  342. return;
  343. }
  344. int threadId;
  345. if (!int.TryParse(cmd[2], out threadId))
  346. {
  347. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  348. return;
  349. }
  350. if (Watchdog.AbortThread(threadId))
  351. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  352. else
  353. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  354. }
  355. protected void ShowInfo()
  356. {
  357. Notice(GetVersionText());
  358. Notice("Startup directory: " + m_startupDirectory);
  359. if (null != m_consoleAppender)
  360. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  361. }
  362. protected string GetVersionText()
  363. {
  364. return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
  365. }
  366. /// <summary>
  367. /// Console output is only possible if a console has been established.
  368. /// That is something that cannot be determined within this class. So
  369. /// all attempts to use the console MUST be verified.
  370. /// </summary>
  371. /// <param name="msg"></param>
  372. protected void Notice(string msg)
  373. {
  374. if (m_console != null)
  375. {
  376. m_console.Output(msg);
  377. }
  378. }
  379. /// <summary>
  380. /// Console output is only possible if a console has been established.
  381. /// That is something that cannot be determined within this class. So
  382. /// all attempts to use the console MUST be verified.
  383. /// </summary>
  384. /// <param name="format"></param>
  385. /// <param name="components"></param>
  386. protected void Notice(string format, params string[] components)
  387. {
  388. if (m_console != null)
  389. m_console.OutputFormat(format, components);
  390. }
  391. /// <summary>
  392. /// Enhance the version string with extra information if it's available.
  393. /// </summary>
  394. protected void EnhanceVersionInformation()
  395. {
  396. string buildVersion = string.Empty;
  397. // The subversion information is deprecated and will be removed at a later date
  398. // Add subversion revision information if available
  399. // Try file "svn_revision" in the current directory first, then the .svn info.
  400. // This allows to make the revision available in simulators not running from the source tree.
  401. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  402. // elsewhere as well
  403. string gitDir = "../.git/";
  404. string gitRefPointerPath = gitDir + "HEAD";
  405. string svnRevisionFileName = "svn_revision";
  406. string svnFileName = ".svn/entries";
  407. string manualVersionFileName = ".version";
  408. string inputLine;
  409. int strcmp;
  410. if (File.Exists(manualVersionFileName))
  411. {
  412. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  413. buildVersion = CommitFile.ReadLine();
  414. m_version += buildVersion ?? "";
  415. }
  416. else if (File.Exists(gitRefPointerPath))
  417. {
  418. // m_log.DebugFormat("[OPENSIM]: Found {0}", gitRefPointerPath);
  419. string rawPointer = "";
  420. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  421. rawPointer = pointerFile.ReadLine();
  422. // m_log.DebugFormat("[OPENSIM]: rawPointer [{0}]", rawPointer);
  423. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  424. if (m.Success)
  425. {
  426. // m_log.DebugFormat("[OPENSIM]: Matched [{0}]", m.Groups[1].Value);
  427. string gitRef = m.Groups[1].Value;
  428. string gitRefPath = gitDir + gitRef;
  429. if (File.Exists(gitRefPath))
  430. {
  431. // m_log.DebugFormat("[OPENSIM]: Found gitRefPath [{0}]", gitRefPath);
  432. using (StreamReader refFile = File.OpenText(gitRefPath))
  433. {
  434. string gitHash = refFile.ReadLine();
  435. m_version += gitHash.Substring(0, 7);
  436. }
  437. }
  438. }
  439. }
  440. else
  441. {
  442. // Remove the else logic when subversion mirror is no longer used
  443. if (File.Exists(svnRevisionFileName))
  444. {
  445. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  446. buildVersion = RevisionFile.ReadLine();
  447. buildVersion.Trim();
  448. RevisionFile.Close();
  449. }
  450. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  451. {
  452. StreamReader EntriesFile = File.OpenText(svnFileName);
  453. inputLine = EntriesFile.ReadLine();
  454. while (inputLine != null)
  455. {
  456. // using the dir svn revision at the top of entries file
  457. strcmp = String.Compare(inputLine, "dir");
  458. if (strcmp == 0)
  459. {
  460. buildVersion = EntriesFile.ReadLine();
  461. break;
  462. }
  463. else
  464. {
  465. inputLine = EntriesFile.ReadLine();
  466. }
  467. }
  468. EntriesFile.Close();
  469. }
  470. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  471. }
  472. }
  473. protected void CreatePIDFile(string path)
  474. {
  475. try
  476. {
  477. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  478. FileStream fs = File.Create(path);
  479. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  480. Byte[] buf = enc.GetBytes(pidstring);
  481. fs.Write(buf, 0, buf.Length);
  482. fs.Close();
  483. m_pidFile = path;
  484. }
  485. catch (Exception)
  486. {
  487. }
  488. }
  489. public string osSecret {
  490. // Secret uuid for the simulator
  491. get { return m_osSecret; }
  492. }
  493. public string StatReport(OSHttpRequest httpRequest)
  494. {
  495. // If we catch a request for "callback", wrap the response in the value for jsonp
  496. if (httpRequest.Query.ContainsKey("callback"))
  497. {
  498. return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
  499. }
  500. else
  501. {
  502. return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
  503. }
  504. }
  505. protected void RemovePIDFile()
  506. {
  507. if (m_pidFile != String.Empty)
  508. {
  509. try
  510. {
  511. File.Delete(m_pidFile);
  512. m_pidFile = String.Empty;
  513. }
  514. catch (Exception)
  515. {
  516. }
  517. }
  518. }
  519. }
  520. }