ServerBase.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. public string GetVersionText()
  732. {
  733. return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
  734. }
  735. /// <summary>
  736. /// Get a report about the registered threads in this server.
  737. /// </summary>
  738. protected string GetThreadsReport()
  739. {
  740. // This should be a constant field.
  741. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
  742. StringBuilder sb = new StringBuilder();
  743. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
  744. sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
  745. int timeNow = Environment.TickCount & Int32.MaxValue;
  746. sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
  747. sb.Append(Environment.NewLine);
  748. foreach (Watchdog.ThreadWatchdogInfo twi in threads)
  749. {
  750. Thread t = twi.Thread;
  751. sb.AppendFormat(
  752. reportFormat,
  753. t.ManagedThreadId,
  754. t.Name,
  755. timeNow - twi.LastTick,
  756. timeNow - twi.FirstTick,
  757. t.Priority,
  758. t.ThreadState);
  759. sb.Append("\n");
  760. }
  761. sb.Append("\n");
  762. // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
  763. // zero active threads.
  764. int totalThreads = Process.GetCurrentProcess().Threads.Count;
  765. if (totalThreads > 0)
  766. sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
  767. sb.Append("Main threadpool (excluding script engine pools)\n");
  768. sb.Append(GetThreadPoolReport());
  769. return sb.ToString();
  770. }
  771. /// <summary>
  772. /// Get a thread pool report.
  773. /// </summary>
  774. /// <returns></returns>
  775. public static string GetThreadPoolReport()
  776. {
  777. string threadPoolUsed = null;
  778. int maxThreads = 0;
  779. int minThreads = 0;
  780. int allocatedThreads = 0;
  781. int inUseThreads = 0;
  782. int waitingCallbacks = 0;
  783. int completionPortThreads = 0;
  784. StringBuilder sb = new StringBuilder();
  785. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  786. {
  787. STPInfo stpi = Util.GetSmartThreadPoolInfo();
  788. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  789. if (stpi != null)
  790. {
  791. threadPoolUsed = "SmartThreadPool";
  792. maxThreads = stpi.MaxThreads;
  793. minThreads = stpi.MinThreads;
  794. inUseThreads = stpi.InUseThreads;
  795. allocatedThreads = stpi.ActiveThreads;
  796. waitingCallbacks = stpi.WaitingCallbacks;
  797. }
  798. }
  799. else if (
  800. Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
  801. || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  802. {
  803. threadPoolUsed = "BuiltInThreadPool";
  804. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  805. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  806. int availableThreads;
  807. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  808. inUseThreads = maxThreads - availableThreads;
  809. allocatedThreads = -1;
  810. waitingCallbacks = -1;
  811. }
  812. if (threadPoolUsed != null)
  813. {
  814. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  815. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  816. sb.AppendFormat("Min threads : {0}\n", minThreads);
  817. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  818. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  819. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  820. }
  821. else
  822. {
  823. sb.AppendFormat("Thread pool not used\n");
  824. }
  825. return sb.ToString();
  826. }
  827. public virtual void HandleThreadsAbort(string module, string[] cmd)
  828. {
  829. if (cmd.Length != 3)
  830. {
  831. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  832. return;
  833. }
  834. int threadId;
  835. if (!int.TryParse(cmd[2], out threadId))
  836. {
  837. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  838. return;
  839. }
  840. if (Watchdog.AbortThread(threadId))
  841. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  842. else
  843. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  844. }
  845. /// <summary>
  846. /// Console output is only possible if a console has been established.
  847. /// That is something that cannot be determined within this class. So
  848. /// all attempts to use the console MUST be verified.
  849. /// </summary>
  850. /// <param name="msg"></param>
  851. protected void Notice(string msg)
  852. {
  853. if (m_console != null)
  854. {
  855. m_console.Output(msg);
  856. }
  857. }
  858. /// <summary>
  859. /// Console output is only possible if a console has been established.
  860. /// That is something that cannot be determined within this class. So
  861. /// all attempts to use the console MUST be verified.
  862. /// </summary>
  863. /// <param name="format"></param>
  864. /// <param name="components"></param>
  865. protected void Notice(string format, params object[] components)
  866. {
  867. if (m_console != null)
  868. m_console.OutputFormat(format, components);
  869. }
  870. public virtual void Shutdown()
  871. {
  872. m_serverStatsCollector.Close();
  873. ShutdownSpecific();
  874. }
  875. /// <summary>
  876. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  877. /// </summary>
  878. protected virtual void ShutdownSpecific() {}
  879. }
  880. }