ServerBase.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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, Util.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. ChecksManager.RegisterConsoleCommands(m_console);
  278. StatsManager.RegisterConsoleCommands(m_console);
  279. }
  280. public void RegisterCommonComponents(IConfigSource configSource)
  281. {
  282. // IConfig networkConfig = configSource.Configs["Network"];
  283. m_serverStatsCollector = new ServerStatsCollector();
  284. m_serverStatsCollector.Initialise(configSource);
  285. m_serverStatsCollector.Start();
  286. }
  287. private void HandleShowThreadpoolCallsActive(string module, string[] args)
  288. {
  289. List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsInProgress().ToList();
  290. calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value));
  291. int namedCalls = 0;
  292. ConsoleDisplayList cdl = new ConsoleDisplayList();
  293. foreach (KeyValuePair<string, int> kvp in calls)
  294. {
  295. if (kvp.Value > 0)
  296. {
  297. cdl.AddRow(kvp.Key, kvp.Value);
  298. namedCalls += kvp.Value;
  299. }
  300. }
  301. cdl.AddRow("TOTAL NAMED", namedCalls);
  302. long allQueuedCalls = Util.TotalQueuedFireAndForgetCalls;
  303. long allRunningCalls = Util.TotalRunningFireAndForgetCalls;
  304. cdl.AddRow("TOTAL QUEUED", allQueuedCalls);
  305. cdl.AddRow("TOTAL RUNNING", allRunningCalls);
  306. cdl.AddRow("TOTAL ANONYMOUS", allQueuedCalls + allRunningCalls - namedCalls);
  307. cdl.AddRow("TOTAL ALL", allQueuedCalls + allRunningCalls);
  308. MainConsole.Instance.Output(cdl.ToString());
  309. }
  310. private void HandleShowThreadpoolCallsComplete(string module, string[] args)
  311. {
  312. List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsMade().ToList();
  313. calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value));
  314. int namedCallsMade = 0;
  315. ConsoleDisplayList cdl = new ConsoleDisplayList();
  316. foreach (KeyValuePair<string, int> kvp in calls)
  317. {
  318. cdl.AddRow(kvp.Key, kvp.Value);
  319. namedCallsMade += kvp.Value;
  320. }
  321. cdl.AddRow("TOTAL NAMED", namedCallsMade);
  322. long allCallsMade = Util.TotalFireAndForgetCallsMade;
  323. cdl.AddRow("TOTAL ANONYMOUS", allCallsMade - namedCallsMade);
  324. cdl.AddRow("TOTAL ALL", allCallsMade);
  325. MainConsole.Instance.Output(cdl.ToString());
  326. }
  327. private void HandleDebugThreadpoolStatus(string module, string[] args)
  328. {
  329. int workerThreads, iocpThreads;
  330. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  331. Notice("Min worker threads: {0}", workerThreads);
  332. Notice("Min IOCP threads: {0}", iocpThreads);
  333. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  334. Notice("Max worker threads: {0}", workerThreads);
  335. Notice("Max IOCP threads: {0}", iocpThreads);
  336. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  337. Notice("Available worker threads: {0}", workerThreads);
  338. Notice("Available IOCP threads: {0}", iocpThreads);
  339. }
  340. private void HandleDebugThreadpoolSet(string module, string[] args)
  341. {
  342. if (args.Length != 6)
  343. {
  344. Notice("Usage: debug threadpool set worker|iocp min|max <n>");
  345. return;
  346. }
  347. int newThreads;
  348. if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
  349. return;
  350. string poolType = args[3];
  351. string bound = args[4];
  352. bool fail = false;
  353. int workerThreads, iocpThreads;
  354. if (poolType == "worker")
  355. {
  356. if (bound == "min")
  357. {
  358. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  359. if (!ThreadPool.SetMinThreads(newThreads, iocpThreads))
  360. fail = true;
  361. }
  362. else
  363. {
  364. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  365. if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads))
  366. fail = true;
  367. }
  368. }
  369. else
  370. {
  371. if (bound == "min")
  372. {
  373. ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
  374. if (!ThreadPool.SetMinThreads(workerThreads, newThreads))
  375. fail = true;
  376. }
  377. else
  378. {
  379. ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
  380. if (!ThreadPool.SetMaxThreads(workerThreads, newThreads))
  381. fail = true;
  382. }
  383. }
  384. if (fail)
  385. {
  386. Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads);
  387. }
  388. else
  389. {
  390. int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;
  391. ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
  392. ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);
  393. Notice("Min worker threads now {0}", minWorkerThreads);
  394. Notice("Min IOCP threads now {0}", minIocpThreads);
  395. Notice("Max worker threads now {0}", maxWorkerThreads);
  396. Notice("Max IOCP threads now {0}", maxIocpThreads);
  397. }
  398. }
  399. private static void HandleDebugThreadpoolLevel(string module, string[] cmdparams)
  400. {
  401. if (cmdparams.Length < 4)
  402. {
  403. MainConsole.Instance.Output("Usage: debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL);
  404. return;
  405. }
  406. string rawLevel = cmdparams[3];
  407. int newLevel;
  408. if (!int.TryParse(rawLevel, out newLevel))
  409. {
  410. MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawLevel);
  411. return;
  412. }
  413. if (newLevel < 0 || newLevel > Util.MAX_THREADPOOL_LEVEL)
  414. {
  415. MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0.." + Util.MAX_THREADPOOL_LEVEL, newLevel);
  416. return;
  417. }
  418. Util.LogThreadPool = newLevel;
  419. MainConsole.Instance.OutputFormat("LogThreadPool set to {0}", newLevel);
  420. }
  421. private void HandleForceGc(string module, string[] args)
  422. {
  423. Notice("Manually invoking runtime garbage collection");
  424. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  425. GC.Collect();
  426. GC.WaitForPendingFinalizers();
  427. GC.Collect();
  428. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
  429. }
  430. public virtual void HandleShow(string module, string[] cmd)
  431. {
  432. List<string> args = new List<string>(cmd);
  433. args.RemoveAt(0);
  434. string[] showParams = args.ToArray();
  435. switch (showParams[0])
  436. {
  437. case "info":
  438. ShowInfo();
  439. break;
  440. case "version":
  441. Notice(GetVersionText());
  442. break;
  443. case "uptime":
  444. Notice(GetUptimeReport());
  445. break;
  446. case "threads":
  447. Notice(GetThreadsReport());
  448. break;
  449. }
  450. }
  451. /// <summary>
  452. /// Change and load configuration file data.
  453. /// </summary>
  454. /// <param name="module"></param>
  455. /// <param name="cmd"></param>
  456. private void HandleConfig(string module, string[] cmd)
  457. {
  458. List<string> args = new List<string>(cmd);
  459. args.RemoveAt(0);
  460. string[] cmdparams = args.ToArray();
  461. if (cmdparams.Length > 0)
  462. {
  463. string firstParam = cmdparams[0].ToLower();
  464. switch (firstParam)
  465. {
  466. case "set":
  467. if (cmdparams.Length < 4)
  468. {
  469. Notice("Syntax: config set <section> <key> <value>");
  470. Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5");
  471. }
  472. else
  473. {
  474. IConfig c;
  475. IConfigSource source = new IniConfigSource();
  476. c = source.AddConfig(cmdparams[1]);
  477. if (c != null)
  478. {
  479. string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
  480. c.Set(cmdparams[2], _value);
  481. Config.Merge(source);
  482. Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value);
  483. }
  484. }
  485. break;
  486. case "get":
  487. case "show":
  488. if (cmdparams.Length == 1)
  489. {
  490. foreach (IConfig config in Config.Configs)
  491. {
  492. Notice("[{0}]", config.Name);
  493. string[] keys = config.GetKeys();
  494. foreach (string key in keys)
  495. Notice(" {0} = {1}", key, config.GetString(key));
  496. }
  497. }
  498. else if (cmdparams.Length == 2 || cmdparams.Length == 3)
  499. {
  500. IConfig config = Config.Configs[cmdparams[1]];
  501. if (config == null)
  502. {
  503. Notice("Section \"{0}\" does not exist.",cmdparams[1]);
  504. break;
  505. }
  506. else
  507. {
  508. if (cmdparams.Length == 2)
  509. {
  510. Notice("[{0}]", config.Name);
  511. foreach (string key in config.GetKeys())
  512. Notice(" {0} = {1}", key, config.GetString(key));
  513. }
  514. else
  515. {
  516. Notice(
  517. "config get {0} {1} : {2}",
  518. cmdparams[1], cmdparams[2], config.GetString(cmdparams[2]));
  519. }
  520. }
  521. }
  522. else
  523. {
  524. Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
  525. Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
  526. }
  527. break;
  528. case "save":
  529. if (cmdparams.Length < 2)
  530. {
  531. Notice("Syntax: config save <path>");
  532. return;
  533. }
  534. string path = cmdparams[1];
  535. Notice("Saving configuration file: {0}", path);
  536. if (Config is IniConfigSource)
  537. {
  538. IniConfigSource iniCon = (IniConfigSource)Config;
  539. iniCon.Save(path);
  540. }
  541. else if (Config is XmlConfigSource)
  542. {
  543. XmlConfigSource xmlCon = (XmlConfigSource)Config;
  544. xmlCon.Save(path);
  545. }
  546. break;
  547. }
  548. }
  549. }
  550. private void HandleSetLogLevel(string module, string[] cmd)
  551. {
  552. if (cmd.Length != 4)
  553. {
  554. Notice("Usage: set log level <level>");
  555. return;
  556. }
  557. if (null == m_consoleAppender)
  558. {
  559. Notice("No appender named Console found (see the log4net config file for this executable)!");
  560. return;
  561. }
  562. string rawLevel = cmd[3];
  563. ILoggerRepository repository = LogManager.GetRepository();
  564. Level consoleLevel = repository.LevelMap[rawLevel];
  565. if (consoleLevel != null)
  566. m_consoleAppender.Threshold = consoleLevel;
  567. else
  568. Notice(
  569. "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
  570. rawLevel);
  571. ShowLogLevel();
  572. }
  573. private void ShowLogLevel()
  574. {
  575. Notice("Console log level is {0}", m_consoleAppender.Threshold);
  576. }
  577. protected virtual void HandleScript(string module, string[] parms)
  578. {
  579. if (parms.Length != 2)
  580. {
  581. Notice("Usage: command-script <path-to-script");
  582. return;
  583. }
  584. RunCommandScript(parms[1]);
  585. }
  586. /// <summary>
  587. /// Run an optional startup list of commands
  588. /// </summary>
  589. /// <param name="fileName"></param>
  590. protected void RunCommandScript(string fileName)
  591. {
  592. if (m_console == null)
  593. return;
  594. if (File.Exists(fileName))
  595. {
  596. m_log.Info("[SERVER BASE]: Running " + fileName);
  597. using (StreamReader readFile = File.OpenText(fileName))
  598. {
  599. string currentCommand;
  600. while ((currentCommand = readFile.ReadLine()) != null)
  601. {
  602. currentCommand = currentCommand.Trim();
  603. if (!(currentCommand == ""
  604. || currentCommand.StartsWith(";")
  605. || currentCommand.StartsWith("//")
  606. || currentCommand.StartsWith("#")))
  607. {
  608. m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
  609. m_console.RunCommand(currentCommand);
  610. }
  611. }
  612. }
  613. }
  614. }
  615. /// <summary>
  616. /// Return a report about the uptime of this server
  617. /// </summary>
  618. /// <returns></returns>
  619. protected string GetUptimeReport()
  620. {
  621. StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
  622. sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
  623. sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
  624. return sb.ToString();
  625. }
  626. protected void ShowInfo()
  627. {
  628. Notice(GetVersionText());
  629. Notice("Startup directory: " + m_startupDirectory);
  630. if (null != m_consoleAppender)
  631. Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
  632. }
  633. /// <summary>
  634. /// Enhance the version string with extra information if it's available.
  635. /// </summary>
  636. protected void EnhanceVersionInformation()
  637. {
  638. string buildVersion = string.Empty;
  639. // The subversion information is deprecated and will be removed at a later date
  640. // Add subversion revision information if available
  641. // Try file "svn_revision" in the current directory first, then the .svn info.
  642. // This allows to make the revision available in simulators not running from the source tree.
  643. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place
  644. // elsewhere as well
  645. string gitDir = "../.git/";
  646. string gitRefPointerPath = gitDir + "HEAD";
  647. string svnRevisionFileName = "svn_revision";
  648. string svnFileName = ".svn/entries";
  649. string manualVersionFileName = ".version";
  650. string inputLine;
  651. int strcmp;
  652. if (File.Exists(manualVersionFileName))
  653. {
  654. using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
  655. buildVersion = CommitFile.ReadLine();
  656. m_version += buildVersion ?? "";
  657. }
  658. else if (File.Exists(gitRefPointerPath))
  659. {
  660. // m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
  661. string rawPointer = "";
  662. using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
  663. rawPointer = pointerFile.ReadLine();
  664. // m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
  665. Match m = Regex.Match(rawPointer, "^ref: (.+)$");
  666. if (m.Success)
  667. {
  668. // m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
  669. string gitRef = m.Groups[1].Value;
  670. string gitRefPath = gitDir + gitRef;
  671. if (File.Exists(gitRefPath))
  672. {
  673. // m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
  674. using (StreamReader refFile = File.OpenText(gitRefPath))
  675. {
  676. string gitHash = refFile.ReadLine();
  677. m_version += gitHash.Substring(0, 7);
  678. }
  679. }
  680. }
  681. }
  682. else
  683. {
  684. // Remove the else logic when subversion mirror is no longer used
  685. if (File.Exists(svnRevisionFileName))
  686. {
  687. StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
  688. buildVersion = RevisionFile.ReadLine();
  689. buildVersion = buildVersion.Trim();
  690. RevisionFile.Close();
  691. }
  692. if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
  693. {
  694. StreamReader EntriesFile = File.OpenText(svnFileName);
  695. inputLine = EntriesFile.ReadLine();
  696. while (inputLine != null)
  697. {
  698. // using the dir svn revision at the top of entries file
  699. strcmp = String.Compare(inputLine, "dir");
  700. if (strcmp == 0)
  701. {
  702. buildVersion = EntriesFile.ReadLine();
  703. break;
  704. }
  705. else
  706. {
  707. inputLine = EntriesFile.ReadLine();
  708. }
  709. }
  710. EntriesFile.Close();
  711. }
  712. m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
  713. }
  714. }
  715. public string GetVersionText()
  716. {
  717. return String.Format("Version: {0} (SIMULATION/{1} - SIMULATION/{2})",
  718. m_version, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax);
  719. }
  720. /// <summary>
  721. /// Get a report about the registered threads in this server.
  722. /// </summary>
  723. protected string GetThreadsReport()
  724. {
  725. // This should be a constant field.
  726. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
  727. StringBuilder sb = new StringBuilder();
  728. Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
  729. sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
  730. int timeNow = Environment.TickCount & Int32.MaxValue;
  731. sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
  732. sb.Append(Environment.NewLine);
  733. foreach (Watchdog.ThreadWatchdogInfo twi in threads)
  734. {
  735. Thread t = twi.Thread;
  736. sb.AppendFormat(
  737. reportFormat,
  738. t.ManagedThreadId,
  739. t.Name,
  740. timeNow - twi.LastTick,
  741. timeNow - twi.FirstTick,
  742. t.Priority,
  743. t.ThreadState);
  744. sb.Append("\n");
  745. }
  746. sb.Append(GetThreadPoolReport());
  747. sb.Append("\n");
  748. int totalThreads = Process.GetCurrentProcess().Threads.Count;
  749. if (totalThreads > 0)
  750. sb.AppendFormat("Total process threads active: {0}\n\n", totalThreads);
  751. return sb.ToString();
  752. }
  753. /// <summary>
  754. /// Get a thread pool report.
  755. /// </summary>
  756. /// <returns></returns>
  757. public static string GetThreadPoolReport()
  758. {
  759. StringBuilder sb = new StringBuilder();
  760. // framework pool is alwasy active
  761. int maxWorkers;
  762. int minWorkers;
  763. int curWorkers;
  764. int maxComp;
  765. int minComp;
  766. int curComp;
  767. try
  768. {
  769. ThreadPool.GetMaxThreads(out maxWorkers, out maxComp);
  770. ThreadPool.GetMinThreads(out minWorkers, out minComp);
  771. ThreadPool.GetAvailableThreads(out curWorkers, out curComp);
  772. curWorkers = maxWorkers - curWorkers;
  773. curComp = maxComp - curComp;
  774. sb.Append("\nFramework main threadpool \n");
  775. sb.AppendFormat("workers: {0} ({1} / {2})\n", curWorkers, maxWorkers, minWorkers);
  776. sb.AppendFormat("Completion: {0} ({1} / {2})\n", curComp, maxComp, minComp);
  777. }
  778. catch { }
  779. if (Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem)
  780. {
  781. sb.AppendFormat("\nThread pool used: Framework main threadpool\n");
  782. return sb.ToString();
  783. }
  784. string threadPoolUsed = null;
  785. int maxThreads = 0;
  786. int minThreads = 0;
  787. int allocatedThreads = 0;
  788. int inUseThreads = 0;
  789. int waitingCallbacks = 0;
  790. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  791. {
  792. STPInfo stpi = Util.GetSmartThreadPoolInfo();
  793. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  794. if (stpi != null)
  795. {
  796. threadPoolUsed = "SmartThreadPool";
  797. maxThreads = stpi.MaxThreads;
  798. minThreads = stpi.MinThreads;
  799. inUseThreads = stpi.InUseThreads;
  800. allocatedThreads = stpi.ActiveThreads;
  801. waitingCallbacks = stpi.WaitingCallbacks;
  802. }
  803. }
  804. if (threadPoolUsed != null)
  805. {
  806. sb.Append("\nThreadpool (excluding script engine pools)\n");
  807. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  808. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  809. sb.AppendFormat("Min threads : {0}\n", minThreads);
  810. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  811. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  812. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  813. }
  814. else
  815. {
  816. sb.AppendFormat("Thread pool not used\n");
  817. }
  818. return sb.ToString();
  819. }
  820. public virtual void HandleThreadsAbort(string module, string[] cmd)
  821. {
  822. if (cmd.Length != 3)
  823. {
  824. MainConsole.Instance.Output("Usage: threads abort <thread-id>");
  825. return;
  826. }
  827. int threadId;
  828. if (!int.TryParse(cmd[2], out threadId))
  829. {
  830. MainConsole.Instance.Output("ERROR: Thread id must be an integer");
  831. return;
  832. }
  833. if (Watchdog.AbortThread(threadId))
  834. MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
  835. else
  836. MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
  837. }
  838. /// <summary>
  839. /// Console output is only possible if a console has been established.
  840. /// That is something that cannot be determined within this class. So
  841. /// all attempts to use the console MUST be verified.
  842. /// </summary>
  843. /// <param name="msg"></param>
  844. protected void Notice(string msg)
  845. {
  846. if (m_console != null)
  847. {
  848. m_console.Output(msg);
  849. }
  850. }
  851. /// <summary>
  852. /// Console output is only possible if a console has been established.
  853. /// That is something that cannot be determined within this class. So
  854. /// all attempts to use the console MUST be verified.
  855. /// </summary>
  856. /// <param name="format"></param>
  857. /// <param name="components"></param>
  858. protected void Notice(string format, params object[] components)
  859. {
  860. if (m_console != null)
  861. m_console.OutputFormat(format, components);
  862. }
  863. public virtual void Shutdown()
  864. {
  865. m_serverStatsCollector.Close();
  866. ShutdownSpecific();
  867. }
  868. /// <summary>
  869. /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
  870. /// </summary>
  871. protected virtual void ShutdownSpecific() {}
  872. }
  873. }