ConsoleBase.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 OpenSim 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.Net;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using log4net;
  34. namespace OpenSim.Framework.Console
  35. {
  36. public class ConsoleBase
  37. {
  38. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. private readonly object m_syncRoot = new object();
  40. public conscmd_callback m_cmdParser;
  41. public string m_componentName;
  42. public ConsoleBase(string componentname, conscmd_callback cmdparser)
  43. {
  44. m_componentName = componentname;
  45. m_cmdParser = cmdparser;
  46. System.Console.WriteLine("Creating new local console");
  47. m_log.Info("[" + m_componentName + "]: Started at " + DateTime.Now.ToString());
  48. }
  49. public void Close()
  50. {
  51. m_log.Info("[" + m_componentName + "]: Shutdown at " + DateTime.Now.ToString());
  52. }
  53. /// <summary>
  54. /// derive an ansi color from a string, ignoring the darker colors.
  55. /// This is used to help automatically bin component tags with colors
  56. /// in various print functions.
  57. /// </summary>
  58. /// <param name="input">arbitrary string for input</param>
  59. /// <returns>an ansii color</returns>
  60. private static ConsoleColor DeriveColor(string input)
  61. {
  62. int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
  63. return (ConsoleColor) colIdx;
  64. }
  65. /// <summary>
  66. /// Sends a warning to the current console output
  67. /// </summary>
  68. /// <param name="format">The message to send</param>
  69. /// <param name="args">WriteLine-style message arguments</param>
  70. public void Warn(string format, params object[] args)
  71. {
  72. WriteNewLine(ConsoleColor.Yellow, format, args);
  73. }
  74. /// <summary>
  75. /// Sends a warning to the current console output
  76. /// </summary>
  77. /// <param name="sender">The module that sent this message</param>
  78. /// <param name="format">The message to send</param>
  79. /// <param name="args">WriteLine-style message arguments</param>
  80. public void Warn(string sender, string format, params object[] args)
  81. {
  82. WritePrefixLine(DeriveColor(sender), sender);
  83. WriteNewLine(ConsoleColor.Yellow, format, args);
  84. }
  85. /// <summary>
  86. /// Sends a notice to the current console output
  87. /// </summary>
  88. /// <param name="format">The message to send</param>
  89. /// <param name="args">WriteLine-style message arguments</param>
  90. public void Notice(string format, params object[] args)
  91. {
  92. WriteNewLine(ConsoleColor.White, format, args);
  93. }
  94. /// <summary>
  95. /// Sends a notice to the current console output
  96. /// </summary>
  97. /// <param name="sender">The module that sent this message</param>
  98. /// <param name="format">The message to send</param>
  99. /// <param name="args">WriteLine-style message arguments</param>
  100. public void Notice(string sender, string format, params object[] args)
  101. {
  102. WritePrefixLine(DeriveColor(sender), sender);
  103. WriteNewLine(ConsoleColor.White, format, args);
  104. }
  105. /// <summary>
  106. /// Sends an error to the current console output
  107. /// </summary>
  108. /// <param name="format">The message to send</param>
  109. /// <param name="args">WriteLine-style message arguments</param>
  110. public void Error(string format, params object[] args)
  111. {
  112. WriteNewLine(ConsoleColor.Red, format, args);
  113. }
  114. /// <summary>
  115. /// Sends an error to the current console output
  116. /// </summary>
  117. /// <param name="sender">The module that sent this message</param>
  118. /// <param name="format">The message to send</param>
  119. /// <param name="args">WriteLine-style message arguments</param>
  120. public void Error(string sender, string format, params object[] args)
  121. {
  122. WritePrefixLine(DeriveColor(sender), sender);
  123. Error(format, args);
  124. }
  125. /// <summary>
  126. /// Sends a status message to the current console output
  127. /// </summary>
  128. /// <param name="format">The message to send</param>
  129. /// <param name="args">WriteLine-style message arguments</param>
  130. public void Status(string format, params object[] args)
  131. {
  132. WriteNewLine(ConsoleColor.Blue, format, args);
  133. }
  134. /// <summary>
  135. /// Sends a status message to the current console output
  136. /// </summary>
  137. /// <param name="sender">The module that sent this message</param>
  138. /// <param name="format">The message to send</param>
  139. /// <param name="args">WriteLine-style message arguments</param>
  140. public void Status(string sender, string format, params object[] args)
  141. {
  142. WritePrefixLine(DeriveColor(sender), sender);
  143. WriteNewLine(ConsoleColor.Blue, format, args);
  144. }
  145. [Conditional("DEBUG")]
  146. public void Debug(string format, params object[] args)
  147. {
  148. WriteNewLine(ConsoleColor.Gray, format, args);
  149. }
  150. [Conditional("DEBUG")]
  151. public void Debug(string sender, string format, params object[] args)
  152. {
  153. WritePrefixLine(DeriveColor(sender), sender);
  154. WriteNewLine(ConsoleColor.Gray, format, args);
  155. }
  156. private void WriteNewLine(ConsoleColor color, string format, params object[] args)
  157. {
  158. try
  159. {
  160. lock (m_syncRoot)
  161. {
  162. try
  163. {
  164. if (color != ConsoleColor.White)
  165. System.Console.ForegroundColor = color;
  166. System.Console.WriteLine(format, args);
  167. System.Console.ResetColor();
  168. }
  169. catch (ArgumentNullException)
  170. {
  171. // Some older systems dont support coloured text.
  172. System.Console.WriteLine(format, args);
  173. }
  174. catch (FormatException)
  175. {
  176. System.Console.WriteLine(args);
  177. }
  178. }
  179. }
  180. catch (ObjectDisposedException)
  181. {
  182. }
  183. }
  184. private void WritePrefixLine(ConsoleColor color, string sender)
  185. {
  186. try
  187. {
  188. lock (m_syncRoot)
  189. {
  190. sender = sender.ToUpper();
  191. System.Console.WriteLine("[" + sender + "] ");
  192. System.Console.Write("[");
  193. try
  194. {
  195. System.Console.ForegroundColor = color;
  196. System.Console.Write(sender);
  197. System.Console.ResetColor();
  198. }
  199. catch (ArgumentNullException)
  200. {
  201. // Some older systems dont support coloured text.
  202. System.Console.WriteLine(sender);
  203. }
  204. System.Console.Write("] \t");
  205. }
  206. }
  207. catch (ObjectDisposedException)
  208. {
  209. }
  210. }
  211. public string ReadLine()
  212. {
  213. try
  214. {
  215. return System.Console.ReadLine();
  216. }
  217. catch (Exception e)
  218. {
  219. m_log.Error("[Console]: System.Console.ReadLine exception " + e.ToString());
  220. return String.Empty;
  221. }
  222. }
  223. public int Read()
  224. {
  225. return System.Console.Read();
  226. }
  227. public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue)
  228. {
  229. IPAddress address;
  230. string addressStr;
  231. while (true)
  232. {
  233. addressStr = CmdPrompt(prompt, defaultvalue);
  234. if (IPAddress.TryParse(addressStr, out address))
  235. {
  236. break;
  237. }
  238. else
  239. {
  240. m_log.Error("Illegal address. Please re-enter.");
  241. }
  242. }
  243. return address;
  244. }
  245. public uint CmdPromptIPPort(string prompt, string defaultvalue)
  246. {
  247. uint port;
  248. string portStr;
  249. while (true)
  250. {
  251. portStr = CmdPrompt(prompt, defaultvalue);
  252. if (uint.TryParse(portStr, out port))
  253. {
  254. if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort)
  255. {
  256. break;
  257. }
  258. }
  259. m_log.Error("Illegal address. Please re-enter.");
  260. }
  261. return port;
  262. }
  263. // Displays a prompt and waits for the user to enter a string, then returns that string
  264. // (Done with no echo and suitable for passwords - currently disabled)
  265. public string PasswdPrompt(string prompt)
  266. {
  267. // FIXME: Needs to be better abstracted
  268. System.Console.WriteLine(String.Format("{0}: ", prompt));
  269. //ConsoleColor oldfg = System.Console.ForegroundColor;
  270. //System.Console.ForegroundColor = System.Console.BackgroundColor;
  271. string temp = System.Console.ReadLine();
  272. //System.Console.ForegroundColor = oldfg;
  273. return temp;
  274. }
  275. // Displays a command prompt and waits for the user to enter a string, then returns that string
  276. public string CmdPrompt(string prompt)
  277. {
  278. System.Console.WriteLine(String.Format("{0}: ", prompt));
  279. return ReadLine();
  280. }
  281. // Displays a command prompt and returns a default value if the user simply presses enter
  282. public string CmdPrompt(string prompt, string defaultresponse)
  283. {
  284. string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse));
  285. if (temp == String.Empty)
  286. {
  287. return defaultresponse;
  288. }
  289. else
  290. {
  291. return temp;
  292. }
  293. }
  294. // Displays a command prompt and returns a default value, user may only enter 1 of 2 options
  295. public string CmdPrompt(string prompt, string defaultresponse, string OptionA, string OptionB)
  296. {
  297. bool itisdone = false;
  298. string temp = CmdPrompt(prompt, defaultresponse);
  299. while (itisdone == false)
  300. {
  301. if ((temp == OptionA) || (temp == OptionB))
  302. {
  303. itisdone = true;
  304. }
  305. else
  306. {
  307. System.Console.WriteLine("Valid options are " + OptionA + " or " + OptionB);
  308. temp = CmdPrompt(prompt, defaultresponse);
  309. }
  310. }
  311. return temp;
  312. }
  313. // Runs a command with a number of parameters
  314. public Object RunCmd(string Cmd, string[] cmdparams)
  315. {
  316. m_cmdParser.RunCmd(Cmd, cmdparams);
  317. return null;
  318. }
  319. // Shows data about something
  320. public void ShowCommands(string ShowWhat)
  321. {
  322. m_cmdParser.Show(ShowWhat);
  323. }
  324. public void Prompt()
  325. {
  326. string tempstr = CmdPrompt(m_componentName + "# ");
  327. RunCommand(tempstr);
  328. }
  329. public void RunCommand(string cmdline)
  330. {
  331. Regex Extractor = new Regex(@"(['""][^""]+['""])\s*|([^\s]+)\s*", RegexOptions.Compiled);
  332. char[] delims = {' ', '"'};
  333. MatchCollection matches = Extractor.Matches(cmdline);
  334. // Get matches
  335. if (matches.Count == 0)
  336. return;
  337. string cmd = matches[0].Value.Trim(delims);
  338. string[] cmdparams = new string[matches.Count - 1];
  339. for (int i = 1; i < matches.Count; i++)
  340. {
  341. cmdparams[i-1] = matches[i].Value.Trim(delims);
  342. }
  343. try
  344. {
  345. RunCmd(cmd, cmdparams);
  346. }
  347. catch (Exception e)
  348. {
  349. m_log.ErrorFormat("[Console]: Command [{0}] failed with exception {1}", cmdline, e.ToString());
  350. }
  351. }
  352. public string LineInfo
  353. {
  354. get
  355. {
  356. string result = String.Empty;
  357. string stacktrace = Environment.StackTrace;
  358. List<string> lines = new List<string>(stacktrace.Split(new string[] {"at "}, StringSplitOptions.None));
  359. if (lines.Count > 4)
  360. {
  361. lines.RemoveRange(0, 4);
  362. string tmpLine = lines[0];
  363. int inIndex = tmpLine.IndexOf(" in ");
  364. if (inIndex > -1)
  365. {
  366. result = tmpLine.Substring(0, inIndex);
  367. int lineIndex = tmpLine.IndexOf(":line ");
  368. if (lineIndex > -1)
  369. {
  370. lineIndex += 6;
  371. result += ", line " + tmpLine.Substring(lineIndex, (tmpLine.Length - lineIndex) - 5);
  372. }
  373. }
  374. }
  375. return result;
  376. }
  377. }
  378. }
  379. }