ServerBase.cs 41 KB

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