ServicesServerBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. // Automagically create the ini file name
  79. //
  80. string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
  81. string iniFile = fileName + ".ini";
  82. IConfig startupConfig = argvConfig.Configs["Startup"];
  83. if (startupConfig != null)
  84. {
  85. // Check if a file name was given on the command line
  86. //
  87. iniFile = startupConfig.GetString("inifile", iniFile);
  88. //
  89. // Check if a prompt was given on the command line
  90. prompt = startupConfig.GetString("prompt", prompt);
  91. }
  92. // Find out of the file name is a URI and remote load it
  93. // if it's possible. Load it as a local file otherwise.
  94. //
  95. Uri configUri;
  96. try
  97. {
  98. if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
  99. configUri.Scheme == Uri.UriSchemeHttp)
  100. {
  101. XmlReader r = XmlReader.Create(iniFile);
  102. m_Config = new XmlConfigSource(r);
  103. }
  104. else
  105. {
  106. m_Config = new IniConfigSource(iniFile);
  107. }
  108. }
  109. catch (Exception)
  110. {
  111. System.Console.WriteLine("Error reading from config source {0}",
  112. iniFile);
  113. Thread.CurrentThread.Abort();
  114. }
  115. // Merge the configuration from the command line into the
  116. // loaded file
  117. //
  118. m_Config.Merge(argvConfig);
  119. // Refresh the startupConfig post merge
  120. //
  121. if (m_Config.Configs["Startup"] != null)
  122. {
  123. startupConfig = m_Config.Configs["Startup"];
  124. }
  125. prompt = startupConfig.GetString("Prompt", prompt);
  126. // Allow derived classes to load config before the console is
  127. // opened.
  128. //
  129. ReadConfig();
  130. // Create main console
  131. //
  132. string consoleType = "local";
  133. if (startupConfig != null)
  134. consoleType = startupConfig.GetString("console", consoleType);
  135. if (consoleType == "basic")
  136. {
  137. MainConsole.Instance = new CommandConsole(prompt);
  138. }
  139. else if (consoleType == "rest")
  140. {
  141. MainConsole.Instance = new RemoteConsole(prompt);
  142. ((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
  143. }
  144. else
  145. {
  146. MainConsole.Instance = new LocalConsole(prompt);
  147. }
  148. // Configure the appenders for log4net
  149. //
  150. OpenSimAppender consoleAppender = null;
  151. FileAppender fileAppender = null;
  152. XmlConfigurator.Configure();
  153. ILoggerRepository repository = LogManager.GetRepository();
  154. IAppender[] appenders = repository.GetAppenders();
  155. foreach (IAppender appender in appenders)
  156. {
  157. if (appender.Name == "Console")
  158. {
  159. consoleAppender = (OpenSimAppender)appender;
  160. }
  161. if (appender.Name == "LogFileAppender")
  162. {
  163. fileAppender = (FileAppender)appender;
  164. }
  165. }
  166. if (consoleAppender == null)
  167. {
  168. System.Console.WriteLine("No console appender found. Server can't start");
  169. Thread.CurrentThread.Abort();
  170. }
  171. else
  172. {
  173. consoleAppender.Console = MainConsole.Instance;
  174. if (null == consoleAppender.Threshold)
  175. consoleAppender.Threshold = Level.All;
  176. }
  177. // Set log file
  178. //
  179. if (fileAppender != null)
  180. {
  181. if (startupConfig != null)
  182. {
  183. fileName = startupConfig.GetString("logfile", fileName+".log");
  184. fileName = Path.GetFullPath(Path.Combine(".", fileName));
  185. fileAppender.File = fileName;
  186. fileAppender.ActivateOptions();
  187. }
  188. }
  189. if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
  190. {
  191. CreatePIDFile(startupConfig.GetString("PIDFile"));
  192. }
  193. // Register the quit command
  194. //
  195. MainConsole.Instance.Commands.AddCommand("base", false, "quit",
  196. "quit",
  197. "Quit the application", HandleQuit);
  198. MainConsole.Instance.Commands.AddCommand("base", false, "shutdown",
  199. "shutdown",
  200. "Quit the application", HandleQuit);
  201. // Register a command to read other commands from a file
  202. MainConsole.Instance.Commands.AddCommand("base", false, "command-script",
  203. "command-script <script>",
  204. "Run a command script from file", HandleScript);
  205. // Allow derived classes to perform initialization that
  206. // needs to be done after the console has opened
  207. //
  208. Initialise();
  209. }
  210. public bool Running
  211. {
  212. get { return m_Running; }
  213. }
  214. public virtual int Run()
  215. {
  216. while (m_Running)
  217. {
  218. MainConsole.Instance.Prompt();
  219. }
  220. if (m_pidFile != String.Empty)
  221. File.Delete(m_pidFile);
  222. return 0;
  223. }
  224. protected virtual void HandleQuit(string module, string[] args)
  225. {
  226. m_Running = false;
  227. m_log.Info("[CONSOLE] Quitting");
  228. }
  229. protected virtual void HandleScript(string module, string[] parms)
  230. {
  231. if (parms.Length != 2)
  232. {
  233. return;
  234. }
  235. RunCommandScript(parms[1]);
  236. }
  237. /// <summary>
  238. /// Run an optional startup list of commands
  239. /// </summary>
  240. /// <param name="fileName"></param>
  241. private void RunCommandScript(string fileName)
  242. {
  243. if (File.Exists(fileName))
  244. {
  245. m_log.Info("[COMMANDFILE]: Running " + fileName);
  246. using (StreamReader readFile = File.OpenText(fileName))
  247. {
  248. string currentCommand;
  249. while ((currentCommand = readFile.ReadLine()) != null)
  250. {
  251. if (currentCommand != String.Empty)
  252. {
  253. m_log.Info("[COMMANDFILE]: Running '" + currentCommand + "'");
  254. MainConsole.Instance.RunCommand(currentCommand);
  255. }
  256. }
  257. }
  258. }
  259. }
  260. protected virtual void ReadConfig()
  261. {
  262. }
  263. protected virtual void Initialise()
  264. {
  265. }
  266. protected void CreatePIDFile(string path)
  267. {
  268. try
  269. {
  270. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  271. FileStream fs = File.Create(path);
  272. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  273. Byte[] buf = enc.GetBytes(pidstring);
  274. fs.Write(buf, 0, buf.Length);
  275. fs.Close();
  276. m_pidFile = path;
  277. }
  278. catch (Exception)
  279. {
  280. }
  281. }
  282. }
  283. }