ServerBase.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. List<string> args = new List<string>(cmd);
  434. args.RemoveAt(0);
  435. string[] showParams = args.ToArray();
  436. switch (showParams[0])
  437. {
  438. case "info":
  439. ShowInfo();
  440. break;
  441. case "version":
  442. Notice(GetVersionText());
  443. break;
  444. case "uptime":
  445. Notice(GetUptimeReport());
  446. break;
  447. case "threads":
  448. Notice(GetThreadsReport());
  449. break;
  450. }
  451. }
  452. /// <summary>
  453. /// Change and load configuration file data.
  454. /// </summary>
  455. /// <param name="module"></param>
  456. /// <param name="cmd"></param>
  457. private void HandleConfig(string module, string[] cmd)
  458. {
  459. List<string> args = new List<string>(cmd);
  460. args.RemoveAt(0);
  461. string[] cmdparams = args.ToArray();
  462. if (cmdparams.Length > 0)
  463. {
  464. string firstParam = cmdparams[0].ToLower();
  465. switch (firstParam)
  466. {
  467. case "set":
  468. if (cmdparams.Length < 4)
  469. {
  470. Notice("Syntax: config set <section> <key> <value>");
  471. Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5");
  472. }
  473. else
  474. {
  475. IConfig c;
  476. IConfigSource source = new IniConfigSource();
  477. c = source.AddConfig(cmdparams[1]);
  478. if (c != null)
  479. {
  480. string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
  481. c.Set(cmdparams[2], _value);
  482. Config.Merge(source);
  483. Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value);
  484. }
  485. }
  486. break;
  487. case "get":
  488. case "show":
  489. if (cmdparams.Length == 1)
  490. {
  491. foreach (IConfig config in Config.Configs)
  492. {
  493. Notice("[{0}]", config.Name);
  494. string[] keys = config.GetKeys();
  495. foreach (string key in keys)
  496. Notice(" {0} = {1}", key, config.GetString(key));
  497. }
  498. }
  499. else if (cmdparams.Length == 2 || cmdparams.Length == 3)
  500. {
  501. IConfig config = Config.Configs[cmdparams[1]];
  502. if (config == null)
  503. {
  504. Notice("Section \"{0}\" does not exist.",cmdparams[1]);
  505. break;
  506. }
  507. else
  508. {
  509. if (cmdparams.Length == 2)
  510. {
  511. Notice("[{0}]", config.Name);
  512. foreach (string key in config.GetKeys())
  513. Notice(" {0} = {1}", key, config.GetString(key));
  514. }
  515. else
  516. {
  517. Notice(
  518. "config get {0} {1} : {2}",
  519. cmdparams[1], cmdparams[2], config.GetString(cmdparams[2]));
  520. }
  521. }
  522. }
  523. else
  524. {
  525. Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
  526. Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
  527. }
  528. break;
  529. case "save":
  530. if (cmdparams.Length < 2)
  531. {
  532. Notice("Syntax: config save <path>");
  533. return;
  534. }
  535. string path = cmdparams[1];
  536. Notice("Saving configuration file: {0}", path);
  537. if (Config is IniConfigSource)
  538. {
  539. IniConfigSource iniCon = (IniConfigSource)Config;
  540. iniCon.Save(path);
  541. }
  542. else if (Config is XmlConfigSource)
  543. {
  544. XmlConfigSource xmlCon = (XmlConfigSource)Config;
  545. xmlCon.Save(path);
  546. }
  547. break;
  548. }
  549. }
  550. }
  551. private void HandleSetLogLevel(string module, string[] cmd)
  552. {
  553. if (cmd.Length != 4)
  554. {
  555. Notice("Usage: set log level <level>");
  556. return;
  557. }
  558. if (null == m_consoleAppender)
  559. {
  560. Notice("No appender named Console found (see the log4net config file for this executable)!");
  561. return;
  562. }
  563. string rawLevel = cmd[3];
  564. ILoggerRepository repository = LogManager.GetRepository();
  565. Level consoleLevel = repository.LevelMap[rawLevel];
  566. if (consoleLevel != null)
  567. m_consoleAppender.Threshold = consoleLevel;
  568. else
  569. Notice(
  570. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  571. rawLevel);
  572. ShowLogLevel();
  573. }
  574. private void ShowLogLevel()
  575. {
  576. if (null == m_consoleAppender)
  577. {
  578. Notice("No appender named Console found (see the log4net config file for this executable)!");
  579. return;
  580. }
  581. Notice("Console log level is {0}", m_consoleAppender.Threshold);
  582. }
  583. protected virtual void HandleScript(string module, string[] parms)
  584. {
  585. if (parms.Length != 2)
  586. {
  587. Notice("Usage: command-script <path-to-script");
  588. return;
  589. }
  590. RunCommandScript(parms[1]);
  591. }
  592. /// <summary>
  593. /// Run an optional startup list of commands
  594. /// </summary>
  595. /// <param name="fileName"></param>
  596. protected void RunCommandScript(string fileName)
  597. {
  598. if (m_console == null)
  599. return;
  600. if (File.Exists(fileName))
  601. {
  602. m_log.Info("[SERVER BASE]: Running " + fileName);
  603. using (StreamReader readFile = File.OpenText(fileName))
  604. {
  605. string currentCommand;
  606. while ((currentCommand = readFile.ReadLine()) != null)
  607. {
  608. currentCommand = currentCommand.Trim();
  609. if (!(currentCommand == ""
  610. || currentCommand.StartsWith(";")
  611. || currentCommand.StartsWith("//")
  612. || currentCommand.StartsWith("#")))
  613. {
  614. m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
  615. m_console.RunCommand(currentCommand);
  616. }
  617. }
  618. }
  619. }
  620. }
  621. /// <summary>
  622. /// Return a report about the uptime of this server
  623. /// </summary>
  624. /// <returns></returns>
  625. protected string GetUptimeReport()
  626. {
  627. StringBuilder sb = new StringBuilder(512);
  628. sb.AppendFormat("Time now is {0}\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  629. sb.AppendFormat("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime.ToString("yyyy-MM-dd HH:mm:ss"));
  630. sb.AppendFormat("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime);
  631. return sb.ToString();
  632. }
  633. protected void ShowInfo()
  634. {
  635. Notice(GetVersionText());
  636. Notice("Startup directory: " + m_startupDirectory);
  637. if (null != m_consoleAppender)
  638. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  639. }
  640. /// <summary>
  641. /// Enhance the version string with extra information if it's available.
  642. /// </summary>
  643. protected void EnhanceVersionInformation()
  644. {
  645. string buildVersion = string.Empty;
  646. string manualVersionFileName = ".version";
  647. string gitDir = "../.git/";
  648. string gitRefPointerPath = gitDir + "HEAD";
  649. if (File.Exists(manualVersionFileName))
  650. {
  651. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  652. buildVersion = CommitFile.ReadLine();
  653. m_version += buildVersion ?? "";
  654. }
  655. else if (File.Exists(gitRefPointerPath))
  656. {
  657. // m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
  658. string rawPointer = "";
  659. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  660. rawPointer = pointerFile.ReadLine();
  661. // m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
  662. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  663. if (m.Success)
  664. {
  665. // m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
  666. string gitRef = m.Groups[1].Value;
  667. string gitRefPath = gitDir + gitRef;
  668. if (File.Exists(gitRefPath))
  669. {
  670. // m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
  671. using (StreamReader refFile = File.OpenText(gitRefPath))
  672. {
  673. string gitHash = refFile.ReadLine();
  674. m_version += gitHash.Substring(0, 7);
  675. }
  676. }
  677. }
  678. }
  679. }
  680. public string GetVersionText()
  681. {
  682. return String.Format("Version: {0} (SIMULATION/{1} - SIMULATION/{2})",
  683. m_version, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax);
  684. }
  685. /// <summary>
  686. /// Get a report about the registered threads in this server.
  687. /// </summary>
  688. protected string GetThreadsReport()
  689. {
  690. // This should be a constant field.
  691. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
  692. StringBuilder sb = new StringBuilder();
  693. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
  694. sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
  695. int timeNow = Environment.TickCount & Int32.MaxValue;
  696. sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
  697. sb.Append(Environment.NewLine);
  698. foreach (Watchdog.ThreadWatchdogInfo twi in threads)
  699. {
  700. Thread t = twi.Thread;
  701. sb.AppendFormat(
  702. reportFormat,
  703. t.ManagedThreadId,
  704. t.Name,
  705. timeNow - twi.LastTick,
  706. timeNow - twi.FirstTick,
  707. t.Priority,
  708. t.ThreadState);
  709. sb.Append("\n");
  710. }
  711. sb.Append(GetThreadPoolReport());
  712. sb.Append("\n");
  713. int totalThreads = Process.GetCurrentProcess().Threads.Count;
  714. if (totalThreads > 0)
  715. sb.AppendFormat("Total process threads active: {0}\n\n", totalThreads);
  716. return sb.ToString();
  717. }
  718. /// <summary>
  719. /// Get a thread pool report.
  720. /// </summary>
  721. /// <returns></returns>
  722. public static string GetThreadPoolReport()
  723. {
  724. StringBuilder sb = new StringBuilder();
  725. // framework pool is alwasy active
  726. int maxWorkers;
  727. int minWorkers;
  728. int curWorkers;
  729. int maxComp;
  730. int minComp;
  731. int curComp;
  732. try
  733. {
  734. ThreadPool.GetMaxThreads(out maxWorkers, out maxComp);
  735. ThreadPool.GetMinThreads(out minWorkers, out minComp);
  736. ThreadPool.GetAvailableThreads(out curWorkers, out curComp);
  737. curWorkers = maxWorkers - curWorkers;
  738. curComp = maxComp - curComp;
  739. sb.Append("\nFramework main threadpool \n");
  740. sb.AppendFormat("workers: {0} ({1} / {2})\n", curWorkers, maxWorkers, minWorkers);
  741. sb.AppendFormat("Completion: {0} ({1} / {2})\n", curComp, maxComp, minComp);
  742. }
  743. catch { }
  744. if (Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem)
  745. {
  746. sb.AppendFormat("\nThread pool used: Framework main threadpool\n");
  747. return sb.ToString();
  748. }
  749. string threadPoolUsed = null;
  750. int maxThreads = 0;
  751. int minThreads = 0;
  752. int allocatedThreads = 0;
  753. int inUseThreads = 0;
  754. int waitingCallbacks = 0;
  755. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  756. {
  757. STPInfo stpi = Util.GetSmartThreadPoolInfo();
  758. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  759. if (stpi != null)
  760. {
  761. threadPoolUsed = "SmartThreadPool";
  762. maxThreads = stpi.MaxThreads;
  763. minThreads = stpi.MinThreads;
  764. inUseThreads = stpi.InUseThreads;
  765. allocatedThreads = stpi.ActiveThreads;
  766. waitingCallbacks = stpi.WaitingCallbacks;
  767. }
  768. }
  769. if (threadPoolUsed != null)
  770. {
  771. sb.Append("\nThreadpool (excluding script engine pools)\n");
  772. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  773. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  774. sb.AppendFormat("Min threads : {0}\n", minThreads);
  775. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  776. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  777. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  778. }
  779. else
  780. {
  781. sb.AppendFormat("Thread pool not used\n");
  782. }
  783. return sb.ToString();
  784. }
  785. public virtual void HandleThreadsAbort(string module, string[] cmd)
  786. {
  787. if (cmd.Length != 3)
  788. {
  789. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  790. return;
  791. }
  792. int threadId;
  793. if (!int.TryParse(cmd[2], out threadId))
  794. {
  795. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  796. return;
  797. }
  798. if (Watchdog.AbortThread(threadId))
  799. MainConsole.Instance.Output("Aborted thread with id {0}", threadId);
  800. else
  801. MainConsole.Instance.Output("ERROR - Thread with id {0} not found in managed threads", threadId);
  802. }
  803. /// <summary>
  804. /// Console output is only possible if a console has been established.
  805. /// That is something that cannot be determined within this class. So
  806. /// all attempts to use the console MUST be verified.
  807. /// </summary>
  808. /// <param name="msg"></param>
  809. protected void Notice(string msg)
  810. {
  811. if (m_console != null)
  812. {
  813. m_console.Output(msg);
  814. }
  815. }
  816. /// <summary>
  817. /// Console output is only possible if a console has been established.
  818. /// That is something that cannot be determined within this class. So
  819. /// all attempts to use the console MUST be verified.
  820. /// </summary>
  821. /// <param name="format"></param>
  822. /// <param name="components"></param>
  823. protected void Notice(string format, params object[] components)
  824. {
  825. if (m_console != null)
  826. m_console.Output(format, components);
  827. }
  828. public virtual void Shutdown()
  829. {
  830. m_serverStatsCollector.Close();
  831. ShutdownSpecific();
  832. }
  833. /// <summary>
  834. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  835. /// </summary>
  836. protected virtual void ShutdownSpecific() {}
  837. }
  838. }