BaseOpenSimServer.cs 16 KB

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