1
0

ServicesServerBase.cs 14 KB

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