BaseOpenSimServer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 OpenSim 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.IO;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Threading;
  33. using System.Timers;
  34. using log4net;
  35. using log4net.Appender;
  36. using log4net.Core;
  37. using log4net.Repository;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Framework.Statistics;
  40. using Timer=System.Timers.Timer;
  41. namespace OpenSim.Framework.Servers
  42. {
  43. /// <summary>
  44. /// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
  45. /// </summary>
  46. public abstract class BaseOpenSimServer
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. /// <summary>
  50. /// This will control a periodic log printout of the current 'show stats' (if they are active) for this
  51. /// server.
  52. /// </summary>
  53. private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
  54. protected ConsoleBase m_console;
  55. /// <summary>
  56. /// Time at which this server was started
  57. /// </summary>
  58. protected DateTime m_startuptime;
  59. /// <summary>
  60. /// Record the initial startup directory for info purposes
  61. /// </summary>
  62. protected string m_startupDirectory = Environment.CurrentDirectory;
  63. /// <summary>
  64. /// Server version information. Usually VersionInfo + information about svn revision, operating system, etc.
  65. /// </summary>
  66. protected string m_version;
  67. protected BaseHttpServer m_httpServer;
  68. public BaseHttpServer HttpServer
  69. {
  70. get { return m_httpServer; }
  71. }
  72. /// <summary>
  73. /// Holds the non-viewer statistics collection object for this service/server
  74. /// </summary>
  75. protected IStatsCollector m_stats;
  76. public BaseOpenSimServer()
  77. {
  78. m_startuptime = DateTime.Now;
  79. m_version = VersionInfo.Version;
  80. m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
  81. m_periodicDiagnosticsTimer.Enabled = true;
  82. // Add ourselves to thread monitoring. This thread will go on to become the console listening thread
  83. Thread.CurrentThread.Name = "ConsoleThread";
  84. ThreadTracker.Add(Thread.CurrentThread);
  85. }
  86. /// <summary>
  87. /// Must be overriden by child classes for their own server specific startup behaviour.
  88. /// </summary>
  89. protected virtual void StartupSpecific()
  90. {
  91. if (m_console != null)
  92. {
  93. SetConsoleLogLevel(new string[] { "ALL" });
  94. m_console.Commands.AddCommand("base", false, "quit",
  95. "quit",
  96. "Quit the application", HandleQuit);
  97. m_console.Commands.AddCommand("base", false, "shutdown",
  98. "shutdown",
  99. "Quit the application", HandleQuit);
  100. m_console.Commands.AddCommand("base", false, "set log level",
  101. "set log level <level>",
  102. "Set the console logging level", HandleLogLevel);
  103. m_console.Commands.AddCommand("base", false, "show info",
  104. "show info",
  105. "Show general information", HandleShow);
  106. m_console.Commands.AddCommand("base", false, "show stats",
  107. "show stats",
  108. "Show statistics", HandleShow);
  109. m_console.Commands.AddCommand("base", false, "show threads",
  110. "show threads",
  111. "Show thread status", HandleShow);
  112. m_console.Commands.AddCommand("base", false, "show uptime",
  113. "show uptime",
  114. "Show server uptime", HandleShow);
  115. m_console.Commands.AddCommand("base", false, "show version",
  116. "show version",
  117. "Show server version", HandleShow);
  118. }
  119. }
  120. /// <summary>
  121. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  122. /// </summary>
  123. public virtual void ShutdownSpecific() {}
  124. /// <summary>
  125. /// Provides a list of help topics that are available. Overriding classes should append their topics to the
  126. /// information returned when the base method is called.
  127. /// </summary>
  128. ///
  129. /// <returns>
  130. /// A list of strings that represent different help topics on which more information is available
  131. /// </returns>
  132. protected virtual List<string> GetHelpTopics() { return new List<string>(); }
  133. /// <summary>
  134. /// Print statistics to the logfile, if they are active
  135. /// </summary>
  136. protected void LogDiagnostics(object source, ElapsedEventArgs e)
  137. {
  138. StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n");
  139. sb.Append(GetUptimeReport());
  140. if (m_stats != null)
  141. {
  142. sb.Append(m_stats.Report());
  143. }
  144. sb.Append(Environment.NewLine);
  145. sb.Append(GetThreadsReport());
  146. m_log.Debug(sb);
  147. }
  148. /// <summary>
  149. /// Get a report about the registered threads in this server.
  150. /// </summary>
  151. protected string GetThreadsReport()
  152. {
  153. StringBuilder sb = new StringBuilder();
  154. List<Thread> threads = ThreadTracker.GetThreads();
  155. if (threads == null)
  156. {
  157. sb.Append("Thread tracking is only enabled in DEBUG mode.");
  158. }
  159. else
  160. {
  161. sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine);
  162. foreach (Thread t in threads)
  163. {
  164. if (t.IsAlive)
  165. {
  166. sb.Append(
  167. "ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", Alive: " + t.IsAlive
  168. + ", Pri: " + t.Priority + ", State: " + t.ThreadState + Environment.NewLine);
  169. }
  170. else
  171. {
  172. try
  173. {
  174. sb.Append("ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", DEAD" + Environment.NewLine);
  175. }
  176. catch
  177. {
  178. sb.Append("THREAD ERROR" + Environment.NewLine);
  179. }
  180. }
  181. }
  182. }
  183. return sb.ToString();
  184. }
  185. /// <summary>
  186. /// Return a report about the uptime of this server
  187. /// </summary>
  188. /// <returns></returns>
  189. protected string GetUptimeReport()
  190. {
  191. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  192. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  193. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  194. return sb.ToString();
  195. }
  196. /// <summary>
  197. /// Set the level of log notices being echoed to the console
  198. /// </summary>
  199. /// <param name="setParams"></param>
  200. private void SetConsoleLogLevel(string[] setParams)
  201. {
  202. ILoggerRepository repository = LogManager.GetRepository();
  203. IAppender[] appenders = repository.GetAppenders();
  204. OpenSimAppender consoleAppender = null;
  205. foreach (IAppender appender in appenders)
  206. {
  207. if (appender.Name == "Console")
  208. {
  209. consoleAppender = (OpenSimAppender)appender;
  210. break;
  211. }
  212. }
  213. if (null == consoleAppender)
  214. {
  215. Notice("No appender named Console found (see the log4net config file for this executable)!");
  216. return;
  217. }
  218. consoleAppender.Console = m_console;
  219. if (setParams.Length > 0)
  220. {
  221. Level consoleLevel = repository.LevelMap[setParams[0]];
  222. if (consoleLevel != null)
  223. consoleAppender.Threshold = consoleLevel;
  224. else
  225. Notice(
  226. String.Format(
  227. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  228. setParams[0]));
  229. }
  230. // If there is no threshold set then the threshold is effectively everything.
  231. Level thresholdLevel
  232. = (null != consoleAppender.Threshold ? consoleAppender.Threshold : Level.All);
  233. Notice(String.Format("Console log level is {0}", thresholdLevel));
  234. }
  235. /// <summary>
  236. /// Performs initialisation of the scene, such as loading configuration from disk.
  237. /// </summary>
  238. public virtual void Startup()
  239. {
  240. m_log.Info("[STARTUP]: Beginning startup processing");
  241. EnhanceVersionInformation();
  242. m_log.Info("[STARTUP]: Version: " + m_version + "\n");
  243. StartupSpecific();
  244. TimeSpan timeTaken = DateTime.Now - m_startuptime;
  245. m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
  246. }
  247. /// <summary>
  248. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  249. /// </summary>
  250. public virtual void Shutdown()
  251. {
  252. ShutdownSpecific();
  253. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  254. Environment.Exit(0);
  255. }
  256. private void HandleQuit(string module, string[] args)
  257. {
  258. Shutdown();
  259. }
  260. private void HandleLogLevel(string module, string[] cmd)
  261. {
  262. if (cmd.Length > 3)
  263. {
  264. string level = cmd[3];
  265. SetConsoleLogLevel(new string[] { level });
  266. }
  267. }
  268. /// <summary>
  269. /// Show help information
  270. /// </summary>
  271. /// <param name="helpArgs"></param>
  272. protected virtual void ShowHelp(string[] helpArgs)
  273. {
  274. Notice("");
  275. if (helpArgs.Length == 0)
  276. {
  277. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  278. Notice("show info - show server information (e.g. startup path).");
  279. if (m_stats != null)
  280. Notice("show stats - show statistical information for this server");
  281. Notice("show threads - list tracked threads");
  282. Notice("show uptime - show server startup time and uptime.");
  283. Notice("show version - show server version.");
  284. Notice("");
  285. return;
  286. }
  287. }
  288. public virtual void HandleShow(string module, string[] cmd)
  289. {
  290. List<string> args = new List<string>(cmd);
  291. args.RemoveAt(0);
  292. string[] showParams = args.ToArray();
  293. switch (showParams[0])
  294. {
  295. case "info":
  296. Notice("Version: " + m_version);
  297. Notice("Startup directory: " + m_startupDirectory);
  298. break;
  299. case "stats":
  300. if (m_stats != null)
  301. Notice(m_stats.Report());
  302. break;
  303. case "threads":
  304. Notice(GetThreadsReport());
  305. break;
  306. case "uptime":
  307. Notice(GetUptimeReport());
  308. break;
  309. case "version":
  310. Notice(
  311. String.Format(
  312. "Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion));
  313. break;
  314. }
  315. }
  316. /// <summary>
  317. /// Console output is only possible if a console has been established.
  318. /// That is something that cannot be determined within this class. So
  319. /// all attempts to use the console MUST be verified.
  320. /// </summary>
  321. protected void Notice(string msg)
  322. {
  323. if (m_console != null)
  324. {
  325. m_console.Notice(msg);
  326. }
  327. }
  328. /// <summary>
  329. /// Enhance the version string with extra information if it's available.
  330. /// </summary>
  331. protected void EnhanceVersionInformation()
  332. {
  333. string buildVersion = string.Empty;
  334. // Add subversion revision information if available
  335. // Try file "svn_revision" in the current directory first, then the .svn info.
  336. // This allows to make the revision available in simulators not running from the source tree.
  337. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  338. // elsewhere as well
  339. string svnRevisionFileName = "svn_revision";
  340. string svnFileName = ".svn/entries";
  341. string inputLine;
  342. int strcmp;
  343. if (File.Exists(svnRevisionFileName))
  344. {
  345. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  346. buildVersion = RevisionFile.ReadLine();
  347. buildVersion.Trim();
  348. RevisionFile.Close();
  349. }
  350. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  351. {
  352. StreamReader EntriesFile = File.OpenText(svnFileName);
  353. inputLine = EntriesFile.ReadLine();
  354. while (inputLine != null)
  355. {
  356. // using the dir svn revision at the top of entries file
  357. strcmp = String.Compare(inputLine, "dir");
  358. if (strcmp == 0)
  359. {
  360. buildVersion = EntriesFile.ReadLine();
  361. break;
  362. }
  363. else
  364. {
  365. inputLine = EntriesFile.ReadLine();
  366. }
  367. }
  368. EntriesFile.Close();
  369. }
  370. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  371. }
  372. }
  373. }