ServicesServerBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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.IO;
  30. using System.Reflection;
  31. using System.Threading;
  32. using System.Text;
  33. using System.Xml;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Console;
  36. using OpenSim.Framework.Monitoring;
  37. using OpenSim.Framework.Servers;
  38. using log4net;
  39. using log4net.Config;
  40. using log4net.Appender;
  41. using log4net.Core;
  42. using log4net.Repository;
  43. using Nini.Config;
  44. namespace OpenSim.Server.Base
  45. {
  46. public class ServicesServerBase : ServerBase
  47. {
  48. // Logger
  49. //
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. // Command line args
  52. //
  53. protected string[] m_Arguments;
  54. protected string m_configDirectory = ".";
  55. // Run flag
  56. //
  57. private bool m_Running = true;
  58. #if (_MONO)
  59. private static Mono.Unix.UnixSignal[] signals;
  60. #endif
  61. // Handle all the automagical stuff
  62. //
  63. public ServicesServerBase(string prompt, string[] args) : base()
  64. {
  65. // Save raw arguments
  66. m_Arguments = args;
  67. // Read command line
  68. ArgvConfigSource argvConfig = new ArgvConfigSource(args);
  69. argvConfig.AddSwitch("Startup", "console", "c");
  70. argvConfig.AddSwitch("Startup", "logfile", "l");
  71. argvConfig.AddSwitch("Startup", "inifile", "i");
  72. argvConfig.AddSwitch("Startup", "prompt", "p");
  73. argvConfig.AddSwitch("Startup", "logconfig", "g");
  74. // Automagically create the ini file name
  75. string fileName = "";
  76. if (Assembly.GetEntryAssembly() != null)
  77. fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
  78. string iniFile = fileName + ".ini";
  79. string logConfig = null;
  80. IConfig startupConfig = argvConfig.Configs["Startup"];
  81. if (startupConfig != null)
  82. {
  83. // Check if a file name was given on the command line
  84. iniFile = startupConfig.GetString("inifile", iniFile);
  85. // Check if a prompt was given on the command line
  86. prompt = startupConfig.GetString("prompt", prompt);
  87. // Check for a Log4Net config file on the command line
  88. logConfig =startupConfig.GetString("logconfig", logConfig);
  89. }
  90. Config = ReadConfigSource(iniFile);
  91. List<string> sources = new List<string>();
  92. sources.Add(iniFile);
  93. int sourceIndex = 1;
  94. while (AddIncludes(Config, sources))
  95. {
  96. for ( ; sourceIndex < sources.Count ; ++sourceIndex)
  97. {
  98. IConfigSource s = ReadConfigSource(sources[sourceIndex]);
  99. Config.Merge(s);
  100. }
  101. }
  102. // Merge OpSys env vars
  103. Console.WriteLine("[CONFIG]: Loading environment variables for Config");
  104. Util.MergeEnvironmentToConfig(Config);
  105. // Merge the configuration from the command line into the loaded file
  106. Config.Merge(argvConfig);
  107. Config.ReplaceKeyValues();
  108. // Refresh the startupConfig post merge
  109. if (Config.Configs["Startup"] != null)
  110. {
  111. startupConfig = Config.Configs["Startup"];
  112. }
  113. if (startupConfig != null)
  114. {
  115. m_configDirectory = startupConfig.GetString("ConfigDirectory", m_configDirectory);
  116. prompt = startupConfig.GetString("Prompt", prompt);
  117. }
  118. // Allow derived classes to load config before the console is opened.
  119. ReadConfig();
  120. // Create main console
  121. string consoleType = "local";
  122. if (startupConfig != null)
  123. consoleType = startupConfig.GetString("console", consoleType);
  124. if (consoleType == "basic")
  125. {
  126. MainConsole.Instance = new CommandConsole(prompt);
  127. }
  128. else if (consoleType == "rest")
  129. {
  130. MainConsole.Instance = new RemoteConsole(prompt);
  131. ((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
  132. }
  133. else if (consoleType == "mock")
  134. {
  135. MainConsole.Instance = new MockConsole();
  136. }
  137. else if (consoleType == "local")
  138. {
  139. MainConsole.Instance = new LocalConsole(prompt, startupConfig);
  140. }
  141. m_console = MainConsole.Instance;
  142. if (logConfig != null)
  143. {
  144. FileInfo cfg = new FileInfo(logConfig);
  145. XmlConfigurator.Configure(cfg);
  146. }
  147. else
  148. {
  149. XmlConfigurator.Configure();
  150. }
  151. LogEnvironmentInformation();
  152. RegisterCommonAppenders(startupConfig);
  153. if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
  154. {
  155. CreatePIDFile(startupConfig.GetString("PIDFile"));
  156. }
  157. RegisterCommonCommands();
  158. RegisterCommonComponents(Config);
  159. #if (_MONO)
  160. Thread signal_thread = new Thread (delegate ()
  161. {
  162. while (true)
  163. {
  164. // Wait for a signal to be delivered
  165. int index = Mono.Unix.UnixSignal.WaitAny (signals, -1);
  166. //Mono.Unix.Native.Signum signal = signals [index].Signum;
  167. ShutdownSpecific();
  168. m_Running = false;
  169. Environment.Exit(0);
  170. }
  171. });
  172. if(!Util.IsWindows())
  173. {
  174. try
  175. {
  176. // linux mac os specifics
  177. signals = new Mono.Unix.UnixSignal[]
  178. {
  179. new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM)
  180. };
  181. ignal_thread.IsBackground = true;
  182. signal_thread.Start();
  183. }
  184. catch (Exception e)
  185. {
  186. m_log.Info("Could not set up UNIX signal handlers. SIGTERM will not");
  187. m_log.InfoFormat("shut down gracefully: {0}", e.Message);
  188. m_log.Debug("Exception was: ", e);
  189. }
  190. }
  191. #endif
  192. // Allow derived classes to perform initialization that
  193. // needs to be done after the console has opened
  194. Initialise();
  195. }
  196. public bool Running
  197. {
  198. get { return m_Running; }
  199. }
  200. public virtual int Run()
  201. {
  202. Watchdog.Enabled = true;
  203. MemoryWatchdog.Enabled = true;
  204. while (m_Running)
  205. {
  206. try
  207. {
  208. MainConsole.Instance.Prompt();
  209. }
  210. catch (Exception e)
  211. {
  212. m_log.ErrorFormat("Command error: {0}", e);
  213. }
  214. }
  215. MainServer.Stop();
  216. MemoryWatchdog.Enabled = false;
  217. Watchdog.Enabled = false;
  218. WorkManager.Stop();
  219. RemovePIDFile();
  220. return 0;
  221. }
  222. protected override void ShutdownSpecific()
  223. {
  224. if(!m_Running)
  225. return;
  226. m_Running = false;
  227. m_log.Info("[CONSOLE] Quitting");
  228. base.ShutdownSpecific();
  229. }
  230. protected virtual void ReadConfig()
  231. {
  232. }
  233. protected virtual void Initialise()
  234. {
  235. }
  236. /// <summary>
  237. /// Adds the included files as ini configuration files
  238. /// </summary>
  239. /// <param name="sources">List of URL strings or filename strings</param>
  240. private bool AddIncludes(IConfigSource configSource, List<string> sources)
  241. {
  242. bool sourcesAdded = false;
  243. //loop over config sources
  244. foreach (IConfig config in configSource.Configs)
  245. {
  246. // Look for Include-* in the key name
  247. string[] keys = config.GetKeys();
  248. foreach (string k in keys)
  249. {
  250. if (k.StartsWith("Include-"))
  251. {
  252. // read the config file to be included.
  253. string file = config.GetString(k);
  254. if (IsUri(file))
  255. {
  256. if (!sources.Contains(file))
  257. {
  258. sourcesAdded = true;
  259. sources.Add(file);
  260. }
  261. }
  262. else
  263. {
  264. string basepath = Path.GetFullPath(m_configDirectory);
  265. // Resolve relative paths with wildcards
  266. string chunkWithoutWildcards = file;
  267. string chunkWithWildcards = string.Empty;
  268. int wildcardIndex = file.IndexOfAny(new char[] { '*', '?' });
  269. if (wildcardIndex != -1)
  270. {
  271. chunkWithoutWildcards = file.Substring(0, wildcardIndex);
  272. chunkWithWildcards = file.Substring(wildcardIndex);
  273. }
  274. string path = Path.Combine(basepath, chunkWithoutWildcards);
  275. path = Path.GetFullPath(path) + chunkWithWildcards;
  276. string[] paths = Util.Glob(path);
  277. // If the include path contains no wildcards, then warn the user that it wasn't found.
  278. if (wildcardIndex == -1 && paths.Length == 0)
  279. {
  280. Console.WriteLine("[CONFIG]: Could not find include file {0}", path);
  281. }
  282. else
  283. {
  284. foreach (string p in paths)
  285. {
  286. if (!sources.Contains(p))
  287. {
  288. sourcesAdded = true;
  289. sources.Add(p);
  290. }
  291. }
  292. }
  293. }
  294. }
  295. }
  296. }
  297. return sourcesAdded;
  298. }
  299. /// <summary>
  300. /// Check if we can convert the string to a URI
  301. /// </summary>
  302. /// <param name="file">String uri to the remote resource</param>
  303. /// <returns>true if we can convert the string to a Uri object</returns>
  304. bool IsUri(string file)
  305. {
  306. Uri configUri;
  307. return Uri.TryCreate(file, UriKind.Absolute,
  308. out configUri) && configUri.Scheme == Uri.UriSchemeHttp;
  309. }
  310. IConfigSource ReadConfigSource(string iniFile)
  311. {
  312. // Find out of the file name is a URI and remote load it if possible.
  313. // Load it as a local file otherwise.
  314. Uri configUri;
  315. IConfigSource s = null;
  316. try
  317. {
  318. if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
  319. configUri.Scheme == Uri.UriSchemeHttp)
  320. {
  321. XmlReader r = XmlReader.Create(iniFile);
  322. s = new XmlConfigSource(r);
  323. }
  324. else
  325. {
  326. s = new IniConfigSource(iniFile);
  327. }
  328. }
  329. catch (Exception e)
  330. {
  331. System.Console.WriteLine("Error reading from config source. {0}", e.Message);
  332. Environment.Exit(1);
  333. }
  334. return s;
  335. }
  336. }
  337. }