ServerBase.cs 39 KB

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