ServerBase.cs 41 KB

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