1
0

ServicesServerBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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.IO;
  29. using System.Xml;
  30. using System.Threading;
  31. using System.Reflection;
  32. using OpenSim.Framework.Console;
  33. using log4net;
  34. using log4net.Config;
  35. using log4net.Appender;
  36. using log4net.Core;
  37. using log4net.Repository;
  38. using Nini.Config;
  39. namespace OpenSim.Server.Base
  40. {
  41. public class ServicesServerBase
  42. {
  43. // Logger
  44. //
  45. private static readonly ILog m_log =
  46. LogManager.GetLogger(
  47. MethodBase.GetCurrentMethod().DeclaringType);
  48. // Command line args
  49. //
  50. protected string[] m_Arguments;
  51. // Configuration
  52. //
  53. protected IConfigSource m_Config = null;
  54. public IConfigSource Config
  55. {
  56. get { return m_Config; }
  57. }
  58. // Run flag
  59. //
  60. private bool m_Running = true;
  61. // PID file
  62. //
  63. private string m_pidFile = String.Empty;
  64. // Handle all the automagical stuff
  65. //
  66. public ServicesServerBase(string prompt, string[] args)
  67. {
  68. // Save raw arguments
  69. //
  70. m_Arguments = args;
  71. // Read command line
  72. //
  73. ArgvConfigSource argvConfig = new ArgvConfigSource(args);
  74. argvConfig.AddSwitch("Startup", "console", "c");
  75. argvConfig.AddSwitch("Startup", "logfile", "l");
  76. argvConfig.AddSwitch("Startup", "inifile", "i");
  77. argvConfig.AddSwitch("Startup", "prompt", "p");
  78. argvConfig.AddSwitch("Startup", "logconfig", "g");
  79. // Automagically create the ini file name
  80. //
  81. string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
  82. string iniFile = fileName + ".ini";
  83. string logConfig = null;
  84. IConfig startupConfig = argvConfig.Configs["Startup"];
  85. if (startupConfig != null)
  86. {
  87. // Check if a file name was given on the command line
  88. //
  89. iniFile = startupConfig.GetString("inifile", iniFile);
  90. //
  91. // Check if a prompt was given on the command line
  92. prompt = startupConfig.GetString("prompt", prompt);
  93. //
  94. // Check for a Log4Net config file on the command line
  95. logConfig =startupConfig.GetString("logconfig",logConfig);
  96. }
  97. // Find out of the file name is a URI and remote load it
  98. // if it's possible. Load it as a local file otherwise.
  99. //
  100. Uri configUri;
  101. try
  102. {
  103. if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
  104. configUri.Scheme == Uri.UriSchemeHttp)
  105. {
  106. XmlReader r = XmlReader.Create(iniFile);
  107. m_Config = new XmlConfigSource(r);
  108. }
  109. else
  110. {
  111. m_Config = new IniConfigSource(iniFile);
  112. }
  113. }
  114. catch (Exception)
  115. {
  116. System.Console.WriteLine("Error reading from config source {0}",
  117. iniFile);
  118. Thread.CurrentThread.Abort();
  119. }
  120. // Merge the configuration from the command line into the
  121. // loaded file
  122. //
  123. m_Config.Merge(argvConfig);
  124. // Refresh the startupConfig post merge
  125. //
  126. if (m_Config.Configs["Startup"] != null)
  127. {
  128. startupConfig = m_Config.Configs["Startup"];
  129. }
  130. prompt = startupConfig.GetString("Prompt", prompt);
  131. // Allow derived classes to load config before the console is
  132. // opened.
  133. //
  134. ReadConfig();
  135. // Create main console
  136. //
  137. string consoleType = "local";
  138. if (startupConfig != null)
  139. consoleType = startupConfig.GetString("console", consoleType);
  140. if (consoleType == "basic")
  141. {
  142. MainConsole.Instance = new CommandConsole(prompt);
  143. }
  144. else if (consoleType == "rest")
  145. {
  146. MainConsole.Instance = new RemoteConsole(prompt);
  147. ((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
  148. }
  149. else
  150. {
  151. MainConsole.Instance = new LocalConsole(prompt);
  152. }
  153. // Configure the appenders for log4net
  154. //
  155. OpenSimAppender consoleAppender = null;
  156. FileAppender fileAppender = null;
  157. if (logConfig != null)
  158. {
  159. FileInfo cfg = new FileInfo(logConfig);
  160. XmlConfigurator.Configure(cfg);
  161. }
  162. else
  163. {
  164. XmlConfigurator.Configure();
  165. }
  166. ILoggerRepository repository = LogManager.GetRepository();
  167. IAppender[] appenders = repository.GetAppenders();
  168. foreach (IAppender appender in appenders)
  169. {
  170. if (appender.Name == "Console")
  171. {
  172. consoleAppender = (OpenSimAppender)appender;
  173. }
  174. if (appender.Name == "LogFileAppender")
  175. {
  176. fileAppender = (FileAppender)appender;
  177. }
  178. }
  179. if (consoleAppender == null)
  180. {
  181. System.Console.WriteLine("No console appender found. Server can't start");
  182. Thread.CurrentThread.Abort();
  183. }
  184. else
  185. {
  186. consoleAppender.Console = MainConsole.Instance;
  187. if (null == consoleAppender.Threshold)
  188. consoleAppender.Threshold = Level.All;
  189. }
  190. // Set log file
  191. //
  192. if (fileAppender != null)
  193. {
  194. if (startupConfig != null)
  195. {
  196. string cfgFileName = startupConfig.GetString("logfile", null);
  197. if (cfgFileName != null)
  198. {
  199. fileAppender.File = cfgFileName;
  200. fileAppender.ActivateOptions();
  201. }
  202. }
  203. }
  204. if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
  205. {
  206. CreatePIDFile(startupConfig.GetString("PIDFile"));
  207. }
  208. // Register the quit command
  209. //
  210. MainConsole.Instance.Commands.AddCommand("base", false, "quit",
  211. "quit",
  212. "Quit the application", HandleQuit);
  213. MainConsole.Instance.Commands.AddCommand("base", false, "shutdown",
  214. "shutdown",
  215. "Quit the application", HandleQuit);
  216. // Register a command to read other commands from a file
  217. MainConsole.Instance.Commands.AddCommand("base", false, "command-script",
  218. "command-script <script>",
  219. "Run a command script from file", HandleScript);
  220. // Allow derived classes to perform initialization that
  221. // needs to be done after the console has opened
  222. //
  223. Initialise();
  224. }
  225. public bool Running
  226. {
  227. get { return m_Running; }
  228. }
  229. public virtual int Run()
  230. {
  231. while (m_Running)
  232. {
  233. MainConsole.Instance.Prompt();
  234. }
  235. if (m_pidFile != String.Empty)
  236. File.Delete(m_pidFile);
  237. return 0;
  238. }
  239. protected virtual void HandleQuit(string module, string[] args)
  240. {
  241. m_Running = false;
  242. m_log.Info("[CONSOLE] Quitting");
  243. }
  244. protected virtual void HandleScript(string module, string[] parms)
  245. {
  246. if (parms.Length != 2)
  247. {
  248. return;
  249. }
  250. RunCommandScript(parms[1]);
  251. }
  252. /// <summary>
  253. /// Run an optional startup list of commands
  254. /// </summary>
  255. /// <param name="fileName"></param>
  256. private void RunCommandScript(string fileName)
  257. {
  258. if (File.Exists(fileName))
  259. {
  260. m_log.Info("[COMMANDFILE]: Running " + fileName);
  261. using (StreamReader readFile = File.OpenText(fileName))
  262. {
  263. string currentCommand;
  264. while ((currentCommand = readFile.ReadLine()) != null)
  265. {
  266. if (currentCommand != String.Empty)
  267. {
  268. m_log.Info("[COMMANDFILE]: Running '" + currentCommand + "'");
  269. MainConsole.Instance.RunCommand(currentCommand);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. protected virtual void ReadConfig()
  276. {
  277. }
  278. protected virtual void Initialise()
  279. {
  280. }
  281. protected void CreatePIDFile(string path)
  282. {
  283. try
  284. {
  285. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  286. FileStream fs = File.Create(path);
  287. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  288. Byte[] buf = enc.GetBytes(pidstring);
  289. fs.Write(buf, 0, buf.Length);
  290. fs.Close();
  291. m_pidFile = path;
  292. }
  293. catch (Exception)
  294. {
  295. }
  296. }
  297. }
  298. }