BaseOpenSimServer.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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.Threading;
  34. using System.Timers;
  35. using log4net;
  36. using log4net.Appender;
  37. using log4net.Core;
  38. using log4net.Repository;
  39. using OpenSim.Framework.Console;
  40. using OpenSim.Framework.Servers;
  41. using OpenSim.Framework.Servers.HttpServer;
  42. using OpenSim.Framework.Statistics;
  43. using Timer=System.Timers.Timer;
  44. using OpenMetaverse;
  45. using OpenMetaverse.StructuredData;
  46. namespace OpenSim.Framework.Servers
  47. {
  48. /// <summary>
  49. /// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
  50. /// </summary>
  51. public abstract class BaseOpenSimServer
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. /// <summary>
  55. /// This will control a periodic log printout of the current 'show stats' (if they are active) for this
  56. /// server.
  57. /// </summary>
  58. private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
  59. protected CommandConsole m_console;
  60. protected OpenSimAppender m_consoleAppender;
  61. protected IAppender m_logFileAppender = null;
  62. /// <summary>
  63. /// Time at which this server was started
  64. /// </summary>
  65. protected DateTime m_startuptime;
  66. /// <summary>
  67. /// Record the initial startup directory for info purposes
  68. /// </summary>
  69. protected string m_startupDirectory = Environment.CurrentDirectory;
  70. /// <summary>
  71. /// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
  72. /// </summary>
  73. protected string m_version;
  74. protected string m_pidFile = String.Empty;
  75. /// <summary>
  76. /// Random uuid for private data
  77. /// </summary>
  78. protected string m_osSecret = String.Empty;
  79. protected BaseHttpServer m_httpServer;
  80. public BaseHttpServer HttpServer
  81. {
  82. get { return m_httpServer; }
  83. }
  84. /// <summary>
  85. /// Holds the non-viewer statistics collection object for this service/server
  86. /// </summary>
  87. protected IStatsCollector m_stats;
  88. public BaseOpenSimServer()
  89. {
  90. m_startuptime = DateTime.Now;
  91. m_version = VersionInfo.Version;
  92. // Random uuid for private data
  93. m_osSecret = UUID.Random().ToString();
  94. m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
  95. m_periodicDiagnosticsTimer.Enabled = true;
  96. // This thread will go on to become the console listening thread
  97. Thread.CurrentThread.Name = "ConsoleThread";
  98. ILoggerRepository repository = LogManager.GetRepository();
  99. IAppender[] appenders = repository.GetAppenders();
  100. foreach (IAppender appender in appenders)
  101. {
  102. if (appender.Name == "LogFileAppender")
  103. {
  104. m_logFileAppender = appender;
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Must be overriden by child classes for their own server specific startup behaviour.
  110. /// </summary>
  111. protected virtual void StartupSpecific()
  112. {
  113. if (m_console != null)
  114. {
  115. ILoggerRepository repository = LogManager.GetRepository();
  116. IAppender[] appenders = repository.GetAppenders();
  117. foreach (IAppender appender in appenders)
  118. {
  119. if (appender.Name == "Console")
  120. {
  121. m_consoleAppender = (OpenSimAppender)appender;
  122. break;
  123. }
  124. }
  125. if (null == m_consoleAppender)
  126. {
  127. Notice("No appender named Console found (see the log4net config file for this executable)!");
  128. }
  129. else
  130. {
  131. m_consoleAppender.Console = m_console;
  132. // If there is no threshold set then the threshold is effectively everything.
  133. if (null == m_consoleAppender.Threshold)
  134. m_consoleAppender.Threshold = Level.All;
  135. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  136. }
  137. m_console.Commands.AddCommand("base", false, "quit",
  138. "quit",
  139. "Quit the application", HandleQuit);
  140. m_console.Commands.AddCommand("base", false, "shutdown",
  141. "shutdown",
  142. "Quit the application", HandleQuit);
  143. m_console.Commands.AddCommand("base", false, "set log level",
  144. "set log level <level>",
  145. "Set the console logging level", HandleLogLevel);
  146. m_console.Commands.AddCommand("base", false, "show info",
  147. "show info",
  148. "Show general information", HandleShow);
  149. m_console.Commands.AddCommand("base", false, "show stats",
  150. "show stats",
  151. "Show statistics", HandleShow);
  152. m_console.Commands.AddCommand("base", false, "show threads",
  153. "show threads",
  154. "Show thread status", HandleShow);
  155. m_console.Commands.AddCommand("base", false, "show uptime",
  156. "show uptime",
  157. "Show server uptime", HandleShow);
  158. m_console.Commands.AddCommand("base", false, "show version",
  159. "show version",
  160. "Show server version", HandleShow);
  161. }
  162. }
  163. /// <summary>
  164. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  165. /// </summary>
  166. public virtual void ShutdownSpecific() {}
  167. /// <summary>
  168. /// Provides a list of help topics that are available. Overriding classes should append their topics to the
  169. /// information returned when the base method is called.
  170. /// </summary>
  171. ///
  172. /// <returns>
  173. /// A list of strings that represent different help topics on which more information is available
  174. /// </returns>
  175. protected virtual List<string> GetHelpTopics() { return new List<string>(); }
  176. /// <summary>
  177. /// Print statistics to the logfile, if they are active
  178. /// </summary>
  179. protected void LogDiagnostics(object source, ElapsedEventArgs e)
  180. {
  181. StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n");
  182. sb.Append(GetUptimeReport());
  183. if (m_stats != null)
  184. {
  185. sb.Append(m_stats.Report());
  186. }
  187. sb.Append(Environment.NewLine);
  188. sb.Append(GetThreadsReport());
  189. m_log.Debug(sb);
  190. }
  191. /// <summary>
  192. /// Get a report about the registered threads in this server.
  193. /// </summary>
  194. protected string GetThreadsReport()
  195. {
  196. StringBuilder sb = new StringBuilder();
  197. ProcessThreadCollection threads = ThreadTracker.GetThreads();
  198. if (threads == null)
  199. {
  200. sb.Append("OpenSim thread tracking is only enabled in DEBUG mode.");
  201. }
  202. else
  203. {
  204. sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine);
  205. foreach (ProcessThread t in threads)
  206. {
  207. sb.Append("ID: " + t.Id + ", TotalProcessorTime: " + t.TotalProcessorTime + ", TimeRunning: " +
  208. (DateTime.Now - t.StartTime) + ", Pri: " + t.CurrentPriority + ", State: " + t.ThreadState);
  209. if (t.ThreadState == System.Diagnostics.ThreadState.Wait)
  210. sb.Append(", Reason: " + t.WaitReason + Environment.NewLine);
  211. else
  212. sb.Append(Environment.NewLine);
  213. }
  214. }
  215. int workers = 0, ports = 0, maxWorkers = 0, maxPorts = 0;
  216. ThreadPool.GetAvailableThreads(out workers, out ports);
  217. ThreadPool.GetMaxThreads(out maxWorkers, out maxPorts);
  218. sb.Append(Environment.NewLine + "*** ThreadPool threads ***" + Environment.NewLine);
  219. sb.Append("workers: " + (maxWorkers - workers) + " (" + maxWorkers + "); ports: " + (maxPorts - ports) + " (" + maxPorts + ")" + Environment.NewLine);
  220. return sb.ToString();
  221. }
  222. /// <summary>
  223. /// Return a report about the uptime of this server
  224. /// </summary>
  225. /// <returns></returns>
  226. protected string GetUptimeReport()
  227. {
  228. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  229. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  230. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  231. return sb.ToString();
  232. }
  233. /// <summary>
  234. /// Performs initialisation of the scene, such as loading configuration from disk.
  235. /// </summary>
  236. public virtual void Startup()
  237. {
  238. m_log.Info("[STARTUP]: Beginning startup processing");
  239. EnhanceVersionInformation();
  240. m_log.Info("[STARTUP]: Version: " + m_version + "\n");
  241. StartupSpecific();
  242. TimeSpan timeTaken = DateTime.Now - m_startuptime;
  243. m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
  244. }
  245. /// <summary>
  246. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  247. /// </summary>
  248. public virtual void Shutdown()
  249. {
  250. ShutdownSpecific();
  251. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  252. RemovePIDFile();
  253. Environment.Exit(0);
  254. }
  255. private void HandleQuit(string module, string[] args)
  256. {
  257. Shutdown();
  258. }
  259. private void HandleLogLevel(string module, string[] cmd)
  260. {
  261. if (null == m_consoleAppender)
  262. {
  263. Notice("No appender named Console found (see the log4net config file for this executable)!");
  264. return;
  265. }
  266. string rawLevel = cmd[3];
  267. ILoggerRepository repository = LogManager.GetRepository();
  268. Level consoleLevel = repository.LevelMap[rawLevel];
  269. if (consoleLevel != null)
  270. m_consoleAppender.Threshold = consoleLevel;
  271. else
  272. Notice(
  273. String.Format(
  274. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  275. rawLevel));
  276. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  277. }
  278. /// <summary>
  279. /// Show help information
  280. /// </summary>
  281. /// <param name="helpArgs"></param>
  282. protected virtual void ShowHelp(string[] helpArgs)
  283. {
  284. Notice("");
  285. if (helpArgs.Length == 0)
  286. {
  287. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  288. Notice("show info - show server information (e.g. startup path).");
  289. if (m_stats != null)
  290. Notice("show stats - show statistical information for this server");
  291. Notice("show threads - list tracked threads");
  292. Notice("show uptime - show server startup time and uptime.");
  293. Notice("show version - show server version.");
  294. Notice("");
  295. return;
  296. }
  297. }
  298. public virtual void HandleShow(string module, string[] cmd)
  299. {
  300. List<string> args = new List<string>(cmd);
  301. args.RemoveAt(0);
  302. string[] showParams = args.ToArray();
  303. switch (showParams[0])
  304. {
  305. case "info":
  306. Notice("Version: " + m_version);
  307. Notice("Startup directory: " + m_startupDirectory);
  308. break;
  309. case "stats":
  310. if (m_stats != null)
  311. Notice(m_stats.Report());
  312. break;
  313. case "threads":
  314. Notice(GetThreadsReport());
  315. break;
  316. case "uptime":
  317. Notice(GetUptimeReport());
  318. break;
  319. case "version":
  320. Notice(
  321. String.Format(
  322. "Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion));
  323. break;
  324. }
  325. }
  326. /// <summary>
  327. /// Console output is only possible if a console has been established.
  328. /// That is something that cannot be determined within this class. So
  329. /// all attempts to use the console MUST be verified.
  330. /// </summary>
  331. protected void Notice(string msg)
  332. {
  333. if (m_console != null)
  334. {
  335. m_console.Output(msg);
  336. }
  337. }
  338. /// <summary>
  339. /// Enhance the version string with extra information if it's available.
  340. /// </summary>
  341. protected void EnhanceVersionInformation()
  342. {
  343. string buildVersion = string.Empty;
  344. // Add commit hash and date information if available
  345. // The commit hash and date are stored in a file bin/.version
  346. // This file can automatically created by a post
  347. // commit script in the opensim git master repository or
  348. // by issuing the follwoing command from the top level
  349. // directory of the opensim repository
  350. // git log -n 1 --pretty="format:%h: %ci" >bin/.version
  351. // For the full git commit hash use %H instead of %h
  352. //
  353. // The subversion information is deprecated and will be removed at a later date
  354. // Add subversion revision information if available
  355. // Try file "svn_revision" in the current directory first, then the .svn info.
  356. // This allows to make the revision available in simulators not running from the source tree.
  357. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  358. // elsewhere as well
  359. string svnRevisionFileName = "svn_revision";
  360. string svnFileName = ".svn/entries";
  361. string gitCommitFileName = ".version";
  362. string inputLine;
  363. int strcmp;
  364. if (File.Exists(gitCommitFileName))
  365. {
  366. StreamReader CommitFile = File.OpenText(gitCommitFileName);
  367. buildVersion = CommitFile.ReadLine();
  368. CommitFile.Close();
  369. m_version += buildVersion ?? "";
  370. }
  371. // Remove the else logic when subversion mirror is no longer used
  372. else
  373. {
  374. if (File.Exists(svnRevisionFileName))
  375. {
  376. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  377. buildVersion = RevisionFile.ReadLine();
  378. buildVersion.Trim();
  379. RevisionFile.Close();
  380. }
  381. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  382. {
  383. StreamReader EntriesFile = File.OpenText(svnFileName);
  384. inputLine = EntriesFile.ReadLine();
  385. while (inputLine != null)
  386. {
  387. // using the dir svn revision at the top of entries file
  388. strcmp = String.Compare(inputLine, "dir");
  389. if (strcmp == 0)
  390. {
  391. buildVersion = EntriesFile.ReadLine();
  392. break;
  393. }
  394. else
  395. {
  396. inputLine = EntriesFile.ReadLine();
  397. }
  398. }
  399. EntriesFile.Close();
  400. }
  401. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  402. }
  403. }
  404. protected void CreatePIDFile(string path)
  405. {
  406. try
  407. {
  408. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  409. FileStream fs = File.Create(path);
  410. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  411. Byte[] buf = enc.GetBytes(pidstring);
  412. fs.Write(buf, 0, buf.Length);
  413. fs.Close();
  414. m_pidFile = path;
  415. }
  416. catch (Exception)
  417. {
  418. }
  419. }
  420. public string osSecret {
  421. // Secret uuid for the simulator
  422. get { return m_osSecret; }
  423. }
  424. public string StatReport(OSHttpRequest httpRequest)
  425. {
  426. // If we catch a request for "callback", wrap the response in the value for jsonp
  427. if (httpRequest.Query.ContainsKey("callback"))
  428. {
  429. return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
  430. }
  431. else
  432. {
  433. return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
  434. }
  435. }
  436. protected void RemovePIDFile()
  437. {
  438. if (m_pidFile != String.Empty)
  439. {
  440. try
  441. {
  442. File.Delete(m_pidFile);
  443. m_pidFile = String.Empty;
  444. }
  445. catch (Exception)
  446. {
  447. }
  448. }
  449. }
  450. }
  451. }