ServerBase.cs 38 KB

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