ServerBase.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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 log4net;
  36. using log4net.Appender;
  37. using log4net.Core;
  38. using log4net.Repository;
  39. using Nini.Config;
  40. using OpenSim.Framework.Console;
  41. using OpenSim.Framework.Monitoring;
  42. namespace OpenSim.Framework.Servers
  43. {
  44. public class ServerBase
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. public IConfigSource Config { get; protected set; }
  48. /// <summary>
  49. /// Console to be used for any command line output. Can be null, in which case there should be no output.
  50. /// </summary>
  51. protected ICommandConsole m_console;
  52. protected OpenSimAppender m_consoleAppender;
  53. protected FileAppender m_logFileAppender;
  54. protected DateTime m_startuptime;
  55. protected string m_startupDirectory = Environment.CurrentDirectory;
  56. protected string m_pidFile = String.Empty;
  57. protected ServerStatsCollector m_serverStatsCollector;
  58. /// <summary>
  59. /// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
  60. /// </summary>
  61. protected string m_version;
  62. public ServerBase()
  63. {
  64. m_startuptime = DateTime.Now;
  65. m_version = VersionInfo.Version;
  66. EnhanceVersionInformation();
  67. }
  68. protected void CreatePIDFile(string path)
  69. {
  70. if (File.Exists(path))
  71. m_log.ErrorFormat(
  72. "[SERVER BASE]: Previous pid file {0} still exists on startup. Possibly previously unclean shutdown.",
  73. path);
  74. try
  75. {
  76. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  77. using (FileStream fs = File.Create(path))
  78. {
  79. Byte[] buf = Encoding.ASCII.GetBytes(pidstring);
  80. fs.Write(buf, 0, buf.Length);
  81. }
  82. m_pidFile = path;
  83. m_log.InfoFormat("[SERVER BASE]: Created pid file {0}", m_pidFile);
  84. }
  85. catch (Exception e)
  86. {
  87. m_log.Warn(string.Format("[SERVER BASE]: Could not create PID file at {0} ", path), e);
  88. }
  89. }
  90. protected void RemovePIDFile()
  91. {
  92. if (m_pidFile != String.Empty)
  93. {
  94. try
  95. {
  96. File.Delete(m_pidFile);
  97. }
  98. catch (Exception e)
  99. {
  100. m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e);
  101. }
  102. m_pidFile = String.Empty;
  103. }
  104. }
  105. /// <summary>
  106. /// Log information about the circumstances in which we're running (OpenSimulator version number, CLR details,
  107. /// etc.).
  108. /// </summary>
  109. public void LogEnvironmentInformation()
  110. {
  111. // FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net
  112. // XmlConfigurator calls first accross servers.
  113. m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory);
  114. m_log.InfoFormat("[SERVER BASE]: OpenSimulator version: {0}", m_version);
  115. // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
  116. // the clr version number doesn't match the project version number under Mono.
  117. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
  118. m_log.InfoFormat(
  119. "[SERVER BASE]: Operating system version: {0}, .NET platform {1}, {2}-bit",
  120. Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32");
  121. }
  122. public void RegisterCommonAppenders(IConfig startupConfig)
  123. {
  124. ILoggerRepository repository = LogManager.GetRepository();
  125. IAppender[] appenders = repository.GetAppenders();
  126. foreach (IAppender appender in appenders)
  127. {
  128. if (appender.Name == "Console")
  129. {
  130. m_consoleAppender = (OpenSimAppender)appender;
  131. }
  132. else if (appender.Name == "LogFileAppender")
  133. {
  134. m_logFileAppender = (FileAppender)appender;
  135. }
  136. }
  137. if (null == m_consoleAppender)
  138. {
  139. Notice("No appender named Console found (see the log4net config file for this executable)!");
  140. }
  141. else
  142. {
  143. // FIXME: This should be done through an interface rather than casting.
  144. m_consoleAppender.Console = (ConsoleBase)m_console;
  145. // If there is no threshold set then the threshold is effectively everything.
  146. if (null == m_consoleAppender.Threshold)
  147. m_consoleAppender.Threshold = Level.All;
  148. Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
  149. }
  150. if (m_logFileAppender != null && startupConfig != null)
  151. {
  152. string cfgFileName = startupConfig.GetString("LogFile", null);
  153. if (cfgFileName != null)
  154. {
  155. m_logFileAppender.File = cfgFileName;
  156. m_logFileAppender.ActivateOptions();
  157. }
  158. m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File);
  159. }
  160. }
  161. /// <summary>
  162. /// Register common commands once m_console has been set if it is going to be set
  163. /// </summary>
  164. public void RegisterCommonCommands()
  165. {
  166. if (m_console == null)
  167. return;
  168. m_console.Commands.AddCommand(
  169. "General", false, "show info", "show info", "Show general information about the server", HandleShow);
  170. m_console.Commands.AddCommand(
  171. "General", false, "show version", "show version", "Show server version", HandleShow);
  172. m_console.Commands.AddCommand(
  173. "General", false, "show uptime", "show uptime", "Show server uptime", HandleShow);
  174. m_console.Commands.AddCommand(
  175. "General", false, "get log level", "get log level", "Get the current console logging level",
  176. (mod, cmd) => ShowLogLevel());
  177. m_console.Commands.AddCommand(
  178. "General", false, "set log level", "set log level <level>",
  179. "Set the console logging level for this session.", HandleSetLogLevel);
  180. m_console.Commands.AddCommand(
  181. "General", false, "config set",
  182. "config set <section> <key> <value>",
  183. "Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.", HandleConfig);
  184. m_console.Commands.AddCommand(
  185. "General", false, "config get",
  186. "config get [<section>] [<key>]",
  187. "Synonym for config show",
  188. HandleConfig);
  189. m_console.Commands.AddCommand(
  190. "General", false, "config show",
  191. "config show [<section>] [<key>]",
  192. "Show config information",
  193. "If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine
  194. + "If a section is given but not a field, then all fields in that section are printed.",
  195. HandleConfig);
  196. m_console.Commands.AddCommand(
  197. "General", false, "config save",
  198. "config save <path>",
  199. "Save current configuration to a file at the given path", HandleConfig);
  200. m_console.Commands.AddCommand(
  201. "General", false, "command-script",
  202. "command-script <script>",
  203. "Run a command script from file", HandleScript);
  204. m_console.Commands.AddCommand(
  205. "General", false, "show threads",
  206. "show threads",
  207. "Show thread status", HandleShow);
  208. m_console.Commands.AddCommand(
  209. "Debug", false, "threads abort",
  210. "threads abort <thread-id>",
  211. "Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort);
  212. m_console.Commands.AddCommand(
  213. "General", false, "threads show",
  214. "threads show",
  215. "Show thread status. Synonym for \"show threads\"",
  216. (string module, string[] args) => Notice(GetThreadsReport()));
  217. m_console.Commands.AddCommand (
  218. "Debug", false, "debug comms set",
  219. "debug comms set serialosdreq true|false",
  220. "Set comms parameters. For debug purposes.",
  221. HandleDebugCommsSet);
  222. m_console.Commands.AddCommand (
  223. "Debug", false, "debug comms status",
  224. "debug comms status",
  225. "Show current debug comms parameters.",
  226. HandleDebugCommsStatus);
  227. m_console.Commands.AddCommand (
  228. "Debug", false, "debug threadpool set",
  229. "debug threadpool set worker|iocp min|max <n>",
  230. "Set threadpool parameters. For debug purposes.",
  231. HandleDebugThreadpoolSet);
  232. m_console.Commands.AddCommand (
  233. "Debug", false, "debug threadpool status",
  234. "debug threadpool status",
  235. "Show current debug threadpool parameters.",
  236. HandleDebugThreadpoolStatus);
  237. m_console.Commands.AddCommand(
  238. "Debug", false, "force gc",
  239. "force gc",
  240. "Manually invoke runtime garbage collection. For debugging purposes",
  241. HandleForceGc);
  242. m_console.Commands.AddCommand(
  243. "General", false, "quit",
  244. "quit",
  245. "Quit the application", (mod, args) => Shutdown());
  246. m_console.Commands.AddCommand(
  247. "General", false, "shutdown",
  248. "shutdown",
  249. "Quit the application", (mod, args) => Shutdown());
  250. ChecksManager.RegisterConsoleCommands(m_console);
  251. StatsManager.RegisterConsoleCommands(m_console);
  252. }
  253. public void RegisterCommonComponents(IConfigSource configSource)
  254. {
  255. IConfig networkConfig = configSource.Configs["Network"];
  256. if (networkConfig != null)
  257. {
  258. WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false);
  259. }
  260. m_serverStatsCollector = new ServerStatsCollector();
  261. m_serverStatsCollector.Initialise(configSource);
  262. m_serverStatsCollector.Start();
  263. }
  264. private void HandleDebugCommsStatus(string module, string[] args)
  265. {
  266. Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint);
  267. }
  268. private void HandleDebugCommsSet(string module, string[] args)
  269. {
  270. if (args.Length != 5)
  271. {
  272. Notice("Usage: debug comms set serialosdreq true|false");
  273. return;
  274. }
  275. if (args[3] != "serialosdreq")
  276. {
  277. Notice("Usage: debug comms set serialosdreq true|false");
  278. return;
  279. }
  280. bool setSerializeOsdRequests;
  281. if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests))
  282. return;
  283. WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests;
  284. Notice("serialosdreq is now {0}", setSerializeOsdRequests);
  285. }
  286. private void HandleDebugThreadpoolStatus(string module, string[] args)
  287. {
  288. int workerThreads, iocpThreads;
  289. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  290. Notice("Min worker threads: {0}", workerThreads);
  291. Notice("Min IOCP threads: {0}", iocpThreads);
  292. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  293. Notice("Max worker threads: {0}", workerThreads);
  294. Notice("Max IOCP threads: {0}", iocpThreads);
  295. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  296. Notice("Available worker threads: {0}", workerThreads);
  297. Notice("Available IOCP threads: {0}", iocpThreads);
  298. }
  299. private void HandleDebugThreadpoolSet(string module, string[] args)
  300. {
  301. if (args.Length != 6)
  302. {
  303. Notice("Usage: debug threadpool set worker|iocp min|max <n>");
  304. return;
  305. }
  306. int newThreads;
  307. if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
  308. return;
  309. string poolType = args[3];
  310. string bound = args[4];
  311. bool fail = false;
  312. int workerThreads, iocpThreads;
  313. if (poolType == "worker")
  314. {
  315. if (bound == "min")
  316. {
  317. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  318. if (!ThreadPool.SetMinThreads(newThreads, iocpThreads))
  319. fail = true;
  320. }
  321. else
  322. {
  323. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  324. if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads))
  325. fail = true;
  326. }
  327. }
  328. else
  329. {
  330. if (bound == "min")
  331. {
  332. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  333. if (!ThreadPool.SetMinThreads(workerThreads, newThreads))
  334. fail = true;
  335. }
  336. else
  337. {
  338. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  339. if (!ThreadPool.SetMaxThreads(workerThreads, newThreads))
  340. fail = true;
  341. }
  342. }
  343. if (fail)
  344. {
  345. Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads);
  346. }
  347. else
  348. {
  349. int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;
  350. ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
  351. ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);
  352. Notice("Min worker threads now {0}", minWorkerThreads);
  353. Notice("Min IOCP threads now {0}", minIocpThreads);
  354. Notice("Max worker threads now {0}", maxWorkerThreads);
  355. Notice("Max IOCP threads now {0}", maxIocpThreads);
  356. }
  357. }
  358. private void HandleForceGc(string module, string[] args)
  359. {
  360. Notice("Manually invoking runtime garbage collection");
  361. GC.Collect();
  362. }
  363. public virtual void HandleShow(string module, string[] cmd)
  364. {
  365. List<string> args = new List<string>(cmd);
  366. args.RemoveAt(0);
  367. string[] showParams = args.ToArray();
  368. switch (showParams[0])
  369. {
  370. case "info":
  371. ShowInfo();
  372. break;
  373. case "version":
  374. Notice(GetVersionText());
  375. break;
  376. case "uptime":
  377. Notice(GetUptimeReport());
  378. break;
  379. case "threads":
  380. Notice(GetThreadsReport());
  381. break;
  382. }
  383. }
  384. /// <summary>
  385. /// Change and load configuration file data.
  386. /// </summary>
  387. /// <param name="module"></param>
  388. /// <param name="cmd"></param>
  389. private void HandleConfig(string module, string[] cmd)
  390. {
  391. List<string> args = new List<string>(cmd);
  392. args.RemoveAt(0);
  393. string[] cmdparams = args.ToArray();
  394. if (cmdparams.Length > 0)
  395. {
  396. string firstParam = cmdparams[0].ToLower();
  397. switch (firstParam)
  398. {
  399. case "set":
  400. if (cmdparams.Length < 4)
  401. {
  402. Notice("Syntax: config set <section> <key> <value>");
  403. Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5");
  404. }
  405. else
  406. {
  407. IConfig c;
  408. IConfigSource source = new IniConfigSource();
  409. c = source.AddConfig(cmdparams[1]);
  410. if (c != null)
  411. {
  412. string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
  413. c.Set(cmdparams[2], _value);
  414. Config.Merge(source);
  415. Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value);
  416. }
  417. }
  418. break;
  419. case "get":
  420. case "show":
  421. if (cmdparams.Length == 1)
  422. {
  423. foreach (IConfig config in Config.Configs)
  424. {
  425. Notice("[{0}]", config.Name);
  426. string[] keys = config.GetKeys();
  427. foreach (string key in keys)
  428. Notice(" {0} = {1}", key, config.GetString(key));
  429. }
  430. }
  431. else if (cmdparams.Length == 2 || cmdparams.Length == 3)
  432. {
  433. IConfig config = Config.Configs[cmdparams[1]];
  434. if (config == null)
  435. {
  436. Notice("Section \"{0}\" does not exist.",cmdparams[1]);
  437. break;
  438. }
  439. else
  440. {
  441. if (cmdparams.Length == 2)
  442. {
  443. Notice("[{0}]", config.Name);
  444. foreach (string key in config.GetKeys())
  445. Notice(" {0} = {1}", key, config.GetString(key));
  446. }
  447. else
  448. {
  449. Notice(
  450. "config get {0} {1} : {2}",
  451. cmdparams[1], cmdparams[2], config.GetString(cmdparams[2]));
  452. }
  453. }
  454. }
  455. else
  456. {
  457. Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
  458. Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
  459. }
  460. break;
  461. case "save":
  462. if (cmdparams.Length < 2)
  463. {
  464. Notice("Syntax: config save <path>");
  465. return;
  466. }
  467. string path = cmdparams[1];
  468. Notice("Saving configuration file: {0}", path);
  469. if (Config is IniConfigSource)
  470. {
  471. IniConfigSource iniCon = (IniConfigSource)Config;
  472. iniCon.Save(path);
  473. }
  474. else if (Config is XmlConfigSource)
  475. {
  476. XmlConfigSource xmlCon = (XmlConfigSource)Config;
  477. xmlCon.Save(path);
  478. }
  479. break;
  480. }
  481. }
  482. }
  483. private void HandleSetLogLevel(string module, string[] cmd)
  484. {
  485. if (cmd.Length != 4)
  486. {
  487. Notice("Usage: set log level <level>");
  488. return;
  489. }
  490. if (null == m_consoleAppender)
  491. {
  492. Notice("No appender named Console found (see the log4net config file for this executable)!");
  493. return;
  494. }
  495. string rawLevel = cmd[3];
  496. ILoggerRepository repository = LogManager.GetRepository();
  497. Level consoleLevel = repository.LevelMap[rawLevel];
  498. if (consoleLevel != null)
  499. m_consoleAppender.Threshold = consoleLevel;
  500. else
  501. Notice(
  502. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  503. rawLevel);
  504. ShowLogLevel();
  505. }
  506. private void ShowLogLevel()
  507. {
  508. Notice("Console log level is {0}", m_consoleAppender.Threshold);
  509. }
  510. protected virtual void HandleScript(string module, string[] parms)
  511. {
  512. if (parms.Length != 2)
  513. {
  514. Notice("Usage: command-script <path-to-script");
  515. return;
  516. }
  517. RunCommandScript(parms[1]);
  518. }
  519. /// <summary>
  520. /// Run an optional startup list of commands
  521. /// </summary>
  522. /// <param name="fileName"></param>
  523. protected void RunCommandScript(string fileName)
  524. {
  525. if (m_console == null)
  526. return;
  527. if (File.Exists(fileName))
  528. {
  529. m_log.Info("[SERVER BASE]: Running " + fileName);
  530. using (StreamReader readFile = File.OpenText(fileName))
  531. {
  532. string currentCommand;
  533. while ((currentCommand = readFile.ReadLine()) != null)
  534. {
  535. currentCommand = currentCommand.Trim();
  536. if (!(currentCommand == ""
  537. || currentCommand.StartsWith(";")
  538. || currentCommand.StartsWith("//")
  539. || currentCommand.StartsWith("#")))
  540. {
  541. m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
  542. m_console.RunCommand(currentCommand);
  543. }
  544. }
  545. }
  546. }
  547. }
  548. /// <summary>
  549. /// Return a report about the uptime of this server
  550. /// </summary>
  551. /// <returns></returns>
  552. protected string GetUptimeReport()
  553. {
  554. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  555. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  556. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  557. return sb.ToString();
  558. }
  559. protected void ShowInfo()
  560. {
  561. Notice(GetVersionText());
  562. Notice("Startup directory: " + m_startupDirectory);
  563. if (null != m_consoleAppender)
  564. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  565. }
  566. /// <summary>
  567. /// Enhance the version string with extra information if it's available.
  568. /// </summary>
  569. protected void EnhanceVersionInformation()
  570. {
  571. string buildVersion = string.Empty;
  572. // The subversion information is deprecated and will be removed at a later date
  573. // Add subversion revision information if available
  574. // Try file "svn_revision" in the current directory first, then the .svn info.
  575. // This allows to make the revision available in simulators not running from the source tree.
  576. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  577. // elsewhere as well
  578. string gitDir = "../.git/";
  579. string gitRefPointerPath = gitDir + "HEAD";
  580. string svnRevisionFileName = "svn_revision";
  581. string svnFileName = ".svn/entries";
  582. string manualVersionFileName = ".version";
  583. string inputLine;
  584. int strcmp;
  585. if (File.Exists(manualVersionFileName))
  586. {
  587. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  588. buildVersion = CommitFile.ReadLine();
  589. m_version += buildVersion ?? "";
  590. }
  591. else if (File.Exists(gitRefPointerPath))
  592. {
  593. // m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
  594. string rawPointer = "";
  595. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  596. rawPointer = pointerFile.ReadLine();
  597. // m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
  598. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  599. if (m.Success)
  600. {
  601. // m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
  602. string gitRef = m.Groups[1].Value;
  603. string gitRefPath = gitDir + gitRef;
  604. if (File.Exists(gitRefPath))
  605. {
  606. // m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
  607. using (StreamReader refFile = File.OpenText(gitRefPath))
  608. {
  609. string gitHash = refFile.ReadLine();
  610. m_version += gitHash.Substring(0, 7);
  611. }
  612. }
  613. }
  614. }
  615. else
  616. {
  617. // Remove the else logic when subversion mirror is no longer used
  618. if (File.Exists(svnRevisionFileName))
  619. {
  620. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  621. buildVersion = RevisionFile.ReadLine();
  622. buildVersion.Trim();
  623. RevisionFile.Close();
  624. }
  625. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  626. {
  627. StreamReader EntriesFile = File.OpenText(svnFileName);
  628. inputLine = EntriesFile.ReadLine();
  629. while (inputLine != null)
  630. {
  631. // using the dir svn revision at the top of entries file
  632. strcmp = String.Compare(inputLine, "dir");
  633. if (strcmp == 0)
  634. {
  635. buildVersion = EntriesFile.ReadLine();
  636. break;
  637. }
  638. else
  639. {
  640. inputLine = EntriesFile.ReadLine();
  641. }
  642. }
  643. EntriesFile.Close();
  644. }
  645. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  646. }
  647. }
  648. protected string GetVersionText()
  649. {
  650. return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
  651. }
  652. /// <summary>
  653. /// Get a report about the registered threads in this server.
  654. /// </summary>
  655. protected string GetThreadsReport()
  656. {
  657. // This should be a constant field.
  658. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
  659. StringBuilder sb = new StringBuilder();
  660. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
  661. sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
  662. int timeNow = Environment.TickCount & Int32.MaxValue;
  663. sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
  664. sb.Append(Environment.NewLine);
  665. foreach (Watchdog.ThreadWatchdogInfo twi in threads)
  666. {
  667. Thread t = twi.Thread;
  668. sb.AppendFormat(
  669. reportFormat,
  670. t.ManagedThreadId,
  671. t.Name,
  672. timeNow - twi.LastTick,
  673. timeNow - twi.FirstTick,
  674. t.Priority,
  675. t.ThreadState);
  676. sb.Append("\n");
  677. }
  678. sb.Append("\n");
  679. // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
  680. // zero active threads.
  681. int totalThreads = Process.GetCurrentProcess().Threads.Count;
  682. if (totalThreads > 0)
  683. sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
  684. sb.Append("Main threadpool (excluding script engine pools)\n");
  685. sb.Append(GetThreadPoolReport());
  686. return sb.ToString();
  687. }
  688. /// <summary>
  689. /// Get a thread pool report.
  690. /// </summary>
  691. /// <returns></returns>
  692. public static string GetThreadPoolReport()
  693. {
  694. string threadPoolUsed = null;
  695. int maxThreads = 0;
  696. int minThreads = 0;
  697. int allocatedThreads = 0;
  698. int inUseThreads = 0;
  699. int waitingCallbacks = 0;
  700. int completionPortThreads = 0;
  701. StringBuilder sb = new StringBuilder();
  702. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  703. {
  704. STPInfo stpi = Util.GetSmartThreadPoolInfo();
  705. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  706. if (stpi != null)
  707. {
  708. threadPoolUsed = "SmartThreadPool";
  709. maxThreads = stpi.MaxThreads;
  710. minThreads = stpi.MinThreads;
  711. inUseThreads = stpi.InUseThreads;
  712. allocatedThreads = stpi.ActiveThreads;
  713. waitingCallbacks = stpi.WaitingCallbacks;
  714. }
  715. }
  716. else if (
  717. Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
  718. || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  719. {
  720. threadPoolUsed = "BuiltInThreadPool";
  721. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  722. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  723. int availableThreads;
  724. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  725. inUseThreads = maxThreads - availableThreads;
  726. allocatedThreads = -1;
  727. waitingCallbacks = -1;
  728. }
  729. if (threadPoolUsed != null)
  730. {
  731. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  732. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  733. sb.AppendFormat("Min threads : {0}\n", minThreads);
  734. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  735. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  736. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  737. }
  738. else
  739. {
  740. sb.AppendFormat("Thread pool not used\n");
  741. }
  742. return sb.ToString();
  743. }
  744. public virtual void HandleThreadsAbort(string module, string[] cmd)
  745. {
  746. if (cmd.Length != 3)
  747. {
  748. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  749. return;
  750. }
  751. int threadId;
  752. if (!int.TryParse(cmd[2], out threadId))
  753. {
  754. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  755. return;
  756. }
  757. if (Watchdog.AbortThread(threadId))
  758. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  759. else
  760. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  761. }
  762. /// <summary>
  763. /// Console output is only possible if a console has been established.
  764. /// That is something that cannot be determined within this class. So
  765. /// all attempts to use the console MUST be verified.
  766. /// </summary>
  767. /// <param name="msg"></param>
  768. protected void Notice(string msg)
  769. {
  770. if (m_console != null)
  771. {
  772. m_console.Output(msg);
  773. }
  774. }
  775. /// <summary>
  776. /// Console output is only possible if a console has been established.
  777. /// That is something that cannot be determined within this class. So
  778. /// all attempts to use the console MUST be verified.
  779. /// </summary>
  780. /// <param name="format"></param>
  781. /// <param name="components"></param>
  782. protected void Notice(string format, params object[] components)
  783. {
  784. if (m_console != null)
  785. m_console.OutputFormat(format, components);
  786. }
  787. public virtual void Shutdown()
  788. {
  789. m_serverStatsCollector.Close();
  790. ShutdownSpecific();
  791. }
  792. /// <summary>
  793. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  794. /// </summary>
  795. protected virtual void ShutdownSpecific() {}
  796. }
  797. }