BaseOpenSimServer.cs 16 KB

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