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.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.Servers;
  40. using OpenSim.Framework.Servers.HttpServer;
  41. using OpenSim.Framework.Statistics;
  42. using Timer=System.Timers.Timer;
  43. using OpenMetaverse;
  44. using OpenMetaverse.StructuredData;
  45. namespace OpenSim.Framework.Servers
  46. {
  47. /// <summary>
  48. /// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
  49. /// </summary>
  50. public abstract class BaseOpenSimServer
  51. {
  52. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. /// <summary>
  54. /// This will control a periodic log printout of the current 'show stats' (if they are active) for this
  55. /// server.
  56. /// </summary>
  57. private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
  58. protected CommandConsole m_console;
  59. protected OpenSimAppender m_consoleAppender;
  60. protected IAppender m_logFileAppender = null;
  61. /// <summary>
  62. /// Time at which this server was started
  63. /// </summary>
  64. protected DateTime m_startuptime;
  65. /// <summary>
  66. /// Record the initial startup directory for info purposes
  67. /// </summary>
  68. protected string m_startupDirectory = Environment.CurrentDirectory;
  69. /// <summary>
  70. /// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
  71. /// </summary>
  72. protected string m_version;
  73. protected string m_pidFile = String.Empty;
  74. /// <summary>
  75. /// Random uuid for private data
  76. /// </summary>
  77. protected string m_osSecret = String.Empty;
  78. protected BaseHttpServer m_httpServer;
  79. public BaseHttpServer HttpServer
  80. {
  81. get { return m_httpServer; }
  82. }
  83. /// <summary>
  84. /// Holds the non-viewer statistics collection object for this service/server
  85. /// </summary>
  86. protected IStatsCollector m_stats;
  87. public BaseOpenSimServer()
  88. {
  89. m_startuptime = DateTime.Now;
  90. m_version = VersionInfo.Version;
  91. // Random uuid for private data
  92. m_osSecret = UUID.Random().ToString();
  93. m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
  94. m_periodicDiagnosticsTimer.Enabled = true;
  95. // Add ourselves to thread monitoring. This thread will go on to become the console listening thread
  96. Thread.CurrentThread.Name = "ConsoleThread";
  97. ThreadTracker.Add(Thread.CurrentThread);
  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. List<Thread> threads = ThreadTracker.GetThreads();
  198. if (threads == null)
  199. {
  200. sb.Append("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 (Thread t in threads)
  206. {
  207. if (t.IsAlive)
  208. {
  209. sb.Append(
  210. "ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", Alive: " + t.IsAlive
  211. + ", Pri: " + t.Priority + ", State: " + t.ThreadState + Environment.NewLine);
  212. }
  213. else
  214. {
  215. try
  216. {
  217. sb.Append("ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", DEAD" + Environment.NewLine);
  218. }
  219. catch
  220. {
  221. sb.Append("THREAD ERROR" + Environment.NewLine);
  222. }
  223. }
  224. }
  225. }
  226. return sb.ToString();
  227. }
  228. /// <summary>
  229. /// Return a report about the uptime of this server
  230. /// </summary>
  231. /// <returns></returns>
  232. protected string GetUptimeReport()
  233. {
  234. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  235. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  236. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  237. return sb.ToString();
  238. }
  239. /// <summary>
  240. /// Performs initialisation of the scene, such as loading configuration from disk.
  241. /// </summary>
  242. public virtual void Startup()
  243. {
  244. m_log.Info("[STARTUP]: Beginning startup processing");
  245. EnhanceVersionInformation();
  246. m_log.Info("[STARTUP]: Version: " + m_version + "\n");
  247. StartupSpecific();
  248. TimeSpan timeTaken = DateTime.Now - m_startuptime;
  249. m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds);
  250. }
  251. /// <summary>
  252. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  253. /// </summary>
  254. public virtual void Shutdown()
  255. {
  256. ShutdownSpecific();
  257. m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
  258. RemovePIDFile();
  259. Environment.Exit(0);
  260. }
  261. private void HandleQuit(string module, string[] args)
  262. {
  263. Shutdown();
  264. }
  265. private void HandleLogLevel(string module, string[] cmd)
  266. {
  267. if (null == m_consoleAppender)
  268. {
  269. Notice("No appender named Console found (see the log4net config file for this executable)!");
  270. return;
  271. }
  272. string rawLevel = cmd[3];
  273. ILoggerRepository repository = LogManager.GetRepository();
  274. Level consoleLevel = repository.LevelMap[rawLevel];
  275. if (consoleLevel != null)
  276. m_consoleAppender.Threshold = consoleLevel;
  277. else
  278. Notice(
  279. String.Format(
  280. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  281. rawLevel));
  282. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  283. }
  284. /// <summary>
  285. /// Show help information
  286. /// </summary>
  287. /// <param name="helpArgs"></param>
  288. protected virtual void ShowHelp(string[] helpArgs)
  289. {
  290. Notice("");
  291. if (helpArgs.Length == 0)
  292. {
  293. Notice("set log level [level] - change the console logging level only. For example, off or debug.");
  294. Notice("show info - show server information (e.g. startup path).");
  295. if (m_stats != null)
  296. Notice("show stats - show statistical information for this server");
  297. Notice("show threads - list tracked threads");
  298. Notice("show uptime - show server startup time and uptime.");
  299. Notice("show version - show server version.");
  300. Notice("");
  301. return;
  302. }
  303. }
  304. public virtual void HandleShow(string module, string[] cmd)
  305. {
  306. List<string> args = new List<string>(cmd);
  307. args.RemoveAt(0);
  308. string[] showParams = args.ToArray();
  309. switch (showParams[0])
  310. {
  311. case "info":
  312. Notice("Version: " + m_version);
  313. Notice("Startup directory: " + m_startupDirectory);
  314. break;
  315. case "stats":
  316. if (m_stats != null)
  317. Notice(m_stats.Report());
  318. break;
  319. case "threads":
  320. Notice(GetThreadsReport());
  321. break;
  322. case "uptime":
  323. Notice(GetUptimeReport());
  324. break;
  325. case "version":
  326. Notice(
  327. String.Format(
  328. "Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion));
  329. break;
  330. }
  331. }
  332. /// <summary>
  333. /// Console output is only possible if a console has been established.
  334. /// That is something that cannot be determined within this class. So
  335. /// all attempts to use the console MUST be verified.
  336. /// </summary>
  337. protected void Notice(string msg)
  338. {
  339. if (m_console != null)
  340. {
  341. m_console.Output(msg);
  342. }
  343. }
  344. /// <summary>
  345. /// Enhance the version string with extra information if it's available.
  346. /// </summary>
  347. protected void EnhanceVersionInformation()
  348. {
  349. string buildVersion = string.Empty;
  350. // Add commit hash and date information if available
  351. // The commit hash and date are stored in a file bin/.version
  352. // This file can automatically created by a post
  353. // commit script in the opensim git master repository or
  354. // by issuing the follwoing command from the top level
  355. // directory of the opensim repository
  356. // git log -n 1 --pretty="format:%h: %ci" >bin/.version
  357. // For the full git commit hash use %H instead of %h
  358. //
  359. // The subversion information is deprecated and will be removed at a later date
  360. // Add subversion revision information if available
  361. // Try file "svn_revision" in the current directory first, then the .svn info.
  362. // This allows to make the revision available in simulators not running from the source tree.
  363. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  364. // elsewhere as well
  365. string svnRevisionFileName = "svn_revision";
  366. string svnFileName = ".svn/entries";
  367. string gitCommitFileName = ".version";
  368. string inputLine;
  369. int strcmp;
  370. if (File.Exists(gitCommitFileName))
  371. {
  372. StreamReader CommitFile = File.OpenText(gitCommitFileName);
  373. buildVersion = Environment.NewLine + "git# " + CommitFile.ReadLine();
  374. CommitFile.Close();
  375. m_version += buildVersion ?? "";
  376. }
  377. // Remove the else logic when subversion mirror is no longer used
  378. else
  379. {
  380. if (File.Exists(svnRevisionFileName))
  381. {
  382. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  383. buildVersion = RevisionFile.ReadLine();
  384. buildVersion.Trim();
  385. RevisionFile.Close();
  386. }
  387. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  388. {
  389. StreamReader EntriesFile = File.OpenText(svnFileName);
  390. inputLine = EntriesFile.ReadLine();
  391. while (inputLine != null)
  392. {
  393. // using the dir svn revision at the top of entries file
  394. strcmp = String.Compare(inputLine, "dir");
  395. if (strcmp == 0)
  396. {
  397. buildVersion = EntriesFile.ReadLine();
  398. break;
  399. }
  400. else
  401. {
  402. inputLine = EntriesFile.ReadLine();
  403. }
  404. }
  405. EntriesFile.Close();
  406. }
  407. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  408. }
  409. }
  410. protected void CreatePIDFile(string path)
  411. {
  412. try
  413. {
  414. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  415. FileStream fs = File.Create(path);
  416. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  417. Byte[] buf = enc.GetBytes(pidstring);
  418. fs.Write(buf, 0, buf.Length);
  419. fs.Close();
  420. m_pidFile = path;
  421. }
  422. catch (Exception)
  423. {
  424. }
  425. }
  426. public string osSecret {
  427. // Secret uuid for the simulator
  428. get { return m_osSecret; }
  429. }
  430. public string StatReport(OSHttpRequest httpRequest)
  431. {
  432. // If we catch a request for "callback", wrap the response in the value for jsonp
  433. if (httpRequest.Query.ContainsKey("callback"))
  434. {
  435. return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
  436. }
  437. else
  438. {
  439. return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
  440. }
  441. }
  442. protected void RemovePIDFile()
  443. {
  444. if (m_pidFile != String.Empty)
  445. {
  446. try
  447. {
  448. File.Delete(m_pidFile);
  449. m_pidFile = String.Empty;
  450. }
  451. catch (Exception)
  452. {
  453. }
  454. }
  455. }
  456. }
  457. }