ServicesServerBase.cs 11 KB

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