BaseOpenSimServer.cs 21 KB

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