ServerBase.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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, "debug threadpool level",
  239. "debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL,
  240. "Turn on logging of activity in the main thread pool.",
  241. "Log levels:\n"
  242. + " 0 = no logging\n"
  243. + " 1 = only first line of stack trace; don't log common threads\n"
  244. + " 2 = full stack trace; don't log common threads\n"
  245. + " 3 = full stack trace, including common threads\n",
  246. HandleDebugThreadpoolLevel);
  247. m_console.Commands.AddCommand(
  248. "Debug", false, "force gc",
  249. "force gc",
  250. "Manually invoke runtime garbage collection. For debugging purposes",
  251. HandleForceGc);
  252. m_console.Commands.AddCommand(
  253. "General", false, "quit",
  254. "quit",
  255. "Quit the application", (mod, args) => Shutdown());
  256. m_console.Commands.AddCommand(
  257. "General", false, "shutdown",
  258. "shutdown",
  259. "Quit the application", (mod, args) => Shutdown());
  260. ChecksManager.RegisterConsoleCommands(m_console);
  261. StatsManager.RegisterConsoleCommands(m_console);
  262. }
  263. public void RegisterCommonComponents(IConfigSource configSource)
  264. {
  265. IConfig networkConfig = configSource.Configs["Network"];
  266. if (networkConfig != null)
  267. {
  268. WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false);
  269. }
  270. m_serverStatsCollector = new ServerStatsCollector();
  271. m_serverStatsCollector.Initialise(configSource);
  272. m_serverStatsCollector.Start();
  273. }
  274. private void HandleDebugCommsStatus(string module, string[] args)
  275. {
  276. Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint);
  277. }
  278. private void HandleDebugCommsSet(string module, string[] args)
  279. {
  280. if (args.Length != 5)
  281. {
  282. Notice("Usage: debug comms set serialosdreq true|false");
  283. return;
  284. }
  285. if (args[3] != "serialosdreq")
  286. {
  287. Notice("Usage: debug comms set serialosdreq true|false");
  288. return;
  289. }
  290. bool setSerializeOsdRequests;
  291. if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests))
  292. return;
  293. WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests;
  294. Notice("serialosdreq is now {0}", setSerializeOsdRequests);
  295. }
  296. private void HandleDebugThreadpoolStatus(string module, string[] args)
  297. {
  298. int workerThreads, iocpThreads;
  299. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  300. Notice("Min worker threads: {0}", workerThreads);
  301. Notice("Min IOCP threads: {0}", iocpThreads);
  302. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  303. Notice("Max worker threads: {0}", workerThreads);
  304. Notice("Max IOCP threads: {0}", iocpThreads);
  305. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  306. Notice("Available worker threads: {0}", workerThreads);
  307. Notice("Available IOCP threads: {0}", iocpThreads);
  308. }
  309. private void HandleDebugThreadpoolSet(string module, string[] args)
  310. {
  311. if (args.Length != 6)
  312. {
  313. Notice("Usage: debug threadpool set worker|iocp min|max <n>");
  314. return;
  315. }
  316. int newThreads;
  317. if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
  318. return;
  319. string poolType = args[3];
  320. string bound = args[4];
  321. bool fail = false;
  322. int workerThreads, iocpThreads;
  323. if (poolType == "worker")
  324. {
  325. if (bound == "min")
  326. {
  327. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  328. if (!ThreadPool.SetMinThreads(newThreads, iocpThreads))
  329. fail = true;
  330. }
  331. else
  332. {
  333. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  334. if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads))
  335. fail = true;
  336. }
  337. }
  338. else
  339. {
  340. if (bound == "min")
  341. {
  342. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  343. if (!ThreadPool.SetMinThreads(workerThreads, newThreads))
  344. fail = true;
  345. }
  346. else
  347. {
  348. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  349. if (!ThreadPool.SetMaxThreads(workerThreads, newThreads))
  350. fail = true;
  351. }
  352. }
  353. if (fail)
  354. {
  355. Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads);
  356. }
  357. else
  358. {
  359. int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;
  360. ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
  361. ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);
  362. Notice("Min worker threads now {0}", minWorkerThreads);
  363. Notice("Min IOCP threads now {0}", minIocpThreads);
  364. Notice("Max worker threads now {0}", maxWorkerThreads);
  365. Notice("Max IOCP threads now {0}", maxIocpThreads);
  366. }
  367. }
  368. private static void HandleDebugThreadpoolLevel(string module, string[] cmdparams)
  369. {
  370. if (cmdparams.Length < 4)
  371. {
  372. MainConsole.Instance.Output("Usage: debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL);
  373. return;
  374. }
  375. string rawLevel = cmdparams[3];
  376. int newLevel;
  377. if (!int.TryParse(rawLevel, out newLevel))
  378. {
  379. MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawLevel);
  380. return;
  381. }
  382. if (newLevel < 0 || newLevel > Util.MAX_THREADPOOL_LEVEL)
  383. {
  384. MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0.." + Util.MAX_THREADPOOL_LEVEL, newLevel);
  385. return;
  386. }
  387. Util.LogThreadPool = newLevel;
  388. MainConsole.Instance.OutputFormat("LogThreadPool set to {0}", newLevel);
  389. }
  390. private void HandleForceGc(string module, string[] args)
  391. {
  392. Notice("Manually invoking runtime garbage collection");
  393. GC.Collect();
  394. }
  395. public virtual void HandleShow(string module, string[] cmd)
  396. {
  397. List<string> args = new List<string>(cmd);
  398. args.RemoveAt(0);
  399. string[] showParams = args.ToArray();
  400. switch (showParams[0])
  401. {
  402. case "info":
  403. ShowInfo();
  404. break;
  405. case "version":
  406. Notice(GetVersionText());
  407. break;
  408. case "uptime":
  409. Notice(GetUptimeReport());
  410. break;
  411. case "threads":
  412. Notice(GetThreadsReport());
  413. break;
  414. }
  415. }
  416. /// <summary>
  417. /// Change and load configuration file data.
  418. /// </summary>
  419. /// <param name="module"></param>
  420. /// <param name="cmd"></param>
  421. private void HandleConfig(string module, string[] cmd)
  422. {
  423. List<string> args = new List<string>(cmd);
  424. args.RemoveAt(0);
  425. string[] cmdparams = args.ToArray();
  426. if (cmdparams.Length > 0)
  427. {
  428. string firstParam = cmdparams[0].ToLower();
  429. switch (firstParam)
  430. {
  431. case "set":
  432. if (cmdparams.Length < 4)
  433. {
  434. Notice("Syntax: config set <section> <key> <value>");
  435. Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5");
  436. }
  437. else
  438. {
  439. IConfig c;
  440. IConfigSource source = new IniConfigSource();
  441. c = source.AddConfig(cmdparams[1]);
  442. if (c != null)
  443. {
  444. string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
  445. c.Set(cmdparams[2], _value);
  446. Config.Merge(source);
  447. Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value);
  448. }
  449. }
  450. break;
  451. case "get":
  452. case "show":
  453. if (cmdparams.Length == 1)
  454. {
  455. foreach (IConfig config in Config.Configs)
  456. {
  457. Notice("[{0}]", config.Name);
  458. string[] keys = config.GetKeys();
  459. foreach (string key in keys)
  460. Notice(" {0} = {1}", key, config.GetString(key));
  461. }
  462. }
  463. else if (cmdparams.Length == 2 || cmdparams.Length == 3)
  464. {
  465. IConfig config = Config.Configs[cmdparams[1]];
  466. if (config == null)
  467. {
  468. Notice("Section \"{0}\" does not exist.",cmdparams[1]);
  469. break;
  470. }
  471. else
  472. {
  473. if (cmdparams.Length == 2)
  474. {
  475. Notice("[{0}]", config.Name);
  476. foreach (string key in config.GetKeys())
  477. Notice(" {0} = {1}", key, config.GetString(key));
  478. }
  479. else
  480. {
  481. Notice(
  482. "config get {0} {1} : {2}",
  483. cmdparams[1], cmdparams[2], config.GetString(cmdparams[2]));
  484. }
  485. }
  486. }
  487. else
  488. {
  489. Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
  490. Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
  491. }
  492. break;
  493. case "save":
  494. if (cmdparams.Length < 2)
  495. {
  496. Notice("Syntax: config save <path>");
  497. return;
  498. }
  499. string path = cmdparams[1];
  500. Notice("Saving configuration file: {0}", path);
  501. if (Config is IniConfigSource)
  502. {
  503. IniConfigSource iniCon = (IniConfigSource)Config;
  504. iniCon.Save(path);
  505. }
  506. else if (Config is XmlConfigSource)
  507. {
  508. XmlConfigSource xmlCon = (XmlConfigSource)Config;
  509. xmlCon.Save(path);
  510. }
  511. break;
  512. }
  513. }
  514. }
  515. private void HandleSetLogLevel(string module, string[] cmd)
  516. {
  517. if (cmd.Length != 4)
  518. {
  519. Notice("Usage: set log level <level>");
  520. return;
  521. }
  522. if (null == m_consoleAppender)
  523. {
  524. Notice("No appender named Console found (see the log4net config file for this executable)!");
  525. return;
  526. }
  527. string rawLevel = cmd[3];
  528. ILoggerRepository repository = LogManager.GetRepository();
  529. Level consoleLevel = repository.LevelMap[rawLevel];
  530. if (consoleLevel != null)
  531. m_consoleAppender.Threshold = consoleLevel;
  532. else
  533. Notice(
  534. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  535. rawLevel);
  536. ShowLogLevel();
  537. }
  538. private void ShowLogLevel()
  539. {
  540. Notice("Console log level is {0}", m_consoleAppender.Threshold);
  541. }
  542. protected virtual void HandleScript(string module, string[] parms)
  543. {
  544. if (parms.Length != 2)
  545. {
  546. Notice("Usage: command-script <path-to-script");
  547. return;
  548. }
  549. RunCommandScript(parms[1]);
  550. }
  551. /// <summary>
  552. /// Run an optional startup list of commands
  553. /// </summary>
  554. /// <param name="fileName"></param>
  555. protected void RunCommandScript(string fileName)
  556. {
  557. if (m_console == null)
  558. return;
  559. if (File.Exists(fileName))
  560. {
  561. m_log.Info("[SERVER BASE]: Running " + fileName);
  562. using (StreamReader readFile = File.OpenText(fileName))
  563. {
  564. string currentCommand;
  565. while ((currentCommand = readFile.ReadLine()) != null)
  566. {
  567. currentCommand = currentCommand.Trim();
  568. if (!(currentCommand == ""
  569. || currentCommand.StartsWith(";")
  570. || currentCommand.StartsWith("//")
  571. || currentCommand.StartsWith("#")))
  572. {
  573. m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
  574. m_console.RunCommand(currentCommand);
  575. }
  576. }
  577. }
  578. }
  579. }
  580. /// <summary>
  581. /// Return a report about the uptime of this server
  582. /// </summary>
  583. /// <returns></returns>
  584. protected string GetUptimeReport()
  585. {
  586. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  587. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  588. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  589. return sb.ToString();
  590. }
  591. protected void ShowInfo()
  592. {
  593. Notice(GetVersionText());
  594. Notice("Startup directory: " + m_startupDirectory);
  595. if (null != m_consoleAppender)
  596. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  597. }
  598. /// <summary>
  599. /// Enhance the version string with extra information if it's available.
  600. /// </summary>
  601. protected void EnhanceVersionInformation()
  602. {
  603. string buildVersion = string.Empty;
  604. // The subversion information is deprecated and will be removed at a later date
  605. // Add subversion revision information if available
  606. // Try file "svn_revision" in the current directory first, then the .svn info.
  607. // This allows to make the revision available in simulators not running from the source tree.
  608. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  609. // elsewhere as well
  610. string gitDir = "../.git/";
  611. string gitRefPointerPath = gitDir + "HEAD";
  612. string svnRevisionFileName = "svn_revision";
  613. string svnFileName = ".svn/entries";
  614. string manualVersionFileName = ".version";
  615. string inputLine;
  616. int strcmp;
  617. if (File.Exists(manualVersionFileName))
  618. {
  619. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  620. buildVersion = CommitFile.ReadLine();
  621. m_version += buildVersion ?? "";
  622. }
  623. else if (File.Exists(gitRefPointerPath))
  624. {
  625. // m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
  626. string rawPointer = "";
  627. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  628. rawPointer = pointerFile.ReadLine();
  629. // m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
  630. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  631. if (m.Success)
  632. {
  633. // m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
  634. string gitRef = m.Groups[1].Value;
  635. string gitRefPath = gitDir + gitRef;
  636. if (File.Exists(gitRefPath))
  637. {
  638. // m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
  639. using (StreamReader refFile = File.OpenText(gitRefPath))
  640. {
  641. string gitHash = refFile.ReadLine();
  642. m_version += gitHash.Substring(0, 7);
  643. }
  644. }
  645. }
  646. }
  647. else
  648. {
  649. // Remove the else logic when subversion mirror is no longer used
  650. if (File.Exists(svnRevisionFileName))
  651. {
  652. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  653. buildVersion = RevisionFile.ReadLine();
  654. buildVersion.Trim();
  655. RevisionFile.Close();
  656. }
  657. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  658. {
  659. StreamReader EntriesFile = File.OpenText(svnFileName);
  660. inputLine = EntriesFile.ReadLine();
  661. while (inputLine != null)
  662. {
  663. // using the dir svn revision at the top of entries file
  664. strcmp = String.Compare(inputLine, "dir");
  665. if (strcmp == 0)
  666. {
  667. buildVersion = EntriesFile.ReadLine();
  668. break;
  669. }
  670. else
  671. {
  672. inputLine = EntriesFile.ReadLine();
  673. }
  674. }
  675. EntriesFile.Close();
  676. }
  677. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  678. }
  679. }
  680. protected string GetVersionText()
  681. {
  682. return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
  683. }
  684. /// <summary>
  685. /// Get a report about the registered threads in this server.
  686. /// </summary>
  687. protected string GetThreadsReport()
  688. {
  689. // This should be a constant field.
  690. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
  691. StringBuilder sb = new StringBuilder();
  692. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
  693. sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
  694. int timeNow = Environment.TickCount & Int32.MaxValue;
  695. sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
  696. sb.Append(Environment.NewLine);
  697. foreach (Watchdog.ThreadWatchdogInfo twi in threads)
  698. {
  699. Thread t = twi.Thread;
  700. sb.AppendFormat(
  701. reportFormat,
  702. t.ManagedThreadId,
  703. t.Name,
  704. timeNow - twi.LastTick,
  705. timeNow - twi.FirstTick,
  706. t.Priority,
  707. t.ThreadState);
  708. sb.Append("\n");
  709. }
  710. sb.Append("\n");
  711. // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
  712. // zero active threads.
  713. int totalThreads = Process.GetCurrentProcess().Threads.Count;
  714. if (totalThreads > 0)
  715. sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
  716. sb.Append("Main threadpool (excluding script engine pools)\n");
  717. sb.Append(GetThreadPoolReport());
  718. return sb.ToString();
  719. }
  720. /// <summary>
  721. /// Get a thread pool report.
  722. /// </summary>
  723. /// <returns></returns>
  724. public static string GetThreadPoolReport()
  725. {
  726. string threadPoolUsed = null;
  727. int maxThreads = 0;
  728. int minThreads = 0;
  729. int allocatedThreads = 0;
  730. int inUseThreads = 0;
  731. int waitingCallbacks = 0;
  732. int completionPortThreads = 0;
  733. StringBuilder sb = new StringBuilder();
  734. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  735. {
  736. STPInfo stpi = Util.GetSmartThreadPoolInfo();
  737. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  738. if (stpi != null)
  739. {
  740. threadPoolUsed = "SmartThreadPool";
  741. maxThreads = stpi.MaxThreads;
  742. minThreads = stpi.MinThreads;
  743. inUseThreads = stpi.InUseThreads;
  744. allocatedThreads = stpi.ActiveThreads;
  745. waitingCallbacks = stpi.WaitingCallbacks;
  746. }
  747. }
  748. else if (
  749. Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
  750. || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  751. {
  752. threadPoolUsed = "BuiltInThreadPool";
  753. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  754. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  755. int availableThreads;
  756. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  757. inUseThreads = maxThreads - availableThreads;
  758. allocatedThreads = -1;
  759. waitingCallbacks = -1;
  760. }
  761. if (threadPoolUsed != null)
  762. {
  763. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  764. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  765. sb.AppendFormat("Min threads : {0}\n", minThreads);
  766. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  767. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  768. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  769. }
  770. else
  771. {
  772. sb.AppendFormat("Thread pool not used\n");
  773. }
  774. return sb.ToString();
  775. }
  776. public virtual void HandleThreadsAbort(string module, string[] cmd)
  777. {
  778. if (cmd.Length != 3)
  779. {
  780. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  781. return;
  782. }
  783. int threadId;
  784. if (!int.TryParse(cmd[2], out threadId))
  785. {
  786. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  787. return;
  788. }
  789. if (Watchdog.AbortThread(threadId))
  790. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  791. else
  792. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  793. }
  794. /// <summary>
  795. /// Console output is only possible if a console has been established.
  796. /// That is something that cannot be determined within this class. So
  797. /// all attempts to use the console MUST be verified.
  798. /// </summary>
  799. /// <param name="msg"></param>
  800. protected void Notice(string msg)
  801. {
  802. if (m_console != null)
  803. {
  804. m_console.Output(msg);
  805. }
  806. }
  807. /// <summary>
  808. /// Console output is only possible if a console has been established.
  809. /// That is something that cannot be determined within this class. So
  810. /// all attempts to use the console MUST be verified.
  811. /// </summary>
  812. /// <param name="format"></param>
  813. /// <param name="components"></param>
  814. protected void Notice(string format, params object[] components)
  815. {
  816. if (m_console != null)
  817. m_console.OutputFormat(format, components);
  818. }
  819. public virtual void Shutdown()
  820. {
  821. m_serverStatsCollector.Close();
  822. ShutdownSpecific();
  823. }
  824. /// <summary>
  825. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  826. /// </summary>
  827. protected virtual void ShutdownSpecific() {}
  828. }
  829. }