BaseOpenSimServer.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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]: OpenSimulator version: " + m_version + Environment.NewLine);
  241. // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
  242. // the clr version number doesn't match the project version number under Mono.
  243. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
  244. m_log.Info("[STARTUP]: Operating system version: " + Environment.OSVersion + Environment.NewLine);
  245. StartupSpecific();
  246. TimeSpan timeTaken = DateTime.Now - m_startuptime;
  247. m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
  248. }
  249. /// <summary>
  250. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  251. /// </summary>
  252. public virtual void Shutdown()
  253. {
  254. ShutdownSpecific();
  255. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  256. RemovePIDFile();
  257. Environment.Exit(0);
  258. }
  259. private void HandleQuit(string module, string[] args)
  260. {
  261. Shutdown();
  262. }
  263. private void HandleLogLevel(string module, string[] cmd)
  264. {
  265. if (null == m_consoleAppender)
  266. {
  267. Notice("No appender named Console found (see the log4net config file for this executable)!");
  268. return;
  269. }
  270. string rawLevel = cmd[3];
  271. ILoggerRepository repository = LogManager.GetRepository();
  272. Level consoleLevel = repository.LevelMap[rawLevel];
  273. if (consoleLevel != null)
  274. m_consoleAppender.Threshold = consoleLevel;
  275. else
  276. Notice(
  277. String.Format(
  278. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  279. rawLevel));
  280. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  281. }
  282. /// <summary>
  283. /// Show help information
  284. /// </summary>
  285. /// <param name="helpArgs"></param>
  286. protected virtual void ShowHelp(string[] helpArgs)
  287. {
  288. Notice("");
  289. if (helpArgs.Length == 0)
  290. {
  291. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  292. Notice("show info - show server information (e.g. startup path).");
  293. if (m_stats != null)
  294. Notice("show stats - show statistical information for this server");
  295. Notice("show threads - list tracked threads");
  296. Notice("show uptime - show server startup time and uptime.");
  297. Notice("show version - show server version.");
  298. Notice("");
  299. return;
  300. }
  301. }
  302. public virtual void HandleShow(string module, string[] cmd)
  303. {
  304. List<string> args = new List<string>(cmd);
  305. args.RemoveAt(0);
  306. string[] showParams = args.ToArray();
  307. switch (showParams[0])
  308. {
  309. case "info":
  310. Notice("Version: " + m_version);
  311. Notice("Startup directory: " + m_startupDirectory);
  312. break;
  313. case "stats":
  314. if (m_stats != null)
  315. Notice(m_stats.Report());
  316. break;
  317. case "threads":
  318. Notice(GetThreadsReport());
  319. break;
  320. case "uptime":
  321. Notice(GetUptimeReport());
  322. break;
  323. case "version":
  324. Notice(
  325. String.Format(
  326. "Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion));
  327. break;
  328. }
  329. }
  330. /// <summary>
  331. /// Console output is only possible if a console has been established.
  332. /// That is something that cannot be determined within this class. So
  333. /// all attempts to use the console MUST be verified.
  334. /// </summary>
  335. protected void Notice(string msg)
  336. {
  337. if (m_console != null)
  338. {
  339. m_console.Output(msg);
  340. }
  341. }
  342. /// <summary>
  343. /// Enhance the version string with extra information if it's available.
  344. /// </summary>
  345. protected void EnhanceVersionInformation()
  346. {
  347. string buildVersion = string.Empty;
  348. // Add commit hash and date information if available
  349. // The commit hash and date are stored in a file bin/.version
  350. // This file can automatically created by a post
  351. // commit script in the opensim git master repository or
  352. // by issuing the follwoing command from the top level
  353. // directory of the opensim repository
  354. // git log -n 1 --pretty="format:%h: %ci" >bin/.version
  355. // For the full git commit hash use %H instead of %h
  356. //
  357. // The subversion information is deprecated and will be removed at a later date
  358. // Add subversion revision information if available
  359. // Try file "svn_revision" in the current directory first, then the .svn info.
  360. // This allows to make the revision available in simulators not running from the source tree.
  361. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  362. // elsewhere as well
  363. string svnRevisionFileName = "svn_revision";
  364. string svnFileName = ".svn/entries";
  365. string gitCommitFileName = ".version";
  366. string inputLine;
  367. int strcmp;
  368. if (File.Exists(gitCommitFileName))
  369. {
  370. StreamReader CommitFile = File.OpenText(gitCommitFileName);
  371. buildVersion = CommitFile.ReadLine();
  372. CommitFile.Close();
  373. m_version += buildVersion ?? "";
  374. }
  375. // Remove the else logic when subversion mirror is no longer used
  376. else
  377. {
  378. if (File.Exists(svnRevisionFileName))
  379. {
  380. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  381. buildVersion = RevisionFile.ReadLine();
  382. buildVersion.Trim();
  383. RevisionFile.Close();
  384. }
  385. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  386. {
  387. StreamReader EntriesFile = File.OpenText(svnFileName);
  388. inputLine = EntriesFile.ReadLine();
  389. while (inputLine != null)
  390. {
  391. // using the dir svn revision at the top of entries file
  392. strcmp = String.Compare(inputLine, "dir");
  393. if (strcmp == 0)
  394. {
  395. buildVersion = EntriesFile.ReadLine();
  396. break;
  397. }
  398. else
  399. {
  400. inputLine = EntriesFile.ReadLine();
  401. }
  402. }
  403. EntriesFile.Close();
  404. }
  405. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  406. }
  407. }
  408. protected void CreatePIDFile(string path)
  409. {
  410. try
  411. {
  412. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  413. FileStream fs = File.Create(path);
  414. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  415. Byte[] buf = enc.GetBytes(pidstring);
  416. fs.Write(buf, 0, buf.Length);
  417. fs.Close();
  418. m_pidFile = path;
  419. }
  420. catch (Exception)
  421. {
  422. }
  423. }
  424. public string osSecret {
  425. // Secret uuid for the simulator
  426. get { return m_osSecret; }
  427. }
  428. public string StatReport(OSHttpRequest httpRequest)
  429. {
  430. // If we catch a request for "callback", wrap the response in the value for jsonp
  431. if (httpRequest.Query.ContainsKey("callback"))
  432. {
  433. return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
  434. }
  435. else
  436. {
  437. return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
  438. }
  439. }
  440. protected void RemovePIDFile()
  441. {
  442. if (m_pidFile != String.Empty)
  443. {
  444. try
  445. {
  446. File.Delete(m_pidFile);
  447. m_pidFile = String.Empty;
  448. }
  449. catch (Exception)
  450. {
  451. }
  452. }
  453. }
  454. }
  455. }