BaseOpenSimServer.cs 22 KB

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